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.

Apps: AI Influencer, Photodump, Fashion Factory, Character Sheet, Turnaround and Fly around run for accounts

Adarshbfdd2eba353a
diff --git a/src/app/api/fly-around/route.ts b/src/app/api/fly-around/route.ts
index f774a400..0623ec8c 100644
--- a/src/app/api/fly-around/route.ts
+++ b/src/app/api/fly-around/route.ts
@@ -1,25 +1,47 @@
+import { bodyTooBig, guestRun, toolViewer, toolWishes } from "@/server/account-tool-run";
import { body, handle, once } from "@/server/shorts-schemas";
import { createFlyAround, FlyAroundSchema, previewFlyAround } from "@/server/fly-around";
+import { bodyFiles, runToolForAccount, withPoolPrice } from "@/server/tool-runs";
import { priceAs } from "@/server/visitor";
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 with only its own pictures, after the checks every tool run gets
+ * (src/server/tool-runs.ts); a guest signs up first.
*/
async function post(request: Request) {
return handle(async () => {
+ const viewer = toolViewer(request);
+ const wishes = viewer.kind === "owner" ? {} : await toolWishes(request);
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();
- if (new URL(request.url).searchParams.get("preview")) return Response.json(previewFlyAround(input));
+ const start = () => createFlyAround(input);
+ if (new URL(request.url).searchParams.get("preview")) return Response.json(await withPoolPrice(request, previewFlyAround(input), start, wishes.place));
+ if (viewer.kind === "account") {
+ return runToolForAccount(request, viewer.account, {
+ tool: "fly-around",
+ files: bodyFiles(input),
+ requestId,
+ wishes,
+ start,
+ ok: (value, gpuWarning) => Response.json({ ...value, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),
+ });
+ }
// 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));
+ const result = await once("fly-around", requestId, start);
return Response.json(result, { 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). */
export async function POST(request: Request) {
+ const viewer = toolViewer(request);
+ const preview = !!new URL(request.url).searchParams.get("preview");
+ if (viewer.kind === "guest" && !preview) return guestRun();
+ if (viewer.kind === "account" && !preview) return bodyTooBig(request) ?? post(request);
return priceAs(request, () => post(request));
}
diff --git a/src/app/api/influencer/route.ts b/src/app/api/influencer/route.ts
index 237514d2..c32393b0 100644
--- a/src/app/api/influencer/route.ts
+++ b/src/app/api/influencer/route.ts
@@ -2,10 +2,14 @@ import { z } from "zod";
import { MAX_CLOTHING, MAX_DIRECTION } from "@/lib/influencer";
import { createInfluencer, previewInfluencer, type InfluencerBody } from "@/server/influencer";
import { refusedRun } from "@/server/connect-refusal";
+import { bodyTooBig, guestRun, toolViewer, toolWishes } from "@/server/account-tool-run";
+import { runToolForAccount, withPoolPrice } from "@/server/tool-runs";
const File = z.string().startsWith("/api/files/").max(500);
const Body = z.object({
+ /** Client nonce: a repeat of it (a second click) gets the run the first one started (an account's). */
+ requestId: z.string().max(64).optional(),
engine: z.enum(["cloud", "open"]),
state: z.record(z.string(), z.unknown()),
direction: z.string().max(MAX_DIRECTION).optional(),
@@ -30,12 +34,34 @@ function bodyError(issues: z.core.$ZodIssue[]): string {
* AI Influencer builder: a character sheet from the builder's picks — Fuobe Soul in the cloud (Nano Banana Pro or
* Seedream 5.0 Pro when asked), the Soul Cast sheet workflow on the open engine, each followed by Qwen-Image-Edit 2511
* for a face, a reference or clothing. `?preview=1` (or POST /api/influencer/estimate) prices it instead.
+ *
+ * The owner's run as always; an account's with only its own files, after the checks every tool run gets
+ * (src/server/tool-runs.ts), on its own GPU or key or on this install's GPUs; a guest signs up first.
*/
export async function POST(request: Request) {
+ const viewer = toolViewer(request);
+ const preview = !!new URL(request.url).searchParams.get("preview");
+ if (viewer.kind === "guest" && !preview) return guestRun();
+ if (viewer.kind === "account" && !preview) {
+ const big = bodyTooBig(request);
+ if (big) return big;
+ }
+ const wishes = viewer.kind === "owner" ? {} : await toolWishes(request);
const parsed = Body.safeParse(await request.json().catch(() => null));
if (!parsed.success) return Response.json({ error: bodyError(parsed.error.issues) }, { status: 400 });
- const body = parsed.data as InfluencerBody;
- if (new URL(request.url).searchParams.get("preview")) return Response.json(previewInfluencer(body));
+ const { requestId, ...body } = parsed.data as InfluencerBody & { requestId?: string };
+ const start = () => createInfluencer(body);
+ if (preview) return Response.json(await withPoolPrice(request, previewInfluencer(body), start, wishes.place));
+ if (viewer.kind === "account") {
+ return runToolForAccount(request, viewer.account, {
+ tool: "influencer",
+ files: [body.photo, ...(body.clothing ?? [])],
+ requestId,
+ wishes,
+ start,
+ ok: (value, gpuWarning) => Response.json({ ...value, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),
+ });
+ }
try {
return Response.json(createInfluencer(body), { status: 201 });
} catch (e) {
diff --git a/src/app/api/photodump/character/route.ts b/src/app/api/photodump/character/route.ts
index 80ce78c6..c55297f8 100644
--- a/src/app/api/photodump/character/route.ts
+++ b/src/app/api/photodump/character/route.ts
@@ -1,6 +1,8 @@
import { z } from "zod";
import { createSheet, previewSheet, type SheetRun } from "@/server/photodump";
import { refusedRun } from "@/server/connect-refusal";
+import { bodyTooBig, guestRun, toolViewer, toolWishes } from "@/server/account-tool-run";
+import { runToolForAccount, withPoolPrice } from "@/server/tool-runs";
const Engine = z.enum(["cloud", "open"]);
@@ -32,13 +34,35 @@ function bodyError(mode: unknown, issues: z.core.$ZodIssue[]): string {
/**
* Character Sheet: a turnaround sheet from 1–5 reference photos, from a Soul Cast build, or from a
* description (the AI Influencer app). `?preview=1` prices it instead.
+ *
+ * The owner's run as always; an account's with only its own pictures, after the checks every tool run gets
+ * (src/server/tool-runs.ts); a guest signs up first.
*/
export async function POST(request: Request) {
- const body = (await request.json().catch(() => null)) as { mode?: unknown } | null;
+ const viewer = toolViewer(request);
+ const preview = !!new URL(request.url).searchParams.get("preview");
+ if (viewer.kind === "guest" && !preview) return guestRun();
+ if (viewer.kind === "account" && !preview) {
+ const big = bodyTooBig(request);
+ if (big) return big;
+ }
+ const wishes = viewer.kind === "owner" ? {} : await toolWishes(request);
+ const body = (await request.json().catch(() => null)) as { mode?: unknown; requestId?: unknown } | null;
const parsed = Body.safeParse(body);
if (!parsed.success) return Response.json({ error: bodyError(body?.mode, parsed.error.issues) }, { status: 400 });
const input = parsed.data as SheetRun;
- if (new URL(request.url).searchParams.get("preview")) return Response.json(previewSheet(input));
+ const start = () => createSheet(input);
+ if (preview) return Response.json(await withPoolPrice(request, previewSheet(input), start, wishes.place));
+ if (viewer.kind === "account") {
+ return runToolForAccount(request, viewer.account, {
+ tool: "character-sheet",
+ files: input.mode === "reference" ? input.images : [],
+ requestId: typeof body?.requestId === "string" && body.requestId.length <= 64 ? body.requestId : undefined,
+ wishes,
+ start,
+ ok: (value, gpuWarning) => Response.json({ ...value, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),
+ });
+ }
try {
return Response.json(createSheet(input), { status: 201 });
} catch (e) {
diff --git a/src/app/api/photodump/fashion/route.ts b/src/app/api/photodump/fashion/route.ts
index 90cf966f..263c6812 100644
--- a/src/app/api/photodump/fashion/route.ts
+++ b/src/app/api/photodump/fashion/route.ts
@@ -1,6 +1,8 @@
import { z } from "zod";
import { createFashion, previewFashion, type FashionRun } from "@/server/photodump";
import { refusedRun } from "@/server/connect-refusal";
+import { bodyTooBig, guestRun, toolViewer, toolWishes } from "@/server/account-tool-run";
+import { runToolForAccount, withPoolPrice } from "@/server/tool-runs";
const File = z.string().startsWith("/api/files/").max(500);
const Engine = z.enum(["cloud", "open"]);
@@ -14,12 +16,36 @@ const Body = z.discriminatedUnion("step", [
/**
* Fashion Factory steps: 4 base shots of the character in the template's set, the outfit (try-on),
* and the photoset (one photo per template shot). `?preview=1` prices a step instead.
+ *
+ * The owner's run as always; an account's outfit and photoset from its own pictures (the base step reads a character
+ * from the owner's library), after the checks every tool run gets (src/server/tool-runs.ts); a guest signs up first.
*/
export async function POST(request: Request) {
- const parsed = Body.safeParse(await request.json().catch(() => null));
+ const viewer = toolViewer(request);
+ const preview = !!new URL(request.url).searchParams.get("preview");
+ if (viewer.kind === "guest" && !preview) return guestRun();
+ if (viewer.kind === "account" && !preview) {
+ const big = bodyTooBig(request);
+ if (big) return big;
+ }
+ const wishes = viewer.kind === "owner" ? {} : await toolWishes(request);
+ const raw = (await request.json().catch(() => null)) as { requestId?: unknown } | null;
+ const parsed = Body.safeParse(raw);
if (!parsed.success) return Response.json({ error: "Template required" }, { status: 400 });
const input = parsed.data as FashionRun;
- if (new URL(request.url).searchParams.get("preview")) return Response.json(previewFashion(input));
+ if (viewer.kind !== "owner" && input.step === "base") return Response.json({ error: "Character not found" }, { status: 404 });
+ const start = () => createFashion(input);
+ if (preview) return Response.json(await withPoolPrice(request, previewFashion(input), start, wishes.place));
+ if (viewer.kind === "account") {
+ return runToolForAccount(request, viewer.account, {
+ tool: "fashion",
+ files: input.step === "outfit" ? [input.base, input.garment] : input.step === "photoset" ? [input.dressed] : [],
+ requestId: typeof raw?.requestId === "string" && raw.requestId.length <= 64 ? raw.requestId : undefined,
+ wishes,
+ start,
+ ok: (value, gpuWarning) => Response.json({ ...value, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),
+ });
+ }
try {
return Response.json(createFashion(input), { status: 201 });
} catch (e) {
diff --git a/src/app/api/photodump/route.ts b/src/app/api/photodump/route.ts
index c907ba2b..5f7a2fd1 100644
--- a/src/app/api/photodump/route.ts
+++ b/src/app/api/photodump/route.ts
@@ -2,6 +2,9 @@ import { connection } from "next/server";
import { z } from "zod";
import { createPhotodump, listUserPacks, previewPhotodump } from "@/server/photodump";
import { refusedRun } from "@/server/connect-refusal";
+import { getPack } from "@/lib/catalog/packs";
+import { bodyTooBig, guestRun, toolViewer, toolWishes } from "@/server/account-tool-run";
+import { runToolForAccount, withPoolPrice } from "@/server/tool-runs";
const Body = z
.object({
@@ -11,6 +14,8 @@ const Body = z
selfie: z.string().startsWith("/api/files/").max(500).optional(),
aspectRatio: z.string().max(10).optional(),
modelId: z.string().max(80).optional(),
+ /** Client nonce: a repeat of it (a second click) gets the run the first one started (an account's). */
+ requestId: z.string().max(64).optional(),
})
.refine((b) => !!b.elementId || !!b.selfie, { message: "Pick a character or add a selfie" });
@@ -23,13 +28,38 @@ export async function GET() {
/**
* Generate a photodump: one photo per pack shot, as one batch. `?preview=1` prices it instead
* (model, photo count, cost, demo, notes, or the error that would stop it).
+ *
+ * The owner's run as always; an account's from a built-in pack and its own selfie (characters and saved packs are the
+ * owner's library), after the checks every tool run gets (src/server/tool-runs.ts); a guest signs up first.
*/
export async function POST(request: Request) {
+ const viewer = toolViewer(request);
+ const preview = !!new URL(request.url).searchParams.get("preview");
+ if (viewer.kind === "guest" && !preview) return guestRun();
+ if (viewer.kind === "account" && !preview) {
+ const big = bodyTooBig(request);
+ if (big) return big;
+ }
+ const wishes = viewer.kind === "owner" ? {} : await toolWishes(request);
const parsed = Body.safeParse(await request.json().catch(() => null));
if (!parsed.success) return Response.json({ error: parsed.error.issues[0]?.message ?? "Pick a pack" }, { status: 400 });
- if (new URL(request.url).searchParams.get("preview")) return Response.json(previewPhotodump(parsed.data));
+ const { requestId, ...input } = parsed.data;
+ // Characters and saved packs are the owner's library: a visitor is never told whether one exists.
+ if (viewer.kind !== "owner" && (input.elementId || !getPack(input.packId))) return Response.json({ error: input.elementId ? "Character not found" : "That pack no longer exists" }, { status: 404 });
+ const start = () => createPhotodump(input);
+ if (preview) return Response.json(await withPoolPrice(request, previewPhotodump(input), start, wishes.place));
+ if (viewer.kind === "account") {
+ return runToolForAccount(request, viewer.account, {
+ tool: "photodump",
+ files: [input.selfie],
+ requestId,
+ wishes,
+ start,
+ ok: (value, gpuWarning) => Response.json({ ...value, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),
+ });
+ }
try {
- return Response.json(createPhotodump(parsed.data), { status: 201 });
+ return Response.json(createPhotodump(input), { status: 201 });
} catch (e) {
return refusedRun(e, request);
}
diff --git a/src/app/api/turnaround/route.ts b/src/app/api/turnaround/route.ts
index ac46f06f..5f5726da 100644
--- a/src/app/api/turnaround/route.ts
+++ b/src/app/api/turnaround/route.ts
@@ -1,6 +1,8 @@
+import { bodyTooBig, guestRun, toolViewer, toolWishes } from "@/server/account-tool-run";
import { requestViewer } from "@/server/auth";
import { recordExists } from "@/server/records";
import { body, handle, once } from "@/server/shorts-schemas";
+import { bodyFiles, runToolForAccount, withPoolPrice } from "@/server/tool-runs";
import { createTurnaround, previewTurnaround, TurnaroundBodySchema, turnaroundRun } from "@/server/turnaround";
import { priceAs } from "@/server/visitor";
import { worldcastContextNow } from "@/server/worldcast-on";
@@ -8,9 +10,13 @@ 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.
+ *
+ * The owner's run as always; an account's with only its own pictures (characters are the owner's library), after the
+ * checks every tool run gets (src/server/tool-runs.ts); a guest signs up first.
*/
async function post(request: Request) {
return handle(async () => {
+ const wishes = requestViewer(request).kind === "owner" ? {} : await toolWishes(request);
const { requestId, ...input } = await body(request, TurnaroundBodySchema, "Pick the engine and the character's pictures");
// Characters are the owner's library: a visitor (public sign-up) is never told whether one exists.
if (input.elementId && (requestViewer(request).kind !== "owner" || !recordExists({ kind: "element", ids: [input.elementId] }))) {
@@ -18,13 +24,29 @@ async function post(request: Request) {
}
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));
+ const start = () => createTurnaround(run);
+ if (new URL(request.url).searchParams.get("preview")) return Response.json(await withPoolPrice(request, previewTurnaround(run), start, wishes.place));
+ const viewer = toolViewer(request);
+ if (viewer.kind === "account") {
+ return runToolForAccount(request, viewer.account, {
+ tool: "turnaround",
+ files: bodyFiles(input),
+ requestId,
+ wishes,
+ start,
+ ok: (value, gpuWarning) => Response.json({ ...value, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),
+ });
+ }
+ const result = await once("turnaround", requestId, start);
return Response.json(result, { status: 201 });
});
}
/** 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) {
+ const viewer = toolViewer(request);
+ const preview = !!new URL(request.url).searchParams.get("preview");
+ if (viewer.kind === "guest" && !preview) return guestRun();
+ if (viewer.kind === "account" && !preview) return bodyTooBig(request) ?? post(request);
return priceAs(request, () => post(request));
}
diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.ts
index 2017838c..601ed6f2 100644
--- a/src/lib/guest-access.ts
+++ b/src/lib/guest-access.ts
@@ -284,6 +284,9 @@ export const ACCOUNT_TOOL_RUNS: readonly RegExp[] = [
/^\/api\/genjutsu\/describe$/,
// Character Swap Studio's jobs on an account's own project (src/server/swap-studio-account.ts).
/^\/api\/swap-studio\/projects\/[^/]+\/(anchors|assemble|clips|masks|prepare|queue|sharpen|transcribe)$/,
+ // Apps made in one go from the account's own pictures (src/server/tool-runs.ts): AI Influencer, Photodump, Fashion
+ // Factory, Character Sheet, Turnaround and Fly around.
+ /^\/api\/(influencer|photodump|photodump\/fashion|photodump\/character|turnaround|fly-around)$/,
];
/**
diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.ts
index 877b3eb5..01bba4dd 100644
--- a/src/server/hosted-run.ts
+++ b/src/server/hosted-run.ts
@@ -578,7 +578,8 @@ export function toolGate(
}
if (planned.route.provider !== "comfyui") return "unplanned";
const gate = poolGate(p, planned, req, () => (deps ? [asPlannedStep(req, planned, true)] : poolSteps(viewer ?? GUEST_PLAN, req)));
- if (!gate.ok) return gate;
+ // A tool adds its LoRAs itself (a person adds none to it): said as a step that runs on an own GPU, not as extra LoRAs.
+ if (!gate.ok) return gate.reason === "loras" ? { ok: false, reason: "notOffered" } : gate;
rows.push(...(gate.steps ?? [asPlannedStep(req, planned, deps > 0)]));
main ??= { req, planned };
}
diff --git a/src/server/tool-runs.ts b/src/server/tool-runs.ts
new file mode 100644
index 00000000..e865b90f
--- /dev/null
+++ b/src/server/tool-runs.ts
@@ -0,0 +1,104 @@
+import "server-only";
+import { onceForAccount, runAccountTool, toolPriceCheck, toolViewer, toolWishes, type ToolStep } from "./account-tool-run";
+import type { Account } from "./auth";
+import { db } from "./db";
+import { captureRun } from "./generations";
+import type { GenerationRequest } from "@/lib/catalog/types";
+import type { PlaceWish } from "./hosted-run";
+import { withoutStamp } from "./run-stamp";
+
+/**
+ * The apps and tools whose run is made in one go by a create function (createInfluencer, createPhotodump,
+ * createTurnaround, createFlyAround…: generations and pipelines, nothing else) open to accounts through the same checks
+ * as every tool run (account-tool-run.ts runAccountTool): their steps are what that create function would make, made in
+ * a transaction that is rolled back (nothing kept, nothing sent), then made for real once every check passed. With
+ * hosted runs on, the run may go to this install's GPUs as one run (placeOf).
+ */
+
+const ROLLED_BACK = Symbol("rolled back");
+
+const depCount = (v: string | null): number => (!v ? 0 : v.startsWith("[") ? (JSON.parse(v) as unknown[]).length : 1);
+
+/**
+ * A run's steps as `start` would make them: every row it makes (a chain's later steps too), with the earlier steps each
+ * waits for, made and thrown away inside one transaction. Call it in the run's own scope (asAccount, runOnPool). A start
+ * that awaits before it makes its rows can't be planned this way.
+ */
+export function dryRunSteps(start: () => unknown): ToolStep[] {
+ const d = db();
+ let steps: ToolStep[] = [];
+ try {
+ d.transaction(() => {
+ const made = captureRun(start);
+ if (made.value && typeof (made.value as { then?: unknown }).then === "function") throw new Error("A run that waits before it starts can't be planned here.");
+ const q = d.prepare("SELECT request_json, depends_on FROM generations WHERE id = ?");
+ steps = made.ids.flatMap((id) => {
+ const r = q.get(id) as { request_json: string; depends_on: string | null } | undefined;
+ return r ? [{ request: withoutStamp(JSON.parse(r.request_json) as GenerationRequest), deps: depCount(r.depends_on) }] : [];
+ });
+ throw ROLLED_BACK;
+ })();
+ } catch (e) {
+ if (e !== ROLLED_BACK) throw e;
+ }
+ return steps;
+}
+
+export interface ToolRoute<T> {
+ /** The tool, for the run limit's key and the logs. */
+ tool: string;
+ /** Every file the body names: only the account's own, or Fuobe's example files. */
+ files: (string | null | undefined)[];
+ /** A client nonce: a repeat of it gets the first run. */
+ requestId?: string;
+ /** Makes the run (createInfluencer…), inside the account's scope. */
+ start: () => T;
+ /** The route's answer for the started run. */
+ ok: (value: T, gpuWarning?: string) => Response;
+ skipGpuCheck?: boolean;
+ /** The place and price the body carries (account-tool-run.ts toolWishes, read before the route reads the body). */
+ wishes?: Awaited<ReturnType<typeof toolWishes>>;
+}
+
+/** An account's run of such a tool: its steps planned from `start`, checked, placed and started (runAccountTool). */
+export async function runToolForAccount<T>(request: Request, account: Account, o: ToolRoute<T>): Promise<Response> {
+ return onceForAccount(
+ account,
+ o.tool,
+ o.requestId,
+ () =>
+ runAccountTool(request, account, {
+ tool: o.tool,
+ files: o.files,
+ plan: () => dryRunSteps(o.start),
+ start: o.start,
+ skipGpuCheck: o.skipGpuCheck,
+ ...o.wishes,
+ }),
+ ({ value, gpuWarning }) => o.ok(value, gpuWarning),
+ );
+}
+
+/**
+ * A tool's price check (`?preview=1`) with its place on this install's GPUs added when the run would go there:
+ * `{ place: "pool", quote, line }` beside the tool's own answer (an account's or a guest's; the owner's as always).
+ */
+export async function withPoolPrice(request: Request, answer: object, start: () => unknown, wish?: PlaceWish): Promise<object> {
+ if (toolViewer(request).kind === "owner" || "error" in answer) return answer;
+ const pool = await toolPriceCheck(request, () => dryRunSteps(start), wish);
+ return pool ? { ...answer, ...pool } : answer;
+}
+
+/** Every stored file a body names (`/api/files/…`), wherever it sits: the files an account's run must own. */
+export function bodyFiles(value: unknown): string[] {
+ const out = new Set<string>();
+ const walk = (v: unknown, depth: number) => {
+ if (depth > 8) return;
+ if (typeof v === "string") {
+ if (v.startsWith("/api/files/")) out.add(v);
+ } else if (Array.isArray(v)) for (const x of v) walk(x, depth + 1);
+ else if (v && typeof v === "object") for (const x of Object.values(v)) walk(x, depth + 1);
+ };
+ walk(value, 0);
+ return [...out];
+}
diff --git a/tests/hosted-app-runs.test.ts b/tests/hosted-app-runs.test.ts
new file mode 100644
index 00000000..cfed2954
--- /dev/null
+++ b/tests/hosted-app-runs.test.ts
@@ -0,0 +1,211 @@
+import http from "node:http";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { listenOnFreePort, startFakeBilling, type FakeBilling } from "./helpers/fake-billing";
+import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";
+import { tempDir } from "./helpers/temp-dir";
+
+/**
+ * The apps made in one go (AI Influencer, Photodump, Fashion Factory, Character Sheet, Turnaround, Fly around) for an
+ * account: on its own GPU as any tool run; with hosted runs on and no GPU of its own, on this install's GPUs as one run
+ * held once; priced before Run with their place there. Characters and saved packs stay the owner's.
+ */
+const dir = tempDir("fuobe-hosted-app-runs-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_HOSTED_RUNS;
+delete process.env.FUOBE_BILLING_URL;
+delete process.env.FUOBE_MODERATION_URL;
+delete process.env.ANTHROPIC_API_KEY;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const probe = http.createServer();
+const comfyPort = await listenOnFreePort(probe);
+await new Promise<void>((r) => probe.close(() => r()));
+const comfy: FakeComfy = await startFakeComfy({ output: "image", delayMs: 0, loras: [] }, comfyPort);
+process.env.COMFYUI_URL = comfy.url;
+
+const auth = await import("@/server/auth");
+const uploadsRoute = await import("@/app/api/uploads/route");
+const gpuRoute = await import("@/app/api/account/gpu/route");
+const routes = {
+ photodump: await import("@/app/api/photodump/route"),
+ character: await import("@/app/api/photodump/character/route"),
+ fashion: await import("@/app/api/photodump/fashion/route"),
+ influencer: await import("@/app/api/influencer/route"),
+ turnaround: await import("@/app/api/turnaround/route"),
+ flyAround: await import("@/app/api/fly-around/route"),
+};
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const billing = await import("@/server/billing");
+const { clearAccountLoras } = await import("@/server/account-loras");
+const { HOSTED_WORDS } = await import("@/server/hosted");
+const { OWN_GPU_TOOL_MESSAGE } = await import("@/lib/guest-access");
+
+let fake: FakeBilling;
+const ids: Record<string, string> = {};
+const cookies: Record<string, string> = {};
+beforeAll(async () => {
+ fake = await startFakeBilling();
+ fake.price = { amount: 0, version: "free" };
+ auth.setPassword("install password");
+ for (const who of ["none", "gpu"]) {
+ ids[who] = auth.createAccount(`apps-${who}@example.com`, "long enough").id;
+ cookies[who] = `${auth.SESSION_COOKIE}=${auth.createSession(ids[who]).value}`;
+ }
+ globalThis.__fuobeTestGpuPort = comfy.port;
+ expect((await gpuRoute.PUT(json("/api/account/gpu", "PUT", { url: comfy.url }, "gpu"))).status).toBe(200);
+});
+afterAll(async () => {
+ globalThis.__fuobeTestDiskFree = undefined;
+ globalThis.__fuobeTestGpuPort = undefined;
+ for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN"]) delete process.env[k];
+ await fake.close();
+ await comfy.close();
+});
+beforeEach(() => {
+ resetRates();
+ billing.resetBillingCache();
+ delete process.env.FUOBE_HOSTED_RUNS;
+ delete process.env.FUOBE_BILLING_URL;
+ delete process.env.FUOBE_BILLING_TOKEN;
+ fake.policy = { hosted: true, pool: {}, uploads: { image: true, video: false, audio: false }, limits: { activeRuns: 0, waiting: 0, runsPerHour: 0, outputsPerRun: 4, maxMegapixels: 0, maxSeconds: 0, keepDays: 7, spaceBytes: 7 }, ttlS: 0 };
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").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,
+ });
+}
+async function upload(who: 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": "image/png", "x-file-name": "me.png", "content-length": String(TINY_PNG.length) }, body: new Uint8Array(TINY_PNG) }));
+ expect(r.status, await r.clone().text()).toBe(201);
+ return ((await r.json()) as { url: string }).url;
+}
+const hostedOn = () => {
+ process.env.FUOBE_HOSTED_RUNS = "1";
+ process.env.FUOBE_BILLING_URL = fake.url;
+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";
+};
+const places = (who: string, since: number) =>
+ (db().prepare("SELECT request_json FROM generations WHERE json_extract(request_json, '$.account') = ? AND created_at >= ? ORDER BY created_at").all(ids[who], since) as { request_json: string }[]).map(
+ (r) => (JSON.parse(r.request_json) as { place?: string }).place ?? "own",
+ );
+const reserves = () => fake.calls_of("/v1/reserve").length;
+
+/** Send a run on the account's own GPU; a LoRA its ComfyUI lacks is put there (the 409 names it), then it is sent again. */
+async function send(call: () => Promise<Response>): Promise<Response> {
+ let r = await call();
+ if (r.status === 409) {
+ const j = (await r.clone().json()) as { code: string; fix?: { items: { file: string }[] } };
+ expect(j.code).toBe("comfy_missing_model");
+ comfy.opts.loras = [...(comfy.opts.loras ?? []), ...j.fix!.items.map((i) => i.file)];
+ clearAccountLoras(ids.gpu);
+ r = await call();
+ }
+ return r;
+}
+
+type Case = {
+ name: string;
+ route: { POST: (r: Request) => Promise<Response> };
+ url: string;
+ body: (pic: string) => Record<string, unknown>;
+ /** Refused on this install's GPUs before Run, in these words (a step that runs only on an own GPU for now). */
+ ownOnly?: string;
+};
+const CASES: Case[] = [
+ { name: "Photodump", route: routes.photodump, url: "/api/photodump", body: (pic) => ({ packId: "winter-special", engine: "open", selfie: pic, aspectRatio: "3:4" }) },
+ // AI Influencer's open sheet carries its casting look's LoRAs, which this install's GPUs don't carry yet.
+ { name: "AI Influencer", route: routes.influencer, url: "/api/influencer", body: () => ({ engine: "open", state: {}, start: "scratch" }), ownOnly: HOSTED_WORDS.notOffered },
+ { name: "Character Sheet", route: routes.character, url: "/api/photodump/character", body: () => ({ mode: "describe", engine: "open", prompt: "a surfer from Lisbon" }) },
+ // The turnaround's angle LoRA isn't one this install's GPUs carry yet, and Fly around's path is drawn from a 3D step.
+ { name: "Turnaround", route: routes.turnaround, url: "/api/turnaround", body: (pic) => ({ engine: "open", views: { front: pic, back: pic } }), ownOnly: HOSTED_WORDS.notOffered },
+ { name: "Fly around", route: routes.flyAround, url: "/api/fly-around", body: (pic) => ({ engine: "open", image: pic, orbit: { degrees: 90, direction: "cw" } }), ownOnly: OWN_GPU_TOOL_MESSAGE },
+];
+
+describe("hosted runs off: an account's app runs as any tool run, on its own GPU", () => {
+ for (const c of CASES) {
+ it(`${c.name}: no GPU or key is asked to connect one; its own GPU runs it`, async () => {
+ const none = await c.route.POST(json(c.url, "POST", c.body(await upload("gpu")), "none"));
+ expect([403, 404], await none.clone().text()).toContain(none.status);
+ const since = Date.now();
+ const pic = await upload("gpu");
+ const r = await send(() => c.route.POST(json(c.url, "POST", c.body(pic), "gpu")));
+ expect(r.status, await r.clone().text()).toBe(201);
+ const made = places("gpu", since);
+ expect(made.length).toBeGreaterThan(0);
+ expect(made.every((p) => p === "own")).toBe(true);
+ });
+ }
+});
+
+describe("hosted runs on: an account with no GPU of its own runs the apps on this install's GPUs", () => {
+ beforeEach(hostedOn);
+ for (const c of CASES) {
+ it(`${c.name}: one hold for the whole run, every step there, and its price check names the place`, async () => {
+ const pic = await upload("none");
+ const check = await c.route.POST(json(`${c.url}?preview=1`, "POST", c.body(pic), "none"));
+ const priced = (await check.json()) as { place?: string; quote?: { allowed: boolean; text: string } };
+ expect(priced.place, JSON.stringify(priced)).toBe("pool");
+ if (c.ownOnly) {
+ // Run stays off and says why; pressed anyway, nothing is held or made.
+ expect(priced.quote).toMatchObject({ allowed: false, text: c.ownOnly });
+ const before = reserves();
+ const since = Date.now();
+ const r = await c.route.POST(json(c.url, "POST", c.body(pic), "none"));
+ expect(r.status).toBe(403);
+ expect(((await r.json()) as { error: string }).error).toBe(c.ownOnly);
+ expect(reserves()).toBe(before);
+ expect(places("none", since)).toEqual([]);
+ return;
+ }
+ expect(priced.quote?.allowed, JSON.stringify(priced.quote)).toBe(true);
+ const since = Date.now();
+ const before = reserves();
+ const r = await c.route.POST(json(c.url, "POST", c.body(pic), "none"));
+ expect(r.status, await r.clone().text()).toBe(201);
+ expect(reserves() - before).toBe(1);
+ const made = places("none", since);
+ expect(made.length).toBeGreaterThan(0);
+ expect(made.every((p) => p === "pool")).toBe(true);
+ });
+ }
+
+ it("an account whose own GPU answers keeps it", async () => {
+ const since = Date.now();
+ const before = reserves();
+ const r = await routes.photodump.POST(json("/api/photodump", "POST", CASES[0].body(await upload("gpu")), "gpu"));
+ expect(r.status, await r.clone().text()).toBe(201);
+ expect(reserves()).toBe(before);
+ expect(places("gpu", since).every((p) => p === "own")).toBe(true);
+ });
+
+ it("characters and saved packs stay the owner's library: a visitor is told they aren't there", async () => {
+ const el = await routes.photodump.POST(json("/api/photodump", "POST", { packId: "winter-special", engine: "open", elementId: "el-1" }, "none"));
+ expect(el.status).toBe(404);
+ const pack = await routes.photodump.POST(json("/api/photodump", "POST", { packId: "my-own-pack", engine: "open", selfie: await upload("none") }, "none"));
+ expect(pack.status).toBe(404);
+ const base = await routes.fashion.POST(json("/api/photodump/fashion", "POST", { step: "base", templateId: "t", elementId: "el-1", engine: "open" }, "none"));
+ expect(base.status).toBe(404);
+ });
+
+ it("another account's file never goes in", async () => {
+ const theirs = await upload("gpu");
+ const r = await routes.photodump.POST(json("/api/photodump", "POST", CASES[0].body(theirs), "none"));
+ expect(r.status).toBeGreaterThanOrEqual(400);
+ expect(r.status).toBeLessThan(500);
+ });
+
+ it("a guest signs up first; its price check is answered", async () => {
+ const r = await routes.flyAround.POST(json("/api/fly-around", "POST", { engine: "open", image: "/api/files/x.png", orbit: { degrees: 90, direction: "cw" } }));
+ expect(r.status).toBe(401);
+ const c = await routes.character.POST(json("/api/photodump/character?preview=1", "POST", { mode: "describe", engine: "open", prompt: "a surfer" }));
+ expect(((await c.json()) as { place?: string }).place).toBe("pool");
+ });
+});
diff --git a/tests/public-signup-tools.test.ts b/tests/public-signup-tools.test.ts
index ff5e2699..80ed3c38 100644
--- a/tests/public-signup-tools.test.ts
+++ b/tests/public-signup-tools.test.ts
@@ -110,14 +110,14 @@ 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/shorts/sessions", "/api/katana", "/api/marketing/runs", "/api/layers/l1/jobs", "/api/layout/plan"]) {
+ for (const p of ["/api/audio-tools", "/api/shorts/sessions", "/api/katana", "/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, an upload and a save to the library: signing up is the next step there.
- for (const p of ["/api/generations", "/api/media/probe", "/api/audio-tools/export?offset=0", "/api/canvases"]) {
+ for (const p of ["/api/generations", "/api/turnaround", "/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");
@@ -129,12 +129,16 @@ 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();
expect((await r.json()).code, p).toBe("own-gpu-tool");
}
+ // The turnaround runs on an account's own GPU or key (src/server/tool-runs.ts): with neither, "Connect your GPU".
+ const turn = proxy(req("/api/turnaround", { method: "POST", cookie }));
+ expect(turn.status).toBe(403);
+ expect(turn.headers.get(access.CONNECT_GPU_HEADER)).toBe("1");
// The mix is kept as the account's own run (the route checks its room, run rate and the studio's checks), whatever the GPU.
expect(passed(proxy(req("/api/audio-tools/export?offset=0", { method: "POST", cookie })))).toBe(true);
});
@@ -145,7 +149,8 @@ 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/cinema/projects/p1/generate", "/api/layout/plan"]) {
+ expect(passed(proxy(req("/api/turnaround", { method: "POST", cookie })))).toBe(true);
+ for (const p of ["/api/audio-tools", "/api/cinema/projects/p1/generate", "/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();
@@ -162,19 +167,18 @@ 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, and its run to an account (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);
+ 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 })))).toBe(true);
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 1fb9de90..4ff83fc0 100644
--- a/tests/public-signup.test.ts
+++ b/tests/public-signup.test.ts
@@ -344,8 +344,10 @@ describe("accounts never see or change the owner's library", () => {
const cookie = auth.createSession(auth.createAccount("[email protected]", "long enough").id).value;
expect(passed(proxy(req("/api/influencer?preview=1", { method: "POST" })))).toBe(true);
expect(passed(proxy(req("/api/influencer?preview=1", { method: "POST", cookie })))).toBe(true);
- // Its run isn't one an account's GPU runs either: the account's own-gpu-tool, not the sign-up card.
- expect(proxy(req("/api/influencer", { method: "POST" })).status).toBe(403);
+ // Its run is an account's (src/server/tool-runs.ts): a guest gets the sign-up card, an account with no GPU or key
+ // "Connect your GPU".
+ expect(proxy(req("/api/influencer", { method: "POST" })).status).toBe(401);
+ expect(proxy(req("/api/influencer", { method: "POST", cookie })).headers.get(access.CONNECT_GPU_HEADER)).toBe("1");
});
});