Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Accounts: a colour grade, a Relight blend and an Export mix save as their own runs

Adarshf2aa27bec870
diff --git a/docs/public-signup.md b/docs/public-signup.md
index c75e2b55..3c6028ee 100644
--- a/docs/public-signup.md
+++ b/docs/public-signup.md
@@ -77,9 +77,7 @@ An account is signed in, but it sees the owner's studio as a guest does:
owner's results, files, uploads, folders, shares, projects (Layers, Cinema, Canvas, storyboards,
elements…) and Assist threads are hidden: the lists come back empty, and other reads answer 403.
Every change to them (create, rename, move, share, delete) answers 403 with `code: "library"`.
- So does Split soundtrack's **Export mix** (`POST /api/audio-tools/export`), which saves into the
- owner's Library, with or without a GPU. Accounts have their own uploads and runs (below), but no
- projects yet.
+ Accounts have their own uploads and runs (below), but no projects yet.
A Canvas Kinetic node renders in the owner's browser; keeping its run on the board
(`PUT /api/canvases/<id>/runs/<node>`) is a canvas change like any other (403 `library` for an account, 401
for a guest), and it takes only the owner's own finished Kinetic Motion results.
@@ -121,7 +119,7 @@ An account is signed in, but it sees the owner's studio as a guest does:
back at once. The live-updates stream isn't sent to accounts: their studios poll instead.
- **Its own uploads are its own.** Only the account that uploaded a file can use it in a run, and
no other account can open it. See [Uploads](#uploads).
-- **Results made in the browser (Kinetic Motion) are its own runs too.** A motion clip rendered in
+- **Results made in the browser are its own runs too.** A motion clip rendered in
the page (an animated end card, a text template, anything made on the Kinetic page) is saved with an upload and
`POST /api/generations/local` (`op: "motion"`, model `local-motion`). No model makes it, so any
account may save one, with or without its own GPU or key (the upload is sent with
@@ -137,8 +135,17 @@ An account is signed in, but it sees the owner's studio as a guest does:
(a refusal answers 422; a result the checks want to see waits for them). It shows in the account's
own runs, never the owner's Library. Nothing
is downloaded straight from the page: the clip is downloaded from the saved result. A guest's
- call answers 401 with the sign-up card. Colour grades and Relight blends stay the owner's
- (403, `code: "library"`).
+ call answers 401 with the sign-up card.
+ A **colour grade** (`op: "grade"`, model `local-color-grade`) and a **Relight blend** (`op: "relight"`,
+ model `local-relight`) are kept the same way: the same upload, its own stored PNG picture or MP4 or WebM clip
+ (400 otherwise), made from its own files only (a file picked on the page stays in the browser, so the grade names
+ no input), within the same run budget and through the same checks (its description and title). Colour grading's
+ **Save to your runs** shows for an account; a guest's Save opens the sign-up card.
+ Split soundtrack's **Export mix** (`POST /api/audio-tools/export`, the WAV in parts) is kept as one of its runs
+ too (`feature` `audio-split-mix`, model `local-mix`): its WAV goes into its own files, no bigger than the room
+ they have left (413), one export at a time (a new one drops the unfinished one), and a part with another viewer's
+ export id answers 404. The last part answers 201 with the run, within the same run budget (429) and through the
+ same checks (422).
## Managing accounts
@@ -400,9 +407,10 @@ The code is `src/server/hosted.ts` (the switch, the place, the line), `src/serve
An account with its own ComfyUI connected, or its own key, can upload files (`POST /api/uploads`,
the file as the request body with its type in `Content-Type` and its name in `X-File-Name`; an
older page's multipart form works up to 26 MB). With neither it answers 403 with
-`code: "connect-gpu"`, and a guest gets 401 with the sign-up card. The one exception is a Kinetic
-Motion result rendered in the page (sent with `x-fuobe-kinetic: 1`): any account may upload its MP4
-or WebM clip and its PNG poster, within the same space, size and upload limits below. Any other type
+`code: "connect-gpu"`, and a guest gets 401 with the sign-up card. The one exception is a result
+rendered in the page (sent with `x-fuobe-kinetic: 1`: a Kinetic Motion clip and its poster, a colour
+grade, a Relight blend): any account may upload its MP4 or WebM clip or its PNG picture, within the
+same space, size and upload limits below. Any other type
sent that way answers 403 `connect-gpu`, and a model run still needs the account's own GPU or key.
| What | Types | Largest |
diff --git a/src/app/api/audio-tools/export/route.ts b/src/app/api/audio-tools/export/route.ts
index fafd615c..637e2834 100644
--- a/src/app/api/audio-tools/export/route.ts
+++ b/src/app/api/audio-tools/export/route.ts
@@ -1,27 +1,76 @@
+import { MIX_FEATURE, MIX_MODEL } from "@/lib/av/split";
+import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "@/server/account-files";
+import { requestViewer, type Account } from "@/server/auth";
import { gateAsProxy, readBodyWithin } from "@/server/direct-gate";
-import { MixExportError, PART_MAX, receiveMixPart } from "@/server/mix-export";
+import { getGeneration, recordLocalGeneration } from "@/server/generations";
+import { moderateRun } from "@/server/hosted-run";
+import { dropMix, keepMix, MixExportError, PART_MAX, receiveMixPart, type FinishedMix, type MixAccount } from "@/server/mix-export";
+import { holdForCheck } from "@/server/output-checks";
+import { hit, unhit } from "@/server/rate";
+import { runAsTenant } from "@/server/tenant";
/**
* Split soundtrack's Export mix, in parts: POST the WAV's bytes as the body, `?offset=` where they start, `&id=` from
- * the first part's answer, `&last=1&name=` on the last part, which answers with the Library asset (201).
+ * the first part's answer, `&last=1&name=` on the last part, which answers (201) with the Library asset for the owner,
+ * or, for an account, with the run it keeps the mix as (its own files and its own runs, never the owner's Library).
*/
export async function POST(request: Request) {
// The proxy doesn't run on this route (a part is bigger than the 4 MB of a body it holds): its checks run here.
const denied = gateAsProxy(request);
if (denied) return denied;
+ const viewer = requestViewer(request);
+ const account = viewer.kind === "account" ? viewer.account : null;
const q = new URL(request.url).searchParams;
const offset = Number(q.get("offset") ?? "0");
if (!Number.isSafeInteger(offset) || offset < 0) return Response.json({ error: "Say where the part starts (offset)" }, { status: 400 });
+ if (account && !diskHasRoom()) return Response.json({ error: ACCOUNT_MESSAGES.diskLow }, { status: 503 });
// Never more than a part, with or without a Content-Length (a chunked body has none).
const data = await readBodyWithin(request, PART_MAX);
if (data === "too-big") return Response.json({ error: "That part is too large" }, { status: 413 });
if (data === null) return Response.json({ error: "That part didn't arrive whole — export the mix again" }, { status: 400 });
try {
- const r = receiveMixPart({ id: q.get("id"), offset, data, last: q.get("last") === "1", name: q.get("name") });
- return Response.json(r, { status: "relPath" in r ? 201 : 200 });
+ const r = receiveMixPart({ id: q.get("id"), offset, data, last: q.get("last") === "1", name: q.get("name"), account: account && mixAccount(account) });
+ if (!("file" in r)) return Response.json(r);
+ return account ? await keepAsRun(account, r) : Response.json(keepMix(r), { status: 201 });
} catch (e) {
if (e instanceof MixExportError) return Response.json({ error: e.message }, { status: e.status });
console.error("[audio-tools/export]", e);
return Response.json({ error: (e as Error).message || "Couldn't save the mix" }, { status: 500 });
}
}
+
+/** The room an account's files have left for a mix: its uploads' share and its whole space. */
+function mixAccount(account: Account): MixAccount {
+ const usage = accountUsage(account.id);
+ const uploads = ACCOUNT_LIMITS.uploadsBytes - usage.uploads;
+ const total = accountTotalBytes(account.id) - usage.total;
+ return { id: account.id, room: uploads <= total ? { bytes: uploads, message: ACCOUNT_MESSAGES.uploadsFull } : { bytes: total, message: filesFullMessage(account.id) } };
+}
+
+/**
+ * An account's finished mix, kept as one of its runs: within its hourly run budget and through the studio's checks (a
+ * result the checks want to see waits for them), stored in its own files. Nothing is kept when it is refused.
+ */
+async function keepAsRun(account: Account, done: FinishedMix): Promise<Response> {
+ const bucket = `run:${account.id}`;
+ const rate = hit(bucket, ACCOUNT_LIMITS.runsPerHour, 60 * 60_000);
+ if (!rate.ok) {
+ dropMix(done.id);
+ return Response.json({ error: ACCOUNT_MESSAGES.runRate }, { status: 429, headers: { "Retry-After": String(rate.retryAfterS), "Cache-Control": "no-store" } });
+ }
+ const title = done.name.replace(/\.wav$/i, "");
+ const place = account.gpu ? ("own-gpu" as const) : account.keys?.fal || account.keys?.replicate ? ("own-key" as const) : ("pool" as const);
+ const checked = await moderateRun(account, { feature: MIX_FEATURE, modelId: MIX_MODEL, op: "mix", prompt: title, inputs: {} }, null, "own", { kind: "audio", place });
+ if (!checked.ok) {
+ unhit(bucket);
+ dropMix(done.id);
+ return Response.json({ error: checked.refusal.body.error, code: checked.refusal.body.code }, { status: 422, headers: { "Cache-Control": "no-store" } });
+ }
+ const asset = keepMix(done, account.id);
+ const output = { url: asset.url, kind: "audio" as const, contentType: "audio/wav" };
+ const g = runAsTenant({ kind: "account", id: account.id }, () => recordLocalGeneration({ feature: MIX_FEATURE, modelId: MIX_MODEL, op: "mix", prompt: title, title, inputs: {}, output }));
+ if (!checked.checkOutputs) return Response.json(g, { status: 201, headers: { "Cache-Control": "no-store" } });
+ // Held until the output check answers, as any account run's files are.
+ holdForCheck(g.id, [{ ...output, assetId: asset.id }]);
+ return Response.json(getGeneration(g.id) ?? g, { status: 201, headers: { "Cache-Control": "no-store" } });
+}
diff --git a/src/app/api/generations/local/route.ts b/src/app/api/generations/local/route.ts
index 490eb913..ae94a2d4 100644
--- a/src/app/api/generations/local/route.ts
+++ b/src/app/api/generations/local/route.ts
@@ -1,7 +1,6 @@
import fs from "node:fs";
import { z } from "zod";
import { imageSize } from "@/lib/image-size";
-import { LIBRARY_MESSAGE } from "@/lib/guest-access";
import { RECIPE_MAX_BYTES, RecipeSchema, type Recipe } from "@/lib/motion/recipe";
import { designSize, exportSize } from "@/lib/motion/sizes";
import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, diskHasRoom } from "@/server/account-files";
@@ -131,11 +130,14 @@ function shownWords(extra: Record<string, unknown> | undefined, title: string |
return [...new Set([...words, title ?? ""].map((w) => w.trim()).filter(Boolean))].join(" · ").slice(0, 2000);
}
+/** What an account's grade or Relight blend is stored as: the picture or clip the page renders. */
+const BROWSER_TYPES = /^(image\/png|video\/(mp4|webm))$/;
+
/**
* Record a result rendered in the browser (a colour grade, a Relight blend, a Kinetic Motion clip) so it shows up in the
- * library. The owner records their own files. An account (public sign-up) records Kinetic Motion clips only, each from
- * files it uploaded itself: the result is its own run (its own list, never the owner's Library), counted with its runs,
- * and through the studio's checks when they are on.
+ * library. The owner records their own files. An account (public sign-up) records them too, each from files it uploaded
+ * itself: the result is its own run (its own list, never the owner's Library), counted with its runs, and through the
+ * studio's checks when they are on.
*/
export async function POST(request: Request) {
const viewer = requestViewer(request);
@@ -179,22 +181,26 @@ export async function POST(request: Request) {
}
const account = viewer.account;
- // Accounts have their own runs, not the owner's Library: only Kinetic Motion results, recorded as their runs.
- if (body.op !== "motion") return refuse(403, LIBRARY_MESSAGE, { code: "library" });
+ // Accounts have their own runs, not the owner's Library: what they make in the browser is recorded as one of them.
if (fileAccount(rel) !== account.id) return refuse(403, NOT_FOUND);
- // Every file the clip names is the account's own: its inputs, its poster, and the recipe's logo, product and pictures.
- const problem = accountInputProblem({ inputs: body.inputs, params: { extra: { ...recipeFiles(body.params?.extra), ...(poster && { _poster: poster }) } } }, account.id);
+ // A grade or a blend is what the page renders: a PNG picture, or an MP4 or WebM clip.
+ if (body.op !== "motion" && !BROWSER_TYPES.test(contentTypeFor(rel))) return refuse(400, "Invalid result");
+ // Every file it names is the account's own: its inputs, its poster, and a clip's recipe's logo, product and pictures.
+ const named = body.op === "motion" ? recipeFiles(body.params?.extra) : {};
+ const problem = accountInputProblem({ inputs: body.inputs, params: { extra: { ...named, ...(poster && { _poster: poster }) } } }, account.id);
if (problem) return refuse(problem.status === 404 ? 403 : problem.status, problem.status === 404 || problem.code === "input-not-yours" ? NOT_FOUND : problem.error, { code: problem.code });
if (!diskHasRoom()) return refuse(503, ACCOUNT_MESSAGES.diskLow);
- // A saved clip is one of the account's runs: the same hourly budget.
+ // A saved result is one of the account's runs: the same hourly budget.
const bucket = `run:${account.id}`;
const rate = hit(bucket, ACCOUNT_LIMITS.runsPerHour, 60 * 60_000);
if (!rate.ok) return Response.json({ error: ACCOUNT_MESSAGES.runRate }, { status: 429, headers: { "Retry-After": String(rate.retryAfterS), "Cache-Control": "no-store" } });
- // The words drawn on the clip and its title (never the page's own summary of them) go through the studio's checks,
- // and are what the run keeps.
- const prompt = shownWords(body.params?.extra, body.title);
+ // The words drawn on a clip and its title (never the page's own summary of them) go through the studio's checks, and
+ // are what the run keeps; a grade or a blend keeps its description, checked with its title.
+ const motion = body.op === "motion";
+ const prompt = motion ? shownWords(body.params?.extra, body.title) : body.prompt;
+ const words = motion ? prompt : [body.prompt, body.title ?? ""].map((w) => w.trim()).filter(Boolean).join(" · ").slice(0, 2000);
const place = account.gpu ? ("own-gpu" as const) : account.keys?.fal || account.keys?.replicate ? ("own-key" as const) : ("pool" as const);
- const checked = await moderateRun(account, { feature: body.feature, modelId: body.modelId, op: body.op, prompt, inputs: body.inputs }, null, "own", { kind: "video", place });
+ const checked = await moderateRun(account, { feature: body.feature, modelId: body.modelId, op: body.op, prompt: words, inputs: body.inputs }, null, "own", { kind: motion ? "video" : body.output.kind, place });
if (!checked.ok) {
unhit(bucket);
return refuse(422, checked.refusal.body.error, { code: checked.refusal.body.code });
diff --git a/src/app/api/uploads/route.ts b/src/app/api/uploads/route.ts
index eaeee6a1..1f98f678 100644
--- a/src/app/api/uploads/route.ts
+++ b/src/app/api/uploads/route.ts
@@ -21,8 +21,9 @@ import { adoptFile, contentTypeFor, saveFile, scratchDir } from "@/server/storag
*
* - The owner: up to 200 MB, the types below.
* - An account (public sign-up): with its own ComfyUI connected or its own fal.ai or Replicate key (something to run
- * its files on), any of the types below; without either, only a Kinetic Motion result rendered in its browser (sent
- * with KINETIC_UPLOAD_HEADER: an MP4 or WebM clip, or its PNG poster), which no model makes. A picture up to 25 MB
+ * its files on), any of the types below; without either, only a result rendered in its browser (sent with
+ * KINETIC_UPLOAD_HEADER: a Kinetic Motion clip or poster, a colour grade, a Relight blend; an MP4 or WebM clip, or a
+ * PNG picture), which no model makes. A picture up to 25 MB
* and 40 megapixels, a
* sound up to 50 MB, a clip up to 95 MB; its uploads up to 1 GB and all its files up to 3 GB; 60 uploads an hour,
* 300 a day, 2 at once. The stored type is read from the file's first bytes, never taken from the client.
@@ -34,7 +35,7 @@ const UNSUPPORTED = "Fuobe can't open that file. Use a JPG, PNG, WebP, GIF, MP4,
/** Names browsers give AVI and Matroska files, to the one Fuobe stores them under. */
const VIDEO_ALIASES: Record<string, string> = { "video/avi": "video/x-msvideo", "video/msvideo": "video/x-msvideo", "video/vnd.avi": "video/x-msvideo", "video/mkv": "video/x-matroska" };
-/** A Kinetic Motion result rendered in the browser: its clip or its poster (the stored type, read from its bytes). */
+/** A result rendered in the browser: a clip or a picture (the stored type, read from its bytes). */
const KINETIC_TYPES = /^(video\/(mp4|webm)|image\/png)$/;
const KIND_CAP: Record<SniffKind, number> = { image: ACCOUNT_LIMITS.imageBytes, audio: ACCOUNT_LIMITS.audioBytes, video: ACCOUNT_LIMITS.videoBytes };
@@ -174,7 +175,8 @@ type Kinds = { image: boolean; video: boolean; audio: boolean };
/**
* What an account with no GPU or key of its own may add: the kinds its runs on this install's GPUs may use (hosted runs
- * on), and a Kinetic Motion result it rendered in its browser (no model makes one).
+ * on), and a result it rendered in its browser (a Kinetic Motion clip or poster, a colour grade, a Relight blend: no
+ * model makes one).
*/
type Without = { hosted: Kinds | null; kinetic: boolean };
diff --git a/src/components/audio-tools/split-tool.tsx b/src/components/audio-tools/split-tool.tsx
index 2fd857d9..a87fe93c 100644
--- a/src/components/audio-tools/split-tool.tsx
+++ b/src/components/audio-tools/split-tool.tsx
@@ -16,7 +16,7 @@ import { Segmented } from "@/components/faceless/controls";
import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";
import { useGeneration } from "@/components/av/use-generation";
import { SelfHostNote } from "@/components/self-host-note";
-import { useAskBeforeUpload, useEngine, useGenerations, useLikelyVisitor } from "@/lib/api";
+import { useAskBeforeUpload, useEngine, useGenerations, useIsAccount, useLikelyVisitor } from "@/lib/api";
import {
backgroundLowered,
clock,
@@ -35,6 +35,7 @@ import {
mixName,
mixPart,
mixPeak,
+ MIX_FEATURE,
mixPlan,
ORIGINAL_MIX,
partFrames,
@@ -494,8 +495,9 @@ function StemTile({
/**
* The mix as it plays (gains, solo, mute; mono stems up-mixed as WebAudio does), kept under full scale, written as a
- * 16-bit WAV and sent to the Library in parts (/api/audio-tools/export): only one part is in memory beside the stems,
- * and no upload cap applies to the whole. The peak is found first, a slice at a time, so the page stays responsive.
+ * 16-bit WAV and sent to the Library in parts (/api/audio-tools/export; an account's mix is kept as one of its runs):
+ * only one part is in memory beside the stems, and no upload cap applies to the whole. The peak is found first, a slice
+ * at a time, so the page stays responsive.
*/
async function exportWav(stems: Stem[], buffers: Partial<Record<StemId, AudioBuffer>>, mix: Mix, name: string): Promise<{ url: string; lowered: boolean }> {
const g = stemGains(mix);
@@ -520,11 +522,13 @@ async function exportWav(stems: Stem[], buffers: Partial<Record<StemId, AudioBuf
const last = f + per >= plan.frames;
const q = new URLSearchParams({ offset: String(offset), ...(id && { id }), ...(last && { last: "1", name }) });
const res = await fetch(`/api/audio-tools/export?${q}`, { method: "POST", headers: { "Content-Type": "application/octet-stream" }, body: new Blob([mixPart(plan, f, f + per, k) as BlobPart]) });
- const body = (await res.json().catch(() => ({}))) as { id?: string; received?: number; url?: string; error?: string };
+ const body = (await res.json().catch(() => ({}))) as { id?: string; received?: number; url?: string; outputs?: OutputFile[]; error?: string };
if (!res.ok) throw responseError(res, body.error ?? "The export didn't finish. Please try again.");
if (last) {
- if (!body.url) throw new Error("Export failed");
- return { url: body.url, lowered: k < 1 };
+ // The owner's mix is a Library file; an account's, the run it was kept as.
+ const url = body.url ?? body.outputs?.[0]?.url;
+ if (!url) throw new Error("Export failed");
+ return { url, lowered: k < 1 };
}
id = body.id ?? "";
offset = body.received ?? 0;
@@ -539,6 +543,7 @@ function Mixer({ stems, source, engine, initial = ORIGINAL_MIX }: { stems: Stem[
const exported = useRef<{ key: string; url: string } | null>(null);
const remux = useAudioToolRun();
const router = useRouter();
+ const account = useIsAccount();
const { apply } = player;
useEffect(() => apply(mix), [apply, mix]);
const preset = presetOf(mix);
@@ -559,7 +564,7 @@ function Mixer({ stems, source, engine, initial = ORIGINAL_MIX }: { stems: Stem[
setBusy("export");
try {
await exportMix();
- toast.success("Mix saved to your Library", { action: { label: "Open Library", onClick: () => router.push("/library") } });
+ toast.success(account ? "Mix saved to your runs" : "Mix saved to your Library", { action: { label: account ? "Open your runs" : "Open Library", onClick: () => router.push("/library") } });
} catch (e) {
toastError(e, "Couldn't export the mix");
} finally {
@@ -600,7 +605,7 @@ function Mixer({ stems, source, engine, initial = ORIGINAL_MIX }: { stems: Stem[
</h3>
<span className="rounded-full bg-success/15 px-2 py-0.5 text-[12px] font-medium text-success">Free · plays in your browser</span>
</div>
- <p className="text-[13px] text-muted-foreground">Every stem is already in your Library. Mixing here is free: nothing runs until you export.</p>
+ <p className="text-[13px] text-muted-foreground">Every stem is already in your {account ? "runs" : "Library"}. Mixing here is free: nothing runs until you export.</p>
{player.failed && (
<p className="text-[13px] text-destructive" role="alert">
{player.failed}
@@ -932,8 +937,9 @@ export function SplitSoundtrackTool() {
/** Earlier splits, and a way back into the mixer for the finished ones (their stems are kept in the Library). */
function Results({ onOpen, open }: { onOpen: (g: Generation) => void; open: string | null }) {
const splits = useGenerations({ features: [SPLIT_FEATURE], limit: 12 });
- const remuxes = useGenerations({ features: [REMUX_FEATURE], limit: 12 });
- const items = [...(remuxes.data ?? []), ...(splits.data ?? [])].sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1));
+ // Mixes put back on a video, and an account's exported mixes (kept as its runs).
+ const made = useGenerations({ features: [REMUX_FEATURE, MIX_FEATURE], limit: 12 });
+ const items = [...(made.data ?? []), ...(splits.data ?? [])].sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1));
const reopen = (splits.data ?? []).filter((g) => g.status === "succeeded" && g.id !== open && stemsOf(g.outputs).length > 0).slice(0, 4);
if (!items.length) return null;
return (
diff --git a/src/components/color-grade-view.tsx b/src/components/color-grade-view.tsx
index 0d796cc7..a4ade2e2 100644
--- a/src/components/color-grade-view.tsx
+++ b/src/components/color-grade-view.tsx
@@ -10,7 +10,7 @@ import { Button } from "@/components/ui/button";
import { PhoneNavButton } from "@/components/nav/phone-nav-button";
import { Slider } from "@/components/ui/slider";
import { kindOfFile, MAX_MB, MediaSlot, type SlotValue } from "@/components/studio/media-slot";
-import { uploadFile, useViewer } from "@/lib/api";
+import { askToSignUp, uploadFile, useIsAccount, useIsGuest, useViewer } from "@/lib/api";
import { applyPreset, CONTROLS, describeGrade, FRAGMENT, isNeutral, NEUTRAL, PRESETS, uniforms, VERTEX, type Grade } from "@/lib/grade";
import { cn } from "@/lib/utils";
import { loseContext as loseGlContext, releaseVideo } from "@/lib/media-release";
@@ -164,8 +164,11 @@ function Grader() {
/** The graded file being rendered, where it goes and (for a clip) how far along it is. */
const [saving, setSaving] = useState<null | { to: "download" | "library"; progress?: number }>(null);
const [saved, setSaved] = useState<string | null>(null);
- // Saving goes to the studio's library, which only its owner can change: everyone else downloads.
+ // The owner saves to the studio's library, an account to its own runs; a guest's Save asks it to sign up first.
const owner = useViewer().data?.owner;
+ const account = useIsAccount();
+ const guest = useIsGuest();
+ const canSave = !!owner || account || guest;
const box = useRef<HTMLDivElement>(null);
const canvas = useRef<HTMLCanvasElement>(null);
const renderer = useRef<GradeRenderer | null>(null);
@@ -296,17 +299,22 @@ function Grader() {
/** A picked file's upload, made the first time the owner saves a grade of it (the stage reads it from this browser). */
const uploadedSource = useRef<{ file: File; url: string } | null>(null);
- /** Where the graded file came from, as the library keeps it: a file on the server, never this browser's blob: address. */
- const sourceUrl = async (from: Input): Promise<string> => {
+ /**
+ * Where the graded file came from, as the library keeps it: a file on the server, never this browser's blob: address.
+ * An account's run names only its own stored files (a file picked here stays in its browser), so none otherwise.
+ */
+ const sourceUrl = async (from: Input): Promise<string | null> => {
+ if (account) return !from.file && from.url.startsWith("/api/files/") ? from.url : null;
if (!from.file) return from.url;
if (from.file.size > MAX_MB * 1024 * 1024) throw new Error(`That file's over ${MAX_MB} MB, so it can't go in your library. Download keeps the graded copy.`);
if (uploadedSource.current?.file !== from.file) uploadedSource.current = { file: from.file, url: (await uploadFile(from.file)).url };
return uploadedSource.current.url;
};
- /** Keeps the graded file in the library, made from `from` (sourceUrl). */
- const record = async (file: File, kind: "image" | "video", from: string) => {
- const asset = await uploadFile(file);
+ /** Keeps the graded file in the library (an account's: in its runs), made from `from` (sourceUrl). */
+ const record = async (file: File, kind: "image" | "video", from: string | null) => {
+ // Rendered here, so any account may keep it (no model made it).
+ const asset = await uploadFile(file, { kinetic: account });
const res = await fetch("/api/generations/local", {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -315,14 +323,14 @@ function Grader() {
modelId: "local-color-grade",
op: "grade",
prompt: describeGrade(grade, PRESETS.find((p) => p.id === preset)?.name),
- inputs: kind === "video" ? { video: from } : { images: [from] },
+ inputs: !from ? {} : kind === "video" ? { video: from } : { images: [from] },
params: { extra: { grade } },
output: { url: asset.url, kind, contentType: asset.contentType },
}),
});
if (!res.ok) throw responseError(res, ((await res.json()) as { error?: string }).error ?? "Couldn't save");
setSaved(asset.url);
- toast.success("Saved to your library");
+ toast.success(account ? "Saved to your runs" : "Saved to your library");
};
/** The graded picture as a PNG, at full size (or the largest this browser's WebGL draws). */
@@ -393,18 +401,19 @@ function Grader() {
};
/**
- * Renders the graded picture or clip in the browser, then downloads it or (the owner) saves it to the library. A save
- * keeps the picked file first, so one the library can't take says so before a clip plays through.
+ * Renders the graded picture or clip in the browser, then downloads it or saves it (the owner's library, an account's
+ * runs). A save keeps the picked file first, so one the library can't take says so before a clip plays through.
*/
const exportTo = async (to: "download" | "library") => {
if (!source || !input) return;
+ if (to === "library" && guest) return askToSignUp("upload");
setSaving({ to, progress: source instanceof HTMLVideoElement ? 0 : undefined });
try {
const from = to === "library" ? await sourceUrl(input) : null;
const file = source instanceof HTMLVideoElement ? await renderVideo(source, (progress) => setSaving({ to, progress })) : await renderImage(source);
if (!file || !alive.current) return;
if (to === "download") downloadBlob(file, file.name);
- else if (from) await record(file, file.type.startsWith("video/") ? "video" : "image", from);
+ else await record(file, file.type.startsWith("video/") ? "video" : "image", from);
} catch (e) {
if (alive.current) toastError(e);
} finally {
@@ -428,7 +437,7 @@ function Grader() {
if (!v?.ref || v.uploading) return;
open({ url: v.ref, kind: v.kind === "video" ? "video" : "image" });
};
- /** A file picked or dropped here: graded in this browser, so anyone can grade their own (uploaded only when the owner saves). */
+ /** A file picked or dropped here: graded in this browser, so anyone can grade their own (the owner's is uploaded when they save). */
const pickFile = (f: File) => open({ url: URL.createObjectURL(f), kind: kindOfFile(f) === "video" ? "video" : "image", file: f });
return (
@@ -456,10 +465,12 @@ function Grader() {
<div>
<p className="font-heading text-[24px] text-white">Grade a photo or a clip</p>
<p className="mt-1 text-[13px]">
- {/* Only the owner saves to the library; everyone else downloads the graded copy. */}
+ {/* The owner saves to the library, an account to its runs; a guest downloads the graded copy. */}
{owner
? "Drop a file, or pick one from your library. Nothing is uploaded until you save."
- : "Drop a photo or a clip, or pick one. It stays in your browser, and Download saves the graded copy."}
+ : account
+ ? "Drop a photo or a clip, or pick one. It stays in your browser until you save the graded copy."
+ : "Drop a photo or a clip, or pick one. It stays in your browser, and Download saves the graded copy."}
</p>
</div>
<div className="flex gap-2">
@@ -592,20 +603,20 @@ function Grader() {
<Button variant="ghost" size="sm" disabled={neutral} onClick={() => (setGrade(NEUTRAL), setPreset(undefined))}>
<RotateCcw /> Reset
</Button>
- <Button className={cn(!owner && "flex-1")} variant={owner ? "outline" : "default"} size="sm" disabled={!source || saving !== null} onClick={() => exportTo("download")}>
+ <Button className={cn(!canSave && "flex-1")} variant={canSave ? "outline" : "default"} size="sm" disabled={!source || saving !== null} onClick={() => exportTo("download")}>
{saving?.to === "download" ? <Loader2 className="animate-spin" /> : <Download />}
{rendering("download") || "Download"}
</Button>
- {owner && (
+ {canSave && (
<Button className="flex-1" size="sm" disabled={!source || neutral || saving !== null} onClick={() => exportTo("library")}>
{saving?.to === "library" ? <Loader2 className="animate-spin" /> : <Save />}
- {rendering("library") || "Save to library"}
+ {rendering("library") || (account ? "Save to your runs" : "Save to library")}
</Button>
)}
</div>
{saved && (
<Link href="/library" className="block text-[12px] text-brand-text underline underline-offset-2">
- Open library
+ {account ? "Open your runs" : "Open library"}
</Link>
)}
</div>
diff --git a/src/components/relight/relight-tool.tsx b/src/components/relight/relight-tool.tsx
index 993e0cda..a14f6a86 100644
--- a/src/components/relight/relight-tool.tsx
+++ b/src/components/relight/relight-tool.tsx
@@ -569,15 +569,16 @@ export function RelightTool({ app }: { app?: { name: string; description: string
setSaving(null);
}
};
- /** Keeps the blend: the owner's Library (a local result), an account's own uploads. Returns its file. */
+ /** Keeps the blend as a result made here: in the owner's Library, or as one of an account's own runs. Returns its file. */
const keep = async (): Promise<string | null> => {
if (keptNow) return keptNow;
const at = blendAt;
setSaving("keep");
try {
const file = new File([await renderFull()], `relight-${stamp()}.png`, { type: "image/png" });
- const asset = await uploadFile(file);
- if (owner) {
+ // Rendered here (no model made it), so any account may upload it.
+ const asset = await uploadFile(file, { kinetic: account });
+ if (owner || account) {
// Its input is the photo it lit (stored first when it is the sample), so Relight on it opens that photo.
const original = await ensureServerPhoto();
const res = await fetch("/api/generations/local", {
@@ -597,7 +598,7 @@ export function RelightTool({ app }: { app?: { name: string; description: string
if (!res.ok) throw responseError(res, ((await res.json().catch(() => ({}))) as { error?: string }).error ?? "Couldn't save");
}
setResults((m) => (current ? new Map(m).set(key, { ...current, kept: { url: asset.url, at } }) : m));
- toast.success(owner ? "Saved to your Library" : "Saved to your uploads");
+ toast.success(owner ? "Saved to your Library" : "Saved to your runs");
return asset.url;
} catch (e) {
toastError(e);
diff --git a/src/lib/api.ts b/src/lib/api.ts
index 5e50b68d..aec31504 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -754,8 +754,8 @@ export function useShareActions() {
// Uploads & assets
/**
- * Upload a file as it is (streamed by the server: src/lib/upload.ts). `kinetic`: a Kinetic Motion clip or poster
- * rendered in the page, which any account may save (KINETIC_UPLOAD_HEADER).
+ * Upload a file as it is (streamed by the server: src/lib/upload.ts). `kinetic`: a result rendered in the page (a
+ * Kinetic Motion clip or poster, a colour grade, a Relight blend), which any account may save (KINETIC_UPLOAD_HEADER).
*/
export async function uploadFile(file: File, opts: { kinetic?: boolean } = {}): Promise<Asset> {
return postFile(file, undefined, opts);
diff --git a/src/lib/av/split.ts b/src/lib/av/split.ts
index 102419b4..229ddbf1 100644
--- a/src/lib/av/split.ts
+++ b/src/lib/av/split.ts
@@ -14,6 +14,9 @@ import { clock, type ToolPlan } from "./audio-tools";
export const SPLIT_FEATURE = "audio-split";
export const SPLIT_MODEL = "oss-dbs-separate";
+/** An account's Export mix, kept as one of its runs (the owner's is an upload in the Library). */
+export const MIX_FEATURE = "audio-split-mix";
+export const MIX_MODEL = "local-mix";
/** Putting a mix back on its video: the open stream-copy mux, or fal's merge on the cloud. */
export const REMUX_FEATURE = "audio-split-remux";
export const REMUX_MODELS: Record<Engine, string> = {
diff --git a/src/lib/catalog/models.ts b/src/lib/catalog/models.ts
index 7b15fdcb..7cfb32aa 100644
--- a/src/lib/catalog/models.ts
+++ b/src/lib/catalog/models.ts
@@ -3287,6 +3287,19 @@ const local: ModelDef[] = [
options: {},
hidden: true,
},
+ // Split soundtrack's Export mix: the stems at the levels set in the mixer, written as a WAV in the browser.
+ {
+ id: "local-mix",
+ name: "Stem mix",
+ vendor: "Fuobe",
+ family: "local",
+ engine: "open",
+ kind: "audio",
+ tagline: "The stems at the levels you set, mixed in your browser",
+ routes: [{ op: "mix", provider: "local", endpoint: "webaudio" }],
+ options: {},
+ hidden: true,
+ },
// Ads Studio: a creative composited over its visual (headline, copy, CTA, logo in the brand fonts), saved from the browser.
{
id: "local-ad-compose",
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index 338d8a14..c849f283 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -41,6 +41,7 @@ export type Operation =
| "grade" // colour grade, rendered in the browser
| "relight" // the Relight tool's blend of a photo and its relit picture, rendered in the browser
| "motion" // motion graphics, rendered in the browser
+ | "mix" // stems → one track at the levels set in the browser (Split soundtrack's Export mix)
| "reframe" // video → same video at a new aspect ratio (AI-filled edges)
| "finalize" // draft video → full-quality render of the same take
| "dialogue" // several speakers → one audio track
@@ -143,6 +144,7 @@ export const OPERATION_LABELS: Record<Operation, string> = {
grade: "Color grade",
relight: "Relight",
motion: "Motion graphics",
+ mix: "Mix",
reframe: "Reframe",
finalize: "Final render",
dialogue: "Dialogue",
@@ -235,6 +237,7 @@ export const OPERATION_OUTPUT: Record<Operation, MediaKind> = {
grade: "image",
relight: "image",
motion: "video",
+ mix: "audio",
reframe: "video",
finalize: "video",
dialogue: "audio",
diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.ts
index af850000..2c327eb9 100644
--- a/src/lib/guest-access.ts
+++ b/src/lib/guest-access.ts
@@ -119,8 +119,6 @@ export function isPriceCheck(method: string, pathname: string, search: string):
* the MCP endpoint…) is refused with "Connect your GPU": it never spends the owner's keys or GPU.
*/
const LIBRARY_CHANGES: [methods: string, path: RegExp][] = [
- // Split soundtrack's Export mix: a WAV saved, in parts, as an asset of the owner's Library (no account's upload).
- ["POST", /^\/api\/audio-tools\/export$/],
["POST", /^\/api\/folders$/],
["PATCH DELETE", /^\/api\/folders\/[^/]+$/],
["PATCH DELETE", /^\/api\/generations\/[^/]+$/],
@@ -199,7 +197,8 @@ const GPU_READS = new Set(["/api/gpu/readiness", "/api/gpu/badges", "/api/gpu/pl
* A change an account may send: signing out, its own GPU and its check, its own fal.ai and Replicate keys, price checks
* (reads go by guestRead, as a guest's), an upload (the route checks it: src/app/api/uploads, which the proxy's matcher
* leaves out), a look at its own clip's header (the route reads only its own files), and a result it made in its
- * browser (POST /api/generations/local: the route takes its own Kinetic Motion clips only).
+ * browser (POST /api/generations/local: a Kinetic Motion clip, a colour grade or a Relight blend of its own files;
+ * POST /api/audio-tools/export: Split soundtrack's Export mix), kept as its own run.
*/
export function accountMayChange(method: string, pathname: string, search: string): boolean {
if (method === "POST" && pathname === "/api/auth/logout") return true;
@@ -217,10 +216,13 @@ export function accountMayChange(method: string, pathname: string, search: strin
if (method === "POST" && (pathname === "/api/reports" || pathname === "/api/billing/interest")) return true;
// Like, pin or review many of its own runs at once (the route checks each is its own, and refuses the rest).
if (method === "POST" && pathname === "/api/generations/bulk") return true;
- // A Kinetic Motion clip it rendered in its browser and uploaded, recorded as its own run (the route checks the files
- // are its own, its run rate and the studio's checks; a grade or a Relight blend stays the owner's there). No model
- // runs, so it needs no GPU or key of its own.
+ // A result it made in its browser and uploaded (a Kinetic Motion clip, a colour grade, a Relight blend), recorded as
+ // its own run (the route checks the files are its own, its run rate and the studio's checks). No model runs, so it
+ // needs no GPU or key of its own.
if (method === "POST" && pathname === "/api/generations/local") return true;
+ // Split soundtrack's Export mix, sent in parts and kept as its own run (the route checks its room, its run rate and
+ // the studio's checks; the proxy's matcher leaves this route out, which runs the proxy itself).
+ if (method === "POST" && pathname === "/api/audio-tools/export") return true;
return isPriceCheck(method, pathname, search);
}
@@ -292,9 +294,10 @@ export const CONNECT_GPU_UPLOAD_MESSAGE = "Connect your GPU, or add a fal.ai or
/** The same, on a studio with paid models off (no keys). */
export const CONNECT_GPU_UPLOAD_OPEN_MESSAGE = "Connect your GPU to add your own files.";
/**
- * Sent with the upload of a Kinetic Motion clip (or its poster) rendered in the browser, set to "1". Saving one needs no
- * model, so an account with neither its own GPU nor its own key may upload it too: an MP4 or WebM clip, or a PNG
- * poster, within the account's space and upload limits (src/app/api/uploads).
+ * Sent with the upload of a result rendered in the browser (a Kinetic Motion clip or its poster, a colour grade, a
+ * Relight blend), set to "1". Saving one needs no model, so an account with neither its own GPU nor its own key may
+ * upload it too: an MP4 or WebM clip, or a PNG picture, within the account's space and upload limits
+ * (src/app/api/uploads).
*/
export const KINETIC_UPLOAD_HEADER = "x-fuobe-kinetic";
/** An account with neither its own GPU nor its own key (the proxy's answer to a run): the card it opens offers both. */
diff --git a/src/server/mix-export.ts b/src/server/mix-export.ts
index f8d5b91b..e29e34f8 100644
--- a/src/server/mix-export.ts
+++ b/src/server/mix-export.ts
@@ -10,8 +10,12 @@ import { adoptFile, scratchDir, type Asset } from "./storage";
* 16-bit WAV and sends it here in parts of MIX_PART_BYTES, which skip the sign-in proxy (it holds at most 4 MB of a
* body; the route runs its checks and reads no more than PART_MAX) and the server appends to a scratch file without
* holding the mix in memory. The first part starts with the WAV header, which says how big the file will be (at most
- * MIX_MAX_BYTES); the last one turns the file into an upload in the Library. A 5.1 film clip's mix outgrows the 200 MB
- * upload cap after about six minutes; this doesn't.
+ * MIX_MAX_BYTES); the last one turns the file into an upload in the Library (keepMix). A 5.1 film clip's mix outgrows the
+ * 200 MB upload cap after about six minutes; this doesn't.
+ *
+ * An account (public sign-up) exports into its own files, never the owner's: its export is its own (a part with its id
+ * from anyone else is refused), one at a time (starting another drops the unfinished one), and no bigger than the room
+ * its files have left. The route records the finished mix as one of its runs.
*/
export class MixExportError extends Error {
@@ -26,7 +30,7 @@ export class MixExportError extends Error {
/** A part may be a little over MIX_PART_BYTES (the first one carries the header). */
export const PART_MAX = MIX_PART_BYTES + 1024 * 1024;
const ID = /^[A-Za-z0-9_-]{16}$/;
-const PART_FILE = /^mix-[A-Za-z0-9_-]{16}\.wav\.part$/;
+const PART_FILE = /^mix-([A-Za-z0-9_-]{16})\.wav\.part$/;
/** Exports nobody finished are removed when the next one starts. */
const STALE_MS = 6 * 60 * 60 * 1000;
@@ -54,22 +58,47 @@ function headOf(file: string): Buffer {
function sweep() {
const dir = scratchDir();
for (const f of fs.readdirSync(dir)) {
- if (!PART_FILE.test(f)) continue;
+ const id = PART_FILE.exec(f)?.[1];
+ if (!id) continue;
const abs = path.join(dir, f);
try {
- if (Date.now() - fs.statSync(abs).mtimeMs > STALE_MS) fs.rmSync(abs, { force: true });
+ if (Date.now() - fs.statSync(abs).mtimeMs > STALE_MS) dropMix(id);
} catch {}
}
}
const mb = (bytes: number) => `${Math.round(bytes / 1024 ** 2)} MB`;
+declare global {
+ /** Who started each export here: an account's id, or null for the owner. */
+ var __fuobeMixBy: Map<string, string | null> | undefined;
+ /** An account's unfinished export, by account. */
+ var __fuobeMixOpen: Map<string, string> | undefined;
+}
+const startedBy = (): Map<string, string | null> => (globalThis.__fuobeMixBy ??= new Map());
+const openFor = (): Map<string, string> => (globalThis.__fuobeMixOpen ??= new Map());
+
+/** Who an export is for: an account, with the room its files have left (the owner's has none to check). */
+export interface MixAccount {
+ id: string;
+ room: { bytes: number; message: string };
+}
+
+/** A finished export, still in the scratch folder: keepMix stores it, dropMix throws it away. */
+export interface FinishedMix {
+ id: string;
+ received: number;
+ file: string;
+ name: string;
+}
+
/**
* One part of an export: the first (no `id`, offset 0) starts it; the others carry its `id` and the offset they start
- * at (the bytes received so far). Gives the export's id and the bytes received, or, for the `last` part, the Library
- * asset of the finished WAV.
+ * at (the bytes received so far). Gives the export's id and the bytes received, and, for the `last` part, the finished
+ * WAV (FinishedMix). `account`: the account sending it (none: the owner).
*/
-export function receiveMixPart(o: { id?: string | null; offset: number; data: Buffer; last: boolean; name?: string | null }): { id: string; received: number } | Asset {
+export function receiveMixPart(o: { id?: string | null; offset: number; data: Buffer; last: boolean; name?: string | null; account?: MixAccount | null }): { id: string; received: number } | FinishedMix {
+ const by = o.account?.id ?? null;
if (o.data.length > PART_MAX) throw new MixExportError(`A part can be at most ${mb(PART_MAX)}`, 413);
let id = o.id ?? "";
let file: string;
@@ -79,13 +108,23 @@ export function receiveMixPart(o: { id?: string | null; offset: number; data: Bu
const declared = declaredWavBytes(o.data);
if (declared === null) throw new MixExportError("An export is a 16-bit PCM WAV file", 415);
if (declared > MIX_MAX_BYTES) throw new MixExportError(`That mix is over the ${mb(MIX_MAX_BYTES)} an export can be`, 413);
+ if (o.account && declared > o.account.room.bytes) throw new MixExportError(o.account.room.message, 413);
total = declared;
sweep();
id = nanoid(16);
file = partPath(id);
+ if (by) {
+ // One unfinished export per account: a new one drops the last.
+ const before = openFor().get(by);
+ if (before) dropMix(before);
+ openFor().set(by, id);
+ }
fs.writeFileSync(file, o.data, { flag: "wx" });
+ startedBy().set(id, by);
} else {
if (!ID.test(id)) throw new MixExportError("That export doesn't exist", 404);
+ // Only the one who started it sends its parts (an export from before a restart is the owner's).
+ if ((startedBy().get(id) ?? null) !== by) throw new MixExportError("That export doesn't exist", 404);
file = partPath(id);
let size: number;
try {
@@ -100,11 +139,30 @@ export function receiveMixPart(o: { id?: string | null; offset: number; data: Bu
}
const received = fs.statSync(/*turbopackIgnore: true*/ file).size;
if (received > total) {
- fs.rmSync(file, { force: true });
+ dropMix(id);
throw new MixExportError("That's more audio than the WAV header says", 413);
}
if (!o.last) return { id, received };
if (received !== total) throw new MixExportError(`The export stopped short (${received} of ${total} bytes) — export the mix again`, 409);
const name = (o.name?.trim() || "Mix").slice(0, 196);
- return adoptFile({ from: file, contentType: "audio/wav", name: /\.wav$/i.test(name) ? name : `${name}.wav`, source: "upload" });
+ return { id, received, file, name: /\.wav$/i.test(name) ? name : `${name}.wav` };
+}
+
+/** Stores a finished export: an upload in the owner's Library, or in the account's own files. */
+export function keepMix(done: FinishedMix, accountId?: string): Asset {
+ const asset = adoptFile({ from: done.file, contentType: "audio/wav", name: done.name, source: "upload", ...(accountId && { accountId }) });
+ forget(done.id);
+ return asset;
+}
+
+/** Throws an export away (unfinished, or refused once finished). */
+export function dropMix(id: string): void {
+ if (ID.test(id)) fs.rmSync(partPath(id), { force: true });
+ forget(id);
+}
+
+function forget(id: string): void {
+ const by = startedBy().get(id);
+ startedBy().delete(id);
+ if (by && openFor().get(by) === id) openFor().delete(by);
}
diff --git a/tests/generations-local-motion.test.ts b/tests/generations-local-motion.test.ts
index d1f9e857..ac3e7158 100644
--- a/tests/generations-local-motion.test.ts
+++ b/tests/generations-local-motion.test.ts
@@ -1,11 +1,13 @@
+import fs from "node:fs";
import http from "node:http";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { NextRequest } from "next/server";
import { tempDir } from "./helpers/temp-dir";
-// Kinetic Motion results through Fuobe (POST /api/generations/local): the owner records its own clip; an account
-// records only its own clip, made from its own files, as its own run (its list, never the owner's Library), within its
-// run rate and through the studio's checks; a guest is told to sign up; the proxy lets an account through to the route.
+// Results made in the browser through Fuobe (POST /api/generations/local): the owner records its own clip; an account
+// records its own clip, colour grade or Relight blend, made from its own files, as its own run (its list, never the
+// owner's Library), within its run rate and through the studio's checks; a guest is told to sign up; the proxy lets an
+// account through to the route. Split soundtrack's Export mix (POST /api/audio-tools/export) is an account's run too.
vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
vi.setConfig({ testTimeout: 30_000 });
@@ -18,8 +20,10 @@ const auth = await import("@/server/auth");
const { proxy } = await import("@/proxy");
const access = await import("@/lib/guest-access");
const { POST } = await import("@/app/api/generations/local/route");
-const { saveFile } = await import("@/server/storage");
-const { generationAccount, fileRecord } = await import("@/server/account-library");
+const exportRoute = await import("@/app/api/audio-tools/export/route");
+const { filesRel, saveFile, scratchDir } = await import("@/server/storage");
+const { generationAccount, fileAccount, fileRecord } = await import("@/server/account-library");
+const { mixPart, mixPlan } = await import("@/lib/av/split");
const { listGenerations, getGeneration } = await import("@/server/generations");
const { hit } = await import("@/server/rate");
const { RECIPE_MAX_BYTES } = await import("@/lib/motion/recipe");
@@ -172,12 +176,56 @@ describe("an account", () => {
expect((await call(body(accountFile(a.id, "image/png", "p.png")), a.cookie)).status).toBe(400);
});
- it("records Kinetic Motion only: a grade stays the owner's library", async () => {
+ it("records its own colour grade and Relight blend as its runs, from its own files only", async () => {
process.env.FUOBE_PUBLIC_SIGNUP = "1";
const a = newAccount();
- const r = await call({ feature: "grade", modelId: "local-color-grade", op: "grade", prompt: "x", inputs: {}, output: { url: accountFile(a.id, "image/png", "g.png"), kind: "image" } }, a.cookie);
- expect(r.status).toBe(403);
- expect((await r.json()).code).toBe("library");
+ const b = newAccount();
+ const png = (id: string, name = "g.png") => accountFile(id, "image/png", name);
+ const grade = (output: string, over: Record<string, unknown> = {}) => ({
+ feature: "grade",
+ modelId: "local-color-grade",
+ op: "grade",
+ prompt: "Warm film · contrast +10",
+ inputs: {},
+ params: { extra: { grade: { contrast: 0.1 } } },
+ output: { url: output, kind: "image", contentType: "image/png" },
+ ...over,
+ });
+ const r = await call(grade(png(a.id)), a.cookie);
+ expect(r.status).toBe(201);
+ const g = await r.json();
+ expect(g).toMatchObject({ modelId: "local-color-grade", op: "grade", kind: "image", status: "succeeded" });
+ expect(generationAccount(g.id)).toBe(a.id);
+ expect(listGenerations({ account: a.id }).map((x) => x.id)).toContain(g.id);
+ expect(listGenerations().map((x) => x.id)).not.toContain(g.id);
+ // Made from its own picture: fine. From another account's or the owner's, or another account's output: refused.
+ expect((await call(grade(png(a.id), { inputs: { images: [png(a.id, "s.png")] } }), a.cookie)).status).toBe(201);
+ expect((await call(grade(png(a.id), { inputs: { images: [png(b.id, "s.png")] } }), a.cookie)).status).toBe(403);
+ expect((await call(grade(png(a.id), { inputs: { images: [ownerFile("image/png", "s.png")] } }), a.cookie)).status).toBe(403);
+ expect((await call(grade(png(b.id)), a.cookie)).status).toBe(403);
+ // Only what the page renders: a PNG picture, or an MP4 or WebM clip.
+ const jpeg = accountFile(a.id, "image/jpeg", "g.jpg");
+ expect((await call(grade(jpeg, { output: { url: jpeg, kind: "image", contentType: "image/jpeg" } }), a.cookie)).status).toBe(400);
+ const clip = accountFile(a.id, "video/webm", "g.webm");
+ expect((await call(grade(clip, { inputs: { video: accountFile(a.id) }, output: { url: clip, kind: "video", contentType: "video/webm" } }), a.cookie)).status).toBe(201);
+ // A Relight blend of its own photo.
+ const blend = await call(
+ {
+ feature: "relight",
+ modelId: "local-relight",
+ op: "relight",
+ prompt: "Warm key light from the left",
+ title: "Golden hour",
+ inputs: { images: [png(a.id, "photo.png")] },
+ params: { extra: { relight: { intensity: 0.8 } } },
+ output: { url: png(a.id, "b.png"), kind: "image", contentType: "image/png" },
+ },
+ a.cookie,
+ );
+ expect(blend.status).toBe(201);
+ expect(generationAccount((await blend.json()).id)).toBe(a.id);
+ // A grade is never recorded as a Relight blend.
+ expect((await call(grade(png(a.id), { modelId: "local-relight" }), a.cookie)).status).toBe(422);
});
it("is held to its run rate", async () => {
@@ -222,6 +270,76 @@ describe("an account", () => {
const g = await r.json();
expect(getGeneration(g.id)!.prompt).toBe(asked.prompt);
});
+
+ it("checks a grade's description with its title, as a picture, and keeps its description", async () => {
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ const addr = moderation!.address() as { port: number };
+ process.env.FUOBE_MODERATION_URL = `http://127.0.0.1:${addr.port}`;
+ const a = newAccount();
+ answer = { allowed: true };
+ const out = accountFile(a.id, "image/png", "g.png");
+ const grade = (prompt: string, title?: string, url = out) => ({ feature: "grade", modelId: "local-color-grade", op: "grade", prompt, ...(title && { title }), inputs: {}, output: { url, kind: "image", contentType: "image/png" } });
+ const r = await call(grade("Teal and orange", "Night grade"), a.cookie);
+ expect(r.status).toBe(201);
+ expect(asked.prompt).toBe("Teal and orange · Night grade");
+ expect(asked.run).toMatchObject({ kind: "image", place: "pool" });
+ expect(getGeneration((await r.json()).id)!.prompt).toBe("Teal and orange");
+ answer = { allowed: false, code: "blocked", text: "This can't be made here." };
+ expect((await call(grade("x", undefined, accountFile(a.id, "image/png", "h.png")), a.cookie)).status).toBe(422);
+ });
+});
+
+describe("an account's Export mix (Split soundtrack)", () => {
+ const send = (q: string, part: Uint8Array, cookie?: string) =>
+ exportRoute.POST(
+ new Request(`http://localhost:3000/api/audio-tools/export?${q}`, {
+ method: "POST",
+ headers: { host: "localhost:3000", "content-type": "application/octet-stream", ...(cookie && { cookie: `${auth.SESSION_COOKIE}=${cookie}` }) },
+ body: Buffer.from(part),
+ }),
+ );
+ const plan = mixPlan([{ channels: [Float32Array.from({ length: 1000 }, (_, i) => Math.sin(i / 10) / 2)], gain: 1 }], 8000);
+ const parts = () => fs.readdirSync(scratchDir()).filter((f) => f.startsWith("mix-"));
+
+ it("keeps the mix as the account's own run, in its own files, and nobody else sends its parts", async () => {
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ const a = newAccount();
+ const b = newAccount();
+ const first = await send("offset=0", mixPart(plan, 0, 500), a.cookie);
+ expect(first.status).toBe(200);
+ const { id, received } = await first.json();
+ for (const cookie of [b.cookie, owner()]) expect((await send(`offset=${received}&id=${id}`, mixPart(plan, 500, 1000), cookie)).status).toBe(404);
+ const done = await send(`offset=${received}&id=${id}&last=1&name=${encodeURIComponent("Film · No dialogue.wav")}`, mixPart(plan, 500, 1000), a.cookie);
+ expect(done.status).toBe(201);
+ const g = await done.json();
+ expect(g).toMatchObject({ feature: "audio-split-mix", modelId: "local-mix", op: "mix", kind: "audio", status: "succeeded", prompt: "Film · No dialogue" });
+ expect(generationAccount(g.id)).toBe(a.id);
+ expect(listGenerations({ account: a.id }).map((x) => x.id)).toContain(g.id);
+ expect(listGenerations().map((x) => x.id)).not.toContain(g.id);
+ expect(fileAccount(filesRel(g.outputs[0].url)!)).toBe(a.id);
+ expect(parts()).toEqual([]);
+ });
+
+ it("holds it to the room its files have left, one export at a time, and its run rate", async () => {
+ process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ const a = newAccount();
+ // A header that says more than its uploads have room for.
+ const big = mixPart(plan, 0, 10);
+ new DataView(big.buffer).setUint32(4, 1.5 * 1024 ** 3, true);
+ const over = await send("offset=0", big, a.cookie);
+ expect(over.status).toBe(413);
+ expect((await over.json()).error).toMatch(/1 GB/);
+ // A new export drops the unfinished one.
+ const one = await (await send("offset=0", mixPart(plan, 0, 500), a.cookie)).json();
+ const two = await (await send("offset=0", mixPart(plan, 0, 500), a.cookie)).json();
+ expect((await send(`offset=${one.received}&id=${one.id}`, mixPart(plan, 500, 600), a.cookie)).status).toBe(404);
+ // Past its run rate the finished mix isn't kept.
+ for (let i = 0; i < 60; i++) hit(`run:${a.id}`, 60, 60 * 60_000);
+ const late = await send(`offset=${two.received}&id=${two.id}&last=1&name=Mix`, mixPart(plan, 500, 1000), a.cookie);
+ expect(late.status).toBe(429);
+ expect(listGenerations({ account: a.id })).toEqual([]);
+ expect(parts()).toEqual([]);
+ });
});
describe("guests and the proxy", () => {
diff --git a/tests/public-signup-tools.test.ts b/tests/public-signup-tools.test.ts
index ae4337ee..ff5e2699 100644
--- a/tests/public-signup-tools.test.ts
+++ b/tests/public-signup-tools.test.ts
@@ -125,7 +125,7 @@ describe("the proxy: PR #15's routes as main treats their kind", () => {
}
});
- it("gives an account the price checks, own-gpu-tool for the runs (a GPU wouldn't run them), and library for the Export mix", async () => {
+ it("gives an account the price checks, own-gpu-tool for the runs (a GPU wouldn't run them), and its own Export mix", async () => {
process.env.FUOBE_PUBLIC_SIGNUP = "1";
const cookie = auth.createSession(newAccount().id).value;
for (const p of ["/api/turnaround/estimate", "/api/turnaround?preview=1", "/api/audio-tools?preview=1"]) expect(passed(proxy(req(p, { method: "POST", cookie }))), p).toBe(true);
@@ -135,11 +135,8 @@ describe("the proxy: PR #15's routes as main treats their kind", () => {
expect(r.headers.get(access.CONNECT_GPU_HEADER), p).toBeNull();
expect((await r.json()).code, p).toBe("own-gpu-tool");
}
- // The mix is saved to the owner's Library: a library change, whatever the GPU.
- const save = proxy(req("/api/audio-tools/export?offset=0", { method: "POST", cookie }));
- expect(save.status).toBe(403);
- expect(save.headers.get(access.CONNECT_GPU_HEADER)).toBeNull();
- expect((await save.json()).code).toBe("library");
+ // The mix is kept as the account's own run (the route checks its room, run rate and the studio's checks), whatever the GPU.
+ expect(passed(proxy(req("/api/audio-tools/export?offset=0", { method: "POST", cookie })))).toBe(true);
});
it("runs an account's MOSS-Image on its own GPU (the studios' generations); the tools say own-gpu-tool", async () => {
@@ -154,7 +151,7 @@ describe("the proxy: PR #15's routes as main treats their kind", () => {
expect(r.headers.get(access.CONNECT_GPU_HEADER), p).toBeNull();
expect((await r.json()).code, p).toBe("own-gpu-tool");
}
- expect((await proxy(req("/api/audio-tools/export?offset=0", { method: "POST", cookie })).json()).code).toBe("library");
+ expect(passed(proxy(req("/api/audio-tools/export?offset=0", { method: "POST", cookie })))).toBe(true);
});
it("keeps the owner's runs and saves unchanged", () => {
diff --git a/tests/request-body-limits.test.ts b/tests/request-body-limits.test.ts
index 8b276e7d..6c31a519 100644
--- a/tests/request-body-limits.test.ts
+++ b/tests/request-body-limits.test.ts
@@ -75,8 +75,9 @@ describe("M-3: the proxy holds at most a few MB of any request body", () => {
expect((await r.call(form(r.path))).status, `${r.name}: guest`).toBe(["finish", "mix export"].includes(r.name) ? 401 : 403);
expect((await r.call(form(r.path, { cookie: owner, headers: { origin: "http://evil.example" } }))).status, `${r.name}: cross-site`).toBe(403);
}
- // An account: only its own run's finish passes the proxy's rules, and "g1" isn't its own.
- for (const r of BIG) expect((await r.call(form(r.path, { cookie: account }))).status, `${r.name}: account`).toBe(403);
+ // An account: its own Export mix passes the proxy's rules (the route then reads the WAV: a form isn't one), and its own
+ // run's finish does too, but "g1" isn't its own.
+ for (const r of BIG) expect((await r.call(form(r.path, { cookie: account }))).status, `${r.name}: account`).toBe(r.name === "mix export" ? 415 : 403);
});
it("each lets the owner through to the route's own checks", async () => {
diff --git a/tests/shell-logic.test.ts b/tests/shell-logic.test.ts
index 767dc4eb..4ec9889f 100644
--- a/tests/shell-logic.test.ts
+++ b/tests/shell-logic.test.ts
@@ -707,11 +707,15 @@ describe("color grading for everyone", () => {
expect(fs.statSync(file).size).toBeLessThan(300 * 1024);
});
- it("downloads the graded result straight from the browser, and only the owner saves it to the library", () => {
- // Download needs no upload (guests and accounts can't change the owner's library); Save stays the owner's.
+ it("downloads the graded result straight from the browser; the owner saves it to the library, an account to its runs", () => {
+ // Download needs no upload. Save is the owner's library or an account's own runs; a guest's Save asks it to sign up.
expect(view).toMatch(/onClick=\{\(\) => exportTo\("download"\)\}/);
expect(view).toMatch(/if \(to === "download"\) downloadBlob\(file, file\.name\);/);
- expect(view).toMatch(/\{owner && \(\s*<Button[^>]*onClick=\{\(\) => exportTo\("library"\)\}/);
+ expect(view).toMatch(/const canSave = !!owner \|\| account \|\| guest;/);
+ expect(view).toMatch(/\{canSave && \(\s*<Button[^>]*onClick=\{\(\) => exportTo\("library"\)\}/);
+ expect(view).toMatch(/if \(to === "library" && guest\) return askToSignUp\("upload"\);/);
+ // An account's graded file is uploaded as a result made in the browser (no GPU or key needed).
+ expect(view).toMatch(/uploadFile\(file, \{ kinetic: account \}\)/);
});
});