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.

Hosted runs: a tool's run reaches this install's GPUs through the studio runs' gate

Adarshbfedc0f42778
diff --git a/src/app/api/genjutsu/route.ts b/src/app/api/genjutsu/route.ts
index 5c8bbb3b..de6868cf 100644
--- a/src/app/api/genjutsu/route.ts
+++ b/src/app/api/genjutsu/route.ts
@@ -1,4 +1,4 @@
-import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer, toolWishes } from "@/server/account-tool-run";
import { createGenjutsu, GenjutsuBodySchema, genjutsuSteps, planGenjutsuRun, startGenjutsu, type GenjutsuRun } from "@/server/genjutsu";
import { body, handle, once } from "@/server/shorts-schemas";
@@ -15,6 +15,7 @@ export async function POST(request: Request) {
if (big) return big;
}
return handle(async () => {
+ const wishes = viewer.kind === "account" ? await toolWishes(request) : {};
const input = await body(request, GenjutsuBodySchema, "Add a clip, pick a mode and add your references");
// A repeated requestId (a second click on Generate) gets the run the first one started.
if (viewer.kind === "owner") {
@@ -27,6 +28,7 @@ export async function POST(request: Request) {
return onceForAccount(viewer.account, "genjutsu", input.requestId, () =>
runAccountTool(request, viewer.account, {
tool: "genjutsu",
+ ...wishes,
files: [input.source.url, input.mask, input.picture?.frame, ...(input.references ?? []), ...look],
plan: async () => genjutsuSteps((run = await planGenjutsuRun(input, { owner: false }))),
start: () => startGenjutsu(run!),
diff --git a/src/app/api/image-to-3d/route.ts b/src/app/api/image-to-3d/route.ts
index 08a3ecff..1e95ddf5 100644
--- a/src/app/api/image-to-3d/route.ts
+++ b/src/app/api/image-to-3d/route.ts
@@ -4,7 +4,7 @@ import type { GenerationRequest } from "@/lib/catalog/types";
import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES } from "@/server/account-files";
import { accountInputProblem } from "@/server/account-inputs";
import { accountEngineMode } from "@/server/account-keys";
-import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer, toolWishes } from "@/server/account-tool-run";
import { createGenerations } from "@/server/generations";
import { GenerationRequestSchema } from "@/server/request-schema";
@@ -24,6 +24,7 @@ export async function POST(request: Request) {
const account = viewer.account;
const big = bodyTooBig(request);
if (big) return big;
+ const wishes = await toolWishes(request);
const text = await request.text().catch(() => "");
if (Buffer.byteLength(text) > ACCOUNT_LIMITS.runBodyBytes) return refuse(413, ACCOUNT_MESSAGES.bodyTooBig);
let raw: unknown = null;
@@ -56,6 +57,7 @@ export async function POST(request: Request) {
() =>
runAccountTool(request, account, {
tool: "image-to-3d",
+ ...wishes,
files,
plan: () => [{ request: run }],
start: () => createGenerations(run),
diff --git a/src/app/api/storyboards/[id]/film/route.ts b/src/app/api/storyboards/[id]/film/route.ts
index 3dbcb715..bef08362 100644
--- a/src/app/api/storyboards/[id]/film/route.ts
+++ b/src/app/api/storyboards/[id]/film/route.ts
@@ -1,5 +1,5 @@
import { z } from "zod";
-import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer, toolWishes } from "@/server/account-tool-run";
import { createStoryboardFilm, planStoryboardFilm, startStoryboardFilm, storyboardFilmSteps, type StoryboardFilmRun } from "@/server/storyboard";
import { refusedRun } from "@/server/connect-refusal";
@@ -21,6 +21,7 @@ export async function POST(request: Request, ctx: RouteContext<"/api/storyboards
const big = bodyTooBig(request);
if (big) return big;
}
+ const wishes = viewer.kind === "account" ? await toolWishes(request) : {};
const parsed = Body.safeParse((await request.json().catch(() => ({}))) ?? {});
if (!parsed.success) return Response.json({ error: "Invalid request" }, { status: 400 });
const { id } = await ctx.params;
@@ -40,6 +41,7 @@ export async function POST(request: Request, ctx: RouteContext<"/api/storyboards
() =>
runAccountTool(request, viewer.account, {
tool: "storyboard-film",
+ ...wishes,
// Its frames are its own runs (planStoryboardFilm reads only its own); no other file goes in.
files: [],
plan: () => storyboardFilmSteps((run = planStoryboardFilm(id, { modelId: parsed.data.modelId }))),
diff --git a/src/app/api/storyboards/route.ts b/src/app/api/storyboards/route.ts
index 65663d17..b433bb88 100644
--- a/src/app/api/storyboards/route.ts
+++ b/src/app/api/storyboards/route.ts
@@ -1,4 +1,4 @@
-import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer, toolWishes } from "@/server/account-tool-run";
import { createStoryboard, planStoryboardRun, startStoryboard, StoryboardBodySchema, storyboardSteps, type StoryboardRun } from "@/server/storyboard";
import { refusedRun } from "@/server/connect-refusal";
import { once } from "@/server/shorts-schemas";
@@ -15,6 +15,7 @@ export async function POST(request: Request) {
const big = bodyTooBig(request);
if (big) return big;
}
+ const wishes = viewer.kind === "account" ? await toolWishes(request) : {};
const parsed = StoryboardBodySchema.safeParse(await request.json().catch(() => null));
if (!parsed.success) return Response.json({ error: parsed.error.issues.map((i) => i.message).join("; ") }, { status: 400 });
const input = parsed.data;
@@ -35,6 +36,7 @@ export async function POST(request: Request) {
() =>
runAccountTool(request, viewer.account, {
tool: "storyboard",
+ ...wishes,
files: input.references ?? [],
plan: async () => storyboardSteps((run = await planStoryboardRun(input, { owner: false }))),
start: () => startStoryboard(run!),
diff --git a/src/app/api/uploads/route.ts b/src/app/api/uploads/route.ts
index 1a2a769c..92efdff5 100644
--- a/src/app/api/uploads/route.ts
+++ b/src/app/api/uploads/route.ts
@@ -4,7 +4,7 @@ import { nanoid } from "nanoid";
import { CONNECT_GPU_HEADER, CONNECT_GPU_UPLOAD_MESSAGE, CONNECT_GPU_UPLOAD_OPEN_MESSAGE, KINETIC_UPLOAD_HEADER } from "@/lib/guest-access";
import { accountProviders, paidAllowed } from "@/server/account-keys";
import { policy as billingPolicy } from "@/server/billing";
-import { poolReady, poolTakesFiles } from "@/server/hosted";
+import { poolReady, poolUploads } from "@/server/hosted";
import { imageSize } from "@/lib/image-size";
import { sniffMedia, type SniffKind } from "@/lib/sniff";
import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "@/server/account-files";
@@ -182,13 +182,13 @@ type Without = { hosted: Kinds | null; kinetic: boolean };
/**
* The kinds of file an account with no GPU or key of its own may add for runs on this install's GPUs (hosted runs): the
- * policy's, and only those this install's GPUs take.
+ * policy's, and only those this install's GPUs take (hosted.ts poolUploads, which the run reads too).
*/
async function hostedUploads(accountId: string): Promise<Kinds | null> {
if (!poolReady()) return null;
const p = await billingPolicy(accountId);
if (!p?.hosted) return null;
- const kinds: Kinds = { image: p.uploads.image && poolTakesFiles("image"), video: p.uploads.video && poolTakesFiles("video"), audio: p.uploads.audio && poolTakesFiles("audio") };
+ const kinds: Kinds = poolUploads(p);
return kinds.image || kinds.video || kinds.audio ? kinds : null;
}
diff --git a/src/proxy.ts b/src/proxy.ts
index a57811db..04357f06 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -283,8 +283,9 @@ function account(request: NextRequest, who: Account): NextResponse {
// A tool its own GPU or key wouldn't run says so first: "Connect your GPU" only for what a GPU or a key unlocks.
if (!ownGpuRun(request.method, pathname)) return ownGpuTool();
// Neither its own GPU nor its own key: nothing it could run on. (Which one a run needs, the route says.)
- // With hosted runs on (FUOBE_HOSTED_RUNS=1), a run in the studios may go to this install's GPUs: the route decides.
- const hosted = hostedRunsOn() && request.method === "POST" && pathname === "/api/generations";
+ // With hosted runs on (FUOBE_HOSTED_RUNS=1), a run in the studios or a tool's run may go to this install's GPUs: the route
+ // decides (hosted-run.ts decidePlace, account-tool-run.ts placeOf).
+ const hosted = hostedRunsOn();
if (!who.gpu && !hasCloudKey(who) && !hosted) return NextResponse.json({ error: CONNECT_GPU_OR_KEY_MESSAGE, code: "connect-gpu" }, { status: 403, headers: { [CONNECT_GPU_HEADER]: "1" } });
return pass(request);
}
diff --git a/src/server/account-tool-run.ts b/src/server/account-tool-run.ts
index 04e0c52b..5c232fcb 100644
--- a/src/server/account-tool-run.ts
+++ b/src/server/account-tool-run.ts
@@ -14,9 +14,14 @@ import { checkAccountLoras } from "./account-loras";
import { requestViewer, type Account } from "./auth";
import { db } from "./db";
import { accountRun, AccountRunError, asAccount, asVisitor, outputKind, previewChained, type AccountRunRefusal } from "./generations";
+import { BILLING_HEADER, type Quote } from "./billing";
+import { queueRelease } from "./billing-outbox";
import { gateGeneration, GPU_SETUP_HEADER } from "./gpu/gate";
import { gpuTargetFor } from "./gpu/target";
-import { moderateRun } from "./hosted-run";
+import { runOnPool } from "./hosted";
+import { decideToolPlace, GUEST_PLAN, moderateRun, poolMayTake, readWishes, reservePool, stepsProblem, toolPoolQuote, type PlaceWish, type PoolLine, type Refusal, type ToolPoolRun } from "./hosted-run";
+import { cancelGeneration, captureRun, stepsOf } from "./generations";
+import { AdmitRefused, admitRun, clientAddress, poolLimitRefusal } from "./pool-limits";
import { hit, unhit } from "./rate";
import { withRunStamp, type RunStamp } from "./run-stamp";
import { once } from "./shorts-schemas";
@@ -38,8 +43,11 @@ import { ShortsError } from "./shorts";
* - a 3D model only on the account's own GPU or key (model3dAllowed): its finish runs on this server under its limits.
*
* Then the tool's own start runs inside asAccount (tenant.ts): every generation it creates is stamped as the account's,
- * reads only its files and goes to its GPU or key. Where a run goes is decided in one place (`placeOf`): today always the
- * account's own GPU or key. Hosted runs (the install's GPUs) hook in there.
+ * reads only its files and goes to its GPU or key. Where a run goes is decided in one place (`placeOf`): with hosted
+ * runs off, always the account's own GPU or key. With them on (FUOBE_HOSTED_RUNS=1), placeOf may put the whole run on
+ * this install's GPUs instead, through the same gate as a studio run (hosted-run.ts decideToolPlace): the policy's
+ * limits, one hold for the whole run priced from every step, and every row stamped for there (runOnPool). The checks of
+ * the account's own GPU above (its provider, the pre-flight, its LoRAs) then don't apply.
*
* The owner's runs never come here: a route runs them as before.
*/
@@ -139,25 +147,81 @@ export interface ToolStep {
deps?: number;
}
-/** Where an account's tool run goes. Today always its own GPU or key ("own"); hosted runs add the install's GPUs ("pool"). */
-export type ToolPlace = { kind: "own" } | { kind: "pool" };
+/**
+ * Where an account's tool run goes: its own GPU or key ("own", as always), this install's GPUs ("pool", hosted runs: the
+ * whole run's decision, policy and price, hosted-run.ts decideToolPlace), or a refusal in the price check's words.
+ */
+export type ToolPlace = { kind: "own" } | ({ kind: "pool" } & ToolPoolRun) | { kind: "refuse"; refusal: Refusal };
/**
* Whether a run placed here may make a 3D model. A 3D model is finished on this server under the account's own limits
* (model3d-finish.ts): allowed on the account's own GPU or key, never on this install's GPUs (hosted runs don't offer 3D yet).
*/
-export const model3dAllowed = (place: ToolPlace): boolean => place.kind === "own";
+export const model3dAllowed = (place: Pick<ToolPlace, "kind">): boolean => place.kind === "own";
+
+/**
+ * Where this run goes. The one place a tool run's placement is decided, as decidePlace decides a studio run's: with
+ * hosted runs off (FUOBE_HOSTED_RUNS unset), or asked for its own GPU, always the account's own GPU or key. On, every
+ * step goes through the same gate as a studio run (hosted-run.ts toolGate); runAccountTool then holds the run's price
+ * once and starts it inside runOnPool and its stamp.
+ */
+export async function placeOf(account: Account, steps: ToolStep[], wish?: PlaceWish): Promise<ToolPlace> {
+ return decideToolPlace(account, steps, wish);
+}
+
+/**
+ * A tool's price check (`?preview=1` or its estimate route) on this install's GPUs: `{ place: "pool", quote, line }` to
+ * add to the tool's own answer, or null when the run wouldn't go there (the tool prices it as today). `plan` gives the
+ * run's steps as the viewer's run plans them; a plan that can't be made prices nothing here (the tool says why).
+ */
+export async function toolPriceCheck(
+ request: Request,
+ plan: () => ToolStep[] | Promise<ToolStep[]>,
+ wish?: PlaceWish,
+): Promise<{ place: "pool"; quote: Quote; line: PoolLine } | null> {
+ const v = toolViewer(request);
+ if (v.kind === "owner") return null;
+ const account = v.kind === "account" ? v.account : null;
+ if (!poolMayTake(account, wish)) return null;
+ let steps: ToolStep[];
+ try {
+ steps = account ? await planAs(account, plan, wish) : await runOnPool(GUEST_PLAN, plan);
+ } catch {
+ return null;
+ }
+ const q = await toolPoolQuote(account, steps, wish, { addr: () => clientAddress(request) });
+ return q && { place: "pool", quote: q.quote, line: q.line };
+}
/**
- * Where this run goes. The one place a tool run's placement is decided: hosted runs (hosted-run.ts decidePlace, the
- * billing hold and runOnPool) hook in here for tools, as POST /api/generations does for the studios. Until then a tool
- * runs on the account's own GPU or key, whatever FUOBE_HOSTED_RUNS says (docs/public-signup.md: "Every other tool still
- * needs the account's own GPU").
+ * What a tool's run body carries beside the tool's own fields (hosted-run.ts readWishes): the place the client prefers
+ * and the price it showed before Run. Read from a copy, before the route reads the body itself.
*/
-export async function placeOf(account: Account, steps: ToolStep[]): Promise<ToolPlace> {
- void account;
- void steps;
- return { kind: "own" };
+export async function toolWishes(request: Request): Promise<{ place?: PlaceWish; shown?: { amount: number; priceVersion: string } | null }> {
+ const raw = await request
+ .clone()
+ .json()
+ .catch(() => null);
+ const { wish, shown } = readWishes(raw);
+ return { ...(wish && { place: wish }), shown };
+}
+
+/**
+ * A tool's plan as the account's own run plans it (its GPU, its keys), as always. When that can't be made (no GPU or
+ * key of its own to plan it on) and the run could go to this install's GPUs, it is planned as a run there instead; the
+ * first plan's refusal stands when neither can be made.
+ */
+async function planAs(account: Account, plan: () => ToolStep[] | Promise<ToolStep[]>, wish: PlaceWish | undefined): Promise<ToolStep[]> {
+ try {
+ return await asAccount(account.id, plan);
+ } catch (e) {
+ if (!poolMayTake(account, wish)) throw e;
+ try {
+ return await runOnPool(account.id, plan);
+ } catch {
+ throw e;
+ }
+ }
}
export interface AccountToolRun<T> {
@@ -174,6 +238,10 @@ export interface AccountToolRun<T> {
start: () => T | Promise<T>;
/** `gpuCheck: "skip"` from the request (the pre-flight's "Run anyway"). */
skipGpuCheck?: boolean;
+ /** The place the client prefers (hosted-run.ts readWishes): "own", "pool", or none. */
+ place?: PlaceWish;
+ /** The price the client showed before Run (hosted-run.ts readWishes). */
+ shown?: { amount: number; priceVersion: string } | null;
}
export type AccountToolResult<T> = { ok: true; value: T; gpuWarning?: string } | { ok: false; response: Response };
@@ -241,23 +309,23 @@ export async function runAccountTool<T>(request: Request, account: Account, run:
if (problem) return back(refuse(problem.status, problem.error, { code: problem.code }));
let steps: ToolStep[];
try {
- steps = await asAccount(id, run.plan);
+ steps = await planAs(account, run.plan, run.place);
} catch (e) {
return back(errorResponse(e));
}
if (!steps.length) return back(refuse(422, "Nothing to run yet."));
- const place = await placeOf(account, steps);
+ const place = await placeOf(account, steps, run.place);
+ if (place.kind === "refuse") return back(refuse(place.refusal.status, place.refusal.body.error, place.refusal.body, place.refusal.headers));
+ if (place.kind === "pool") return startOnPool(request, account, run, steps, files, place, back);
let gpuWarning: string | undefined;
let kind: MediaKind = "video";
let onKey = false;
try {
// Each step's provider must be one the account has; a 3D model only where model3dAllowed says.
const planned: Planned[] = steps.map((s) => ({ step: s, p: asAccount(id, () => previewChained(s.request, s.deps ?? 0)) }));
- if (place.kind === "own") {
- for (const provider of new Set(planned.map((x) => x.p.route.provider))) {
- const own = accountRun(id, provider, "submit");
- if ("error" in own) return back(refusalResponse(own));
- }
+ for (const provider of new Set(planned.map((x) => x.p.route.provider))) {
+ const own = accountRun(id, provider, "submit");
+ if ("error" in own) return back(refusalResponse(own));
}
if (!model3dAllowed(place) && planned.some(({ p }) => outputKind(p.op, p.model) === "model3d" && p.model.id !== ANY_ANGLE.buildModel)) return back(ownGpuTool());
// GPU pre-flight on its own ComfyUI: a step sure to fail for something missing stops the run with the plan that
@@ -282,10 +350,7 @@ export async function runAccountTool<T>(request: Request, account: Account, run:
return back(errorResponse(e));
}
// The moderation service's check (none set: nothing is checked), on the run's words and its files.
- const first = steps.find((s) => !s.deps) ?? steps[0];
- const words = steps.map((s) => s.request.prompt?.trim()).filter(Boolean);
- const checked: GenerationRequest = { ...first.request, prompt: [...new Set(words)].join("\n").slice(0, 8000), inputs: filesAsInputs(files) };
- const mod = await moderateRun(account, checked, null, "own", { kind, place: onKey ? "own-key" : "own-gpu" });
+ const mod = await moderateRun(account, checkedRequest(steps, files), null, "own", { kind, place: onKey ? "own-key" : "own-gpu" });
if (!mod.ok) return back(refuse(mod.refusal.status, mod.refusal.body.error, mod.refusal.body, mod.refusal.headers));
const stamp: RunStamp | null = mod.checkOutputs ? { checkOutputs: true } : null;
// Counted again just before the run is stored, with nothing awaited in between.
@@ -297,3 +362,96 @@ export async function runAccountTool<T>(request: Request, account: Account, run:
return back(errorResponse(e));
}
}
+
+/** What the moderation service checks of a tool's run: its words (every step's, once each) and its files. */
+function checkedRequest(steps: ToolStep[], files: string[]): GenerationRequest {
+ const first = steps.find((s) => !s.deps) ?? steps[0];
+ const words = steps.map((s) => s.request.prompt?.trim()).filter(Boolean);
+ return { ...first.request, prompt: [...new Set(words)].join("\n").slice(0, 8000), inputs: filesAsInputs(files) };
+}
+
+const isThenable = (v: unknown): v is PromiseLike<unknown> => !!v && typeof (v as { then?: unknown }).then === "function";
+
+/**
+ * A tool run on this install's GPUs (placeOf said "pool"): the policy's limits on runs there (never for light work
+ * only), the moderation service's check, one hold for the whole run priced from every step (none for light work: free),
+ * then the run made as the account's run there (runOnPool, every row stamped with its place and hold) and counted in
+ * the same transaction (admitRun). Every row it makes is checked against the policy again before anything is sent
+ * (stepsProblem): a step the policy doesn't allow stops the whole run, its rows are stopped, and its hold goes back.
+ * Its own GPU's checks (the pre-flight, its LoRAs) don't apply here.
+ */
+async function startOnPool<T>(
+ request: Request,
+ account: Account,
+ run: AccountToolRun<T>,
+ steps: ToolStep[],
+ files: string[],
+ pool: Extract<ToolPlace, { kind: "pool" }>,
+ back: (response: Response) => AccountToolResult<T>,
+): Promise<AccountToolResult<T>> {
+ const id = account.id;
+ const addr = clientAddress(request);
+ const over = pool.light ? null : poolLimitRefusal(id, pool.policy, addr);
+ if (over) return back(refuse(over.status, over.error, { code: over.code }, { "Retry-After": String(over.retryAfterS) }));
+ const kind = outputKind(pool.main.planned.op, pool.main.planned.model);
+ const mod = await moderateRun(account, checkedRequest(steps, files), null, "pool", { kind, place: "pool" });
+ if (!mod.ok) return back(refuse(mod.refusal.status, mod.refusal.body.error, mod.refusal.body, mod.refusal.headers));
+ let stamp: RunStamp;
+ if (pool.light) stamp = { place: "pool", light: true, ...(mod.checkOutputs && { checkOutputs: true }) };
+ else {
+ const held = await reservePool(account, pool.main.req, pool.main.planned, run.shown ?? null, mod.checkOutputs, pool.steps);
+ if (!held.ok) return back(refuse(held.refusal.status, held.refusal.body.error, held.refusal.body, held.refusal.headers));
+ stamp = held.stamp;
+ }
+ const release = () => {
+ if (stamp.hold) queueRelease(stamp.hold);
+ };
+ const notOffered = (error: string) => refuse(403, error, { code: "not-offered" }, { [BILLING_HEADER]: "not-offered" });
+ type Made = { value: T | Promise<T>; ids: string[]; start: () => void };
+ let admitted: { ok: true; value: Made } | { ok: false; refusal: { status: number; error: string; code: string; retryAfterS?: number } };
+ try {
+ admitted = runOnPool(id, () =>
+ withRunStamp(stamp, () =>
+ admitRun({ accountId: id, pool: pool.light ? null : { policy: pool.policy, addr } }, (): Made => {
+ const made = captureRun(run.start);
+ // A tool that makes its rows as it goes (after an await) is checked once they are all made, below.
+ if (!isThenable(made.value)) {
+ const problem = stepsProblem(pool.policy, stepsOf(made.ids));
+ if (problem) throw new AdmitRefused({ status: 403, error: problem, code: "not-offered" });
+ }
+ return made;
+ }),
+ ),
+ );
+ } catch (e) {
+ release();
+ return back(errorResponse(e));
+ }
+ if (!admitted.ok) {
+ release();
+ const r = admitted.refusal;
+ return back(r.code === "not-offered" ? notOffered(r.error) : refuse(r.status, r.error, { code: r.code }, { "Retry-After": String(r.retryAfterS ?? 30) }));
+ }
+ const made = admitted.value;
+ /** Stop what was made (nothing of it was sent) and give the hold back. */
+ const undo = () => {
+ for (const g of made.ids) void cancelGeneration(g);
+ release();
+ };
+ let value: T;
+ try {
+ value = await made.value;
+ } catch (e) {
+ undo();
+ return back(errorResponse(e));
+ }
+ if (isThenable(made.value)) {
+ const problem = stepsProblem(pool.policy, stepsOf(made.ids));
+ if (problem) {
+ undo();
+ return back(notOffered(problem));
+ }
+ }
+ made.start();
+ return { ok: true, value };
+}
diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.ts
index f8a5228f..877b3eb5 100644
--- a/src/server/hosted-run.ts
+++ b/src/server/hosted-run.ts
@@ -26,10 +26,10 @@ import {
} from "./billing";
import { getModel } from "@/lib/catalog";
import { PLACE_ASK_HEADER } from "@/lib/guest-access";
-import { createGenerations, outputKind, plannedSteps, previewGeneration, type PlannedStep } from "./generations";
+import { createGenerations, outputKind, plannedSteps, previewChained, previewGeneration, type PlannedStep } from "./generations";
import { loadIndex } from "./gpu/index-file";
import { poolLane } from "./computer/pool";
-import { HOSTED_GUEST_WORDS, HOSTED_WORDS, inputCounts, poolAllows, poolAllowsRun, poolOnWorkers, poolReady, poolRunsProvider, poolTakes, poolTakesFiles, POOL_LANE, queueFacts, runFacts, runOnPool, workflowPicks } from "./hosted";
+import { HOSTED_GUEST_WORDS, HOSTED_WORDS, inputCounts, poolAllows, poolAllowsRun, poolOnWorkers, poolReady, poolRunsProvider, poolTakes, poolUploads, POOL_LANE, queueFacts, runFacts, runOnPool, workflowPicks } from "./hosted";
import { withRunStamp } from "./run-stamp";
import { hostedRunsOn } from "./hosted-switch";
import { checkRun, moderationConfigured } from "./moderation";
@@ -86,13 +86,13 @@ export type PlaceDecision =
| { kind: "pool"; planned: Planned; policy: Policy; steps: RunFacts["steps"]; req: GenerationRequest; capped: boolean; light: boolean }
| { kind: "refuse"; refusal: Refusal };
-const OWN: PlaceDecision = { kind: "own" };
+const OWN = { kind: "own" } as const;
/** What an account whose own GPU didn't answer is asked, when its run named no place (never moved and charged unasked). */
export const OWN_GPU_QUIET = "Your GPU isn't answering right now. Run this on this studio's GPUs instead, or try again when your GPU is back.";
/** A run this install's GPUs won't take, refused in the words the price check before Run gives too. */
-const notOffered = (error: string): PlaceDecision => ({ kind: "refuse", refusal: { status: 403, body: { error, code: "not-offered" }, headers: { [BILLING_HEADER]: "not-offered" } } });
+const notOffered = (error: string): { kind: "refuse"; refusal: Refusal } => ({ kind: "refuse", refusal: { status: 403, body: { error, code: "not-offered" }, headers: { [BILLING_HEADER]: "not-offered" } } });
const askPlace = (): Refusal => ({ status: 409, body: { error: OWN_GPU_QUIET, code: "own-gpu-offline" }, headers: { [PLACE_ASK_HEADER]: "1" } });
@@ -107,13 +107,20 @@ const stepEndpoint = (s: PlannedStep): string | undefined => {
return (m?.routes.find((r) => r.op === s.op && r.provider === s.provider) ?? m?.routes.find((r) => r.provider === s.provider))?.endpoint;
};
+/**
+ * A text step (the install's AI helper writing a script, lyrics or a translation) inside a run on this install's GPUs:
+ * it runs on the helper, costs nothing and is never counted against the policy's limits.
+ */
+export const helperStep = (provider: string): boolean => provider === "llm";
+
/**
* A ComfyUI step of CPU work (the requirements index marks it `cpu`: no model file, no first-run download, no graphics
* memory and no card its nodes need, such as a filter, a trim, a join, adding sound or a Ken Burns move): light work that
* costs nothing, that every policy allows, and that is never counted. A step whose nodes run on the card (RTX Video) is
- * GPU work, model file or not.
+ * GPU work, model file or not. A chain's text step (helperStep) is free too.
*/
function freeStep(s: PlannedStep): boolean {
+ if (helperStep(s.provider)) return true;
if (s.provider !== "comfyui") return false;
const endpoint = stepEndpoint(s);
if (!endpoint) return false;
@@ -216,8 +223,8 @@ export function poolGate(
if (req.loras?.length) return { ok: false, reason: "loras" };
if (p) {
const inputs = inputCounts(req);
- const takes = (k: "image" | "video" | "audio") => p.uploads[k] && poolTakesFiles(k);
- if ((inputs.image && !takes("image")) || (inputs.video && !takes("video")) || (inputs.audio && !takes("audio"))) return { ok: false, reason: "inputs" };
+ const takes = poolUploads(p);
+ if ((inputs.image && !takes.image) || (inputs.video && !takes.video) || (inputs.audio && !takes.audio)) return { ok: false, reason: "inputs" };
}
// Every step of a chain, not only its first: each one the policy must allow, and the run is priced for all of them.
const steps = planSteps();
@@ -230,7 +237,7 @@ export function poolGate(
* The account a guest's price check plans a chain's later steps under: no real account has it (account ids hold no
* colon), and nothing planned under it is kept (plannedSteps throws every row away).
*/
-const GUEST_PLAN = "guest:plan";
+export const GUEST_PLAN = "guest:plan";
/** Every row a run would make on this install's GPUs, for an account or (planned as nobody's) for a guest's price check. */
const stepsFor = (account: Account | null, req: GenerationRequest) => poolSteps(account?.id ?? GUEST_PLAN, req);
@@ -506,3 +513,154 @@ export async function poolQuote(
}
return { planned, quote: q, line: line(queue, q) };
}
+
+/**
+ * Tool runs (account-tool-run.ts: Genjutsu, Storyboard, Character Swap Studio, the apps and the other tools that plan a
+ * run as a pipeline of generations): the same decision as a studio run's, made once for the whole run. Every step goes
+ * through poolGate as a studio run would (a chain's later steps too); the run is priced once from every step, held once,
+ * and counted once against the policy's limits. A text step (a script, lyrics, a translation) runs on the install's AI
+ * helper for free; a join, a trim or adding sound is free CPU work. A run with no ComfyUI step at all stays where it
+ * runs today.
+ */
+
+/** One step of a tool's run, as the tool planned it: its request, and how many earlier steps it waits for. */
+export interface ToolRunStep {
+ request: GenerationRequest;
+ deps?: number;
+}
+
+/** A tool run on this install's GPUs: its policy, the step it is priced and held as, its steps priced once, and whether it is light work only. */
+export interface ToolPoolRun {
+ policy: Policy;
+ main: { req: GenerationRequest; planned: Planned };
+ steps: RunFacts["steps"];
+ light: boolean;
+}
+
+export type ToolPlaceDecision = { kind: "own" } | ({ kind: "pool" } & ToolPoolRun) | { kind: "refuse"; refusal: Refusal };
+
+/** A planned step as a row it would make (for a step that waits, whose own chain can't be planned before its inputs exist). */
+const asPlannedStep = (req: GenerationRequest, p: Planned, waits: boolean): PlannedStep => ({
+ id: "",
+ modelId: p.model.id,
+ op: p.op,
+ provider: p.route.provider,
+ kind: outputKind(p.op, p.model),
+ presetId: req.presetId ?? null,
+ waits,
+});
+
+/**
+ * Every step of a tool's run through poolGate, as `viewer` (an account's id, or null for a guest's price check):
+ * "unplanned" when a step can't be planned on this install's GPUs (a cloud model, a request with something wrong: the
+ * run goes where it goes today, which says what), or the first step's refusal; passed, the step the run is priced as
+ * (its first ComfyUI step) and every row the run would make.
+ */
+export function toolGate(
+ p: Policy | null,
+ viewer: string | null,
+ steps: ToolRunStep[],
+): "unplanned" | { ok: false; reason: GateReason } | { ok: true; main: ToolPoolRun["main"]; rows: PlannedStep[] } {
+ let main: ToolPoolRun["main"] | null = null;
+ const rows: PlannedStep[] = [];
+ for (const step of steps) {
+ const deps = step.deps ?? 0;
+ const { req } = poolRequest(step.request, p);
+ let planned: Planned;
+ try {
+ planned = runOnPool(viewer, () => previewChained(req, deps));
+ } catch {
+ return "unplanned";
+ }
+ if (helperStep(planned.route.provider)) {
+ rows.push(asPlannedStep(req, planned, deps > 0));
+ continue;
+ }
+ 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;
+ rows.push(...(gate.steps ?? [asPlannedStep(req, planned, deps > 0)]));
+ main ??= { req, planned };
+ }
+ return main ? { ok: true, main, rows } : "unplanned";
+}
+
+/**
+ * Where an account's tool run goes: decidePlace's order for a whole run. With hosted runs off, or asked for its own GPU,
+ * always "own" (today). An account with a GPU of its own keeps it first (unless the policy puts this install's first),
+ * and a run this install's GPUs won't take goes there; with none, it runs here or is refused in the price check's words.
+ */
+export async function decideToolPlace(account: Account, steps: ToolRunStep[], wish: PlaceWish): Promise<ToolPlaceDecision> {
+ if (!hostedRunsOn() || wish === "own" || !poolReady() || !steps.length) return OWN;
+ const ownFallback = !!accountGpu(account.id) && wish !== "pool";
+ let p = cachedPolicy(account.id);
+ let ownOffline = false;
+ if (ownFallback && !prefersPool(p)) {
+ const [online, read] = await Promise.all([ownGpuOnline(account.id), p === undefined ? billingPolicy(account.id) : Promise.resolve(p)]);
+ p = read;
+ if (!prefersPool(p)) {
+ if (online) return OWN;
+ ownOffline = true;
+ }
+ }
+ if (p === undefined) p = await billingPolicy(account.id);
+ if (!p) return ownFallback ? OWN : { kind: "refuse", refusal: billingRefusal("paused", BILLING_WAIT.run) };
+ if (!p.hosted) return wish === "pool" ? notOffered(HOSTED_WORDS.notHosted) : OWN;
+ const gate = toolGate(p, account.id, steps);
+ if (gate === "unplanned") return OWN;
+ if (!gate.ok) {
+ if (ownFallback) return OWN;
+ const error = gateWords(gate.reason, false);
+ return gate.reason === "model3d" ? { kind: "refuse", refusal: { status: 403, body: { error, code: "own-gpu-tool" }, headers: {} } } : notOffered(error);
+ }
+ if (ownOffline) return { kind: "refuse", refusal: askPlace() };
+ return { kind: "pool", policy: p, main: gate.main, steps: pricedSteps(gate.rows), light: lightRun(gate.rows) };
+}
+
+/**
+ * A tool's price check on this install's GPUs (hosted runs on): the billing service's quote for the whole run, priced
+ * once from every step, and where it would stand in line; refused before Run for what the run would be refused for (the
+ * same toolGate, and the policy's limits). Null when the run wouldn't go there (its own GPU, its own key, today's answer).
+ */
+export async function toolPoolQuote(
+ account: Account | null,
+ steps: ToolRunStep[],
+ wish: PlaceWish,
+ o: { addr?: () => string | null } = {},
+): Promise<{ quote: Quote; line: PoolLine } | null> {
+ if (!hostedRunsOn() || wish === "own" || !poolReady() || !steps.length) return null;
+ const p = await billingPolicy(account?.id ?? null);
+ const hasGpu = !!account && !!accountGpu(account.id);
+ if (account && hasGpu && wish !== "pool" && !prefersPool(p) && (await ownGpuOnline(account.id))) return null;
+ if (p && !p.hosted) return null;
+ const gate = toolGate(p, account?.id ?? null, steps);
+ if (gate === "unplanned") return null;
+ const lineOf = (endpoint: string | undefined, q?: Quote): PoolLine => {
+ const facts = queueFacts(account?.id ?? null, endpoint);
+ return { place: Math.max(0, facts.ahead) + 1, etaSeconds: q?.etaS ?? facts.etaS ?? null };
+ };
+ if (!gate.ok) {
+ if (hasGpu && wish !== "pool") return null;
+ return { quote: notOfferedQuote(gateWords(gate.reason, !account)), line: lineOf(undefined) };
+ }
+ const endpoint = gate.main.planned.route.endpoint;
+ if (lightRun(gate.rows)) return { quote: FREE_QUOTE, line: lineOf(endpoint) };
+ const { req, planned } = gate.main;
+ const facts = { ...runOnPool(account?.id ?? null, () => runFacts(req, planned, outputKind(planned.op, planned.model))), steps: pricedSteps(gate.rows) };
+ let q = await billingQuote(account ? accountFacts(account) : null, facts, queueFacts(account?.id ?? null, endpoint));
+ if (q.allowed && account && p) {
+ const over = poolLimitRefusal(account.id, p, o.addr ?? null);
+ if (over) q = { ...q, allowed: false, code: "limit", text: over.error };
+ }
+ return { quote: q, line: lineOf(endpoint, q) };
+}
+
+/**
+ * Could a viewer's tool run go to this install's GPUs, before its plan is made: hosted runs ready, not asked for its own
+ * GPU, and no GPU of its own that goes first (or this install's asked for, or put first by the policy as last read). A
+ * tool whose plan can't be made as the viewer's own run (no GPU or key of its own to plan it on) is planned here then.
+ */
+export function poolMayTake(account: Account | null, wish: PlaceWish): boolean {
+ if (!hostedRunsOn() || wish === "own" || !poolReady()) return false;
+ return !account || !accountGpu(account.id) || wish === "pool" || prefersPool(cachedPolicy(account.id));
+}
diff --git a/src/server/hosted.ts b/src/server/hosted.ts
index 14e811bf..da1c3600 100644
--- a/src/server/hosted.ts
+++ b/src/server/hosted.ts
@@ -85,16 +85,29 @@ export function poolTakes(endpoint: string | undefined): boolean {
}
/**
- * The steps a run on this install's GPUs can carry out there: ComfyUI's. The price check, the run's admission and its
- * submit read this one table, so a run is refused before Run when a step of it couldn't run there (a text step, a step
- * made in the browser, a cloud model), never part way through.
+ * The steps a run on this install's GPUs can carry out there: ComfyUI's, and a chain's text steps (a script, lyrics, a
+ * translation), which the install's AI helper writes for free. The price check, the run's admission and its submit read
+ * this one table, so a run is refused before Run when a step of it couldn't run there (a step made in the browser, a
+ * cloud model), never part way through.
*/
-const POOL_PROVIDERS: ReadonlySet<string> = new Set(["comfyui"]);
+const POOL_PROVIDERS: ReadonlySet<string> = new Set(["comfyui", "llm"]);
export const poolRunsProvider = (provider: string): boolean => POOL_PROVIDERS.has(provider);
/** May a run on this install's GPUs send them this kind of file (the workers take only the kinds the install allows)? */
export const poolTakesFiles = (kind: "image" | "video" | "audio"): boolean => !poolOnWorkers() || workersTake(kind);
+/**
+ * The kinds of input file a run on this install's GPUs may use, read in one place by the upload route, the price check
+ * and the run: a kind the policy's `uploads` allows and the install's GPUs take (poolTakesFiles). With no billing
+ * service the policy is the open one (pictures only), and clips and sound follow what the workers take
+ * (FUOBE_POOL_MEDIA_INPUTS): each worker makes every clip and sound again before its ComfyUI reads it.
+ */
+export function poolUploads(p: Pick<Policy, "uploads">): { image: boolean; video: boolean; audio: boolean } {
+ const open = !billingConfigured() && poolOnWorkers();
+ const takes = (kind: "image" | "video" | "audio") => (!!p.uploads?.[kind] || (open && kind !== "image")) && poolTakesFiles(kind);
+ return { image: takes("image"), video: takes("video"), audio: takes("audio") };
+}
+
/**
* Run `fn` as an account's run on this install's GPUs: as the account (its own files and runs only), on this install's
* ComfyUI server, the open engine, no demo outputs.
diff --git a/src/server/swap-studio-account.ts b/src/server/swap-studio-account.ts
index a022a881..54edf4cd 100644
--- a/src/server/swap-studio-account.ts
+++ b/src/server/swap-studio-account.ts
@@ -3,7 +3,7 @@ import { headers } from "next/headers";
import type { z } from "zod";
import { GUEST_HEADER, GUEST_LIBRARY_MESSAGE } from "@/lib/guest-access";
import { projectRefsProblem, projectSavesLimited } from "./account-projects";
-import { bodyTooBig, guestRun, refusalResponse, runAccountTool, toolViewer } from "./account-tool-run";
+import { bodyTooBig, guestRun, refusalResponse, runAccountTool, toolViewer, toolWishes } from "./account-tool-run";
import { requestViewer, type Account } from "./auth";
import { AccountRunError, asAccount } from "./generations";
import { recordExists } from "./records";
@@ -45,7 +45,11 @@ function refused(e: unknown): Response {
* One of an account's jobs (see the header): `files` the request names itself (a clip's upload), checked first; then the
* job planned, checked and started as one run. A job that makes nothing (a clip the cloud reads as filmed) is a save.
*/
-export async function runSwapJob(request: Request, account: Account, job: { run: () => unknown; files?: (string | null | undefined)[]; status?: number }): Promise<Response> {
+export async function runSwapJob(
+ request: Request,
+ account: Account,
+ job: { run: () => unknown; files?: (string | null | undefined)[]; status?: number; wishes?: Awaited<ReturnType<typeof toolWishes>> },
+): Promise<Response> {
const bad = refsRefused(account.id, job.files ?? []);
if (bad) return bad;
let planned: Awaited<ReturnType<typeof planSwapJob>>;
@@ -65,7 +69,7 @@ export async function runSwapJob(request: Request, account: Account, job: { run:
}
}
const files = [...(job.files ?? []), ...planned.files].filter((f): f is string => !!f);
- const r = await runAccountTool(request, account, { tool: "character-swap", files, plan: () => planned.steps, start: () => startSwapJob(job.run) });
+ const r = await runAccountTool(request, account, { tool: "character-swap", files, plan: () => planned.steps, start: () => startSwapJob(job.run), ...job.wishes });
return r.ok ? Response.json(r.value, { status }) : r.response;
}
@@ -91,11 +95,12 @@ export function jobRoute<S extends z.ZodType>(
}
return handle(async () => {
const { id } = await ctx.params;
+ const wishes = viewer.kind === "account" ? await toolWishes(request) : {};
const b = await body(request, schema, message);
if (viewer.kind === "owner") return Response.json(await start(id, b), { status: opts.status ?? 201 });
const no = opts.refuse?.(b);
if (no) return no;
- return runSwapJob(request, viewer.account, { run: () => start(id, b), files: opts.files?.(b), status: opts.status });
+ return runSwapJob(request, viewer.account, { run: () => start(id, b), files: opts.files?.(b), status: opts.status, wishes });
}, request);
};
}
diff --git a/tests/hosted-tool-runs.test.ts b/tests/hosted-tool-runs.test.ts
new file mode 100644
index 00000000..ec5930d5
--- /dev/null
+++ b/tests/hosted-tool-runs.test.ts
@@ -0,0 +1,240 @@
+import http from "node:http";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { NextRequest } from "next/server";
+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";
+
+/**
+ * A tool's run (Storyboard here, and every tool that runs through account-tool-run.ts) for an account with no GPU of its
+ * own: with hosted runs on it runs on this install's GPUs through the same gate as a studio run, held and counted once
+ * however many steps it has; with them off, or for an account whose own GPU answers, nothing changes.
+ */
+const dir = tempDir("fuobe-hosted-tool-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 boardsRoute = await import("@/app/api/storyboards/route");
+const gpuRoute = await import("@/app/api/account/gpu/route");
+const { proxy } = await import("@/proxy");
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const billing = await import("@/server/billing");
+const hostedRun = await import("@/server/hosted-run");
+const toolRun = await import("@/server/account-tool-run");
+const { createGenerations } = await import("@/server/generations");
+const { OWN_GPU_TOOL_MESSAGE } = await import("@/lib/guest-access");
+const { drainOutbox } = await import("@/server/billing-outbox");
+
+let fake: FakeBilling;
+const ids: Record<string, string> = {};
+const cookies: Record<string, string> = {};
+beforeAll(async () => {
+ fake = await startFakeBilling();
+ auth.setPassword("install password");
+ for (const who of ["none", "gpu"]) {
+ ids[who] = auth.createAccount(`tools-${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_HOSTED_FREE", "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_HOSTED_FREE;
+ 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: 7, waiting: 7, runsPerHour: 70, outputsPerRun: 2, maxMegapixels: 7, maxSeconds: 7, 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,
+ });
+}
+const viaProxy = (url: string, who: string) =>
+ proxy(new NextRequest(`http://localhost:3000${url}`, { method: "POST", headers: { host: "localhost:3000", cookie: cookies[who], "content-type": "application/json" }, body: "{}" }));
+const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";
+
+const SCENES = ["A model in an emerald gown on a palace stair at midnight", "She runs to a vintage car under the lamps", "The car on a coast road at dawn"];
+const board = async (who: string, extra: Record<string, unknown> = {}) => {
+ const r = await boardsRoute.POST(json("/api/storyboards", "POST", { engine: "open", scenes: SCENES, ...extra }, who));
+ return { status: r.status, body: (await r.json()) as { items?: { id: string }[]; error?: string; code?: string } };
+};
+/** The stored requests of an account's runs (as the runner reads them). */
+const stored = (who: string) =>
+ (db().prepare("SELECT request_json FROM generations WHERE json_extract(request_json, '$.account') = ? AND status IN ('queued', 'running', 'succeeded') ORDER BY created_at").all(ids[who]) as { request_json: string }[]).map(
+ (r) => JSON.parse(r.request_json) as { place?: string; hold?: string; light?: boolean },
+ );
+const reserves = () => fake.calls_of("/v1/reserve").length;
+const useBilling = () => {
+ process.env.FUOBE_BILLING_URL = fake.url;
+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";
+};
+
+describe("hosted runs off (the default): tool runs are as before", () => {
+ it("an account with no GPU or key is asked to connect one, at the proxy and at the route", async () => {
+ const at = await viaProxy("/api/storyboards", "none");
+ expect(at.status).toBe(403);
+ expect(((await at.json()) as { code: string }).code).toBe("connect-gpu");
+ const r = await board("none");
+ expect(r.status).toBe(403);
+ expect(r.body.code).toBe("connect-gpu");
+ expect(stored("none")).toEqual([]);
+ });
+
+ it("the seam answers its own GPU or key, whatever the steps", async () => {
+ const place = await toolRun.placeOf(auth.accountById(ids.none)!, [{ request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" } }]);
+ expect(place).toEqual({ kind: "own" });
+ });
+});
+
+describe("hosted runs on", () => {
+ beforeEach(() => {
+ process.env.FUOBE_HOSTED_RUNS = "1";
+ process.env.FUOBE_HOSTED_FREE = "1";
+ });
+
+ it("a tool's run reaches its route for an account with no GPU of its own; other tools still say so", async () => {
+ expect(passed(await viaProxy("/api/storyboards", "none"))).toBe(true);
+ const other = await viaProxy("/api/enhance", "none");
+ expect(other.status).toBe(403);
+ expect(((await other.json()) as { code: string }).code).toBe("own-gpu-tool");
+ });
+
+ it("a board runs on this install's GPUs: every step stamped for there", async () => {
+ const r = await board("none");
+ expect(r.status, JSON.stringify(r.body)).toBe(201);
+ const rows = stored("none");
+ expect(rows.length).toBe(SCENES.length);
+ expect(rows.every((q) => q.place === "pool")).toBe(true);
+ });
+
+ it("with a billing service: one hold for the whole run, priced from every step, on every row", async () => {
+ useBilling();
+ const before = reserves();
+ // The price the client showed before Run comes back with the run (a run priced higher is asked about again).
+ const r = await board("none", { shown: { amount: fake.price.amount, priceVersion: fake.price.version } });
+ expect(r.status, JSON.stringify(r.body)).toBe(201);
+ expect(reserves() - before).toBe(1);
+ const reserve = fake.calls_of("/v1/reserve").at(-1)!.body as { run: { steps?: { model: string; jobs: number }[] } };
+ expect(reserve.run.steps?.reduce((n, s) => n + s.jobs, 0)).toBe(SCENES.length);
+ const holds = new Set(stored("none").map((q) => q.hold));
+ expect(holds.size).toBe(1);
+ expect([...holds][0]).toBeTruthy();
+ });
+
+ it("a model the policy keeps off this install's GPUs refuses the run before anything is held or made", async () => {
+ useBilling();
+ fake.policy = { ...fake.policy, pool: { deny: ["oss-z-image-turbo"] } };
+ const steps = [{ request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" } }];
+ const place = await toolRun.placeOf(auth.accountById(ids.none)!, steps);
+ expect(place.kind).toBe("refuse");
+ if (place.kind === "refuse") expect(place.refusal.body.code).toBe("not-offered");
+ const before = reserves();
+ const rows = stored("none").length;
+ const r = await toolRun.runAccountTool(json("/api/x", "POST", {}, "none"), auth.accountById(ids.none)!, { tool: "test", files: [], plan: () => steps, start: () => createGenerations(steps[0].request) });
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(((await r.response.json()) as { code: string }).code).toBe("not-offered");
+ expect(reserves()).toBe(before);
+ expect(stored("none").length).toBe(rows);
+ });
+
+ it("a row the start makes that the policy doesn't allow stops the whole run, and its hold goes back", async () => {
+ useBilling();
+ fake.policy = { ...fake.policy, pool: { deny: ["oss-flux1-schnell"] } };
+ const plan = [{ request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" } }];
+ const rows = stored("none").length;
+ const r = await toolRun.runAccountTool(json("/api/x", "POST", {}, "none"), auth.accountById(ids.none)!, {
+ tool: "test",
+ files: [],
+ shown: { amount: fake.price.amount, priceVersion: fake.price.version },
+ plan: () => plan,
+ // A start that makes more than it planned: a step the policy leaves out.
+ start: () => [...createGenerations(plan[0].request), ...createGenerations({ feature: "image", modelId: "oss-flux1-schnell", prompt: "a fox in red" })],
+ });
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.response.status).toBe(403);
+ expect(stored("none").length).toBe(rows);
+ await drainOutbox();
+ const hold = [...fake.holds.values()].at(-1);
+ expect(hold?.released).toBe(true);
+ });
+
+ it("a 3D model stays on an account's own GPU: refused here in the tools' words", async () => {
+ const steps = [{ request: { feature: "3d", modelId: "oss-pixal3d", op: "image-to-3d" as const, prompt: "", inputs: { images: ["/api/files/x.png"] } } }];
+ const place = await toolRun.placeOf(auth.accountById(ids.none)!, steps);
+ expect(place.kind).toBe("refuse");
+ if (place.kind === "refuse") {
+ expect(place.refusal.body.code).toBe("own-gpu-tool");
+ expect(place.refusal.body.error).toBe(OWN_GPU_TOOL_MESSAGE);
+ }
+ });
+
+ it("an account whose own GPU answers keeps it, and asking for its own GPU always keeps it", async () => {
+ const steps = [{ request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" } }];
+ expect(await toolRun.placeOf(auth.accountById(ids.gpu)!, steps)).toEqual({ kind: "own" });
+ expect(await toolRun.placeOf(auth.accountById(ids.none)!, steps, "own")).toEqual({ kind: "own" });
+ expect((await toolRun.placeOf(auth.accountById(ids.gpu)!, steps, "pool")).kind).toBe("pool");
+ });
+
+ it("the price check before Run answers for the whole run: place, quote and line", async () => {
+ useBilling();
+ const plan = () => [
+ { request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" } },
+ { request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox at night" }, deps: 1 },
+ ];
+ const asNone = new Request("http://localhost:3000/api/x?preview=1", { method: "POST", headers: { host: "localhost:3000", cookie: cookies.none } });
+ const check = await toolRun.toolPriceCheck(asNone, plan);
+ expect(check?.place).toBe("pool");
+ expect(check?.quote.allowed).toBe(true);
+ expect(check?.line.place).toBeGreaterThanOrEqual(1);
+ const quote = fake.calls_of("/v1/quote").at(-1)!.body as { run: { steps?: { jobs: number }[] } };
+ expect(quote.run.steps?.reduce((n, s) => n + s.jobs, 0)).toBe(2);
+ // A guest's is priced too (as nobody's run); the owner's never comes here.
+ const guest = await toolRun.toolPriceCheck(new Request("http://localhost:3000/api/x?preview=1", { method: "POST", headers: { host: "localhost:3000" } }), plan);
+ expect(guest?.place).toBe("pool");
+ // A run asked for on its own GPU isn't priced here.
+ expect(await toolRun.toolPriceCheck(asNone, plan, "own")).toBeNull();
+ });
+});
+
+describe("text steps inside a run on this install's GPUs", () => {
+ const step = (modelId: string, provider: string, i: number) => ({ id: `s${i}`, modelId, op: "t2i", provider, kind: "image", presetId: null, waits: i > 0 });
+ it("run on the install's AI helper: allowed, never priced, never counted", () => {
+ const steps = [step("oss-text-llm", "llm", 0), step("oss-z-image-turbo", "comfyui", 1)];
+ expect(hostedRun.stepsProblem(billing.OPEN_POLICY, steps)).toBeNull();
+ expect(hostedRun.pricedSteps(steps).map((s) => s.model)).toEqual(["oss-z-image-turbo"]);
+ expect(hostedRun.lightRun(steps)).toBe(false);
+ // A cloud step still can't run there.
+ expect(hostedRun.stepsProblem(billing.OPEN_POLICY, [...steps, step("fal-flux", "fal", 2)])).not.toBeNull();
+ });
+});
+
+void TINY_PNG;
diff --git a/tests/pool-limits.test.ts b/tests/pool-limits.test.ts
index 9f080d38..a713ec02 100644
--- a/tests/pool-limits.test.ts
+++ b/tests/pool-limits.test.ts
@@ -737,10 +737,10 @@ describe("a run's price facts", () => {
const p = { ...billing.OPEN_POLICY, pool: { deny: ["oss-qwen-image-edit"] } };
expect(hostedRun.stepsProblem(p, steps([["oss-z-image-turbo", "comfyui"]]))).toBeNull();
expect(hostedRun.stepsProblem(p, steps([["oss-z-image-turbo", "comfyui"], ["oss-qwen-image-edit", "comfyui"]]))).not.toBeNull();
- // A cloud step can't run here, and neither can a text step or one made in the browser: the run is refused before
- // Run, never part way through.
+ // A cloud step can't run here, and neither can one made in the browser: the run is refused before Run, never part
+ // way through. (A text step runs on the install's AI helper: hosted-tool-runs.test.ts.)
expect(hostedRun.stepsProblem(billing.OPEN_POLICY, steps([["oss-z-image-turbo", "comfyui"], ["fal-flux", "fal"]]))).not.toBeNull();
- for (const provider of ["llm", "local", "mock"]) {
+ for (const provider of ["local", "mock"]) {
expect(hostedRun.stepsProblem({ ...billing.OPEN_POLICY, pool: { allow: ["oss-z-image-turbo"] } }, steps([["oss-z-image-turbo", "comfyui"], ["some-step", provider]])), provider).toBe(hosted.HOSTED_WORDS.notOffered);
}
expect(hostedRun.pricedSteps(steps([["oss-z-image-turbo", "comfyui"], ["oss-z-image-turbo", "comfyui"]]))).toEqual([expect.objectContaining({ model: "oss-z-image-turbo", jobs: 2 })]);