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.

Video tools, Turnaround, Fly around and Katana: accounts run them on their own GPU or key

Adarsha116e225b1c2
diff --git a/docs/public-signup.md b/docs/public-signup.md
index c4c0036c..86429275 100644
--- a/docs/public-signup.md
+++ b/docs/public-signup.md
@@ -276,15 +276,12 @@ cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188
the studio's local LLM is refused; "Enhance prompt" uses Fuobe's offline wording. Other tools
(Canvas, Assist, Marketing…) answer 403 with `code: "own-gpu-tool"`, because they
plan with the studio's own AI helpers or keep projects of their own. So do the Audio hub's Split
- soundtrack and Edit speech and Video tools → Remove dialogue (all `POST /api/audio-tools`) and the
- turnaround video (`POST /api/turnaround`), though their price checks work, priced for the account's
- own GPU. Split soundtrack's, Edit speech's and Remove dialogue's pages say so up front ("Split
+ soundtrack and Edit speech and Video tools → Remove dialogue (all `POST /api/audio-tools`), though their price
+ checks work, priced for the account's own GPU. Split soundtrack's, Edit speech's and Remove dialogue's pages say so up front ("Split
soundtrack isn't available here", "Edit speech isn't available here", "Remove dialogue isn't
available here"), with their upload and run off. Result menus don't offer Remove dialogue, Clean up
dialogue or Edit speech to a guest or an account, and Captions doesn't offer them "Fix this line"
- (it opens Edit speech). Restore & colourise
- and Remove a person (its mask preview and "Redo from here", `POST /api/remove-object/preview` and
- `/reroll`, answer `own-gpu-tool` too) are left out of the Video tools tabs and the result menus for them.
+ (it opens Edit speech). Restore & colourise is left out of the Video tools tabs and the result menus for them.
A hosted model whose calls haven't yet passed a live run with a real key (`src/lib/catalog/hosted-untested.ts`:
MiniMax H3 Max's lip sync, relight, insert, looks and Turbo, H3 Lite and HighSpeed, Vidu Q4, the Mureka songs and
song tools, MiniMax Music 3, ElevenLabs Music, Lyria 3.5, the hosted voice cleaners, Meshy retexture, Tripo P2,
@@ -329,8 +326,8 @@ cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188
finished on this server (the web GLB the viewer loads) under its limits (`src/server/model3d-finish.ts`): one account's
finish at a time across the server, at low priority; a model over 300 MB, a server or account short of room, or more
than 60 finishes in an hour keep the model as it came (still viewable and downloadable). Its turntable is recorded in
- the browser ("Record turntable"), not on the server. Refine detail, the TRELLIS.2 final, Idol 3D's other sides and
- Film it photoreal stay the owner's, and Retexture opens once its cloud models pass a live call. On this install's
+ the browser ("Record turntable"), not on the server. Film it photoreal runs as a Fly around (below). Refine detail, the TRELLIS.2 final and Idol 3D's other sides stay
+ the owner's, and Retexture opens once its cloud models pass a live call. On this install's
GPUs (hosted runs) 3D isn't offered yet. A guest gets the sign-up card.
- **Character Swap Studio.** An account keeps Character Swap projects of its own (`/character-swap`; `GET`/`POST
/api/swap-studio/projects`, `GET`/`PATCH`/`DELETE /api/swap-studio/projects/<id>`): its own only (another account's,
@@ -371,6 +368,21 @@ cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188
sheets), and a retried photo replaces the failed one for good (it has no Trash). The price is its run's: free on its
GPU, its own key's price on the cloud engine. A guest gets the sign-up card on Generate, on Create pack, on New
character and before choosing a photo.
+- **Video tools, Turnaround video, Fly around and Katana.** An account runs Remove object and Remove a person
+ (`POST /api/remove-object`, its mask preview `.../preview` and "Redo from here" `.../reroll`), Evolution
+ (`POST /api/evolution`), Mixed Media (`POST /api/mixed-media`, a preview frame `.../preview` and "Try again"
+ `.../retry`), Turnaround video (`POST /api/turnaround`), Fly around (`POST /api/fly-around`: Image to 3D's "Film it
+ photoreal" and the exact orbits) and Katana (`POST /api/katana`, `.../<id>/retry`) the same way as Genjutsu's: every
+ step on the account's ComfyUI or its own fal.ai or Replicate key, with only its own files, after the same checks, and
+ a run counts once against its limits. Their price checks are priced for the account's own GPU or key. Their results
+ are its own runs (each tool's history, "Your …" feeds and its runs list), to open and download. "Redo from here" and
+ "Try again" take only its own removal or render, and a Mixed Media render's frame count (`GET
+ /api/mixed-media/progress`) answers for its own renders only (anyone else's reads as 404). Evolution's direction
+ (`POST /api/evolution/direction`, and a run sent without one) is written by Fuobe's offline writer, never the studio's
+ AI helper. Turnaround and Fly around never use the studio's WorldCast worker for an account; a character from the
+ owner's library answers 404. Katana's runs are its own projects (`GET /api/katana`, `GET`/`DELETE
+ /api/katana/<id>`): up to 50, another account's or the owner's read as 404, deleted with the account. A guest gets
+ the sign-up card.
- **Files a run takes.** A run on your GPU takes only files you uploaded here, or your own results.
A link or a `data:` URI answers 400 with `code: "input-not-allowed"`, someone else's file 403
(`input-not-yours`), and a file that has expired 404 (`input-gone`, "That file has expired.
diff --git a/src/app/api/evolution/direction/route.ts b/src/app/api/evolution/direction/route.ts
index 585c1592..48cbbda0 100644
--- a/src/app/api/evolution/direction/route.ts
+++ b/src/app/api/evolution/direction/route.ts
@@ -1,10 +1,18 @@
+import { guestRun, toolViewer } from "@/server/account-tool-run";
import { DirectionSchema, writeDirection } from "@/server/evolution";
+import { asAccount } from "@/server/generations";
import { body, handle } from "@/server/shorts-schemas";
-/** Write the creative direction from the references and your words: Claude, Ollama, or Fuobe's offline writer. Never generates. */
+/**
+ * Write the creative direction from the references and your words: Claude, Ollama, or Fuobe's offline writer. Never
+ * generates. A signed-in account's is always the offline writer's (never this studio's AI helper); a guest signs up first.
+ */
export async function POST(request: Request) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
return handle(async () => {
const input = await body(request, DirectionSchema, "Pick how much should change, then add references or a few words");
- return Response.json(await writeDirection(input));
+ const write = () => writeDirection(input);
+ return Response.json(await (viewer.kind === "account" ? asAccount(viewer.account.id, write) : write()));
}, request);
}
diff --git a/src/app/api/evolution/estimate/route.ts b/src/app/api/evolution/estimate/route.ts
index 99391f00..05c8adab 100644
--- a/src/app/api/evolution/estimate/route.ts
+++ b/src/app/api/evolution/estimate/route.ts
@@ -1,6 +1,6 @@
+import { priceAsRun } from "@/server/account-tool-run";
import { estimateEvolution, EvolutionEstimateSchema } from "@/server/evolution";
import { body, handle } from "@/server/shorts-schemas";
-import { priceAs } from "@/server/visitor";
/** The price, the pieces and the notes for the current settings, before anything runs ("Free" on your GPU). */
async function post(request: Request) {
@@ -10,7 +10,7 @@ async function post(request: Request) {
});
}
-/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+/** Priced as the asker's run would go: an account's on its own GPU or key, a guest's on the open engine, never a demo. */
export async function POST(request: Request) {
- return priceAs(request, () => post(request));
+ return priceAsRun(request, () => post(request));
}
diff --git a/src/app/api/evolution/route.ts b/src/app/api/evolution/route.ts
index 5514ffb7..9501bd78 100644
--- a/src/app/api/evolution/route.ts
+++ b/src/app/api/evolution/route.ts
@@ -1,12 +1,40 @@
-import { createEvolution, EvolutionBodySchema } from "@/server/evolution";
+import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { createEvolution, EvolutionBodySchema, evolutionSteps, planEvolutionRun, startEvolution, type EvolutionRun } from "@/server/evolution";
import { body, handle, once } from "@/server/shorts-schemas";
-/** Evolve a clip (Fuobe Evolution): the direction is written first when none is given; pieces are joined and the sound put back. */
+/**
+ * Evolve a clip (Fuobe Evolution): the direction is written first when none is given; pieces are joined and the sound put
+ * back. The owner's run as always; an account's on its own GPU or its own fal.ai or Replicate key, with its own files and
+ * Fuobe's offline writer for the direction, after the checks every tool run gets (src/server/account-tool-run.ts); a
+ * guest signs up first.
+ */
export async function POST(request: Request) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
+ if (viewer.kind === "account") {
+ const big = bodyTooBig(request);
+ if (big) return big;
+ }
return handle(async () => {
const input = await body(request, EvolutionBodySchema, "Add a clip and pick how much should change");
// A repeated requestId (a second click on Evolve) gets the run the first one started.
- const result = await once("evolution", input.requestId, () => createEvolution(input));
- return Response.json(result, { status: 201 });
+ if (viewer.kind === "owner") {
+ const result = await once("evolution", input.requestId, () => createEvolution(input));
+ return Response.json(result, { status: 201 });
+ }
+ let run: EvolutionRun | null = null;
+ return onceForAccount(
+ viewer.account,
+ "evolution",
+ input.requestId,
+ () =>
+ runAccountTool(request, viewer.account, {
+ tool: "evolution",
+ files: [input.source.url, ...input.references],
+ plan: async () => evolutionSteps((run = await planEvolutionRun(input))),
+ start: () => startEvolution(run!),
+ }),
+ ({ value, gpuWarning }) => Response.json({ ...value, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),
+ );
}, request);
}
diff --git a/src/app/api/fly-around/route.ts b/src/app/api/fly-around/route.ts
index f774a400..add880bf 100644
--- a/src/app/api/fly-around/route.ts
+++ b/src/app/api/fly-around/route.ts
@@ -1,25 +1,52 @@
+import { bodyTooBig, guestRun, onceForAccount, priceAsRun, runAccountTool, toolViewer } from "@/server/account-tool-run";
import { body, handle, once } from "@/server/shorts-schemas";
-import { createFlyAround, FlyAroundSchema, previewFlyAround } from "@/server/fly-around";
-import { priceAs } from "@/server/visitor";
+import { createFlyAround, flyAroundSteps, FlyAroundSchema, planFlyAroundRun, previewFlyAround, startFlyAround, type FlyAroundRun } from "@/server/fly-around";
import { worldcastContextNow } from "@/server/worldcast-on";
/**
* Fly around: a still filmed along an exact camera path (an orbit's numbers, a preset or keys), on either
* engine. `?preview=1` plans and prices it without running it. Fuobe DoP, Image to 3D, Canvas and Assist call it.
+ * The owner's run as always; an account's on its own GPU or its own fal.ai or Replicate key, with its own files, after
+ * the checks every tool run gets (src/server/account-tool-run.ts); a guest signs up first.
*/
async function post(request: Request) {
return handle(async () => {
const { requestId, ...input } = await body(request, FlyAroundSchema, "Pick the engine, the still and the path");
- // The WorldCast worker's answer, fresh, before the plan reads it (N7-9).
- await worldcastContextNow();
+ // The WorldCast worker's answer, fresh, before the plan reads it (N7-9). An account's run never uses it.
+ // An account's run never uses the studio's WorldCast worker, nor asks it anything.
+ if (toolViewer(request).kind !== "account") await worldcastContextNow();
if (new URL(request.url).searchParams.get("preview")) return Response.json(previewFlyAround(input));
- // A plan that can't run (FlyAroundError) is a 422 with its reason, as any planner's error is.
- const result = await once("fly-around", requestId, () => createFlyAround(input));
- return Response.json(result, { status: 201 });
+ const viewer = toolViewer(request);
+ if (viewer.kind !== "account") {
+ // A plan that can't run (FlyAroundError) is a 422 with its reason, as any planner's error is.
+ const result = await once("fly-around", requestId, () => createFlyAround(input));
+ return Response.json(result, { status: 201 });
+ }
+ let run: FlyAroundRun | null = null;
+ return onceForAccount(
+ viewer.account,
+ "fly-around",
+ requestId,
+ () =>
+ runAccountTool(request, viewer.account, {
+ tool: "fly-around",
+ files: [input.image, input.render, ...(input.views ?? []), ...Object.values(input.sides ?? {})],
+ plan: () => flyAroundSteps((run = planFlyAroundRun(input))),
+ start: () => startFlyAround(run!),
+ }),
+ ({ value, gpuWarning }) => Response.json({ ...value, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),
+ );
}, request);
}
-/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+/** A price check (`?preview=1`) is priced as the asker's run would go; a guest's run signs up first. */
export async function POST(request: Request) {
- return priceAs(request, () => post(request));
+ const viewer = toolViewer(request);
+ if (new URL(request.url).searchParams.get("preview")) return priceAsRun(request, () => post(request));
+ if (viewer.kind === "guest") return guestRun();
+ if (viewer.kind === "account") {
+ const big = bodyTooBig(request);
+ if (big) return big;
+ }
+ return post(request);
}
diff --git a/src/app/api/katana/[id]/retry/route.ts b/src/app/api/katana/[id]/retry/route.ts
index e5515613..b9a137d6 100644
--- a/src/app/api/katana/[id]/retry/route.ts
+++ b/src/app/api/katana/[id]/retry/route.ts
@@ -1,14 +1,49 @@
-import { getKatana, rerunKatana, retryKatana } from "@/server/katana";
+import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";
import { refusedRun } from "@/server/connect-refusal";
+import { asAccount } from "@/server/generations";
+import { getKatana, katanaRoom, katanaRetrySteps, katanaRunSteps, planKatanaRun, rerunBody, rerunKatana, retryKatana, startKatana, type KatanaRun } from "@/server/katana";
-/** Retry the failed steps of a run (and the ones after them); `?all=1` starts the same run again from scratch. */
+const notFound = () => Response.json({ error: "Not found" }, { status: 404 });
+
+/**
+ * Retry the failed steps of a run (and the ones after them); `?all=1` starts the same run again from scratch. An account
+ * retries its own runs only, on its own GPU or key (src/server/account-tool-run.ts); a guest signs up first.
+ */
export async function POST(request: Request, ctx: RouteContext<"/api/katana/[id]/retry">) {
const { id } = await ctx.params;
- if (!getKatana(id)) return Response.json({ error: "Not found" }, { status: 404 });
- try {
- const all = new URL(request.url).searchParams.get("all") === "1";
- return Response.json(all ? rerunKatana(id) : retryKatana(id), { status: 201 });
- } catch (e) {
- return refusedRun(e, request);
+ const all = new URL(request.url).searchParams.get("all") === "1";
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
+ if (viewer.kind === "owner") {
+ if (!getKatana(id)) return notFound();
+ try {
+ return Response.json(all ? rerunKatana(id) : retryKatana(id), { status: 201 });
+ } catch (e) {
+ return refusedRun(e, request);
+ }
}
+ const account = viewer.account;
+ const big = bodyTooBig(request);
+ if (big) return big;
+ const job = asAccount(account.id, () => getKatana(id));
+ if (!job) return notFound();
+ let run: KatanaRun | null = null;
+ return onceForAccount(
+ account,
+ all ? "katana-rerun" : "katana-retry",
+ request.headers.get("x-request-id") ?? undefined,
+ () =>
+ runAccountTool(request, account, {
+ tool: "katana",
+ // Its own reference and photos, checked again (a file it deleted since can't go in).
+ files: [job.reference, ...job.photos],
+ plan: () => {
+ if (!all) return katanaRetrySteps(id);
+ katanaRoom(account.id);
+ return katanaRunSteps((run = planKatanaRun(rerunBody(id))));
+ },
+ start: () => (all ? startKatana(run!) : retryKatana(id)),
+ }),
+ ({ value }) => Response.json(value, { status: 201 }),
+ );
}
diff --git a/src/app/api/katana/[id]/route.ts b/src/app/api/katana/[id]/route.ts
index 88fad2dc..26b43ac7 100644
--- a/src/app/api/katana/[id]/route.ts
+++ b/src/app/api/katana/[id]/route.ts
@@ -1,15 +1,28 @@
import { connection } from "next/server";
+import { toolViewer } from "@/server/account-tool-run";
+import { asAccount } from "@/server/generations";
import { deleteKatana, getKatana } from "@/server/katana";
-export async function GET(_req: Request, ctx: RouteContext<"/api/katana/[id]">) {
+const notFound = () => Response.json({ error: "Not found" }, { status: 404 });
+
+/** One run: the owner's, or a signed-in account's own (another's reads as not found). */
+export async function GET(request: Request, ctx: RouteContext<"/api/katana/[id]">) {
await connection();
const { id } = await ctx.params;
- const job = getKatana(id);
- return job ? Response.json(job) : Response.json({ error: "Not found" }, { status: 404 });
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return notFound();
+ const job = viewer.kind === "account" ? asAccount(viewer.account.id, () => getKatana(id)) : getKatana(id);
+ return job ? Response.json(job, { headers: { "Cache-Control": "no-store" } }) : notFound();
}
-/** Forget the run: steps still running are stopped first (the clips it made stay in the Library). */
-export async function DELETE(_req: Request, ctx: RouteContext<"/api/katana/[id]">) {
+/**
+ * Forget the run: steps still running are stopped first (the clips it made stay in the Library, or in an account's
+ * runs). An account forgets its own runs only.
+ */
+export async function DELETE(request: Request, ctx: RouteContext<"/api/katana/[id]">) {
const { id } = await ctx.params;
- return deleteKatana(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return notFound();
+ const done = viewer.kind === "account" ? asAccount(viewer.account.id, () => deleteKatana(id)) : deleteKatana(id);
+ return done ? new Response(null, { status: 204 }) : notFound();
}
diff --git a/src/app/api/katana/route.ts b/src/app/api/katana/route.ts
index 76347ff7..9f907e2e 100644
--- a/src/app/api/katana/route.ts
+++ b/src/app/api/katana/route.ts
@@ -1,24 +1,67 @@
import { connection } from "next/server";
-import { createKatana, KatanaBody, listKatana, previewKatana } from "@/server/katana";
+import { bodyTooBig, guestRun, onceForAccount, priceAsRun, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { asAccount } from "@/server/generations";
+import { createKatana, KatanaBody, katanaRoom, katanaRunSteps, listKatana, planKatanaRun, previewKatana, startKatana, type KatanaRun } from "@/server/katana";
import { connectRefusal } from "@/server/connect-refusal";
-import { priceAs } from "@/server/visitor";
-/** Recent Katana runs with the state of every step. */
+/**
+ * Recent Katana runs with the state of every step: the owner's, or a signed-in account's own (its jobs are its own
+ * projects, src/server/katana.ts). A guest's list is empty (the proxy answers it).
+ */
export async function GET(request: Request) {
await connection();
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return Response.json({ items: [] });
const limit = Number(new URL(request.url).searchParams.get("limit") ?? 20);
- return Response.json({ items: listKatana(Number.isFinite(limit) ? limit : 20) });
+ const list = () => listKatana(Number.isFinite(limit) ? limit : 20);
+ return Response.json({ items: viewer.kind === "account" ? asAccount(viewer.account.id, list) : list() }, { headers: { "Cache-Control": "no-store" } });
}
-/** Start a run; `?preview=1` only plans and prices it (segments, steps, cost). */
-async function post(request: Request) {
- const parsed = KatanaBody.safeParse(await request.json().catch(() => null));
- if (!parsed.success) {
- const path = String(parsed.error.issues[0]?.path[0] ?? "");
- const msg = path === "reference" ? "Add the reference edit" : path === "photos" ? "Add 1–5 photos of your subject" : path === "instructions" ? "Keep the instructions under 2,000 characters" : "Check the Katana settings";
- return Response.json({ error: msg }, { status: 400 });
- }
+const badBody = (path: string) =>
+ Response.json(
+ { error: path === "reference" ? "Add the reference edit" : path === "photos" ? "Add 1–5 photos of your subject" : path === "instructions" ? "Keep the instructions under 2,000 characters" : "Check the Katana settings" },
+ { status: 400 },
+ );
+
+/**
+ * Start a run; `?preview=1` only plans and prices it (segments, steps, cost). The owner's run as always; an account's on
+ * its own GPU or its own fal.ai or Replicate key, with its own files, after the checks every tool run gets
+ * (src/server/account-tool-run.ts), kept as its own job; a guest signs up first.
+ */
+export async function POST(request: Request) {
const preview = new URL(request.url).searchParams.get("preview") === "1";
+ const viewer = toolViewer(request);
+ if (preview) return priceAsRun(request, () => post(request, true));
+ if (viewer.kind === "guest") return guestRun();
+ if (viewer.kind === "owner") return post(request, false);
+ const big = bodyTooBig(request);
+ if (big) return big;
+ const parsed = KatanaBody.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return badBody(String(parsed.error.issues[0]?.path[0] ?? ""));
+ const input = parsed.data;
+ const account = viewer.account;
+ let run: KatanaRun | null = null;
+ return onceForAccount(
+ account,
+ "katana",
+ request.headers.get("x-request-id") ?? undefined,
+ () =>
+ runAccountTool(request, account, {
+ tool: "katana",
+ files: [input.reference, ...input.photos],
+ plan: () => {
+ katanaRoom(account.id);
+ return katanaRunSteps((run = planKatanaRun(input)));
+ },
+ start: () => startKatana(run!),
+ }),
+ ({ value }) => Response.json(value, { status: 201 }),
+ );
+}
+
+async function post(request: Request, preview: boolean) {
+ const parsed = KatanaBody.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return badBody(String(parsed.error.issues[0]?.path[0] ?? ""));
try {
if (preview) return Response.json(previewKatana(parsed.data));
return Response.json(createKatana(parsed.data), { status: 201 });
@@ -27,8 +70,3 @@ async function post(request: Request) {
return connectRefusal(e, request, preview) ?? Response.json({ error: (e as Error).message }, { status: 422 });
}
}
-
-/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
-export async function POST(request: Request) {
- return priceAs(request, () => post(request));
-}
diff --git a/src/app/api/mixed-media/estimate/route.ts b/src/app/api/mixed-media/estimate/route.ts
index dbc89c0c..920c5f1a 100644
--- a/src/app/api/mixed-media/estimate/route.ts
+++ b/src/app/api/mixed-media/estimate/route.ts
@@ -1,6 +1,6 @@
+import { priceAsRun } from "@/server/account-tool-run";
import { estimateMixed } from "@/server/mixed-media";
import { MixedEstimateSchema, body, handle } from "@/server/shorts-schemas";
-import { priceAs } from "@/server/visitor";
/** Frames, cost of the render and of a preview frame, and notes for the current settings. */
async function post(request: Request) {
@@ -10,7 +10,7 @@ async function post(request: Request) {
});
}
-/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+/** Priced as the asker's run would go: an account's on its own GPU or key, a guest's on the open engine, never a demo. */
export async function POST(request: Request) {
- return priceAs(request, () => post(request));
+ return priceAsRun(request, () => post(request));
}
diff --git a/src/app/api/mixed-media/preview/route.ts b/src/app/api/mixed-media/preview/route.ts
index 93e7704c..5874ee10 100644
--- a/src/app/api/mixed-media/preview/route.ts
+++ b/src/app/api/mixed-media/preview/route.ts
@@ -1,10 +1,31 @@
-import { createMixedPreview } from "@/server/mixed-media";
+import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { createMixedPreview, mixedSteps, planMixedPreviewRun, startMixed, type MixedRun } from "@/server/mixed-media";
import { MixedBodySchema, body, handle, once } from "@/server/shorts-schemas";
-/** Generate one frame with the current settings before the full video. */
+/** Generate one frame with the current settings before the full video. An account's runs on its own GPU or key; a guest signs up first. */
export async function POST(request: Request) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
+ if (viewer.kind === "account") {
+ const big = bodyTooBig(request);
+ if (big) return big;
+ }
return handle(async () => {
const input = await body(request, MixedBodySchema, "Pick a preset and upload a clip first");
- return Response.json(await once("mixed-preview", input.requestId, () => createMixedPreview(input)), { status: 201 });
+ if (viewer.kind === "owner") return Response.json(await once("mixed-preview", input.requestId, () => createMixedPreview(input)), { status: 201 });
+ let run: MixedRun | null = null;
+ return onceForAccount(
+ viewer.account,
+ "mixed-preview",
+ input.requestId,
+ () =>
+ runAccountTool(request, viewer.account, {
+ tool: "mixed-media",
+ files: [input.source.url, input.anchor, input.frameUrl],
+ plan: async () => mixedSteps((run = await planMixedPreviewRun(input))),
+ start: () => startMixed(run!).final,
+ }),
+ ({ value }) => Response.json(value, { status: 201 }),
+ );
}, request);
}
diff --git a/src/app/api/mixed-media/progress/route.ts b/src/app/api/mixed-media/progress/route.ts
index 4a11a714..764a0b90 100644
--- a/src/app/api/mixed-media/progress/route.ts
+++ b/src/app/api/mixed-media/progress/route.ts
@@ -1,12 +1,19 @@
+import { toolViewer } from "@/server/account-tool-run";
+import { asAccount } from "@/server/generations";
import { framesProgress } from "@/server/mixed-media";
import { handle } from "@/server/shorts-schemas";
-/** How far a per-frame render's frame edits are (?id=<the render's finished video>): counts, and the first frame that failed. */
+/**
+ * How far a per-frame render's frame edits are (?id=<the render's finished video>): counts, and the first frame that
+ * failed. An account reads its own renders only (another's reads as gone); a guest has none (the proxy answers it).
+ */
export async function GET(request: Request) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return Response.json({ error: "This render no longer exists" }, { status: 404 });
return handle(() => {
const id = new URL(request.url).searchParams.get("id")?.trim() ?? "";
if (!id || id.length > 64) return Response.json({ error: "Which render?" }, { status: 400 });
- const progress = framesProgress(id);
+ const progress = viewer.kind === "account" ? asAccount(viewer.account.id, () => framesProgress(id)) : framesProgress(id);
return progress ? Response.json(progress) : Response.json({ error: "This render no longer exists" }, { status: 404 });
});
}
diff --git a/src/app/api/mixed-media/retry/route.ts b/src/app/api/mixed-media/retry/route.ts
index 3b16d706..6b3a2ea5 100644
--- a/src/app/api/mixed-media/retry/route.ts
+++ b/src/app/api/mixed-media/retry/route.ts
@@ -1,11 +1,37 @@
import { z } from "zod";
-import { retryMixed } from "@/server/mixed-media";
+import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { mixedSteps, planMixedRetry, retryMixed, startMixed, type MixedRun } from "@/server/mixed-media";
import { body, handle, once } from "@/server/shorts-schemas";
-/** Run a render again with the same settings ("Try again" in History); a repeated requestId gets the first answer. */
+const RetrySchema = z.object({ id: z.string().min(1).max(64), requestId: z.string().trim().min(8).max(64).optional() });
+
+/**
+ * Run a render again with the same settings ("Try again" in History); a repeated requestId gets the first answer. An
+ * account retries its own render only, on its own GPU or key (src/server/account-tool-run.ts); a guest signs up first.
+ */
export async function POST(request: Request) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
+ if (viewer.kind === "account") {
+ const big = bodyTooBig(request);
+ if (big) return big;
+ }
return handle(async () => {
- const input = await body(request, z.object({ id: z.string().min(1).max(64), requestId: z.string().trim().min(8).max(64).optional() }), "Pick a render to try again");
- return Response.json(await once("mixed-retry", input.requestId, () => retryMixed(input.id)), { status: 201 });
+ const input = await body(request, RetrySchema, "Pick a render to try again");
+ if (viewer.kind === "owner") return Response.json(await once("mixed-retry", input.requestId, () => retryMixed(input.id)), { status: 201 });
+ let run: MixedRun | null = null;
+ return onceForAccount(
+ viewer.account,
+ "mixed-retry",
+ input.requestId,
+ () =>
+ runAccountTool(request, viewer.account, {
+ tool: "mixed-media",
+ files: [],
+ plan: () => mixedSteps((run = planMixedRetry(input.id))),
+ start: () => startMixed(run!),
+ }),
+ ({ value }) => Response.json(value, { status: 201 }),
+ );
}, request);
}
diff --git a/src/app/api/mixed-media/route.ts b/src/app/api/mixed-media/route.ts
index 44b4af32..38f411e3 100644
--- a/src/app/api/mixed-media/route.ts
+++ b/src/app/api/mixed-media/route.ts
@@ -1,12 +1,40 @@
-import { createMixed } from "@/server/mixed-media";
+import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { createMixed, mixedSteps, planMixedRun, startMixed, type MixedRun } from "@/server/mixed-media";
import { MixedBodySchema, body, handle, once } from "@/server/shorts-schemas";
-/** Render a Mixed Media video (open: per frame; cloud: cut → frames or restyle → original sound). `items` leaves out the per-frame edits (`frames` counts them). */
+/**
+ * Render a Mixed Media video (open: per frame; cloud: cut → frames or restyle → original sound). `items` leaves out the
+ * per-frame edits (`frames` counts them). The owner's render as always; an account's on its own GPU or its own fal.ai or
+ * Replicate key, with its own files, after the checks every tool run gets (src/server/account-tool-run.ts); a guest
+ * signs up first.
+ */
export async function POST(request: Request) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
+ if (viewer.kind === "account") {
+ const big = bodyTooBig(request);
+ if (big) return big;
+ }
return handle(async () => {
const input = await body(request, MixedBodySchema, "Pick a preset, upload a clip and choose up to 10 seconds");
// A repeated requestId (a second click on Generate video) gets the render the first one started.
- const { final, items, frames } = await once("mixed-render", input.requestId, () => createMixed(input));
- return Response.json({ final, items, frames }, { status: 201 });
+ if (viewer.kind === "owner") {
+ const { final, items, frames } = await once("mixed-render", input.requestId, () => createMixed(input));
+ return Response.json({ final, items, frames }, { status: 201 });
+ }
+ let run: MixedRun | null = null;
+ return onceForAccount(
+ viewer.account,
+ "mixed-render",
+ input.requestId,
+ () =>
+ runAccountTool(request, viewer.account, {
+ tool: "mixed-media",
+ files: [input.source.url, input.anchor, input.frameUrl],
+ plan: async () => mixedSteps((run = await planMixedRun(input))),
+ start: () => startMixed(run!),
+ }),
+ ({ value, gpuWarning }) => Response.json({ final: value.final, items: value.items, frames: value.frames, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),
+ );
}, request);
}
diff --git a/src/app/api/remove-object/estimate/route.ts b/src/app/api/remove-object/estimate/route.ts
index a5d54fae..1ed99f61 100644
--- a/src/app/api/remove-object/estimate/route.ts
+++ b/src/app/api/remove-object/estimate/route.ts
@@ -1,6 +1,6 @@
+import { priceAsRun } from "@/server/account-tool-run";
import { estimateRemoval, RemovalEstimateSchema } from "@/server/remove-object";
import { body, handle } from "@/server/shorts-schemas";
-import { priceAs } from "@/server/visitor";
/** The price, the pieces and the notes for the current settings, before anything runs. */
async function post(request: Request) {
@@ -10,7 +10,7 @@ async function post(request: Request) {
});
}
-/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+/** Priced as the asker's run would go: an account's on its own GPU or key, a guest's on the open engine, never a demo. */
export async function POST(request: Request) {
- return priceAs(request, () => post(request));
+ return priceAsRun(request, () => post(request));
}
diff --git a/src/app/api/remove-object/preview/route.ts b/src/app/api/remove-object/preview/route.ts
index a4dff067..d200538c 100644
--- a/src/app/api/remove-object/preview/route.ts
+++ b/src/app/api/remove-object/preview/route.ts
@@ -1,11 +1,37 @@
-import { createRemovalPreview, RemovalBodySchema } from "@/server/remove-object";
+import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { createRemovalPreview, planRemovalPreview, RemovalBodySchema, removalSteps, startRemoval, type RemovalRun } from "@/server/remove-object";
import { body, handle, once } from "@/server/shorts-schemas";
-/** A mask preview of the first seconds: what the engine would remove (SAM 3.1). */
+/**
+ * A mask preview of the first seconds: what the engine would remove (SAM 3.1). An account's runs on its own GPU or key
+ * (src/server/account-tool-run.ts); a guest signs up first.
+ */
export async function POST(request: Request) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
+ if (viewer.kind === "account") {
+ const big = bodyTooBig(request);
+ if (big) return big;
+ }
return handle(async () => {
const input = await body(request, RemovalBodySchema, "Add a clip and say, click or paint what to remove");
- const preview = await once("remove-object-preview", input.requestId, () => createRemovalPreview(input));
- return Response.json(preview, { status: 201 });
+ if (viewer.kind === "owner") {
+ const preview = await once("remove-object-preview", input.requestId, () => createRemovalPreview(input));
+ return Response.json(preview, { status: 201 });
+ }
+ let run: RemovalRun | null = null;
+ return onceForAccount(
+ viewer.account,
+ "remove-object-preview",
+ input.requestId,
+ () =>
+ runAccountTool(request, viewer.account, {
+ tool: "remove-object",
+ files: [input.source.url, input.mask],
+ plan: async () => removalSteps((run = await planRemovalPreview(input))),
+ start: () => startRemoval(run!).final,
+ }),
+ ({ value }) => Response.json(value, { status: 201 }),
+ );
}, request);
}
diff --git a/src/app/api/remove-object/reroll/route.ts b/src/app/api/remove-object/reroll/route.ts
index 484023a7..95fe2349 100644
--- a/src/app/api/remove-object/reroll/route.ts
+++ b/src/app/api/remove-object/reroll/route.ts
@@ -1,11 +1,37 @@
-import { createRemovalReroll, RerollSchema } from "@/server/remove-object";
+import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { createRemovalReroll, planRemovalReroll, removalSteps, RerollSchema, startRemoval, type RemovalRun } from "@/server/remove-object";
import { body, handle, once } from "@/server/shorts-schemas";
-/** "Redo from here": an H3 person removal drawn again from one window, the windows before it kept exactly. */
+/**
+ * "Redo from here": an H3 person removal drawn again from one window, the windows before it kept exactly. An account
+ * redoes its own removal only, on its own GPU (src/server/account-tool-run.ts); a guest signs up first.
+ */
export async function POST(request: Request) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
+ if (viewer.kind === "account") {
+ const big = bodyTooBig(request);
+ if (big) return big;
+ }
return handle(async () => {
const input = await body(request, RerollSchema, "Pick the window to redo");
- const made = await once("remove-object-reroll", input.requestId, () => createRemovalReroll(input));
- return Response.json(made, { status: 201 });
+ if (viewer.kind === "owner") {
+ const made = await once("remove-object-reroll", input.requestId, () => createRemovalReroll(input));
+ return Response.json(made, { status: 201 });
+ }
+ let run: RemovalRun | null = null;
+ return onceForAccount(
+ viewer.account,
+ "remove-object-reroll",
+ input.requestId,
+ () =>
+ runAccountTool(request, viewer.account, {
+ tool: "remove-object",
+ files: [],
+ plan: () => removalSteps((run = planRemovalReroll(input))),
+ start: () => startRemoval(run!),
+ }),
+ ({ value, gpuWarning }) => Response.json({ final: value.final, items: value.items, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),
+ );
}, request);
}
diff --git a/src/app/api/remove-object/route.ts b/src/app/api/remove-object/route.ts
index 61fe705e..a27a3e00 100644
--- a/src/app/api/remove-object/route.ts
+++ b/src/app/api/remove-object/route.ts
@@ -1,12 +1,39 @@
-import { createRemoval, RemovalBodySchema } from "@/server/remove-object";
+import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { createRemoval, planRemovalRun, RemovalBodySchema, removalSteps, startRemoval, type RemovalRun } from "@/server/remove-object";
import { body, handle, once } from "@/server/shorts-schemas";
-/** Remove an object from a clip: the pieces or windows are erased, joined, and the clip's sound put back. */
+/**
+ * Remove an object from a clip: the pieces or windows are erased, joined, and the clip's sound put back. The owner's run
+ * as always; an account's on its own GPU or its own fal.ai or Replicate key, with its own files, after the checks every
+ * tool run gets (src/server/account-tool-run.ts); a guest signs up first.
+ */
export async function POST(request: Request) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
+ if (viewer.kind === "account") {
+ const big = bodyTooBig(request);
+ if (big) return big;
+ }
return handle(async () => {
const input = await body(request, RemovalBodySchema, "Add a clip and say, click or paint what to remove");
// A repeated requestId (a second click on Remove) gets the run the first one started.
- const { final, items } = await once("remove-object", input.requestId, () => createRemoval(input));
- return Response.json({ final, items }, { status: 201 });
+ if (viewer.kind === "owner") {
+ const { final, items } = await once("remove-object", input.requestId, () => createRemoval(input));
+ return Response.json({ final, items }, { status: 201 });
+ }
+ let run: RemovalRun | null = null;
+ return onceForAccount(
+ viewer.account,
+ "remove-object",
+ input.requestId,
+ () =>
+ runAccountTool(request, viewer.account, {
+ tool: "remove-object",
+ files: [input.source.url, input.mask],
+ plan: async () => removalSteps((run = await planRemovalRun(input))),
+ start: () => startRemoval(run!),
+ }),
+ ({ value, gpuWarning }) => Response.json({ final: value.final, items: value.items, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),
+ );
}, request);
}
diff --git a/src/app/api/turnaround/estimate/route.ts b/src/app/api/turnaround/estimate/route.ts
index 62cfc194..c87fc8aa 100644
--- a/src/app/api/turnaround/estimate/route.ts
+++ b/src/app/api/turnaround/estimate/route.ts
@@ -1,8 +1,8 @@
import { requestViewer } from "@/server/auth";
+import { priceAsRun } from "@/server/account-tool-run";
import { recordExists } from "@/server/records";
import { body, handle } from "@/server/shorts-schemas";
import { previewTurnaround, TurnaroundBodySchema, turnaroundRun } from "@/server/turnaround";
-import { priceAs } from "@/server/visitor";
import { worldcastContextNow } from "@/server/worldcast-on";
/**
@@ -23,7 +23,7 @@ async function post(request: Request) {
});
}
-/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+/** Priced as the asker's run would go: an account's on its own GPU or key, a guest's on the open engine, never a demo. */
export async function POST(request: Request) {
- return priceAs(request, () => post(request));
+ return priceAsRun(request, () => post(request));
}
diff --git a/src/app/api/turnaround/route.ts b/src/app/api/turnaround/route.ts
index ac46f06f..93e1eeb7 100644
--- a/src/app/api/turnaround/route.ts
+++ b/src/app/api/turnaround/route.ts
@@ -1,13 +1,15 @@
import { requestViewer } from "@/server/auth";
+import { bodyTooBig, guestRun, onceForAccount, priceAsRun, runAccountTool, toolViewer } from "@/server/account-tool-run";
import { recordExists } from "@/server/records";
import { body, handle, once } from "@/server/shorts-schemas";
-import { createTurnaround, previewTurnaround, TurnaroundBodySchema, turnaroundRun } from "@/server/turnaround";
-import { priceAs } from "@/server/visitor";
+import { createTurnaround, planTurnaroundRun, previewTurnaround, startTurnaround, TurnaroundBodySchema, turnaroundRun, turnaroundSteps, type TurnaroundRun } from "@/server/turnaround";
import { worldcastContextNow } from "@/server/worldcast-on";
/**
* Turnaround video (build plan N7-6): a 360° turnaround of a cast sheet or a character, on either engine. `?preview=1` plans
- * and prices it (the route, the pictures drawn first, the film's frames, the GPU it needs) without running it.
+ * and prices it (the route, the pictures drawn first, the film's frames, the GPU it needs) without running it. The owner's
+ * run as always; an account's on its own GPU or its own fal.ai or Replicate key, with its own pictures, after the checks
+ * every tool run gets (src/server/account-tool-run.ts); a guest signs up first.
*/
async function post(request: Request) {
return handle(async () => {
@@ -16,15 +18,41 @@ async function post(request: Request) {
if (input.elementId && (requestViewer(request).kind !== "owner" || !recordExists({ kind: "element", ids: [input.elementId] }))) {
return Response.json({ error: "Character not found" }, { status: 404 });
}
- await worldcastContextNow();
+ // An account's run never uses the studio's WorldCast worker, nor asks it anything.
+ if (toolViewer(request).kind !== "account") await worldcastContextNow();
const run = turnaroundRun(input);
if (new URL(request.url).searchParams.get("preview")) return Response.json(previewTurnaround(run));
- const result = await once("turnaround", requestId, () => createTurnaround(run));
- return Response.json(result, { status: 201 });
+ const viewer = toolViewer(request);
+ if (viewer.kind !== "account") {
+ const result = await once("turnaround", requestId, () => createTurnaround(run));
+ return Response.json(result, { status: 201 });
+ }
+ let planned: TurnaroundRun | null = null;
+ return onceForAccount(
+ viewer.account,
+ "turnaround",
+ requestId,
+ () =>
+ runAccountTool(request, viewer.account, {
+ tool: "turnaround",
+ files: [...Object.values(input.views ?? {}), input.sheet],
+ plan: () => turnaroundSteps((planned = planTurnaroundRun(run))),
+ start: () => startTurnaround(planned!),
+ }),
+ ({ value, gpuWarning }) => Response.json({ ...value, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),
+ );
});
}
-/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+/** A price check (`?preview=1`) is priced as the asker's run would go; a guest's run signs up first. */
export async function POST(request: Request) {
- return priceAs(request, () => post(request));
+ const viewer = toolViewer(request);
+ const preview = !!new URL(request.url).searchParams.get("preview");
+ if (preview) return priceAsRun(request, () => post(request));
+ if (viewer.kind === "guest") return guestRun();
+ if (viewer.kind === "account") {
+ const big = bodyTooBig(request);
+ if (big) return big;
+ }
+ return post(request);
}
diff --git a/src/components/cinema/cinema-feed.tsx b/src/components/cinema/cinema-feed.tsx
index 8d4b2ac5..8739ca67 100644
--- a/src/components/cinema/cinema-feed.tsx
+++ b/src/components/cinema/cinema-feed.tsx
@@ -57,7 +57,7 @@ import { getModel } from "@/lib/catalog";
import type { CinemaFolder } from "@/lib/catalog/cinema";
import type { Generation, OutputFile } from "@/lib/catalog/types";
import { formatCost, timeAgo } from "@/lib/format";
-import { useEngineMode, useIsOwner, useLikelyVisitor } from "@/lib/api";
+import { useEngineMode, useIsOwner } from "@/lib/api";
import { finishedTakes, finishIn2k, REGEN_OFFERED } from "@/lib/catalog/regenerate";
import { useSubmitGuard } from "@/components/shorts/hooks";
import { cn } from "@/lib/utils";
@@ -205,8 +205,6 @@ function TileMenu({ u, folders, projectId, handlers, onDelete }: { u: Unit; fold
const finished = useContext(FinishedIn2k);
// One paid submit at a time, with a nonce the server answers a repeat with (a double click is one 2K render).
const guard = useSubmitGuard();
- // Remove a person runs on a self-hosted Fuobe only: a guest or an account isn't sent there.
- const visitor = useLikelyVisitor();
// The Trash is the owner's: anyone else's Delete is for good.
const owner = useIsOwner();
const o = u.output;
@@ -274,13 +272,11 @@ function TileMenu({ u, folders, projectId, handlers, onDelete }: { u: Unit; fold
<DropdownMenuItem onClick={() => handlers.onReference(o.url, "video")}>
<ImagePlus /> Use as reference clip
</DropdownMenuItem>
- {!visitor && (
- <DropdownMenuItem asChild>
- <Link href={`/video-tools/remove-person?video=${encodeURIComponent(o.url)}`}>
- <UserX /> Remove a person
- </Link>
- </DropdownMenuItem>
- )}
+ <DropdownMenuItem asChild>
+ <Link href={`/video-tools/remove-person?video=${encodeURIComponent(o.url)}`}>
+ <UserX /> Remove a person
+ </Link>
+ </DropdownMenuItem>
{finish && (
<DropdownMenuItem
onClick={() =>
diff --git a/src/components/evolution/evolution-tool.tsx b/src/components/evolution/evolution-tool.tsx
index 367f59fe..5a2c1acf 100644
--- a/src/components/evolution/evolution-tool.tsx
+++ b/src/components/evolution/evolution-tool.tsx
@@ -9,7 +9,6 @@ import { Textarea } from "@/components/ui/textarea";
import { StepList, type StepRow } from "@/components/av/step-list";
import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";
import { useGenerationList } from "@/components/av/use-generation";
-import { SelfHostNote } from "@/components/self-host-note";
import { VideoCompare } from "@/components/remove-object/video-compare";
import { useSubmitGuard } from "@/components/shorts/hooks";
import { ClipBar, ClipDrop, costText, Field, Segmented } from "@/components/shorts/ui";
@@ -17,7 +16,7 @@ import { clipDuration, clipSize, useSourceClip } from "@/components/shorts/use-s
import { Feed } from "@/components/studio/feed";
import { fileToList, MediaSlot, type SlotValue } from "@/components/studio/media-slot";
import { VideoTrimmer, type TrimRange, type VideoTrimmerHandle } from "@/components/studio/video-trimmer";
-import { useEngine, useGenerations, useLikelyVisitor } from "@/lib/api";
+import { useEngine, useGenerations } from "@/lib/api";
import { DIRECTION_CUT_NOTE, directionPrompt, EVOLUTION, EVOLUTION_CLOUD_NOTE, EVOLUTION_DEFAULT_RESOLUTION, EVOLUTION_RESOLUTIONS, INTENSITIES, type Intensity } from "@/lib/catalog/evolution";
import { chainState } from "@/lib/catalog/shorts";
import { downloadHref, downloadName } from "@/lib/library";
@@ -56,9 +55,6 @@ async function frameDataUrl(blob: Blob | null | undefined): Promise<string | und
*/
export function EvolutionTool() {
const [engine] = useEngine();
- // Evolution doesn't run on an account's own GPU or key yet (only the studios' generations do): said up front, and
- // the upload and Evolve are off, instead of a run the server refuses.
- const visitor = useLikelyVisitor();
const source = useSourceClip(EVOLUTION.maxBytes);
const clip = source.clip;
const trimmer = useRef<VideoTrimmerHandle>(null);
@@ -112,7 +108,7 @@ export function EvolutionTool() {
: estimate.isError
? (estimate.error as Error).message
: null;
- const blocker = visitor ? "Evolution isn't available here" : setupBlocker;
+ const blocker = setupBlocker;
const reset = () => {
source.clear();
@@ -159,21 +155,18 @@ export function EvolutionTool() {
};
return (
- <ToolShell title="Video tools" wide selfHostedOnly>
+ <ToolShell title="Video tools" wide>
{!clip && (
<ToolHero
title="Take a clip further"
- subtitle={`Evolution keeps your clip's motion and timing and takes the rest where your references and words point${visitor ? "." : ", free on your own ComfyUI."}`}
- >
- {visitor && <SelfHostNote className="mt-3 max-w-xl">Evolution isn&apos;t available here.</SelfHostNote>}
- </ToolHero>
+ subtitle={`Evolution keeps your clip's motion and timing and takes the rest where your references and words point, free on your own ComfyUI.`}
+ />
)}
<div className={cn("mx-auto", clip ? "pt-4" : "mt-8 max-w-[640px]")}>
{!clip ? (
<ClipDrop
accept={EVOLUTION.accept}
limits={LIMITS}
- disabled={visitor}
onFile={(f) => {
const err = source.pick(f);
if (err) toast.error(err);
@@ -267,7 +260,7 @@ export function EvolutionTool() {
className="max-h-64 resize-y"
/>
<div className="flex flex-wrap items-center gap-2">
- <Button size="sm" variant="outline" className="rounded-full" onClick={() => void write()} disabled={actions.direction.isPending || !clip || refs.some((r) => r.uploading) || visitor}>
+ <Button size="sm" variant="outline" className="rounded-full" onClick={() => void write()} disabled={actions.direction.isPending || !clip || refs.some((r) => r.uploading)}>
{actions.direction.isPending ? <Loader2 className="size-3.5 animate-spin" /> : <Sparkles className="size-3.5" />} Write it for me
</Button>
<span className="text-[12px] text-muted-foreground">
@@ -288,7 +281,7 @@ export function EvolutionTool() {
) : (
<>
<p className="flex items-center gap-1.5 text-[15px] font-semibold tabular-nums">
- {costText(est, engine, visitor)}
+ {costText(est, engine)}
{estimate.isFetching && <Loader2 className="size-3 animate-spin text-muted-foreground" aria-label="Updating the price" />}
</p>
{est && (
@@ -300,7 +293,7 @@ export function EvolutionTool() {
</>
)}
</div>
- <Button className="rounded-full" onClick={start} disabled={!!blocker || actions.run.isPending || visitor}>
+ <Button className="rounded-full" onClick={start} disabled={!!blocker || actions.run.isPending}>
{actions.run.isPending ? <Loader2 className="size-4 animate-spin" /> : <Wand2 className="size-4" />} Evolve
</Button>
</div>
diff --git a/src/components/evolution/hooks.ts b/src/components/evolution/hooks.ts
index 5024a063..4fe76f27 100644
--- a/src/components/evolution/hooks.ts
+++ b/src/components/evolution/hooks.ts
@@ -5,6 +5,7 @@ import type { Intensity } from "@/lib/catalog/evolution";
import type { Engine, Generation } from "@/lib/catalog/types";
import { useDebounced } from "@/components/faceless/hooks";
import { send } from "@/components/shorts/hooks";
+import { COMPUTER_KICK_EVENT } from "@/lib/api";
/** React Query hooks for /api/evolution/** (the Evolution tab of Video tools). */
@@ -59,6 +60,8 @@ export function useEvolutionActions() {
run: useMutation({
mutationFn: (b: EvolutionBody) => send<{ final: Generation; items: Generation[]; direction: string; by: DirectionAnswer["by"] | "you" }>("/api/evolution", "POST", b),
onSuccess: (r) => {
+ // The tab that runs this person's jobs on the ComfyUI on this computer asks for them at once.
+ window.dispatchEvent(new Event(COMPUTER_KICK_EVENT));
r.items.forEach((g) => qc.setQueryData(["generation", g.id], g));
void qc.invalidateQueries({ queryKey: ["generations"] });
},
diff --git a/src/components/fly-around-run.ts b/src/components/fly-around-run.ts
index 402f24b3..dfe41822 100644
--- a/src/components/fly-around-run.ts
+++ b/src/components/fly-around-run.ts
@@ -4,6 +4,7 @@ import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tansta
import type { CameraKey } from "@/lib/camera-path";
import type { ExactOrbit } from "@/lib/exact-orbit";
import type { Engine, Generation } from "@/lib/catalog/types";
+import { COMPUTER_KICK_EVENT } from "@/lib/api";
import { formatCost } from "@/lib/format";
import { responseError, toastError } from "@/lib/refusals";
@@ -64,6 +65,8 @@ export function useFlyAround(body: FlyAroundBody | null) {
const run = useMutation({
mutationFn: (b: FlyAroundBody) => post<{ items: Generation[]; final: Generation }>("/api/fly-around", b),
onSuccess: () => {
+ // The tab that runs this person's jobs on the ComfyUI on this computer (an account's "Your GPU") asks for them at once.
+ window.dispatchEvent(new Event(COMPUTER_KICK_EVENT));
void qc.invalidateQueries({ queryKey: ["generations"] });
void qc.invalidateQueries({ queryKey: ["library-facets"] });
},
diff --git a/src/components/katana/hooks.ts b/src/components/katana/hooks.ts
index 6e5b6847..cdd47b0c 100644
--- a/src/components/katana/hooks.ts
+++ b/src/components/katana/hooks.ts
@@ -1,7 +1,7 @@
"use client";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { useGenerationEvents } from "@/lib/api";
+import { COMPUTER_KICK_EVENT, useGenerationEvents } from "@/lib/api";
import type { KatanaJobView, Segment } from "@/lib/av/katana";
import type { Engine } from "@/lib/catalog/types";
import { responseError } from "@/lib/refusals";
@@ -59,11 +59,18 @@ export function useKatanaPreview(body: KatanaBody | null) {
});
}
+/**
+ * A run started: the tab that runs this person's jobs on the ComfyUI on this computer (an account's "Your GPU") asks for
+ * them at once, as after a studio run.
+ */
+const kick = () => window.dispatchEvent(new Event(COMPUTER_KICK_EVENT));
+
export function useKatanaActions() {
const qc = useQueryClient();
const start = useMutation({
mutationFn: (body: KatanaBody) => post<KatanaJobView>("/api/katana", body),
onSuccess: (job) => {
+ kick();
qc.setQueryData<KatanaJobView[]>(["katana"], (xs) => [job, ...(xs ?? [])]);
void qc.invalidateQueries({ queryKey: ["generations"] });
},
@@ -80,6 +87,7 @@ export function useKatanaActions() {
const retry = useMutation({
mutationFn: async ({ id, all }: { id: string; all?: boolean }) => json<KatanaJobView>(await fetch(`/api/katana/${id}/retry${all ? "?all=1" : ""}`, { method: "POST" })),
onSuccess: (job, { all }) => {
+ kick();
qc.setQueryData<KatanaJobView[]>(["katana"], (xs) => (all ? [job, ...(xs ?? [])] : (xs ?? []).map((j) => (j.id === job.id ? job : j))));
void qc.invalidateQueries({ queryKey: ["generations"] });
},
diff --git a/src/components/katana/katana-studio.tsx b/src/components/katana/katana-studio.tsx
index 16651956..c45169fd 100644
--- a/src/components/katana/katana-studio.tsx
+++ b/src/components/katana/katana-studio.tsx
@@ -18,9 +18,8 @@ import { frameDiff, openVideo, releaseVideo, sampleFrames } from "@/components/a
import { MediaDrop } from "@/components/av/media-drop";
import { StepList, type StepRow } from "@/components/av/step-list";
import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";
-import { SelfHostNote } from "@/components/self-host-note";
import { ExampleRow } from "@/components/studio/example-row";
-import { useEngine, useLikelyVisitor, useModelAccess, useStatus } from "@/lib/api";
+import { useAskBeforeUpload, useEngine, useIsGuest, useModelAccess, useStatus } from "@/lib/api";
import { againPrice, againWhere, placeholdersOn } from "@/lib/demo-mode";
import { formatCueTime } from "@/lib/av/cue-edit";
import { againKeys, detectCutIndices, KATANA_LIMITS, katanaProgress, katanaStage, motionModel, MOTION_MODELS, nearestAspect, OPEN_KEYFRAME_PHOTOS, planSegments, refineCut, refineTimes, type KatanaJobView, type Segment } from "@/lib/av/katana";
@@ -58,9 +57,7 @@ async function findCuts(src: string, duration: number, onProgress: (p: number) =
}
}
-/** visitor: a guest or an account, whose own GPU doesn't run Katana yet (the page says so). */
-const money = (usd: number | null | undefined, demo?: boolean, open?: boolean, visitor?: boolean) =>
- visitor && (demo || open) ? "Not available here" : demo ? "Placeholder · free" : open ? "Free · your GPU" : usd == null ? "Price unknown" : `≈ $${usd.toFixed(2)}`;
+const money = (usd: number | null | undefined, demo?: boolean, open?: boolean) => (demo ? "Placeholder · free" : open ? "Free · your GPU" : usd == null ? "Price unknown" : `≈ $${usd.toFixed(2)}`);
/**
* Katana: rebuild a reference edit with your subject, shot for shot.
@@ -68,9 +65,10 @@ const money = (usd: number | null | undefined, demo?: boolean, open?: boolean, v
*/
export function KatanaStudio({ examples }: { examples?: ExampleRowData | null }) {
const [engine] = useEngine();
- // An edit doesn't run on an account's own GPU or key yet (only the studios' generations do): said up front, and the
- // uploads and Recreate are off, instead of a run the server refuses.
- const visitor = useLikelyVisitor();
+ // A guest is asked to sign up, and an account with neither its own GPU nor its own key to connect one, before a photo
+ // is added (the reference's drop asks the same).
+ const askFirst = useAskBeforeUpload();
+ const guest = useIsGuest();
const jobs = useKatanaJobs();
const { start } = useKatanaActions();
const [reference, setReference] = useState<SlotValue | null>(null);
@@ -133,8 +131,7 @@ export function KatanaStudio({ examples }: { examples?: ExampleRowData | null })
: preview.error
? (preview.error as Error).message
: null;
- // A guest or an account reads why Recreate is off, not a step on an upload that is off too.
- const blocker = visitor ? "Katana isn't available here" : setupBlocker;
+ const blocker = setupBlocker;
const scan = async () => {
if (!reference || !meta || scanning !== null) return;
@@ -154,7 +151,6 @@ export function KatanaStudio({ examples }: { examples?: ExampleRowData | null })
};
const go = () => {
- if (visitor) return;
if (blocker || !body) return void toast(blocker ?? "Not ready yet", { id: "katana-blocker" });
start.mutate(body, {
onSuccess: (j) => toast.success(`Katana started · ${j.segments.length} segment${j.segments.length === 1 ? "" : "s"}`),
@@ -163,13 +159,10 @@ export function KatanaStudio({ examples }: { examples?: ExampleRowData | null })
};
return (
- <ToolShell title="Katana" selfHostedOnly>
- <ToolHero title="Recreate the edit. Make it yours." subtitle="Drop a reference edit and up to 5 photos of your subject — Katana rebuilds it shot for shot, at the original cut times, with the original sound.">
- {visitor && <SelfHostNote className="mt-3 max-w-xl">Katana isn&apos;t available here.</SelfHostNote>}
- </ToolHero>
+ <ToolShell title="Katana">
+ <ToolHero title="Recreate the edit. Make it yours." subtitle="Drop a reference edit and up to 5 photos of your subject — Katana rebuilds it shot for shot, at the original cut times, with the original sound." />
<div className="mx-auto mt-8 grid max-w-[1040px] gap-4 lg:grid-cols-[minmax(0,6fr)_minmax(0,5fr)]">
- {/* A guest's or an account's files would be uploaded for an edit that can't start here. */}
- <div inert={visitor} className={cn("min-w-0 space-y-3", visitor && "opacity-50")}>
+ <div className="min-w-0 space-y-3">
<MediaDrop
kind="video"
value={reference}
@@ -243,7 +236,22 @@ export function KatanaStudio({ examples }: { examples?: ExampleRowData | null })
</div>
<div className="min-w-0 space-y-3">
<Panel title="Your subject" aside={<span className="text-[12px] text-muted-foreground">{photos.length}/5</span>}>
- <div inert={visitor} className={cn("flex flex-wrap gap-2", visitor && "opacity-50")}>
+ <div
+ className="flex flex-wrap gap-2"
+ // Anyone whose upload would be refused gets its card instead of the file chooser.
+ onClickCapture={(e) => {
+ if (askFirst()) {
+ e.preventDefault();
+ e.stopPropagation();
+ }
+ }}
+ onDropCapture={(e) => {
+ if (askFirst()) {
+ e.preventDefault();
+ e.stopPropagation();
+ }
+ }}
+ >
{photos.map((p) => (
<MediaSlot key={p.id} label="Photo" kind="image" value={p} onChange={(v) => setPhotos((xs) => (v ? xs.map((x) => (x.id === p.id ? { ...v, id: p.id } : x)) : xs.filter((x) => x.id !== p.id)))} size="lg" />
))}
@@ -297,19 +305,19 @@ export function KatanaStudio({ examples }: { examples?: ExampleRowData | null })
{preview.data ? (
<>
{preview.data.segments.length} segment{preview.data.segments.length === 1 ? "" : "s"} · {preview.data.steps} steps ·{" "}
- <span className="font-mono text-foreground">{money(preview.data.costUsd, preview.data.demo, engine === "open", visitor)}</span>
+ <span className="font-mono text-foreground">{money(preview.data.costUsd, preview.data.demo, engine === "open")}</span>
</>
) : (
(blocker ?? "Pricing…")
)}
</p>
- <Button size="lg" className={cn("rounded-full", blocker && "bg-muted text-muted-foreground hover:bg-muted")} onClick={go} disabled={start.isPending || scanning !== null || visitor}>
+ <Button size="lg" className={cn("rounded-full", blocker && "bg-muted text-muted-foreground hover:bg-muted")} onClick={go} disabled={start.isPending || scanning !== null}>
{start.isPending ? <Loader2 className="size-4 animate-spin" /> : <Sparkles className="size-4" />} Recreate
</Button>
</div>
</div>
</div>
- {examples && (visitor || (jobs.isSuccess && !jobs.data.length)) && <ExampleRow row={examples} className="mt-12" />}
+ {examples && (guest || (jobs.isSuccess && !jobs.data.length)) && <ExampleRow row={examples} className="mt-12" />}
<Runs jobs={jobs.data} loading={jobs.isLoading} />
</ToolShell>
);
diff --git a/src/components/mixed-media/hooks.ts b/src/components/mixed-media/hooks.ts
index bd71432c..4632c283 100644
--- a/src/components/mixed-media/hooks.ts
+++ b/src/components/mixed-media/hooks.ts
@@ -5,7 +5,7 @@ import { keepPreviousData, useMutation, useQueries, useQuery, useQueryClient } f
import { useDeferredValue } from "react";
import type { MixedMode, MixedResolution, MixedValues } from "@/lib/catalog/mixed-media";
import type { Engine, Generation } from "@/lib/catalog/types";
-import { useGenerationEvents } from "@/lib/api";
+import { COMPUTER_KICK_EVENT, useGenerationEvents } from "@/lib/api";
import { send } from "@/components/shorts/hooks";
/** React Query hooks for /api/mixed-media/** (renders, preview frames, estimates). */
@@ -139,6 +139,12 @@ export function renderSteps(chain: (Generation | undefined)[]): { g?: Generation
/** A per-frame render (its frames go back together in an images-to-video step; a retry may keep the extraction from before). */
export const isFrameRender = (chain: (Generation | undefined)[]) => chain.some((g) => g?.op === "extract-frames" || g?.op === "images-to-video");
+/**
+ * A run started: the tab that runs this person's jobs on the ComfyUI on this computer (an account's "Your GPU") asks for
+ * them at once, as after a studio run.
+ */
+const kick = () => window.dispatchEvent(new Event(COMPUTER_KICK_EVENT));
+
export function useMixedActions() {
const qc = useQueryClient();
const seed = (g: Generation) => qc.setQueryData(["mixed-media", "generation", g.id], g);
@@ -146,18 +152,23 @@ export function useMixedActions() {
render: useMutation({
mutationFn: (b: MixedBody) => send<{ final: Generation; items: Generation[]; frames?: number }>("/api/mixed-media", "POST", b),
onSuccess: (r) => {
+ kick();
r.items.forEach(seed);
void qc.invalidateQueries({ queryKey: ["generations"] });
},
}),
preview: useMutation({
mutationFn: (b: MixedBody) => send<Generation>("/api/mixed-media/preview", "POST", b),
- onSuccess: seed,
+ onSuccess: (g) => {
+ kick();
+ seed(g);
+ },
}),
/** Run a finished-or-failed render again with the same settings (History's "Try again"). */
retry: useMutation({
mutationFn: (v: { id: string; requestId?: string }) => send<{ final: Generation; items: Generation[]; frames?: number }>("/api/mixed-media/retry", "POST", v),
onSuccess: (r) => {
+ kick();
r.items.forEach(seed);
void qc.invalidateQueries({ queryKey: ["generations"] });
},
diff --git a/src/components/mixed-media/mixed-studio.tsx b/src/components/mixed-media/mixed-studio.tsx
index 36886526..973159cb 100644
--- a/src/components/mixed-media/mixed-studio.tsx
+++ b/src/components/mixed-media/mixed-studio.tsx
@@ -7,7 +7,6 @@ import { useDeferredValue, useEffect, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { PhoneNavButton } from "@/components/nav/phone-nav-button";
-import { SelfHostNote } from "@/components/self-host-note";
import { EngineSwitch } from "@/components/studio/engine-switch";
import { MediaThumb } from "@/components/studio/result-media";
import { VideoTrimmer, type VideoTrimmerHandle } from "@/components/studio/video-trimmer";
@@ -15,7 +14,7 @@ import { LookCard } from "@/components/shorts/preset-card";
import { useSubmitGuard } from "@/components/shorts/hooks";
import { ClipBar, ClipDrop, costText, Field, Segmented, tabKeys } from "@/components/shorts/ui";
import { clipDuration, clipSize, useSourceClip } from "@/components/shorts/use-source-clip";
-import { uploadFile, useEngine, useLikelyVisitor, useModelAccess, useStatus } from "@/lib/api";
+import { uploadFile, useEngine, useModelAccess, useStatus } from "@/lib/api";
import { paidSuffix, placeholdersOn } from "@/lib/demo-mode";
import { keepOffered, offered } from "@/lib/model-access";
import {
@@ -92,9 +91,6 @@ export function MixedStudio({
const [tab, setTab] = useState<Tab>("presets");
const body = useSwapFade<HTMLDivElement>(tab);
const [engine, setEngine, engineMode] = useEngine();
- // A render doesn't run on an account's own GPU or key yet (only the studios' generations do): said up front, and the
- // upload, the preview and Generate are off, instead of a run the server refuses.
- const visitor = useLikelyVisitor();
useEffect(() => {
const t = new URLSearchParams(window.location.search).get("tab");
// eslint-disable-next-line react-hooks/set-state-in-effect -- read once after hydration
@@ -129,7 +125,7 @@ export function MixedStudio({
</TabRow>
<div className="ml-auto shrink-0">
{/* A phone's header has room for the tabs, not "Add key" too. */}
- <EngineSwitch value={engine} onChange={setEngine} wordless selfHostedOnly />
+ <EngineSwitch value={engine} onChange={setEngine} wordless />
</div>
<PhoneNavButton />
</header>
@@ -144,12 +140,11 @@ export function MixedStudio({
<p className="text-[12px] font-semibold tracking-[0.14em] text-brand-text uppercase">No prompts, just vibe</p>
<h2 className="mt-2 font-heading text-display text-balance">Turn any video into mixed-media art</h2>
<p className="mx-auto mt-2 max-w-[560px] text-body text-pretty text-muted-foreground">
- 33 looks, each with its own colours and materials. Preview one frame, then make the whole clip
- {visitor ? "." : ", free on your GPU."}
+ 33 looks, each with its own colours and materials. Preview one frame, then make the whole clip, free on your
+ GPU.
</p>
- {visitor && <SelfHostNote className="mx-auto mt-3 max-w-[560px]">Mixed Media isn&apos;t available here.</SelfHostNote>}
</div>
- <Workspace visitor={visitor} engine={engine} models={models[engine]} frameModels={frameModels[engine]} />
+ <Workspace engine={engine} models={models[engine]} frameModels={frameModels[engine]} />
</>
)}
</div>
@@ -199,7 +194,7 @@ function How({ onStart, cloud, reveal }: { onStart: () => void; cloud: boolean;
);
}
-function Workspace({ visitor, engine, models, frameModels }: { visitor: boolean; engine: Engine; models: RestyleModelInfo[]; frameModels: RestyleModelInfo[] }) {
+function Workspace({ engine, models, frameModels }: { engine: Engine; models: RestyleModelInfo[]; frameModels: RestyleModelInfo[] }) {
const [hasClip, setHasClip] = useState(false);
const [presetId, setPresetId] = useState<string | null>(null);
const preset = MIXED_PRESETS.find((p) => p.id === presetId) ?? null;
@@ -280,7 +275,7 @@ function Workspace({ visitor, engine, models, frameModels }: { visitor: boolean;
)}
</section>
<aside ref={panel} id="mm-editor" className="scrollbar-none min-w-0 scroll-mt-16 lg:sticky lg:top-[calc(var(--chrome-top)+1rem)] lg:max-h-[calc(var(--content-h)-4.5rem)] lg:overflow-y-auto lg:overscroll-contain lg:rounded-2xl">
- <Editor visitor={visitor} engine={engine} models={models} frameModels={frameModels} preset={preset} values={values} setValues={setValues} onClip={setHasClip} />
+ <Editor engine={engine} models={models} frameModels={frameModels} preset={preset} values={values} setValues={setValues} onClip={setHasClip} />
</aside>
{preset && !panelVisible && (
<div className="fixed inset-x-3 bottom-[max(calc(var(--chrome-bottom)+0.75rem),env(safe-area-inset-bottom))] z-30 lg:hidden">
@@ -305,7 +300,6 @@ const LIMITS = "MP4 or MOV · 1 to 10 s · up to 50 MB · at least 4 FPS";
type FpsChoice = number | "manual";
function Editor({
- visitor,
engine,
models: restyleModels,
frameModels,
@@ -314,8 +308,6 @@ function Editor({
setValues,
onClip,
}: {
- /** A guest or an account: the upload, the preview and Generate are off (the page says it runs on a self-hosted Fuobe). */
- visitor: boolean;
engine: Engine;
models: RestyleModelInfo[];
frameModels: RestyleModelInfo[];
@@ -358,8 +350,7 @@ function Editor({
const [pickedModel, setModel] = useState<Record<string, string>>({});
const modelId = (models.some((m) => m.id === pickedModel[slot]) && pickedModel[slot]) || models[0]?.id;
const model = models.find((m) => m.id === modelId);
- // An open model is free on a self-hosted Fuobe: a guest or an account reads that, not "your GPU".
- const priceOf = (m?: RestyleModelInfo) => (visitor && m?.engine === "open" ? "Not available here" : m?.price);
+ const priceOf = (m?: RestyleModelInfo) => m?.price;
const original = modelId === MIXED_ORIGINAL;
const [previewId, setPreviewId] = useState<string | null>(null);
// Every main step of the latest render (cut → frames or restyle → sound), so a failed step shows its own error.
@@ -436,7 +427,7 @@ function Editor({
// The preview frame is a run of its own: on the cloud its button says its price (the estimate's, per frame), else "· paid";
// nothing on your GPU (free) or while placeholders are on.
const placeholders = placeholdersOn(useStatus().data?.demoMode);
- const previewPaid = cloud && !visitor && !(est ? est.demo : placeholders) ? paidSuffix(est?.previewUsd) : "";
+ const previewPaid = cloud && !(est ? est.demo : placeholders) ? paidSuffix(est?.previewUsd) : "";
// A new clip, preset or engine starts without a preview (and so does another frame editor: the preview is its own work).
const key = `${preset?.id}|${clip?.preview}|${engine}|${mode === "fast" ? "" : modelId}`;
@@ -466,7 +457,7 @@ function Editor({
: estimate.error
? (estimate.error as Error).message
: null;
- const blocker = visitor ? "Mixed Media isn't available here" : setupBlocker;
+ const blocker = setupBlocker;
// One preview and one render per click: a second click while one is on its way does nothing,
// and the server answers a repeated request id with what the first one started.
@@ -524,7 +515,6 @@ function Editor({
<ClipDrop
accept={MIXED.accept}
limits={LIMITS}
- disabled={visitor}
onFile={(f) => {
const err = source.pick(f);
if (err) toast.error(err);
@@ -561,7 +551,7 @@ function Editor({
<Field
label="Restyle"
- hint={frameMode ? `Every frame drawn again${cloud ? " · priced per frame" : visitor ? "" : " · free on your GPU"}` : smooth ? `First frame, then carried through${cloud ? " · priced per second" : visitor ? "" : " · free on your GPU"}` : "One video-to-video pass · priced by the model"}
+ hint={frameMode ? `Every frame drawn again${cloud ? " · priced per frame" : " · free on your GPU"}` : smooth ? `First frame, then carried through${cloud ? " · priced per second" : " · free on your GPU"}` : "One video-to-video pass · priced by the model"}
>
<Segmented<MixedMode> label="Restyle" value={mode} onChange={setMode} options={MODE_OPTIONS.filter((o) => MIXED_MODES[engine].includes(o.value))} />
</Field>
@@ -654,7 +644,7 @@ function Editor({
{model && (
<p className="text-[12px] leading-snug text-muted-foreground">
{smooth
- ? `Fuobe Original: the first frame takes the look, then every frame follows it${cloud ? ", at 720p" : visitor ? " (480p, 16 fps)" : " (480p, 16 fps on your GPU)"}.`
+ ? `Fuobe Original: the first frame takes the look, then every frame follows it${cloud ? ", at 720p" : " (480p, 16 fps on your GPU)"}.`
: original
? "Fuobe Original: every frame drawn again in the look, along its own outlines."
: plainTagline(model.tagline)}
@@ -665,7 +655,7 @@ function Editor({
<div className="space-y-2 rounded-xl border p-3">
<div className="flex items-center justify-between gap-2">
<span className="text-[13px] font-medium">Preview frame</span>
- <span className="font-mono text-[12px] text-muted-foreground tabular-nums">Preview costs: {est ? costText({ costUsd: est.previewUsd, demo: est.demo }, engine, visitor) : "—"}</span>
+ <span className="font-mono text-[12px] text-muted-foreground tabular-nums">Preview costs: {est ? costText({ costUsd: est.previewUsd, demo: est.demo }, engine) : "—"}</span>
</div>
<p className="text-[12px] text-muted-foreground">Generate one frame with your current settings before creating the full video.</p>
{preview && (
@@ -699,7 +689,7 @@ function Editor({
<button
type="button"
onClick={makePreview}
- disabled={previewBusy || visitor}
+ disabled={previewBusy}
aria-disabled={!!blocker || previewBusy}
className={cn(
"flex h-9 w-full items-center justify-center gap-2 rounded-full border text-[13px] font-medium",
@@ -729,7 +719,7 @@ function Editor({
</span>
<span className="flex items-center gap-1.5 font-mono text-[13px] font-medium tabular-nums" aria-live="polite">
{estimate.isFetching && <Loader2 className="size-3 animate-spin text-muted-foreground" />}
- {body ? costText(est, engine, visitor) : "—"}
+ {body ? costText(est, engine) : "—"}
</span>
</div>
{frameMode && cloud && est && !est.demo && typeof est.perFrameUsd === "number" && (
@@ -752,7 +742,7 @@ function Editor({
<button
type="button"
onClick={generate}
- disabled={actions.render.isPending || visitor}
+ disabled={actions.render.isPending}
aria-disabled={!!blocker || actions.render.isPending}
aria-describedby={blocker ? "mm-blocker" : undefined}
className={cn(
diff --git a/src/components/model3d/model-card.tsx b/src/components/model3d/model-card.tsx
index 321c5526..b7f1fcd1 100644
--- a/src/components/model3d/model-card.tsx
+++ b/src/components/model3d/model-card.tsx
@@ -5,7 +5,7 @@ import Link from "next/link";
import { createElement, useCallback, useEffect, useEffectEvent, useRef, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
-import { uploadFile, useEngine, useHydrated, useIsOwner, useModelAccess } from "@/lib/api";
+import { uploadFile, useAskBeforeUpload, useEngine, useHydrated, useIsOwner, useModelAccess } from "@/lib/api";
import { offered } from "@/lib/model-access";
import { FINAL_3D, RETEXTURE_MODELS, animateSpinHref, animationName, finalBuildHref, FRONT_YAW, model3dView, photorealAngle, photorealBody, stillOf, turnOrbit, type Model3dView } from "@/lib/av/model3d";
import { anyAngleHref } from "@/lib/catalog/any-angle";
@@ -139,8 +139,10 @@ export function ModelCard({
const [filming, setFilming] = useState<number | null>(null);
const pendingFilm = useRef(false);
const photorealStand = engine === "open" ? "/api/files/placeholder.mp4" : undefined;
- // Filmed by this studio's own worker (WorldCast), so the owner's only.
- const photoreal = owner ? photorealBody(view, engine, photorealStand, drawn) : null;
+ // A signed-in account's is filmed on its own GPU or its own key (never the studio's WorldCast worker); a guest is asked
+ // to sign up first.
+ const photoreal = photorealBody(view, engine, photorealStand, drawn);
+ const askFirst = useAskBeforeUpload();
const fly = useFlyAround(photoreal && !view.rigged && (view.glb || view.turntable) ? photoreal : null);
// Retexture's cloud models, where this viewer may run one (an account's own key runs only the ones checked live).
const access = useModelAccess();
@@ -227,6 +229,7 @@ export function ModelCard({
setShow("3d");
};
const film = () => {
+ if (askFirst("run")) return;
if (engine === "cloud" || !view.glb) {
const body = photorealBody(view, engine, engine === "open" ? view.turntable : undefined, drawn);
if (body) fly.run.mutate(body, { onSuccess: () => void toast.success("Filming the photoreal orbit — it shows up with your 3D models") });
@@ -236,7 +239,7 @@ export function ModelCard({
pendingFilm.current = true;
setShow("3d");
};
- const canFilm = owner && !!photoreal && !view.rigged && (engine === "cloud" || (view.glb ? canRecord && !failed : !!view.turntable));
+ const canFilm = !!photoreal && !view.rigged && (engine === "cloud" || (view.glb ? canRecord && !failed : !!view.turntable));
const filmBusy = filming !== null || fly.run.isPending;
const spin = view.rigged ? null : animateSpinHref(view, recorded?.saved);
// Draft then final (idol-6): an Idol 3D splat's picture, rebuilt as a textured mesh with TRELLIS.2.
diff --git a/src/components/remove-object/hooks.ts b/src/components/remove-object/hooks.ts
index e7802142..de631fab 100644
--- a/src/components/remove-object/hooks.ts
+++ b/src/components/remove-object/hooks.ts
@@ -6,6 +6,7 @@ import type { RemoveMode } from "@/lib/catalog/remove-object";
import type { Engine, Generation, PixelPoint } from "@/lib/catalog/types";
import { useDebounced } from "@/components/faceless/hooks";
import { send } from "@/components/shorts/hooks";
+import { COMPUTER_KICK_EVENT } from "@/lib/api";
/** React Query hooks for /api/remove-object/** (the Remove object tab of Video tools). */
@@ -57,6 +58,12 @@ export function useRemovalEstimate(body: RemovalBody | null) {
});
}
+/**
+ * A run started: the tab that runs this person's jobs on the ComfyUI on this computer (an account's "Your GPU") asks for
+ * them at once, as after a studio run.
+ */
+const kick = () => window.dispatchEvent(new Event(COMPUTER_KICK_EVENT));
+
export function useRemovalActions() {
const qc = useQueryClient();
const seed = (g: Generation) => qc.setQueryData(["generation", g.id], g);
@@ -64,6 +71,7 @@ export function useRemovalActions() {
run: useMutation({
mutationFn: (b: RemovalBody) => send<{ final: Generation; items: Generation[] }>("/api/remove-object", "POST", b),
onSuccess: (r) => {
+ kick();
r.items.forEach(seed);
void qc.invalidateQueries({ queryKey: ["generations"] });
},
@@ -71,13 +79,17 @@ export function useRemovalActions() {
reroll: useMutation({
mutationFn: (b: { id: string; window: number; seed?: number; requestId?: string }) => send<{ final: Generation; items: Generation[] }>("/api/remove-object/reroll", "POST", b),
onSuccess: (r) => {
+ kick();
r.items.forEach(seed);
void qc.invalidateQueries({ queryKey: ["generations"] });
},
}),
preview: useMutation({
mutationFn: (b: RemovalBody) => send<Generation>("/api/remove-object/preview", "POST", b),
- onSuccess: seed,
+ onSuccess: (g) => {
+ kick();
+ seed(g);
+ },
}),
};
}
diff --git a/src/components/remove-object/remove-object-tool.tsx b/src/components/remove-object/remove-object-tool.tsx
index 8431ac44..fe7eb6b1 100644
--- a/src/components/remove-object/remove-object-tool.tsx
+++ b/src/components/remove-object/remove-object-tool.tsx
@@ -13,7 +13,6 @@ import { Textarea } from "@/components/ui/textarea";
import { StepList, type StepRow } from "@/components/av/step-list";
import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";
import { useGeneration, useGenerationList } from "@/components/av/use-generation";
-import { SelfHostNote } from "@/components/self-host-note";
import { useSubmitGuard } from "@/components/shorts/hooks";
import { ClipBar, ClipDrop, costText, Field, Segmented } from "@/components/shorts/ui";
import { clipDuration, clipSize, useSourceClip } from "@/components/shorts/use-source-clip";
@@ -21,7 +20,7 @@ import { Feed } from "@/components/studio/feed";
import { radioKeys, radioTab } from "@/components/studio/radio-keys";
import { SketchEditor, type Stroke } from "@/components/studio/sketch-editor";
import { VideoTrimmer, type TrimRange, type VideoTrimmerHandle } from "@/components/studio/video-trimmer";
-import { useEngine, useGenerations, useLikelyVisitor, useModelAccess, useSoundLive } from "@/lib/api";
+import { useEngine, useGenerations, useModelAccess, useSoundLive } from "@/lib/api";
import {
CLICK_OPEN_PROBLEM,
chooseEraser,
@@ -86,9 +85,6 @@ const personInUrl = () => new URLSearchParams(window.location.search).get("perso
export function RemoveObjectTool({ person = false }: { person?: boolean } = {}) {
const [engine, setEngine, engineMode] = useEngine();
- // Removing an object doesn't run on an account's own GPU or key yet (only the studios' generations do): said up front,
- // and the upload, the mask preview and Remove are off, instead of a run the server refuses.
- const visitor = useLikelyVisitor();
const access = useModelAccess();
const source = useSourceClip(REMOVE.maxBytes);
const clip = source.clip;
@@ -255,8 +251,7 @@ export function RemoveObjectTool({ person = false }: { person?: boolean } = {})
: estimate.isError
? (estimate.error as Error).message
: null;
- const toolName = personAsked ? "Remove a person" : "Remove object";
- const blocker = visitor ? `${toolName} isn't available here` : setupBlocker;
+ const blocker = setupBlocker;
const start = () => {
if (blocker || !body) return void toast(blocker ?? "Not ready yet", { id: "remove-blocker" });
@@ -272,7 +267,7 @@ export function RemoveObjectTool({ person = false }: { person?: boolean } = {})
const canPreview = !!body && est?.previewUsd != null;
const makePreview = () => {
- if (visitor || !body || !canPreview || !est) return;
+ if (!body || !canPreview || !est) return;
const of = { exact: est.previewExact, eraser: est.modelName, green: est.previewGreen };
void previewGuard(JSON.stringify(body), (requestId) => actions.preview.mutateAsync({ ...body, requestId }))
.then((g) => g && setPreviewOf({ id: g.id, ...of }))
@@ -281,25 +276,22 @@ export function RemoveObjectTool({ person = false }: { person?: boolean } = {})
const preview = useGeneration(previewOf?.id ?? null).data;
return (
- <ToolShell title="Video tools" wide selfHostedOnly>
+ <ToolShell title="Video tools" wide>
{!clip && (
<ToolHero
title={personAsked ? "Remove a person from a video" : "Remove anything from a video"}
subtitle={
personAsked
- ? `Name who goes, check their green mask, and the scene is rebuilt behind them — redo any part that comes out weak${visitor ? "." : ", free on your own ComfyUI."}`
- : `Type what goes, click it, or paint over it — the gap is filled frame by frame and the sound stays${visitor ? "." : ", free on your own ComfyUI."}`
+ ? `Name who goes, check their green mask, and the scene is rebuilt behind them — redo any part that comes out weak, free on your own ComfyUI.`
+ : `Type what goes, click it, or paint over it — the gap is filled frame by frame and the sound stays, free on your own ComfyUI.`
}
- >
- {visitor && <SelfHostNote className="mt-3 max-w-xl">{toolName} isn&apos;t available here.</SelfHostNote>}
- </ToolHero>
+ />
)}
<div className={cn("mx-auto", clip ? "pt-4" : "mt-8 max-w-[640px]")}>
{!clip ? (
<ClipDrop
accept={REMOVE.accept}
limits={LIMITS}
- disabled={visitor}
onFile={(f) => {
const err = source.pick(f);
if (err) toast.error(err);
@@ -534,11 +526,11 @@ export function RemoveObjectTool({ person = false }: { person?: boolean } = {})
<div className="space-y-3 border-t pt-3">
{body && est?.previewUsd != null && (
<div className="flex items-center gap-2">
- <Button variant="outline" size="sm" className="rounded-full" onClick={makePreview} disabled={actions.preview.isPending || (preview && (preview.status === "queued" || preview.status === "running")) || visitor}>
+ <Button variant="outline" size="sm" className="rounded-full" onClick={makePreview} disabled={actions.preview.isPending || (preview && (preview.status === "queued" || preview.status === "running"))}>
{actions.preview.isPending ? <Loader2 className="size-3.5 animate-spin" /> : <Eye className="size-3.5" />} {est.previewGreen ? "Check the green mask" : "Preview the mask"}
</Button>
<span className="min-w-0 text-[12px] leading-snug text-muted-foreground">
- first {REMOVE.previewSeconds} s · {est.demo ? "demo" : engine === "open" ? (visitor ? "not available here" : "free") : costText({ costUsd: est.previewUsd, demo: false }, "cloud")}
+ first {REMOVE.previewSeconds} s · {est.demo ? "demo" : engine === "open" ? "free" : costText({ costUsd: est.previewUsd, demo: false }, "cloud")}
{!est.previewExact && ` · how SAM 3.1 reads it — ${est.modelName} finds the object itself`}
</span>
</div>
@@ -550,7 +542,7 @@ export function RemoveObjectTool({ person = false }: { person?: boolean } = {})
) : (
<>
<p className="flex items-center gap-1.5 text-[15px] font-semibold tabular-nums">
- {costText(est, engine, visitor)}
+ {costText(est, engine)}
{estimate.isFetching && <Loader2 className="size-3 animate-spin text-muted-foreground" aria-label="Updating the price" />}
</p>
{est && (
@@ -561,7 +553,7 @@ export function RemoveObjectTool({ person = false }: { person?: boolean } = {})
</>
)}
</div>
- <Button className="rounded-full" onClick={start} disabled={!!blocker || actions.run.isPending || visitor}>
+ <Button className="rounded-full" onClick={start} disabled={!!blocker || actions.run.isPending}>
{actions.run.isPending ? <Loader2 className="size-4 animate-spin" /> : <EraserIcon className="size-4" />} Remove it
</Button>
</div>
diff --git a/src/components/turnaround/turnaround-dialog.tsx b/src/components/turnaround/turnaround-dialog.tsx
index 7d7248c6..25360693 100644
--- a/src/components/turnaround/turnaround-dialog.tsx
+++ b/src/components/turnaround/turnaround-dialog.tsx
@@ -13,7 +13,7 @@ import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } f
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Progress } from "@/components/ui/progress";
import { Switch } from "@/components/ui/switch";
-import { useEngine, useGenerations, useLikelyVisitor } from "@/lib/api";
+import { COMPUTER_KICK_EVENT, useEngine, useGenerations, useLikelyVisitor } from "@/lib/api";
import { SOUL_ID_COPY } from "@/lib/catalog/training";
import {
FILL_NAMES,
@@ -215,6 +215,8 @@ function TurnaroundForm({ pictures, name, realPerson: realDefault = false, eleme
onRun ? { items: await onRun(b) } : post<{ items: Generation[]; filmId: string }>("/api/turnaround", { ...b, requestId }),
// The film: the one the server names, else the joined clips, else the one video the run makes (drawn pictures are stills).
onSuccess: ({ items, filmId }) => {
+ // The tab that runs this person's jobs on the ComfyUI on this computer (an account's "Your GPU") asks for them at once.
+ window.dispatchEvent(new Event(COMPUTER_KICK_EVENT));
const front = (p?.route ?? route) === "stills" ? p?.frames.find((f) => f.side === "front")?.url : undefined;
onStarted({ ids: items.map((g) => g.id), filmId: filmId ?? (items.find((g) => g.op === "concat") ?? items.find((g) => g.kind === "video") ?? items[0])?.id, ...(front && { front }) });
},
diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.ts
index 0dcfc2d1..821a9ac6 100644
--- a/src/lib/guest-access.ts
+++ b/src/lib/guest-access.ts
@@ -299,6 +299,14 @@ export const ACCOUNT_TOOL_RUNS: readonly RegExp[] = [
/^\/api\/cinema\/projects\/[^/]+\/(generate|items\/[^/]+\/(retry|finish))$/,
// The photo apps: Photodump, Fashion Factory, Character Sheet, AI Influencer, and a retry of its own photo.
/^\/api\/(photodump(\/(fashion|character|retry))?|influencer)$/,
+ // Video tools: Remove object (a mask preview, and "Redo from here" on its own removal), Evolution (its direction is
+ // Fuobe's offline writer's), Mixed Media (a preview frame, and "Try again" on its own render), Turnaround video and
+ // Fly around (Image to 3D's "Film it photoreal"), and Katana (a retry or Run again of its own run).
+ /^\/api\/remove-object(\/(preview|reroll))?$/,
+ /^\/api\/evolution(\/direction)?$/,
+ /^\/api\/mixed-media(\/(preview|retry))?$/,
+ /^\/api\/(turnaround|fly-around)$/,
+ /^\/api\/katana(\/[^/]+\/retry)?$/,
];
/**
@@ -320,6 +328,9 @@ export const ACCOUNT_PROJECT_ROUTES: RegExp[] = [
/^\/api\/starters\/cinema\.[^/]+$/,
// Photodump and Fashion Factory: its own packs and its own characters (src/server/photodump.ts).
/^\/api\/photodump\/(packs|characters)(\/[^/]+)?$/,
+ // Katana: its own runs (the list, one run, forgetting one), and how far its own Mixed Media render's frames are.
+ /^\/api\/katana(\/[^/]+)?$/,
+ /^\/api\/mixed-media\/progress$/,
];
export const accountProjectRoute = (pathname: string): boolean => ACCOUNT_PROJECT_ROUTES.some((r) => r.test(pathname));
diff --git a/src/lib/hubs.ts b/src/lib/hubs.ts
index b1ee6e47..a1294c2e 100644
--- a/src/lib/hubs.ts
+++ b/src/lib/hubs.ts
@@ -50,10 +50,10 @@ export const HUB_MODES: Record<HubKind, HubMode[]> = {
"video-tools": [
{ id: "matte", label: "Remove background" },
{ id: "green-screen", label: "Green screen" },
- { id: "remove-object", label: "Remove object", selfHostedOnly: true },
+ { id: "remove-object", label: "Remove object" },
{ id: "remove-dialogue", label: "Remove dialogue", selfHostedOnly: true },
- { id: "remove-person", label: "Remove a person", ownerOnly: true, selfHostedOnly: true },
- { id: "evolution", label: "Evolution", selfHostedOnly: true },
+ { id: "remove-person", label: "Remove a person" },
+ { id: "evolution", label: "Evolution" },
{ id: "restore", label: "Restore & colourise", ownerOnly: true, selfHostedOnly: true },
{ id: "relight", label: "Relight" },
{ id: "depth", label: "Depth map" },
diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.ts
index 2c184fd6..5f60db3a 100644
--- a/src/lib/output-actions.ts
+++ b/src/lib/output-actions.ts
@@ -116,7 +116,7 @@ export interface ActionContext {
export const draftRenderPaid = (placeholders: boolean | undefined): string => (placeholders ? "" : " · paid");
/** Hand-offs to tools a guest or an account can't open (they run on a self-hosted Fuobe only). */
-const OWNER_ONLY_ACTIONS: ReadonlySet<OutputActionId> = new Set<OutputActionId>(["restore-video", "remove-dialogue", "remove-person", "clean-dialogue", "edit-speech"]);
+const OWNER_ONLY_ACTIONS: ReadonlySet<OutputActionId> = new Set<OutputActionId>(["restore-video", "remove-dialogue", "clean-dialogue", "edit-speech"]);
const q = (url: string) => encodeURIComponent(url);
diff --git a/src/server/evolution.ts b/src/server/evolution.ts
index 2f9f6576..4ea967a0 100644
--- a/src/server/evolution.ts
+++ b/src/server/evolution.ts
@@ -19,7 +19,7 @@ import {
type Intensity,
} from "@/lib/catalog/evolution";
import { SHORTS, vaceDownsample, type PlanStep } from "@/lib/catalog/shorts";
-import type { Engine, Generation } from "@/lib/catalog/types";
+import type { Engine, Generation, GenerationRequest } from "@/lib/catalog/types";
import { ACCESS_PLACE } from "@/lib/model-access";
import { createPipeline } from "./chains";
import { llmText, llmTextBackend } from "./enhance";
@@ -29,6 +29,7 @@ import { probeOllama } from "./providers/llm";
import { engineMode, getSetting } from "./settings";
import { probeSource, ShortsError } from "./shorts";
import { readRef } from "./storage";
+import { tenantAccount } from "./tenant";
/**
* Video tools → Evolution (Fuobe Evolution, build plan O13): plans, prices and starts a run (src/lib/catalog/evolution.ts)
@@ -138,6 +139,9 @@ export async function writeDirection(body: z.infer<typeof DirectionSchema>): Pro
mustMatchMode(body.engine);
if (body.references.length > EVOLUTION.maxReferences) throw new ShortsError(`Use up to ${EVOLUTION.maxReferences} references`, 422);
const offline = (why: string): DirectionAnswer => ({ direction: offlineDirection({ intensity: body.intensity as Intensity, idea: body.idea, references: body.references.length }), by: "offline", why });
+ // A signed-in account's direction is Fuobe's offline writer's: never this studio's AI helper (its LLM or its key), and
+ // no word about the studio's setup.
+ if (tenantAccount()) return { direction: offline("").direction, by: "offline" };
if (getSetting("demoMode") === "on") return offline("demo mode");
const textModel = getModel(body.engine === "open" ? "oss-text-llm" : "text-llm");
if (!textModel || !offeredModel(textModel)) return offline(`the text model is switched off in ${ACCESS_PLACE}`);
@@ -267,8 +271,36 @@ export function estimateEvolution(body: z.infer<typeof EvolutionEstimateSchema>)
};
}
+/** A planned run: its steps, the key of the finished video's step, and the direction it uses. Nothing is created yet. */
+export interface EvolutionRun {
+ steps: PlanStep[];
+ final: string;
+ direction: string;
+ by: DirectionAnswer["by"] | "you";
+}
+
+/** A planned run's steps as the requests they make, with how many earlier steps each waits for (account-tool-run.ts). */
+export const evolutionSteps = (r: EvolutionRun): { request: GenerationRequest; deps: number }[] => r.steps.map((s) => ({ request: withChain(s), deps: s.after?.length ?? 0 }));
+
+/** Start a planned run; returns the finished video's generation, every step and the direction used. */
+export function startEvolution(r: EvolutionRun): { final: Generation; items: Generation[]; direction: string; by: DirectionAnswer["by"] | "you" } {
+ let p: ReturnType<typeof createPipeline>;
+ try {
+ p = createPipeline(r.steps);
+ } catch (e) {
+ if (e instanceof ConnectComfyError) throw e;
+ throw new ShortsError((e as Error).message, 422);
+ }
+ return { final: p.byKey[r.final], items: p.items, direction: r.direction, by: r.by };
+}
+
/** Start the run; a run with no direction gets one written first. Returns the finished video's generation and the direction used. */
export async function createEvolution(body: z.infer<typeof EvolutionBodySchema>): Promise<{ final: Generation; items: Generation[]; direction: string; by: DirectionAnswer["by"] | "you" }> {
+ return startEvolution(await planEvolutionRun(body));
+}
+
+/** Plan the run (the clip's header is read, a direction written when none is given); nothing is created. */
+export async function planEvolutionRun(body: z.infer<typeof EvolutionBodySchema>): Promise<EvolutionRun> {
mustMatchMode(body.engine);
mustBeOffered(body.engine);
if (body.resolution && !EVOLUTION_RESOLUTIONS[body.engine].includes(body.resolution)) throw new ShortsError(`Pick ${resolutionChoices(body.engine)}`, 422);
@@ -284,12 +316,5 @@ export async function createEvolution(body: z.infer<typeof EvolutionBodySchema>)
}
const { input } = planInput(body, info, direction, true);
const plan = planEvolution(input);
- let p: ReturnType<typeof createPipeline>;
- try {
- p = createPipeline(plan.steps);
- } catch (e) {
- if (e instanceof ConnectComfyError) throw e;
- throw new ShortsError((e as Error).message, 422);
- }
- return { final: p.byKey[plan.final], items: p.items, direction, by };
+ return { steps: plan.steps, final: plan.final, direction, by };
}
diff --git a/src/server/fly-around.ts b/src/server/fly-around.ts
index e0f03b64..e587a6bf 100644
--- a/src/server/fly-around.ts
+++ b/src/server/fly-around.ts
@@ -4,7 +4,7 @@ import { z } from "zod";
import { DISTANCE, MAX_KEYS } from "@/lib/camera-path";
import { EXACT_LIMITS } from "@/lib/exact-orbit";
import { FLY_VIEWS_MAX, planFlyAround, type FlyAroundInput, type FlyAroundPlan, type FlyStep } from "@/lib/catalog/fly-around";
-import type { Generation } from "@/lib/catalog/types";
+import type { Generation, GenerationRequest } from "@/lib/catalog/types";
import { cancelGeneration, createGenerations, previewChained, previewGeneration } from "./generations";
import { isOffered } from "./model-access";
import { worldcastDepths } from "./worldcast";
@@ -155,9 +155,28 @@ export interface FlyAroundResult {
/** Plan, check every step, then run them. */
export function createFlyAround(input: FlyAroundInput): FlyAroundResult {
+ return startFlyAround(planFlyAroundRun(input));
+}
+
+/** A planned fly-around: its steps and its priced preview. Nothing is created yet. */
+export interface FlyAroundRun {
+ steps: FlyStep[];
+ preview: FlyAroundPreview;
+}
+
+/** Plan and check every step (nothing is created); a blocker is a FlyAroundError. */
+export function planFlyAroundRun(input: FlyAroundInput): FlyAroundRun {
const preview = previewFlyAround(input);
if (preview.blocker) throw new FlyAroundError(preview.blocker);
+ return { steps: plan(input).steps, preview };
+}
+
+/** A planned fly-around's steps as the requests they make, with how many earlier steps each waits for (account-tool-run.ts). */
+export const flyAroundSteps = (r: FlyAroundRun): { request: GenerationRequest; deps: number }[] => r.steps.map((s) => ({ request: s.request, deps: s.after?.length ?? 0 }));
+
+/** Start a planned fly-around as one batch, the film first. */
+export function startFlyAround(r: FlyAroundRun): FlyAroundResult {
const batchId = nanoid(10);
- const items = runFlySteps(plan(input).steps, batchId);
- return { final: items[0], items, batchId, plan: preview };
+ const items = runFlySteps(r.steps, batchId);
+ return { final: items[0], items, batchId, plan: r.preview };
}
diff --git a/src/server/katana.ts b/src/server/katana.ts
index 4ec7b564..226ad44d 100644
--- a/src/server/katana.ts
+++ b/src/server/katana.ts
@@ -2,22 +2,37 @@ import "server-only";
import { nanoid } from "nanoid";
import { z } from "zod";
import type { PlannedJob } from "@/lib/assist";
-import { finalKey, KATANA_FEATURE, KATANA_LIMITS, katanaSteps, katanaStage, motionModel, MOTION_MODELS, planSegments, currentMotionModel, stepsToRedo, type KatanaInput, type KatanaJob, type KatanaJobView, type Segment } from "@/lib/av/katana";
+import { finalKey, KATANA_FEATURE, KATANA_LIMITS, katanaSteps, katanaStage, motionModel, MOTION_MODELS, planSegments, currentMotionModel, stepsToRedo, type KatanaInput, type KatanaJob, type KatanaJobView, type KatanaStep, type Segment } from "@/lib/av/katana";
import { getModel } from "@/lib/catalog";
-import type { Engine, Generation } from "@/lib/catalog/types";
+import type { Engine, Generation, GenerationRequest } from "@/lib/catalog/types";
+import { ACCOUNT_PROJECT_LIMITS, createAccountProject, deleteAccountProject, getAccountProject, listAccountProjects, updateAccountProject, type AccountProject } from "./account-projects";
import { createPipeline } from "./chains";
import { db } from "./db";
import { cancelGeneration, createGenerations, getGeneration, previewChained } from "./generations";
import { firstOn } from "./model-access";
import { engineMode } from "./settings";
+import { ShortsError } from "./shorts";
import { storedMedia } from "./storage";
+import { tenantAccount } from "./tenant";
/**
* Katana jobs: a reference edit rebuilt with your subject (src/lib/av/katana.ts plans it). The steps
* are chained generations in one batch; the job row keeps what was asked and which generation makes
* each step, so the studio and Assist can follow it.
+ *
+ * The owner's jobs are rows of katana_jobs. A signed-in account's (public sign-up) are its own projects of kind "katana"
+ * (account-projects.ts), read and changed only inside its own work (asAccount): another account's job, or the owner's,
+ * reads as not found, and the owner's list never has an account's. They go when the account is deleted.
*/
+/** An account's jobs, in the account project store. */
+const KIND = "katana";
+
+/** What an account's job keeps: the job without its id and times (the project row has them). */
+type KatanaData = Omit<KatanaJob, "id" | "createdAt" | "updatedAt">;
+
+const fromProject = (p: AccountProject<KatanaData>): KatanaJob => ({ ...p.data, id: p.id, createdAt: p.createdAt, updatedAt: p.updatedAt });
+
interface Row {
id: string;
data_json: string;
@@ -37,12 +52,26 @@ function view(j: KatanaJob): KatanaJobView {
}
export function getKatana(id: string): KatanaJobView | null {
+ const account = tenantAccount();
+ if (account) {
+ const p = getAccountProject<KatanaData>(account, KIND, id);
+ return p ? view(fromProject(p)) : null;
+ }
const r = db().prepare("SELECT * FROM katana_jobs WHERE id = ?").get(id) as Row | undefined;
return r ? view(toJob(r)) : null;
}
export function listKatana(limit = 20): KatanaJobView[] {
- const rows = db().prepare("SELECT * FROM katana_jobs ORDER BY updated_at DESC LIMIT ?").all(Math.max(1, Math.min(100, limit))) as Row[];
+ const n = Math.max(1, Math.min(100, limit));
+ const account = tenantAccount();
+ if (account) {
+ return listAccountProjects(account, KIND)
+ .slice(0, n)
+ .map((s) => getAccountProject<KatanaData>(account, KIND, s.id))
+ .filter((p): p is AccountProject<KatanaData> => !!p)
+ .map((p) => view(fromProject(p)));
+ }
+ const rows = db().prepare("SELECT * FROM katana_jobs ORDER BY updated_at DESC LIMIT ?").all(n) as Row[];
return rows.map((r) => view(toJob(r)));
}
@@ -57,6 +86,8 @@ function stopUnfinished(ids: string[]): void {
export function deleteKatana(id: string): boolean {
const j = getKatana(id);
if (j) stopUnfinished(Object.values(j.steps));
+ const account = tenantAccount();
+ if (account) return deleteAccountProject(account, KIND, id);
return db().prepare("DELETE FROM katana_jobs WHERE id = ?").run(id).changes > 0;
}
@@ -64,10 +95,18 @@ function saveJob(j: KatanaJob): KatanaJob {
const { id, createdAt, ...data } = j;
const now = Date.now();
delete (data as Partial<KatanaJob>).updatedAt;
+ const account = tenantAccount();
+ if (account) {
+ const saved = updateAccountProject(account, KIND, id, { data, summary: summaryOf(data) });
+ return { ...j, id, createdAt, updatedAt: saved?.updatedAt ?? now };
+ }
db().prepare("UPDATE katana_jobs SET data_json = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(data), now, id);
return { ...j, id, createdAt, updatedAt: now };
}
+/** An account's job's line in its list. */
+const summaryOf = (d: KatanaData) => ({ engine: d.engine, segments: d.segments.length });
+
const inputOf = (j: KatanaJob): KatanaInput => ({
engine: j.engine,
reference: j.reference,
@@ -80,11 +119,8 @@ const inputOf = (j: KatanaJob): KatanaInput => ({
title: j.title,
});
-/**
- * Retry a run whose steps failed: the failed steps and every step after them are made again (new
- * generations in the same batch, fed by the steps that did finish); nothing that succeeded is paid twice.
- */
-export function retryKatana(id: string): KatanaJobView {
+/** The steps a retry makes again: the failed ones and every step after them (in order), with the job. */
+function retryPlan(id: string): { j: Omit<KatanaJobView, "generations">; steps: KatanaStep[]; redo: string[] } {
const found = getKatana(id);
if (!found) throw new Error("This run no longer exists");
const { generations, ...j } = found;
@@ -96,7 +132,21 @@ export function retryKatana(id: string): KatanaJobView {
.map(([k]) => k);
if (!failed.length) throw new Error("No step failed — the run is done or still going");
const steps = katanaSteps(inputOf(j));
- const redo = stepsToRedo(steps, failed);
+ return { j, steps, redo: stepsToRedo(steps, failed) };
+}
+
+/** What a retry would make, as the requests it makes (account-tool-run.ts checks them before anything starts). */
+export function katanaRetrySteps(id: string): { request: GenerationRequest; deps: number }[] {
+ const { steps, redo } = retryPlan(id);
+ return redo.map((key) => toolStep(steps.find((x) => x.key === key)!));
+}
+
+/**
+ * Retry a run whose steps failed: the failed steps and every step after them are made again (new
+ * generations in the same batch, fed by the steps that did finish); nothing that succeeded is paid twice.
+ */
+export function retryKatana(id: string): KatanaJobView {
+ const { j, steps, redo } = retryPlan(id);
// Old steps downstream of the failure that are still waiting would fail anyway: stop them now.
stopUnfinished(redo.map((k) => j.steps[k]).filter(Boolean));
const ids = { ...j.steps };
@@ -120,10 +170,7 @@ export function retryKatana(id: string): KatanaJobView {
/** The same reference, photos and settings as a new run. */
export function rerunKatana(id: string): KatanaJobView {
- const j = getKatana(id);
- if (!j) throw new Error("This run no longer exists");
- const aspect = j.aspectRatio === "16:9" || j.aspectRatio === "9:16" || j.aspectRatio === "1:1" ? j.aspectRatio : undefined;
- return createKatana({ ...inputOf(j), aspectRatio: aspect, duration: j.segments.at(-1)?.end });
+ return createKatana(rerunBody(id));
}
const Seg = z.object({ start: z.number().min(0).max(KATANA_LIMITS.maxReference), end: z.number().min(0).max(KATANA_LIMITS.maxReference + 1) });
@@ -183,9 +230,39 @@ export function planKatana(body: KatanaRequest): { input: KatanaInput; engine: E
};
}
-export function createKatana(body: KatanaRequest): KatanaJobView {
+/** A step as the request it makes, with how many earlier steps it waits for. */
+const toolStep = (s: KatanaStep): { request: GenerationRequest; deps: number } => ({ request: s.chain ? { ...s.request, chain: s.chain } : s.request, deps: [s.after ?? []].flat().length });
+
+/** A planned run (nothing is created yet): its input, engine and steps. */
+export interface KatanaRun {
+ input: KatanaInput;
+ engine: Engine;
+ steps: KatanaStep[];
+}
+
+/** Plan a run: its segments and steps, validated (reads the reference's header only). */
+export function planKatanaRun(body: KatanaRequest): KatanaRun {
const { input, engine } = planKatana(body);
- const steps = katanaSteps(input);
+ return { input, engine, steps: katanaSteps(input) };
+}
+
+/** A planned run's steps as the requests they make (account-tool-run.ts). */
+export const katanaRunSteps = (r: KatanaRun) => r.steps.map(toolStep);
+
+/** The same reference, photos and settings as a new run's request (Run again). */
+export function rerunBody(id: string): KatanaRequest {
+ const j = getKatana(id);
+ if (!j) throw new Error("This run no longer exists");
+ const aspect = j.aspectRatio === "16:9" || j.aspectRatio === "9:16" || j.aspectRatio === "1:1" ? j.aspectRatio : undefined;
+ return { ...inputOf(j), aspectRatio: aspect, duration: j.segments.at(-1)?.end };
+}
+
+export function createKatana(body: KatanaRequest): KatanaJobView {
+ return startKatana(planKatanaRun(body));
+}
+
+/** Start a planned run and keep its job (the owner's row, or the account's own project). */
+export function startKatana({ input, engine, steps }: KatanaRun): KatanaJobView {
const run = createPipeline(steps, {});
const now = Date.now();
const job: KatanaJob = {
@@ -206,6 +283,16 @@ export function createKatana(body: KatanaRequest): KatanaJobView {
updatedAt: now,
};
const { id, createdAt, updatedAt, ...data } = job;
+ const account = tenantAccount();
+ if (account) {
+ try {
+ return view(fromProject(createAccountProject<KatanaData>(account, KIND, { name: data.title, data, summary: summaryOf(data) })));
+ } catch (e) {
+ // Kept no job: the steps just made are stopped (nothing more is spent).
+ stopUnfinished(Object.values(job.steps));
+ throw e;
+ }
+ }
db().prepare("INSERT INTO katana_jobs (id, data_json, created_at, updated_at) VALUES (?, ?, ?, ?)").run(id, JSON.stringify(data), createdAt, updatedAt);
return view(job);
}
@@ -283,3 +370,13 @@ export const katanaTool = {
};
export { KATANA_FEATURE, katanaStage };
+
+/**
+ * An account keeps its Katana runs as its own projects: room for one more, checked before anything is made (a
+ * ShortsError, 409, when it has as many as it may keep).
+ */
+export function katanaRoom(accountId: string): void {
+ if (listAccountProjects(accountId, KIND).length >= ACCOUNT_PROJECT_LIMITS.projects) {
+ throw new ShortsError(`You can keep up to ${ACCOUNT_PROJECT_LIMITS.projects} Katana runs. Delete one to make another.`, 409);
+ }
+}
diff --git a/src/server/mixed-media.ts b/src/server/mixed-media.ts
index fdb6a412..56fc3a8e 100644
--- a/src/server/mixed-media.ts
+++ b/src/server/mixed-media.ts
@@ -29,7 +29,8 @@ import {
import { mixedLoras } from "@/lib/catalog/mixed-media-looks";
import { clipLengthProblem, originalSegmentProblem, planSegments, type PlanStep } from "@/lib/catalog/shorts";
import { sourceSeconds, takesImage } from "@/lib/catalog/shorts-models";
-import type { Engine, Generation, ProviderId } from "@/lib/catalog/types";
+import type { Engine, Generation, GenerationRequest, ProviderId } from "@/lib/catalog/types";
+import { generationAccount } from "./account-library";
import { createPipeline } from "./chains";
import { db } from "./db";
import { ConnectComfyError, DROPPED_UNUSED, getGeneration, previewChained, unfilledRequest, waitedOnFailure } from "./generations";
@@ -37,6 +38,7 @@ import { withoutMissingOnComfy, withoutUnreachableCivitai } from "./loras";
import { comfyLoraFiles, probeComfy } from "./providers/comfyui";
import { engineMode, getSetting } from "./settings";
import { probeSource, ShortsError } from "./shorts";
+import { tenantAccount } from "./tenant";
/**
* Mixed Media renders and preview frames. No table of its own: every render is a pipeline of
@@ -171,7 +173,9 @@ async function planInput(body: MixedBody, opts: { probe: boolean }): Promise<{ i
let reach = original && mode !== "fast" ? withoutUnreachableCivitai(mixedLoras(preset.id), body.engine === "open" ? "comfyui" : "fal") : undefined;
// On your GPU without a LoRA folder (Settings → LoRAs) Fuobe can't download one, so ComfyUI must have it already: a LoRA
// it doesn't list is left out and said here, rather than the render failing once it's handed over.
- if (reach?.loras.length && body.engine === "open" && !getSetting("comfyLorasDir") && (await probeComfy())) {
+ // An account's own ComfyUI is asked when its run is checked (account-tool-run.ts: the LoRAs it lacks, before anything
+ // is queued), never on a price check.
+ if (reach?.loras.length && body.engine === "open" && !tenantAccount() && !getSetting("comfyLorasDir") && (await probeComfy())) {
const onComfy = withoutMissingOnComfy(reach.loras, await comfyLoraFiles());
reach = { loras: onComfy.loras, notes: [...reach.notes, ...onComfy.notes] };
}
@@ -275,14 +279,44 @@ function run(steps: PlanStep[], opts: { existing?: Record<string, string> } = {}
/** What the page follows of a render: every step but the per-frame edits (their count instead). */
const followed = (p: { items: Generation[] }) => ({ items: p.items.filter((g) => g.feature !== MIXED_FRAME_FEATURE), frames: p.items.filter((g) => g.feature === MIXED_FRAME_FEATURE).length });
-/** Start the full render; returns the finished video's generation (the others wait for it). */
-export async function createMixed(body: MixedBody): Promise<{ final: Generation; items: Generation[]; frames: number }> {
+/** A planned render (or retry, or preview frame): its steps and the finished video's key. Nothing is created yet. */
+export interface MixedRun {
+ steps: PlanStep[];
+ final: string;
+ /** A retry: the steps it keeps (their ids), and the waiting steps it stops once the new ones are made. */
+ existing?: Record<string, string>;
+ stop?: string[];
+}
+
+/** A planned run's steps as the requests they make, with how many earlier steps each waits for (account-tool-run.ts). */
+export const mixedSteps = (r: MixedRun): { request: GenerationRequest; deps: number }[] => r.steps.map((s) => ({ request: withChain(s), deps: s.after?.length ?? 0 }));
+
+/** Start a planned render or retry; returns the finished video's generation, the steps the page follows and the frame count. */
+export function startMixed(r: MixedRun): { final: Generation; items: Generation[]; frames: number } {
+ const p = run(r.steps, r.existing ? { existing: r.existing } : {});
+ // Old steps that would only fail after the ones they wait for: stop them (nothing was spent on them yet).
+ for (const id of r.stop ?? []) cancelWaiting(id);
+ return { final: p.byKey[r.final], ...followed(p) };
+}
+
+/** Plan the full render (the clip's header is read; nothing is created). */
+export async function planMixedRun(body: MixedBody): Promise<MixedRun> {
const { input } = await planInput(body, { probe: true });
const plan = planMixed(input);
- const p = run(plan.steps);
- return { final: p.byKey[plan.final], ...followed(p) };
+ return { steps: plan.steps, final: plan.final };
+}
+
+/** Start the full render; returns the finished video's generation (the others wait for it). */
+export async function createMixed(body: MixedBody): Promise<{ final: Generation; items: Generation[]; frames: number }> {
+ return startMixed(await planMixedRun(body));
}
+/**
+ * Whether this render is the asker's own: an account's own run, or the owner's when the owner asks (an account's render
+ * reads as gone to anyone else).
+ */
+const ownRender = (id: string) => (generationAccount(id) ?? null) === (tenantAccount() ?? null);
+
interface StepRow {
id: string;
feature: string;
@@ -324,8 +358,13 @@ function renderSteps(finalId: string): StepRow[] | null {
* running, which aren't made or paid for again. A render with nothing failed is made again from its first step.
*/
export function retryMixed(id: string): { final: Generation; items: Generation[]; frames: number } {
+ return startMixed(planMixedRetry(id));
+}
+
+/** Plan a retry (nothing is created): the steps made anew, the ones kept and the waiting ones to stop. */
+export function planMixedRetry(id: string): MixedRun {
const final = getGeneration(id);
- if (!final || final.feature !== MIXED_FEATURE) throw new ShortsError("This render no longer exists", 404);
+ if (!final || final.feature !== MIXED_FEATURE || !ownRender(id)) throw new ShortsError("This render no longer exists", 404);
const mode = engineMode();
if (mode !== "both" && mode !== final.engine) {
throw new ShortsError(mode === "open" ? "This install runs open-source models only (Settings → Engine mode)" : "This install runs cloud models only (Settings → Engine mode)", 422);
@@ -347,10 +386,7 @@ export function retryMixed(id: string): { final: Generation; items: Generation[]
for (const c of chain ?? []) if (c.slot !== "images" && c.slot !== "videos" && c.slot !== "audios" && c.slot !== "prompt") delete inputs[c.slot];
return { key: r.id, request: { ...request, inputs: Object.keys(inputs).length ? inputs : undefined }, ...(after.length ? { after, chain } : {}) };
});
- const p = run(steps, { existing });
- // Old steps that would only fail after the ones they wait for: stop them (nothing was spent on them yet).
- for (const r of again) if (r.status === "queued" && r.depends_on) cancelWaiting(r.id);
- return { final: p.byKey[id], ...followed(p) };
+ return { steps, final: id, existing, stop: again.filter((r) => r.status === "queued" && r.depends_on).map((r) => r.id) };
}
/** Stop a step still waiting for its inputs (nothing spent yet). */
@@ -374,6 +410,8 @@ export interface FramesProgress {
/** A per-frame render's frame edits at a glance (the page follows the main steps, not hundreds of frames), by its finished video's id. */
export function framesProgress(finalId: string): FramesProgress | null {
+ // Another's render reads as gone (an account's to the owner, the owner's or another account's to an account).
+ if (getGeneration(finalId) && !ownRender(finalId)) return null;
const rows = renderSteps(finalId);
if (!rows) return getGeneration(finalId) ? { total: 0, done: 0, running: 0 } : null;
const frames = rows.filter((r) => r.feature === MIXED_FRAME_FEATURE);
@@ -391,10 +429,15 @@ export function framesProgress(finalId: string): FramesProgress | null {
return out;
}
-/** One frame with the current settings. */
-export async function createMixedPreview(body: MixedBody): Promise<Generation> {
+/** Plan one frame with the current settings (nothing is created). */
+export async function planMixedPreviewRun(body: MixedBody): Promise<MixedRun> {
const { input } = await planInput(body, { probe: true });
if (input.engine === "cloud" && !body.frameUrl?.startsWith("/api/files/")) throw new ShortsError("Couldn't grab a frame from this clip in the browser — generate the full video instead");
- const step = planMixedPreview({ ...input, frameUrl: body.frameUrl });
- return run([step]).byKey.preview;
+ return { steps: [planMixedPreview({ ...input, frameUrl: body.frameUrl })], final: "preview" };
+}
+
+/** One frame with the current settings. */
+export async function createMixedPreview(body: MixedBody): Promise<Generation> {
+ const r = await planMixedPreviewRun(body);
+ return run(r.steps).byKey[r.final];
}
diff --git a/src/server/remove-object.ts b/src/server/remove-object.ts
index 04260c1b..a57718b3 100644
--- a/src/server/remove-object.ts
+++ b/src/server/remove-object.ts
@@ -31,7 +31,8 @@ import {
reviewOfOutput,
} from "@/lib/catalog/remove-object";
import type { PlanStep } from "@/lib/catalog/shorts";
-import type { Engine, GenParams, Generation, PixelPoint } from "@/lib/catalog/types";
+import type { Engine, GenParams, Generation, GenerationRequest, PixelPoint } from "@/lib/catalog/types";
+import { generationAccount } from "./account-library";
import { createPipeline } from "./chains";
import { ConnectComfyError, getGeneration, previewChained } from "./generations";
import { db } from "./db";
@@ -41,6 +42,7 @@ import { decodePng } from "./png";
import { engineMode } from "./settings";
import { probeSource, ShortsError } from "./shorts";
import { readRef } from "./storage";
+import { tenantAccount } from "./tenant";
/**
* Video tools → Remove object: plans, prices and starts a removal (src/lib/catalog/remove-object.ts) as one
@@ -345,20 +347,44 @@ function run(steps: PlanStep[]) {
}
}
-/** Start the removal; returns the finished video's generation (the other steps wait for each other). */
-export async function createRemoval(body: RemovalBody): Promise<{ final: Generation; items: Generation[] }> {
+/** A planned run: its steps and the key of the one that makes the finished video. Nothing is created yet. */
+export interface RemovalRun {
+ steps: PlanStep[];
+ final: string;
+}
+
+/** A planned run's steps as the requests they make, with how many earlier steps each waits for (account-tool-run.ts). */
+export const removalSteps = (r: RemovalRun): { request: GenerationRequest; deps: number }[] => r.steps.map((s) => ({ request: withChain(s), deps: s.after?.length ?? 0 }));
+
+/** Start a planned run; returns the finished video's generation and every step. */
+export function startRemoval(r: RemovalRun): { final: Generation; items: Generation[] } {
+ const p = run(r.steps);
+ return { final: p.byKey[r.final], items: p.items };
+}
+
+/** Plan a removal (the clip's header and the paint are read; nothing is created). */
+export async function planRemovalRun(body: RemovalBody): Promise<RemovalRun> {
const { input } = await planInput(body, { probe: true });
const plan = planRemoval(input);
- const p = run(plan.steps);
- return { final: p.byKey[plan.final], items: p.items };
+ return { steps: plan.steps, final: plan.final };
}
-/** A mask preview of the first seconds: what the engine would remove. */
-export async function createRemovalPreview(body: RemovalBody): Promise<Generation> {
+/** Start the removal; returns the finished video's generation (the other steps wait for each other). */
+export async function createRemoval(body: RemovalBody): Promise<{ final: Generation; items: Generation[] }> {
+ return startRemoval(await planRemovalRun(body));
+}
+
+/** Plan a mask preview of the first seconds (nothing is created). */
+export async function planRemovalPreview(body: RemovalBody): Promise<RemovalRun> {
const { input } = await planInput(body, { probe: true, preview: true });
const steps = planMaskPreview(input);
if (!steps) throw new ShortsError(input.engine === "open" ? "The open engine previews masks of what you type — your paint is the preview here" : "Name, click or paint what to remove first", 422);
- return run(steps).byKey.preview;
+ return { steps, final: "preview" };
+}
+
+/** A mask preview of the first seconds: what the engine would remove. */
+export async function createRemovalPreview(body: RemovalBody): Promise<Generation> {
+ return startRemoval(await planRemovalPreview(body)).final;
}
// ---------------------------------------------------------------------------
@@ -412,8 +438,17 @@ function askedAgain<T extends object>(request: T): T {
* after it continue from it; then the clip's sound goes back on as before. Returns the new finished video.
*/
export async function createRemovalReroll(body: RerollBody): Promise<{ final: Generation; items: Generation[] }> {
+ return startRemoval(planRemovalReroll(body));
+}
+
+/**
+ * Plan "Redo from here" (nothing is created). The removal must be the asker's own: an account's own run, or the owner's
+ * when the owner asks; anyone else's reads as not found.
+ */
+export function planRemovalReroll(body: RerollBody): RemovalRun {
const erase = getGeneration(body.id);
if (!erase || (erase.feature !== REMOVE.feature && erase.feature !== REMOVE.stepFeature)) throw new ShortsError(NOT_FOUND, 404);
+ if ((generationAccount(erase.id) ?? null) !== (tenantAccount() ?? null)) throw new ShortsError(NOT_FOUND, 404);
if (!getEraserCleanFrame(erase.modelId)) throw new ShortsError("Only an H3 person removal can be redone from a window", 422);
if (erase.status !== "succeeded") throw new ShortsError("Wait for the removal to finish first", 409);
mustMatchMode("open");
@@ -469,8 +504,7 @@ export async function createRemovalReroll(body: RerollBody): Promise<{ final: Ge
chain: cut ? [{ slot: "video" }, { slot: "audio" }] : [{ slot: "video" }],
});
}
- const p = run(steps);
- return { final: p.byKey[mux ? "final" : "erase0"], items: p.items };
+ return { steps, final: mux ? "final" : "erase0" };
}
const getEraserCleanFrame = (modelId: string) => !!chooseEraserById(modelId)?.cleanFrame;
diff --git a/src/server/turnaround.ts b/src/server/turnaround.ts
index e7787a1d..9e80bf83 100644
--- a/src/server/turnaround.ts
+++ b/src/server/turnaround.ts
@@ -4,7 +4,7 @@ import { z } from "zod";
import { getModel } from "@/lib/catalog";
import { routesFor } from "@/lib/catalog/plan";
import { planTurnaround, routeOfModel, type TurnaroundContext, type TurnaroundInput, type TurnaroundPlan, type TurnaroundPreview, type TurnStep } from "@/lib/catalog/turnaround";
-import type { Generation } from "@/lib/catalog/types";
+import type { Generation, GenerationRequest } from "@/lib/catalog/types";
import { needsConsent } from "@/lib/catalog/training";
import { getElement } from "./elements";
import { cancelGeneration, createGenerations, previewChained, previewGeneration } from "./generations";
@@ -201,6 +201,17 @@ export interface TurnaroundResult {
* when it was confirmed (GenerationRequest.consentAt; the training's time for a character trained with it).
*/
export function createTurnaround(input: TurnaroundRequest): TurnaroundResult {
+ return startTurnaround(planTurnaroundRun(input));
+}
+
+/** A planned turnaround: its steps (consent recorded) and its priced preview. Nothing is created yet. */
+export interface TurnaroundRun {
+ steps: TurnStep[];
+ preview: TurnaroundPreview;
+}
+
+/** Plan and check every step (nothing is created); a blocker is a TurnaroundError. */
+export function planTurnaroundRun(input: TurnaroundRequest): TurnaroundRun {
const preview = previewTurnaround(input);
if (preview.blocker) throw new TurnaroundError(preview.blocker);
const plan = planTurnaround(input, turnaroundContext());
@@ -208,7 +219,15 @@ export function createTurnaround(input: TurnaroundRequest): TurnaroundResult {
const consentAt = input.consent ? Date.now() : input.consentOnFile;
for (const s of plan.steps) s.request.consentAt = consentAt;
}
+ return { steps: plan.steps, preview };
+}
+
+/** A planned turnaround's steps as the requests they make, with how many earlier steps each waits for (account-tool-run.ts). */
+export const turnaroundSteps = (r: TurnaroundRun): { request: GenerationRequest; deps: number }[] => r.steps.map((s) => ({ request: s.request, deps: s.after?.length ?? 0 }));
+
+/** Start a planned turnaround as one batch, the film first. */
+export function startTurnaround(r: TurnaroundRun): TurnaroundResult {
const batchId = nanoid(10);
- const items = runTurnaroundSteps(plan.steps, batchId);
- return { final: items[0], items, filmId: items[0].id, batchId, plan: preview };
+ const items = runTurnaroundSteps(r.steps, batchId);
+ return { final: items[0], items, filmId: items[0].id, batchId, plan: r.preview };
}
diff --git a/tests/account-video-tools.test.ts b/tests/account-video-tools.test.ts
new file mode 100644
index 00000000..9b419fb6
--- /dev/null
+++ b/tests/account-video-tools.test.ts
@@ -0,0 +1,491 @@
+import fs from "node:fs";
+import path from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { NextRequest } from "next/server";
+import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";
+import { tempDir } from "./helpers/temp-dir";
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+/**
+ * Video tools for a signed-in account (public sign-up): Remove object (and Remove a person), Evolution, Mixed Media,
+ * Turnaround video, Fly around and Katana run on the account's own ComfyUI (a stand-in here) through the same generations
+ * every studio run makes, with only its own files, and their runs (and Katana's jobs) stay its own. A guest gets the
+ * sign-up card; another account, the owner's library, the studio's ComfyUI and its AI helper are never reached.
+ */
+const dir = tempDir("fuobe-account-video-tools-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";
+process.env.OLLAMA_URL = "http://owner-llm.test:11434";
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_ALLOW_PRIVATE_URLS;
+delete process.env.FUOBE_HOSTED_RUNS;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+// Plain fetch is the install's own ComfyUI, its LLM or anything else: recorded, so a test sees that nothing reached them.
+const realFetch = globalThis.fetch;
+const fetched: string[] = [];
+globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = new URL(String(input instanceof Request ? input.url : input));
+ if (url.hostname === "127.0.0.1") return realFetch(input, init);
+ fetched.push(url.toString());
+ if (url.host !== "owner-comfy.test:8188") return new Response("not stubbed", { status: 599 });
+ if (url.pathname === "/system_stats") return Response.json({ system: { comfyui_version: "owner", ram_total: 1 }, devices: [] });
+ return Response.json({});
+}) as typeof fetch;
+
+const auth = await import("@/server/auth");
+const removeRoute = await import("@/app/api/remove-object/route");
+const removePreviewRoute = await import("@/app/api/remove-object/preview/route");
+const rerollRoute = await import("@/app/api/remove-object/reroll/route");
+const removeEstimateRoute = await import("@/app/api/remove-object/estimate/route");
+const evolutionRoute = await import("@/app/api/evolution/route");
+const directionRoute = await import("@/app/api/evolution/direction/route");
+const evolutionEstimateRoute = await import("@/app/api/evolution/estimate/route");
+const mixedRoute = await import("@/app/api/mixed-media/route");
+const mixedPreviewRoute = await import("@/app/api/mixed-media/preview/route");
+const mixedRetryRoute = await import("@/app/api/mixed-media/retry/route");
+const mixedProgressRoute = await import("@/app/api/mixed-media/progress/route");
+const mixedEstimateRoute = await import("@/app/api/mixed-media/estimate/route");
+const turnaroundRoute = await import("@/app/api/turnaround/route");
+const flyRoute = await import("@/app/api/fly-around/route");
+const katanaRoute = await import("@/app/api/katana/route");
+const katanaOneRoute = await import("@/app/api/katana/[id]/route");
+const katanaRetryRoute = await import("@/app/api/katana/[id]/retry/route");
+const uploadsRoute = await import("@/app/api/uploads/route");
+const gpuRoute = await import("@/app/api/account/gpu/route");
+const { proxy } = await import("@/proxy");
+const access = await import("@/lib/guest-access");
+const { getGeneration } = await import("@/server/generations");
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const { clearAccountLoras } = await import("@/server/account-loras");
+const { saveFile } = await import("@/server/storage");
+const { runAsTenant } = await import("@/server/tenant");
+const { ACCOUNT_LIMITS } = await import("@/server/account-files");
+const { listAccountProjects } = await import("@/server/account-projects");
+const { listKatana } = await import("@/server/katana");
+const { purgeAccount } = await import("@/server/account-sweep");
+const { setSetting } = await import("@/server/settings");
+
+const CLIP = fs.readFileSync(path.join(__dirname, "fixtures/shorts-12s.mp4"));
+const src = { duration: 12, fps: 16, width: 72, height: 128, hasAudio: true };
+
+let fake: FakeComfy;
+let a = "";
+let b = "";
+let c = "";
+const cookies: Record<string, string> = {};
+beforeAll(async () => {
+ fake = await startFakeComfy({ loras: [], delayMs: 0 });
+ globalThis.__fuobeTestGpuPort = fake.port;
+ auth.setPassword("install password");
+ // The owner's AI helper is set up: an account's run must still never use it.
+ setSetting("enhanceProvider", "ollama");
+ for (const [k, email] of [
+ ["a", "[email protected]"],
+ ["b", "[email protected]"],
+ ["c", "[email protected]"],
+ ] as const) {
+ const id = auth.createAccount(email, "long enough").id;
+ cookies[k] = `${auth.SESSION_COOKIE}=${auth.createSession(id).value}`;
+ if (k === "a") a = id;
+ if (k === "b") b = id;
+ if (k === "c") c = id;
+ }
+ cookies.owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;
+ // A and B link their own ComfyUI; C has neither a GPU nor a key.
+ for (const who of ["a", "b"]) expect((await gpuRoute.PUT(json("/api/account/gpu", "PUT", { url: fake.url }, who))).status).toBe(200);
+});
+afterAll(async () => {
+ globalThis.fetch = realFetch;
+ globalThis.__fuobeTestGpuPort = undefined;
+ globalThis.__fuobeTestDiskFree = undefined;
+ await fake.close();
+});
+beforeEach(() => {
+ resetRates();
+ for (const id of [a, b]) clearAccountLoras(id);
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running') AND json_extract(request_json, '$.account') IS NOT NULL").run();
+});
+
+function json(url: string, method: string, body: unknown, who?: string): Request {
+ const text = JSON.stringify(body);
+ return new Request(`http://localhost:3000${url}`, {
+ method,
+ headers: { host: "localhost:3000", "content-type": "application/json", "content-length": String(Buffer.byteLength(text)), ...(who && { cookie: cookies[who] }) },
+ body: text,
+ });
+}
+const get = (url: string, who?: string) => new Request(`http://localhost:3000${url}`, { headers: { host: "localhost:3000", ...(who && { cookie: cookies[who] }) } });
+const del = (url: string, who?: string) => new Request(`http://localhost:3000${url}`, { method: "DELETE", headers: { host: "localhost:3000", ...(who && { cookie: cookies[who] }) } });
+const params = <T,>(p: T) => ({ params: Promise.resolve(p) }) as never;
+
+const viaProxy = (url: string, method = "GET", who?: string) =>
+ proxy(new NextRequest(`http://localhost:3000${url}`, { method, headers: { host: "localhost:3000", ...(who && { cookie: cookies[who] }), ...(method !== "GET" && { "content-type": "application/json" }) }, ...(method !== "GET" && { body: "{}" }) }));
+const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";
+
+async function upload(who: string, data: Buffer, type: string, name: string): Promise<string> {
+ const r = await uploadsRoute.POST(new Request("http://localhost:3000/api/uploads", { method: "POST", headers: { host: "localhost:3000", cookie: cookies[who], "content-type": type, "x-file-name": name, "content-length": String(data.length) }, body: new Uint8Array(data) }));
+ expect(r.status, await r.clone().text()).toBe(201);
+ return ((await r.json()) as { url: string }).url;
+}
+
+/** Tick the runner until the row is done (or the time is up). */
+async function settle(id: string, ms = 30_000) {
+ const end = Date.now() + ms;
+ for (;;) {
+ await globalThis.__fuobeRunner?.tick();
+ const g = getGeneration(id, { includeDeleted: true });
+ if (!g || (g.status !== "queued" && g.status !== "running") || Date.now() > end) return g;
+ await new Promise((r) => setTimeout(r, 100));
+ }
+}
+
+/**
+ * What the studio reads of its own ComfyUI and AI helper to say whether they answer (their status, read by every run's
+ * model switches): never a job or a call to them.
+ */
+const notStatus = (u: string) => !/\/(system_stats|api\/tags)$/.test(u);
+
+type Run = { final: { id: string }; items: { id: string; batchId: string | null }[] };
+
+/** Send a run; a LoRA its ComfyUI lacks is put there (the 409 names it), then it is sent again. */
+async function start(send: () => Promise<Response>): Promise<Response> {
+ let r = await send();
+ if (r.status === 409) {
+ const j = (await r.clone().json()) as { code: string; fix?: { items: { file: string }[] } };
+ if (j.code === "comfy_missing_model" && j.fix) {
+ fake.opts.loras = [...(fake.opts.loras ?? []), ...j.fix.items.map((i) => i.file)];
+ for (const id of [a, b]) clearAccountLoras(id);
+ r = await send();
+ }
+ }
+ return r;
+}
+
+/**
+ * The run is the account's from end to end: one batch, every step stamped as its own and sent to its own ComfyUI,
+ * nothing reaching the studio's ComfyUI or its AI helper, and the result is its own file it can open.
+ */
+async function ranAsOwn(r: Response, who: "a" | "b", account: string): Promise<string> {
+ expect(r.status, await r.clone().text()).toBe(201);
+ const body = (await r.json()) as Run;
+ const final = body.final.id;
+ expect(new Set(body.items.map((g) => g.batchId)).size).toBe(1);
+ const batch = body.items[0].batchId;
+ const steps = (db().prepare("SELECT id FROM generations WHERE batch_id IS ?").all(batch) as { id: string }[]).map((x) => x.id);
+ for (const id of steps) {
+ const g = getGeneration(id)!;
+ expect(g.request.account, id).toBe(account);
+ expect(g.provider, id).toBe("comfyui");
+ }
+ const done = await settle(final);
+ const why = steps.map((id) => getGeneration(id)!).map((g) => `${g.modelId} ${g.op} ${g.status} ${g.error ?? ""}`).join(" | ");
+ expect(done?.status, why).toBe("succeeded");
+ for (const id of steps) expect(getGeneration(id)!.status, id).toBe("succeeded");
+ // Every step went to its own ComfyUI; nothing reached the install's ComfyUI or AI helper.
+ expect(fake.log.filter((e) => e.path === "/prompt").length).toBeGreaterThanOrEqual(1);
+ expect(fetched.filter(notStatus), why).toEqual([]);
+ const out = done!.outputs[0];
+ expect(out.url).toMatch(/^\/api\/files\/outputs\//);
+ expect((db().prepare("SELECT account_id FROM assets WHERE id = ?").get(out.assetId) as { account_id: string }).account_id).toBe(account);
+ expect(passed(viaProxy(out.url, "GET", who))).toBe(true);
+ expect(passed(viaProxy(`/api/generations/${final}`, "GET", who))).toBe(true);
+ return final;
+}
+
+const RUNS = [
+ "/api/remove-object",
+ "/api/remove-object/preview",
+ "/api/remove-object/reroll",
+ "/api/evolution",
+ "/api/evolution/direction",
+ "/api/mixed-media",
+ "/api/mixed-media/preview",
+ "/api/mixed-media/retry",
+ "/api/turnaround",
+ "/api/fly-around",
+ "/api/katana",
+ "/api/katana/k1/retry",
+];
+
+describe("the proxy opens the video tools to accounts, and keeps the sign-up card for guests", () => {
+ it("a guest gets the sign-up card on every run; price checks stay open", async () => {
+ for (const p of RUNS) {
+ const r = viaProxy(p, "POST");
+ expect(r.status, p).toBe(401);
+ expect(r.headers.get(access.GUEST_HEADER), p).toBe("1");
+ expect((await r.json()).error, p).toBe(access.GUEST_RUN_MESSAGE);
+ }
+ for (const p of ["/api/remove-object/estimate", "/api/evolution/estimate", "/api/mixed-media/estimate", "/api/turnaround/estimate", "/api/turnaround?preview=1", "/api/fly-around?preview=1", "/api/katana?preview=1"]) {
+ expect(passed(viaProxy(p, "POST")), p).toBe(true);
+ }
+ // Its Katana list is empty; one run, forgetting one and a render's progress are closed.
+ const list = viaProxy("/api/katana", "GET");
+ expect(await list.json()).toEqual({ items: [] });
+ expect(viaProxy("/api/katana/k1", "GET").status).toBe(401);
+ expect(viaProxy("/api/katana/k1", "DELETE").status).toBe(401);
+ expect(viaProxy("/api/mixed-media/progress?id=x", "GET").status).toBe(401);
+ });
+
+ it("an account with its own GPU reaches every route; one with neither a GPU nor a key is asked to connect one", async () => {
+ for (const p of RUNS) {
+ expect(passed(viaProxy(p, "POST", "a")), p).toBe(true);
+ if (p === "/api/katana") continue;
+ const r = viaProxy(p, "POST", "c");
+ expect(r.status, p).toBe(403);
+ expect(r.headers.get(access.CONNECT_GPU_HEADER), p).toBe("1");
+ expect((await r.json()).code, p).toBe("connect-gpu");
+ }
+ // Katana's list, one run and forgetting one are its own (the routes answer with its own only).
+ for (const [p, m] of [
+ ["/api/katana", "GET"],
+ ["/api/katana/k1", "GET"],
+ ["/api/katana/k1", "DELETE"],
+ ["/api/mixed-media/progress", "GET"],
+ ] as const) {
+ expect(passed(viaProxy(p, m, "a")), `${m} ${p}`).toBe(true);
+ expect(passed(viaProxy(p, m, "c")), `${m} ${p}`).toBe(true);
+ }
+ });
+
+ it("the routes refuse a guest themselves", async () => {
+ for (const [route, p] of [
+ [removeRoute, "/api/remove-object"],
+ [removePreviewRoute, "/api/remove-object/preview"],
+ [rerollRoute, "/api/remove-object/reroll"],
+ [evolutionRoute, "/api/evolution"],
+ [directionRoute, "/api/evolution/direction"],
+ [mixedRoute, "/api/mixed-media"],
+ [mixedPreviewRoute, "/api/mixed-media/preview"],
+ [mixedRetryRoute, "/api/mixed-media/retry"],
+ [turnaroundRoute, "/api/turnaround"],
+ [flyRoute, "/api/fly-around"],
+ [katanaRoute, "/api/katana"],
+ ] as const) {
+ const r = await route.POST(json(p, "POST", {}));
+ expect(r.status, p).toBe(401);
+ expect(r.headers.get(access.GUEST_HEADER), p).toBe("1");
+ }
+ const retry = await katanaRetryRoute.POST(json("/api/katana/k1/retry", "POST", {}), params({ id: "k1" }));
+ expect(retry.status).toBe(401);
+ });
+});
+
+describe("an account runs the video tools on its own ComfyUI", () => {
+ let clip = "";
+ let pic = "";
+ let back = "";
+ beforeAll(async () => {
+ clip = await upload("a", CLIP, "video/mp4", "skate.mp4");
+ pic = await upload("a", TINY_PNG, "image/png", "me.png");
+ back = await upload("a", TINY_PNG, "image/png", "back.png");
+ });
+ beforeEach(() => {
+ fake.log.length = 0;
+ fetched.length = 0;
+ // Every step answers a clip and a picture (a cut keeps its first frame): each chained slot finds its kind.
+ fake.opts.output = "both";
+ });
+
+ const removal = (over: Record<string, unknown> = {}) => ({ engine: "open", mode: "type", prompt: "the skateboard", source: { url: clip, name: "skate.mp4", ...src }, range: { start: 0, end: 3 }, ...over });
+
+ it("prices each tool for its own GPU, never as a demo", async () => {
+ const r = await removeEstimateRoute.POST(json("/api/remove-object/estimate", "POST", removal(), "a"));
+ expect(r.status, await r.clone().text()).toBe(200);
+ expect((await r.json()).demo).toBe(false);
+ const e = await evolutionEstimateRoute.POST(json("/api/evolution/estimate", "POST", { engine: "open", source: { url: clip, ...src }, range: { start: 0, end: 6 } }, "a"));
+ expect(e.status, await e.clone().text()).toBe(200);
+ expect((await e.json()).demo).toBe(false);
+ const m = await mixedEstimateRoute.POST(json("/api/mixed-media/estimate", "POST", { engine: "open", presetId: "mixed-sketch", source: { url: clip, ...src }, range: { start: 0, end: 1 }, fps: 8, resolution: "1K" }, "a"));
+ expect(m.status, await m.clone().text()).toBe(200);
+ expect((await m.json()).demo).toBe(false);
+ });
+
+ it("removes an object end to end, and a second click with the same request id gets the same run", async () => {
+ const r = await start(() => removeRoute.POST(json("/api/remove-object", "POST", removal({ requestId: "remove-same-1" }), "a")));
+ const final = await ranAsOwn(r, "a", a);
+ const again = await removeRoute.POST(json("/api/remove-object", "POST", removal({ requestId: "remove-same-1" }), "a"));
+ expect(again.status).toBe(201);
+ expect(((await again.json()) as Run).final.id).toBe(final);
+ // Its history lists it (GET /api/generations is its own runs).
+ expect(passed(viaProxy("/api/generations?features=remove-object", "GET", "a"))).toBe(true);
+ // "Redo from here" takes only its own removal: B's and the owner's ask read as not found.
+ for (const who of ["b", "owner"] as const) {
+ const other = await rerollRoute.POST(json("/api/remove-object/reroll", "POST", { id: final, window: 0 }, who));
+ expect(other.status, who).toBe(404);
+ }
+ const own = await rerollRoute.POST(json("/api/remove-object/reroll", "POST", { id: final, window: 0 }, "a"));
+ expect(own.status).toBe(422);
+ expect((await own.json()).error).toMatch(/H3 person removal/);
+ });
+
+ it("evolves a clip end to end with Fuobe's offline writer, never the studio's AI helper", async () => {
+ const d = await directionRoute.POST(json("/api/evolution/direction", "POST", { engine: "open", intensity: "medium", idea: "paper cut", references: [pic] }, "a"));
+ expect(d.status, await d.clone().text()).toBe(200);
+ const said = (await d.json()) as { by: string; why?: string; direction: string };
+ expect(said.by).toBe("offline");
+ expect(said.why).toBeUndefined();
+ expect(said.direction.length).toBeGreaterThan(10);
+ const r = await start(() => evolutionRoute.POST(json("/api/evolution", "POST", { engine: "open", source: { url: clip, ...src }, range: { start: 0, end: 6 }, references: [pic] }, "a")));
+ const body = (await r.clone().json()) as { by: string };
+ expect(body.by).toBe("offline");
+ await ranAsOwn(r, "a", a);
+ });
+
+ it("renders Mixed Media end to end; its retry and progress take only its own render", async () => {
+ const body = { engine: "open", presetId: "mixed-sketch", source: { url: clip, ...src }, range: { start: 0, end: 1 }, fps: 4, resolution: "1K" };
+ const r = await start(() => mixedRoute.POST(json("/api/mixed-media", "POST", body, "a")));
+ const final = await ranAsOwn(r, "a", a);
+ const progress = await mixedProgressRoute.GET(get(`/api/mixed-media/progress?id=${final}`, "a"));
+ expect(progress.status).toBe(200);
+ for (const who of ["b", "owner"] as const) {
+ expect((await mixedProgressRoute.GET(get(`/api/mixed-media/progress?id=${final}`, who))).status, who).toBe(404);
+ expect((await mixedRetryRoute.POST(json("/api/mixed-media/retry", "POST", { id: final }, who))).status, who).toBe(404);
+ }
+ // Its own render runs again on its own ComfyUI.
+ const again = await start(() => mixedRetryRoute.POST(json("/api/mixed-media/retry", "POST", { id: final }, "a")));
+ expect(again.status, await again.clone().text()).toBe(201);
+ const made = (await again.json()) as Run;
+ for (const g of made.items) expect(getGeneration(g.id)!.request.account).toBe(a);
+ // A preview frame is its own too.
+ const p = await start(() => mixedPreviewRoute.POST(json("/api/mixed-media/preview", "POST", body, "a")));
+ expect(p.status, await p.clone().text()).toBe(201);
+ expect(getGeneration(((await p.json()) as { id: string }).id)!.request.account).toBe(a);
+ });
+
+ it("films a turnaround and a fly around end to end, never asking the studio's WorldCast worker", async () => {
+ const t = await start(() => turnaroundRoute.POST(json("/api/turnaround", "POST", { engine: "open", views: { front: pic, back }, name: "Ada" }, "a")));
+ await ranAsOwn(t, "a", a);
+ // A character from the owner's library is never found for an account.
+ const el = await turnaroundRoute.POST(json("/api/turnaround", "POST", { engine: "open", views: { front: pic }, elementId: "owner-character" }, "a"));
+ expect(el.status).toBe(404);
+ fake.log.length = 0;
+ const render = await upload("a", CLIP, "video/mp4", "orbit.mp4");
+ const f = await start(() => flyRoute.POST(json("/api/fly-around", "POST", { engine: "open", image: pic, render, orbit: { degrees: 90, direction: "cw" }, feature: "model3d-film", title: "Photoreal orbit" }, "a")));
+ await ranAsOwn(f, "a", a);
+ });
+
+ it("recreates an edit with Katana end to end; its jobs are its own projects", async () => {
+ const body = { engine: "open", reference: clip, photos: [pic], segments: [{ start: 0, end: 3 }], duration: 12, title: "My edit" };
+ const r = await start(() => katanaRoute.POST(json("/api/katana", "POST", body, "a")));
+ expect(r.status, await r.clone().text()).toBe(201);
+ const job = (await r.json()) as { id: string; steps: Record<string, string>; final: string };
+ const final = job.steps[job.final];
+ for (const id of Object.values(job.steps)) expect(getGeneration(id)!.request.account).toBe(a);
+ const done = await settle(final);
+ const why = Object.values(job.steps).map((id) => getGeneration(id)!).map((g) => `${g.modelId} ${g.op} ${g.status} ${g.error ?? ""}`).join(" | ");
+ expect(done?.status, why).toBe("succeeded");
+ expect(fetched.filter(notStatus)).toEqual([]);
+ // Its list and the job are its own; B and the owner never see it.
+ const mine = (await (await katanaRoute.GET(get("/api/katana", "a"))).json()) as { items: { id: string }[] };
+ expect(mine.items.map((j) => j.id)).toEqual([job.id]);
+ expect((await katanaOneRoute.GET(get(`/api/katana/${job.id}`, "a"), params({ id: job.id }))).status).toBe(200);
+ const theirs = (await (await katanaRoute.GET(get("/api/katana", "b"))).json()) as { items: unknown[] };
+ expect(theirs.items).toEqual([]);
+ expect(listKatana().map((j) => j.id)).not.toContain(job.id);
+ expect((await katanaOneRoute.GET(get(`/api/katana/${job.id}`, "b"), params({ id: job.id }))).status).toBe(404);
+ expect((await katanaOneRoute.GET(get(`/api/katana/${job.id}`, "owner"), params({ id: job.id }))).status).toBe(404);
+ expect((await katanaOneRoute.DELETE(del(`/api/katana/${job.id}`, "b"), params({ id: job.id }))).status).toBe(404);
+ expect((await katanaRetryRoute.POST(json(`/api/katana/${job.id}/retry?all=1`, "POST", {}, "b"), params({ id: job.id }))).status).toBe(404);
+ // The owner's job is never in reach of an account.
+ const t = Date.now();
+ db().prepare("INSERT INTO katana_jobs (id, data_json, created_at, updated_at) VALUES ('owner-job', ?, ?, ?)").run(JSON.stringify({ title: "Owner", steps: {}, segments: [], photos: [] }), t, t);
+ expect((await katanaOneRoute.GET(get("/api/katana/owner-job", "a"), params({ id: "owner-job" }))).status).toBe(404);
+ expect((await katanaOneRoute.DELETE(del("/api/katana/owner-job", "a"), params({ id: "owner-job" }))).status).toBe(404);
+ expect((db().prepare("SELECT COUNT(*) AS n FROM katana_jobs WHERE id = 'owner-job'").get() as { n: number }).n).toBe(1);
+ // Run again: a new job of its own, on its own ComfyUI.
+ const again = await start(() => katanaRetryRoute.POST(json(`/api/katana/${job.id}/retry?all=1`, "POST", {}, "a"), params({ id: job.id })));
+ expect(again.status, await again.clone().text()).toBe(201);
+ const second = (await again.json()) as { id: string; steps: Record<string, string> };
+ expect(second.id).not.toBe(job.id);
+ for (const id of Object.values(second.steps)) expect(getGeneration(id)!.request.account).toBe(a);
+ // Forgetting one is its own: gone from its list.
+ expect((await katanaOneRoute.DELETE(del(`/api/katana/${job.id}`, "a"), params({ id: job.id }))).status).toBe(204);
+ expect(listAccountProjects(a, "katana").map((p) => p.id)).toEqual([second.id]);
+ });
+
+ it("another account's files, the owner's files and links never go in", async () => {
+ const own = await upload("b", TINY_PNG, "image/png", "b.png");
+ const ownerClip = saveFile({ data: CLIP, contentType: "video/mp4", source: "upload", name: "owner.mp4" }).url;
+ const tries: [string, () => Promise<Response>][] = [
+ ["remove", () => removeRoute.POST(json("/api/remove-object", "POST", removal(), "b"))],
+ ["evolution", () => evolutionRoute.POST(json("/api/evolution", "POST", { engine: "open", source: { url: clip, ...src }, references: [own] }, "b"))],
+ ["mixed", () => mixedRoute.POST(json("/api/mixed-media", "POST", { engine: "open", presetId: "mixed-sketch", source: { url: clip, ...src }, range: { start: 0, end: 1 }, fps: 4, resolution: "1K" }, "b"))],
+ ["turnaround", () => turnaroundRoute.POST(json("/api/turnaround", "POST", { engine: "open", views: { front: pic } }, "b"))],
+ ["fly", () => flyRoute.POST(json("/api/fly-around", "POST", { engine: "open", image: pic, orbit: { degrees: 90, direction: "cw" } }, "b"))],
+ ["katana", () => katanaRoute.POST(json("/api/katana", "POST", { engine: "open", reference: clip, photos: [own], segments: [{ start: 0, end: 3 }], duration: 12 }, "b"))],
+ ["owner's clip", () => removeRoute.POST(json("/api/remove-object", "POST", removal({ source: { url: ownerClip, ...src } }), "a"))],
+ ];
+ fake.log.length = 0;
+ for (const [what, send] of tries) {
+ const r = await send();
+ expect(r.status, what).toBe(403);
+ expect((await r.json()).code, what).toBe("input-not-yours");
+ }
+ expect(fake.log.some((e) => e.path === "/prompt")).toBe(false);
+ const link = await removeRoute.POST(json("/api/remove-object", "POST", removal({ source: { url: "https://example.com/a.mp4" } }), "a"));
+ expect(link.status).toBe(400);
+ });
+
+ it("asks an account with neither a GPU nor a key to connect one, before anything is made", async () => {
+ const own = runAsTenant({ kind: "account", id: c }, () => saveFile({ data: CLIP, contentType: "video/mp4", source: "upload", name: "c.mp4" }).url);
+ const pc = runAsTenant({ kind: "account", id: c }, () => saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload", name: "c.png" }).url);
+ const n = (db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n;
+ for (const send of [
+ () => removeRoute.POST(json("/api/remove-object", "POST", removal({ source: { url: own, ...src } }), "c")),
+ () => evolutionRoute.POST(json("/api/evolution", "POST", { engine: "open", source: { url: own, ...src }, range: { start: 0, end: 6 }, direction: "A paper world." }, "c")),
+ () => katanaRoute.POST(json("/api/katana", "POST", { engine: "open", reference: own, photos: [pc], segments: [{ start: 0, end: 3 }], duration: 12 }, "c")),
+ () => flyRoute.POST(json("/api/fly-around", "POST", { engine: "open", image: pc, render: own, orbit: { degrees: 90, direction: "cw" } }, "c")),
+ ]) {
+ const r = await send();
+ expect(r.status, await r.clone().text()).toBe(403);
+ expect(r.headers.get(access.CONNECT_GPU_HEADER)).toBe("1");
+ expect((await r.json()).code).toBe("connect-gpu");
+ }
+ expect((db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n).toBe(n);
+ expect(listAccountProjects(c, "katana")).toEqual([]);
+ });
+
+ it("keeps the account's limits: runs going at once, and a body over what a run may weigh", async () => {
+ const now = Date.now();
+ const add = db().prepare(
+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'remove-object', 'oss-trim', 'open', 'comfyui', 'trim', 'video', 'queued', ?, '[]', ?, ?)",
+ );
+ for (let i = 0; i < ACCOUNT_LIMITS.activeRuns; i++) add.run(`busy-${i}`, JSON.stringify({ feature: "remove-object", modelId: "oss-trim", account: a }), now, now);
+ for (const send of [
+ () => removeRoute.POST(json("/api/remove-object", "POST", removal(), "a")),
+ () => katanaRoute.POST(json("/api/katana", "POST", { engine: "open", reference: clip, photos: [pic], segments: [{ start: 0, end: 3 }], duration: 12 }, "a")),
+ () => flyRoute.POST(json("/api/fly-around", "POST", { engine: "open", image: pic, orbit: { degrees: 90, direction: "cw" } }, "a")),
+ ]) {
+ const r = await send();
+ expect(r.status).toBe(429);
+ expect((await r.json()).code).toBe(access.ACTIVE_RUNS_CODE);
+ }
+ db().prepare("DELETE FROM generations WHERE id LIKE 'busy-%'").run();
+ const big = (p: string) =>
+ new Request(`http://localhost:3000${p}`, { method: "POST", headers: { host: "localhost:3000", cookie: cookies.a, "content-type": "application/json", "content-length": String(ACCOUNT_LIMITS.runBodyBytes + 1) }, body: "{}" });
+ for (const [route, p] of [
+ [removeRoute, "/api/remove-object"],
+ [evolutionRoute, "/api/evolution"],
+ [mixedRoute, "/api/mixed-media"],
+ [turnaroundRoute, "/api/turnaround"],
+ [flyRoute, "/api/fly-around"],
+ [katanaRoute, "/api/katana"],
+ ] as const) {
+ expect((await route.POST(big(p))).status, p).toBe(413);
+ }
+ });
+
+ it("an account's Katana runs go with the account", async () => {
+ const bClip = await upload("b", CLIP, "video/mp4", "b.mp4");
+ const bPic = await upload("b", TINY_PNG, "image/png", "b2.png");
+ const r = await start(() => katanaRoute.POST(json("/api/katana", "POST", { engine: "open", reference: bClip, photos: [bPic], segments: [{ start: 0, end: 3 }], duration: 12 }, "b")));
+ expect(r.status, await r.clone().text()).toBe(201);
+ expect(listAccountProjects(b, "katana")).toHaveLength(1);
+ await purgeAccount(b);
+ expect(listAccountProjects(b, "katana")).toEqual([]);
+ });
+});
diff --git a/tests/e2e/video-tools-accounts-live.mjs b/tests/e2e/video-tools-accounts-live.mjs
new file mode 100644
index 00000000..be8f728d
--- /dev/null
+++ b/tests/e2e/video-tools-accounts-live.mjs
@@ -0,0 +1,144 @@
+// Remove object, Remove a person, Evolution, Mixed Media, Turnaround video, Fly around and Katana for visitors (a studio
+// with a password and public sign-up, fuobe.com by default), through their routes and in a browser at phone and desktop
+// widths. A guest: the sign-up card on every run, the price checks open, an empty Katana list, no "isn't available here"
+// note, and the sign-up card when it chooses a clip. A signed-in account (a throwaway one this script makes and deletes):
+// its runs reach the routes (a bad request is a 400, nobody else's run or render is found), its own empty Katana list,
+// the pages' upload and run buttons on, and the connect card when it has neither a GPU nor a key.
+// No run is started (that needs the account's own GPU or key).
+// Usage: node tests/e2e/video-tools-accounts-live.mjs [appUrl] [--shots <dir>] Exits 1 on a failed check.
+import fs from "node:fs";
+import path from "node:path";
+import crypto from "node:crypto";
+import { launch } from "./_browser.mjs";
+
+const argv = process.argv.slice(2);
+const flag = (k) => (argv.includes(k) ? argv[argv.indexOf(k) + 1] : undefined);
+const app = (argv.find((a, i) => !a.startsWith("--") && argv[i - 1] !== "--shots") ?? "https://fuobe.com").replace(/\/$/, "");
+const shots = flag("--shots");
+if (shots) fs.mkdirSync(shots, { recursive: true });
+
+const failures = [];
+const check = (label, ok, extra = "") => {
+ console.log(`${ok ? "ok " : "FAIL"} ${label.padEnd(78)}${extra ? ` ${extra}` : ""}`);
+ if (!ok) failures.push(label);
+};
+
+const clip = { url: "/api/files/placeholder.mp4", duration: 12, fps: 24, width: 720, height: 1280, hasAudio: true };
+const PRICES = [
+ ["/api/remove-object/estimate", { engine: "open", mode: "type", prompt: "the cup", source: clip, range: { start: 0, end: 3 } }],
+ ["/api/evolution/estimate", { engine: "open", source: clip, range: { start: 0, end: 6 } }],
+ ["/api/mixed-media/estimate", { engine: "open", presetId: "mixed-sketch", source: clip, range: { start: 0, end: 2 }, fps: 8, resolution: "1K" }],
+ ["/api/turnaround?preview=1", { engine: "open", views: { front: "/api/files/placeholder.png" } }],
+ ["/api/fly-around?preview=1", { engine: "open", image: "/api/files/placeholder.png", orbit: { degrees: 90, direction: "cw" } }],
+];
+const RUNS = ["/api/remove-object", "/api/remove-object/preview", "/api/remove-object/reroll", "/api/evolution", "/api/evolution/direction", "/api/mixed-media", "/api/mixed-media/preview", "/api/mixed-media/retry", "/api/turnaround", "/api/fly-around", "/api/katana", "/api/katana/nope/retry"];
+
+/** The route checks, as a guest (`req`: a context's request, signed out) or as the account (signed in). */
+async function routes(req, who) {
+ const send = (method, p, data) => req.fetch(`${app}${p}`, { method, headers: { origin: app, "content-type": "application/json" }, ...(data !== undefined && { data }) });
+ const body = async (r) => r.json().catch(() => ({}));
+ for (const [p, data] of PRICES) {
+ const r = await send("POST", p, data);
+ const e = await body(r);
+ check(`${who}: the price check ${p.replace(/\?.*/, "")} works, never as a demo`, r.status() === 200 && e.demo === false, `${r.status()} ${JSON.stringify(e).slice(0, 80)}`);
+ }
+ const list = await send("GET", "/api/katana");
+ check(`${who}: its Katana list is empty`, list.status() === 200 && JSON.stringify(await body(list)) === '{"items":[]}', String(list.status()));
+ if (who === "guest") {
+ for (const p of RUNS) {
+ const r = await send("POST", p, {});
+ check(`guest: POST ${p} asks to sign up`, r.status() === 401 && r.headers()["x-fuobe-guest"] === "1", String(r.status()));
+ }
+ for (const [method, p] of [
+ ["GET", "/api/katana/nope"],
+ ["DELETE", "/api/katana/nope"],
+ ["GET", "/api/mixed-media/progress?id=nope"],
+ ]) {
+ const r = await send(method, p);
+ check(`guest: ${method} ${p} is closed`, r.status() === 401, String(r.status()));
+ }
+ return;
+ }
+ // The account with neither a GPU nor a key: a run is asked to connect one (the proxy, or the route's own checks).
+ for (const p of RUNS.filter((x) => x !== "/api/katana")) {
+ const r = await send("POST", p, {});
+ check(`account: POST ${p} asks to connect a GPU or key`, r.status() === 403 && (await body(r)).code === "connect-gpu", String(r.status()));
+ }
+ const bad = await send("POST", "/api/katana", {});
+ check("account: a Katana run reaches the route (a bad request is a 400)", bad.status() === 400, String(bad.status()));
+ for (const [method, p] of [
+ ["GET", "/api/katana/nope"],
+ ["DELETE", "/api/katana/nope"],
+ ["GET", "/api/mixed-media/progress?id=nope"],
+ ]) {
+ const r = await send(method, p);
+ check(`account: ${method} ${p} is not found`, r.status() === 404, String(r.status()));
+ }
+}
+
+const PAGES = [
+ ["remove-object", "/video-tools/remove-object", /Remove object isn't available here/, "Choose a video"],
+ ["remove-person", "/video-tools/remove-person", /Remove a person isn't available here/, "Choose a video"],
+ ["evolution", "/video-tools/evolution", /Evolution isn't available here/, "Choose a video"],
+ ["mixed-media", "/mixed-media", /Mixed Media isn't available here/, "Choose a video"],
+ ["katana", "/katana", /Katana isn't available here/, "Upload a video"],
+];
+
+const browser = await launch();
+const email = `video-ui-${crypto.randomBytes(5).toString("hex")}@example.com`;
+const password = crypto.randomBytes(18).toString("base64url");
+let signedUp = false;
+const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
+try {
+ const page = await context.newPage();
+ await routes(page.request, "guest");
+ const look = async (who) => {
+ for (const [width, height] of [
+ [1440, 1000],
+ [390, 844],
+ ]) {
+ await page.setViewportSize({ width, height });
+ for (const [name, url, note, choose] of PAGES) {
+ await page.goto(`${app}${url}`, { waitUntil: "load", timeout: 60_000 });
+ await page.waitForTimeout(2500);
+ const at = `${who} ${name} @${width}`;
+ check(`${at}: no "isn't available here" note`, (await page.getByText(note).count()) === 0);
+ check(`${at}: no price says "Not available here"`, (await page.getByText("Not available here").count()) === 0);
+ const scroll = await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);
+ check(`${at}: no sideways scroll`, scroll <= 1, String(scroll));
+ const button = page.getByRole("button", { name: choose });
+ check(`${at}: the clip drop is on`, (await button.count()) > 0 && (await button.first().isEnabled()));
+ if (shots) await page.screenshot({ path: path.join(shots, `${name}-${who}-${width}.png`) });
+ if (width !== 1440) continue;
+ // Choosing a clip asks first: the sign-up card for a guest, the connect card for an account with no GPU or key.
+ await button.first().click();
+ await page.waitForTimeout(1500);
+ const card = who === "guest" ? /Create a free account/ : /Connect your GPU|your own files/;
+ check(`${at}: choosing a clip opens the ${who === "guest" ? "sign-up" : "connect"} card`, (await page.getByText(card).count()) > 0);
+ await page.keyboard.press("Escape");
+ await page.waitForTimeout(400);
+ }
+ }
+ await page.setViewportSize({ width: 1440, height: 1000 });
+ };
+ await look("guest");
+
+ // A throwaway account (signed in in this browser), then the same checks.
+ const res = await page.request.post(`${app}/api/auth/signup`, { data: { email, password }, headers: { origin: app } });
+ signedUp = res.ok();
+ check("signed up a throwaway account", signedUp, String(res.status()));
+ if (signedUp) {
+ await routes(page.request, "account");
+ await look("account");
+ }
+} finally {
+ if (signedUp) {
+ const page = context.pages()[0];
+ const del = await page.request.delete(`${app}/api/auth/me`, { data: { password }, headers: { origin: app } });
+ console.log(`deleted the throwaway account: ${del.status()}`);
+ check("deleted the throwaway account", del.status() === 204, String(del.status()));
+ }
+ await browser.close();
+}
+console.log(failures.length ? `${failures.length} failed` : "all ok");
+process.exit(failures.length ? 1 : 0);
diff --git a/tests/nav-bar.test.ts b/tests/nav-bar.test.ts
index efd80a64..b90068f1 100644
--- a/tests/nav-bar.test.ts
+++ b/tests/nav-bar.test.ts
@@ -175,7 +175,7 @@ describe("the launcher's columns", () => {
expect(subs("genjutsu")).toEqual(["Motion transfer", "Character swap", "Object swap", "Restyle", "Insert", "From picture", "Finish"]);
expect(subs("upscale")).toEqual(["Image", "Video", "FPS Boost", "SDR to HDR", "Export"]);
expect(subs("audio")).toEqual(["Speech", "Dialogue", "Voice change", "See all 15"]);
- expect(subs("video-tools")).toEqual(["Relight", "Captions", "Remove object", "See all 11"]);
+ expect(subs("video-tools")).toEqual(["Relight", "Captions", "Remove object", "See all 12"]);
for (const w of ["Click to Ad", "Ads Studio", "Ad Multiplier", "Motion transfer", "FPS Boost"]) expect(words(html)).toContain(w);
// Under a hairline, quieter than a row, with no picture and no line of their own (nav-subs.css: 24 px
// names with a mouse, 44 px pills to tap on a touch screen).
diff --git a/tests/public-signup-tools.test.ts b/tests/public-signup-tools.test.ts
index b51ad8a9..9758e188 100644
--- a/tests/public-signup-tools.test.ts
+++ b/tests/public-signup-tools.test.ts
@@ -110,15 +110,15 @@ describe("the proxy: PR #15's routes as main treats their kind", () => {
process.env.FUOBE_PUBLIC_SIGNUP = "1";
for (const p of ["/api/turnaround/estimate", "/api/turnaround?preview=1", "/api/audio-tools?preview=1"]) expect(passed(proxy(req(p, { method: "POST" }))), p).toBe(true);
// Signing up wouldn't run these (an account's own GPU or key doesn't either): the account's answer, not the card.
- for (const p of ["/api/turnaround", "/api/audio-tools", "/api/katana", "/api/marketing/runs", "/api/layers/l1/jobs", "/api/layout/plan"]) {
+ for (const p of ["/api/audio-tools", "/api/marketing/runs", "/api/layers/l1/jobs", "/api/layout/plan"]) {
const r = proxy(req(p, { method: "POST" }));
expect(r.status, p).toBe(403);
expect(r.headers.get(access.GUEST_HEADER), p).toBeNull();
expect(await r.json(), p).toEqual({ error: access.OWN_GPU_TOOL_MESSAGE, code: "own-gpu-tool" });
}
- // The studios' runs, a tool an account runs on its own GPU (Shorts), an upload and a save to the library: signing up
- // is the next step there.
- for (const p of ["/api/generations", "/api/shorts/sessions", "/api/media/probe", "/api/audio-tools/export?offset=0", "/api/canvases"]) {
+ // The studios' runs, the tools an account runs on its own GPU (Shorts, Turnaround video, Katana), an upload and a save
+ // to the library: signing up is the next step there.
+ for (const p of ["/api/generations", "/api/shorts/sessions", "/api/turnaround", "/api/katana", "/api/media/probe", "/api/audio-tools/export?offset=0", "/api/canvases"]) {
const r = proxy(req(p, { method: "POST" }));
expect(r.status, p).toBe(401);
expect(r.headers.get(access.GUEST_HEADER), p).toBe("1");
@@ -130,7 +130,7 @@ describe("the proxy: PR #15's routes as main treats their kind", () => {
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);
- for (const p of ["/api/turnaround", "/api/audio-tools"]) {
+ for (const p of ["/api/audio-tools"]) {
const r = proxy(req(p, { method: "POST", cookie }));
expect(r.status, p).toBe(403);
expect(r.headers.get(access.CONNECT_GPU_HEADER), p).toBeNull();
@@ -146,7 +146,9 @@ describe("the proxy: PR #15's routes as main treats their kind", () => {
const cookie = auth.createSession(a.id).value;
auth.setAccountGpu(a.id, { url: "https://gpu.example" });
expect(passed(proxy(req("/api/generations", { method: "POST", cookie })))).toBe(true);
- for (const p of ["/api/turnaround", "/api/audio-tools", "/api/layout/plan"]) {
+ // Turnaround video runs on its own GPU too (tests/account-video-tools.test.ts).
+ expect(passed(proxy(req("/api/turnaround", { method: "POST", cookie })))).toBe(true);
+ for (const p of ["/api/audio-tools", "/api/layout/plan"]) {
const r = proxy(req(p, { method: "POST", cookie }));
expect(r.status, p).toBe(403);
expect(r.headers.get(access.CONNECT_GPU_HEADER), p).toBeNull();
@@ -165,19 +167,19 @@ describe("the proxy: PR #15's routes as main treats their kind", () => {
});
describe("Fly around under the sign-up rules", () => {
- it("opens its price check to guests and accounts, and answers its run with own-gpu-tool", async () => {
+ it("opens its price check to guests and accounts; an account runs it on its own GPU and a guest signs up first", async () => {
process.env.FUOBE_PUBLIC_SIGNUP = "1";
expect(access.isPriceCheck("POST", "/api/fly-around", "?preview=1")).toBe(true);
expect(access.isPriceCheck("POST", "/api/fly-around", "")).toBe(false);
const a = newAccount();
auth.setAccountGpu(a.id, { url: "https://gpu.example" });
const cookie = auth.createSession(a.id).value;
- for (const c of [undefined, cookie]) {
- expect(passed(proxy(req("/api/fly-around?preview=1", { method: "POST", cookie: c })))).toBe(true);
- const r = proxy(req("/api/fly-around", { method: "POST", cookie: c }));
- expect(r.status).toBe(403);
- expect((await r.json()).code).toBe("own-gpu-tool");
- }
+ for (const c of [undefined, cookie]) expect(passed(proxy(req("/api/fly-around?preview=1", { method: "POST", cookie: c })))).toBe(true);
+ // Its run goes to the route, which runs it on the account's own GPU or key (tests/account-video-tools.test.ts).
+ expect(passed(proxy(req("/api/fly-around", { method: "POST", cookie })))).toBe(true);
+ const guest = proxy(req("/api/fly-around", { method: "POST" }));
+ expect(guest.status).toBe(401);
+ expect(guest.headers.get(access.GUEST_HEADER)).toBe("1");
expect(passed(proxy(req("/api/fly-around", { method: "POST", cookie: auth.createSession().value })))).toBe(true);
});
diff --git a/tests/public-signup.test.ts b/tests/public-signup.test.ts
index 3ed29383..3f0be02f 100644
--- a/tests/public-signup.test.ts
+++ b/tests/public-signup.test.ts
@@ -220,7 +220,6 @@ describe("accounts never run on the owner's keys or GPU", () => {
for (const p of [
"/api/canvases/c1/run",
"/api/layers/l1/jobs",
- "/api/katana/k1/retry",
"/api/enhance",
"/api/brands/b1/chat",
"/api/faceless/episodes/e1/render",
@@ -230,9 +229,6 @@ describe("accounts never run on the owner's keys or GPU", () => {
// Restore & colourise: its run and its prompt writer.
"/api/restore",
"/api/restore/prompt",
- // Remove a person on H3: its mask preview and "Redo from here".
- "/api/remove-object/preview",
- "/api/remove-object/reroll",
// Plan layout plans with the studio's own AI helper.
"/api/layout/plan",
// Regenerate in Faceless and Shorts segments (n7-10): studio jobs, like their renders.
@@ -244,9 +240,17 @@ describe("accounts never run on the owner's keys or GPU", () => {
expect(r.headers.get(access.CONNECT_GPU_HEADER), p).toBeNull();
expect((await r.json()).code, p).toBe("own-gpu-tool");
}
- // Cinema Studio's takes run on its own GPU or key (tests/account-cinema.test.ts): with neither, connect one first. A
- // run route that ignores ?preview=1 isn't a price check.
- for (const p of ["/api/cinema/projects/p1/generate", "/api/cinema/projects/p1/generate?preview=1", "/api/cinema/projects/p1/items/g1/finish"]) {
+ // Cinema Studio's takes and the video tools (Remove a person's mask preview and "Redo from here", Katana's retry) run
+ // on its own GPU or key (tests/account-cinema.test.ts, tests/account-video-tools.test.ts): with neither, connect one
+ // first. A run route that ignores ?preview=1 isn't a price check.
+ for (const p of [
+ "/api/cinema/projects/p1/generate",
+ "/api/cinema/projects/p1/generate?preview=1",
+ "/api/cinema/projects/p1/items/g1/finish",
+ "/api/remove-object/preview",
+ "/api/remove-object/reroll",
+ "/api/katana/k1/retry",
+ ]) {
const r = proxy(req(p, { method: "POST", cookie }));
expect(r.status, p).toBe(403);
expect(r.headers.get(access.CONNECT_GPU_HEADER), p).toBe("1");
diff --git a/tests/regenerate-offered.test.ts b/tests/regenerate-offered.test.ts
index 1296933a..e3a2228c 100644
--- a/tests/regenerate-offered.test.ts
+++ b/tests/regenerate-offered.test.ts
@@ -88,17 +88,17 @@ describe("tools a guest or an account can't open", () => {
expect(ids(upload(), { visitor: true })).not.toContain("restore-video");
});
- it("leaves Remove a person and Clean up dialogue out of a visitor's result menus, and keeps them for the owner", () => {
+ it("leaves Clean up dialogue out of a visitor's result menus and keeps it for the owner; Remove a person is everyone's", () => {
// An uploaded clip gets both (a clip with sound).
expect(ids(upload())).toEqual(expect.arrayContaining(["remove-person", "clean-dialogue"]));
const visitor = ids(upload(), { visitor: true });
- expect(visitor).not.toContain("remove-person");
+ // An account runs Remove a person on its own GPU (tests/account-video-tools.test.ts); a guest signs up there.
+ expect(visitor).toContain("remove-person");
expect(visitor).not.toContain("clean-dialogue");
- expect(ids(gen(), { visitor: true })).not.toContain("remove-person");
});
- it("leaves Restore & colourise's and Remove a person's Video tools tabs out for a visitor: Remove dialogue's page says it isn't available here", () => {
+ it("leaves Restore & colourise's Video tools tab out for a visitor; Remove a person's tab is everyone's", () => {
const tabs = Object.fromEntries(HUB_MODES["video-tools"].map((m) => [m.id, m.ownerOnly ?? false]));
- expect(tabs).toMatchObject({ restore: true, "remove-person": true, "remove-dialogue": false, matte: false, evolution: false });
+ expect(tabs).toMatchObject({ restore: true, "remove-person": false, "remove-dialogue": false, matte: false, evolution: false, "remove-object": false });
});
});