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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Hosted runs: Shorts, Cinema Studio and the palette lock reach this install's GPUs
Adarsh36bfb7f3cac0
diff --git a/src/app/api/cinema/projects/[id]/generate/route.ts b/src/app/api/cinema/projects/[id]/generate/route.tsindex ab935f48..7a0ade10 100644--- a/src/app/api/cinema/projects/[id]/generate/route.ts+++ b/src/app/api/cinema/projects/[id]/generate/route.ts@@ -1,4 +1,4 @@-import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";+import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolPriceCheck, toolViewer } from "@/server/account-tool-run";import { cinemaSteps, generateInProject, prepareCinemaRun, startCinemaRun, type CinemaRun } from "@/server/cinema-generate";import { GenerateBody, body, fileRefs, handle, withStatus } from "@/server/cinema-schemas";@@ -8,6 +8,9 @@ import { GenerateBody, body, fileRefs, handle, withStatus } from "@/server/cinem* always; a signed-in account's in its own project, on its own GPU or its own fal.ai or Replicate key,* with its own files, after the checks a studio run gets (src/server/account-tool-run.ts); a guest* signs up first.+ *+ * A `?preview=1` is a price check: `{ place: "pool", quote, line }` when the run would go to this install's+ * GPUs, or `{ place: "own" }` (its own GPU or key) — nothing is made.*/export async function POST(request: Request, ctx: RouteContext<"/api/cinema/projects/[id]/generate">) {const viewer = toolViewer(request);@@ -19,6 +22,10 @@ export async function POST(request: Request, ctx: RouteContext<"/api/cinema/projreturn handle(async () => {const { id } = await ctx.params;const b = await body(request, GenerateBody, "That request isn't valid");+ if (new URL(request.url).searchParams.get("preview") === "1") {+ const pool = viewer.kind === "owner" ? null : await toolPriceCheck(request, () => withStatus(() => cinemaSteps(prepareCinemaRun(id, b.input, b.folderId ?? null))));+ return Response.json(pool ?? { place: "own" });+ }if (viewer.kind === "owner") return Response.json(generateInProject(id, b.input, b.folderId ?? null), { status: 201 });let run: CinemaRun | null = null;return onceForAccount(diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.tsindex 7eb82687..2cf1a24e 100644--- a/src/app/api/generations/route.ts+++ b/src/app/api/generations/route.ts@@ -110,7 +110,7 @@ export async function POST(request: Request) {return refuse(403, r.error, { code: r.code, ...(r.provider && { provider: r.provider }) }, headers);};// Beside the request (never in it): the place the client prefers, and the price it showed (hosted runs, billing hook).- const { wish, shown } = readWishes(body);+ const { wish, shown } = readWishes(body, request.headers);const refusedBy = (r: Refusal) => {if (account) unhit(`run:${account.id}`);return refuse(r.status, r.body.error, r.body, r.headers);diff --git a/src/app/api/palettes/lock/route.ts b/src/app/api/palettes/lock/route.tsindex dc0f2986..70b37277 100644--- a/src/app/api/palettes/lock/route.ts+++ b/src/app/api/palettes/lock/route.ts@@ -1,6 +1,8 @@import { z } from "zod";+import { bodyTooBig, guestRun, toolViewer, toolWishes } from "@/server/account-tool-run";import { createLockedRun, SignatureSchema } from "@/server/palettes";import { ClientExtra } from "@/server/request-schema";+import { runToolForAccount } from "@/server/tool-runs";const Hex = z.string().regex(/^#?[0-9a-fA-F]{6}$/);@@ -31,12 +33,40 @@ const RequestSchema = z.object({signature: SignatureSchema,});-const Body = z.object({ request: RequestSchema, colors: z.array(Hex).min(1).max(16), strength: z.number().min(0).max(1).optional() });+const Body = z.object({+ request: RequestSchema,+ colors: z.array(Hex).min(1).max(16),+ strength: z.number().min(0).max(1).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(),+});-/** Make the images, then recolour each one to the palette (open engine: a chained palette-transfer step). */+/**+ * Make the images, then recolour each one to the palette (open engine: a chained palette-transfer step). 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),+ * on its own GPU or on this install's GPUs; a guest signs up first.+ */export async function POST(request: Request) {+ const viewer = toolViewer(request);+ if (viewer.kind === "guest") return guestRun();+ if (viewer.kind === "account") {+ const big = bodyTooBig(request);+ if (big) return big;+ }+ const wishes = viewer.kind === "account" ? await toolWishes(request) : {};const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ") }, { status: 400 });+ if (viewer.kind === "account") {+ const { request: asked, colors, strength, requestId } = parsed.data;+ return runToolForAccount(request, viewer.account, {+ tool: "palette-lock",+ files: asked.inputs?.images ?? [],+ requestId,+ wishes,+ start: () => createLockedRun(asked as Parameters<typeof createLockedRun>[0], colors, strength),+ ok: ({ items }, gpuWarning) => Response.json({ items, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),+ });+ }try {const { items } = createLockedRun(parsed.data.request as Parameters<typeof createLockedRun>[0], parsed.data.colors, parsed.data.strength);return Response.json({ items }, { status: 201 });diff --git a/src/app/api/shorts/estimate/route.ts b/src/app/api/shorts/estimate/route.tsindex 66da9eb2..08f99b9c 100644--- a/src/app/api/shorts/estimate/route.ts+++ b/src/app/api/shorts/estimate/route.ts@@ -1,17 +1,20 @@-import { priceAsRun } from "@/server/account-tool-run";-import { estimateShorts } from "@/server/shorts";+import { priceAsRun, toolPriceCheck } from "@/server/account-tool-run";+import { estimateShorts, planSessionRun, shortsSteps } from "@/server/shorts";import { ShortsEstimateSchema, body, handle } from "@/server/shorts-schemas";/*** What a session would cost (or that it runs as a demo), how many segments it makes, and notes. A visitor (public* sign-up) gets the price of its run as it would go: an account's on its own GPU or its own key (with its own presets),- * a guest's on the open engine; never a demo (src/server/account-tool-run.ts priceAsRun).+ * a guest's on the open engine; never a demo (src/server/account-tool-run.ts priceAsRun). A run that would go to this+ * install's GPUs adds `{ place: "pool", quote, line }` (toolPriceCheck), as every tool's price check does.*/export async function POST(request: Request) {return priceAsRun(request, () =>handle(async () => {const input = await body(request, ShortsEstimateSchema, "Pick a preset and the part of the clip to restyle");- return Response.json(await estimateShorts(input));+ const estimate = await estimateShorts(input);+ const pool = await toolPriceCheck(request, async () => shortsSteps((await planSessionRun(input)).plan.steps));+ return Response.json(pool ? { ...estimate, ...pool } : estimate);}),);}diff --git a/src/components/palettes/use-signature.ts b/src/components/palettes/use-signature.tsindex 7873a6c6..584e7937 100644--- a/src/components/palettes/use-signature.ts+++ b/src/components/palettes/use-signature.ts@@ -4,7 +4,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";import { useCallback } from "react";import { applySignature, withSignatureWords, type Signature, type SignedRequest } from "@/lib/catalog/palettes";import type { Generation, GenerationRequest } from "@/lib/catalog/types";-import { useIsVisitor } from "@/lib/api";+import { useIsGuest } from "@/lib/api";import { responseError } from "@/lib/refusals";import { useCatalog } from "@/components/studio/catalog";import { usePalettes } from "./hooks";@@ -13,14 +13,14 @@ import { usePalettes } from "./hooks";* The composer's hook for the style signature (Color signature + Moodboard chips): `apply` routes a* request for the picked palette and moodboard (pure, src/lib/catalog/palettes.ts) — the composer* plans and prices with it while you type and sends what it returns. `lock` sends a run whose- * images are recolored afterwards (open engine) through POST /api/palettes/lock: the owner's only, so a- * guest's or a free account's request never carries a lock.+ * images are recolored afterwards (open engine) through POST /api/palettes/lock: the owner's or an account's run+ * (with the place and price the composer shows), so only a guest's request never carries a lock.*/export function useSignature(enabled: boolean, signature: Signature | undefined) {const { getModel } = useCatalog();// The palette list carries which models take a palette natively; the chip has usually loaded it already.const { caps } = usePalettes(enabled && !!signature?.palette);- const visitor = useIsVisitor();+ const visitor = useIsGuest();const apply = useCallback((req: GenerationRequest): SignedRequest & { worded: GenerationRequest } => {const signed = enabled && signature ? applySignature(req, signature, { caps, getModel, visitor }) : { request: req, modelId: req.modelId, notes: [] };@@ -31,7 +31,7 @@ export function useSignature(enabled: boolean, signature: Signature | undefined));const qc = useQueryClient();const lock = useMutation({- mutationFn: async (b: { request: GenerationRequest; colors: string[] }) => {+ mutationFn: async (b: { request: GenerationRequest; colors: string[]; place?: "own" | "pool"; shown?: { amount: number; priceVersion: string } }) => {const res = await fetch("/api/palettes/lock", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(b) });const body = (await res.json().catch(() => ({}))) as { items?: Generation[]; error?: string };if (!res.ok) throw responseError(res, body.error ?? "Something went wrong. Please try again.");diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsxindex 28f819c5..91fcf1d8 100644--- a/src/components/studio/composer.tsx+++ b/src/components/studio/composer.tsx@@ -846,16 +846,16 @@ export function Composer({ docked }: { docked: boolean }) {const sent = signature.apply(buildRequest(config.feature, songDraft(draft, model, config.slots), resolvesOnServer ? studioOp : op, config.promptSuffix, config.multiRef?.kind, framesCtx, targetFor(draft.modelId)),);+ // Hosted runs: where it should go, and the price shown (the server checks both; a higher price comes back to confirm).+ const hosted = viewerInfo?.hosted ? { ...(runPlace && { place: runPlace }), ...(poolPrice && hostedQuote && { shown: { amount: hostedQuote.amount, priceVersion: hostedQuote.priceVersion } }) } : {};// Open palette lock: the images are recoloured to the palette by a chained step (POST /api/palettes/lock).- if (sent.lock) return signature.lock.mutate({ request: sent.request, colors: sent.lock.colors }, { onError: (e) => toastError(e) });+ if (sent.lock) return signature.lock.mutate({ request: sent.request, colors: sent.lock.colors, ...hosted }, { onError: (e) => toastError(e) });// If the server's pre-flight stops it (409 gpu-setup), the guided fix that opens can try again, or run it anyway.setGpuRetry(() => submitRef.current(),() => submitRef.current(true),model?.kind,);- // Hosted runs: where it should go, and the price shown (the server checks both; a higher price comes back to confirm).- const hosted = viewerInfo?.hosted ? { ...(runPlace && { place: runPlace }), ...(poolPrice && hostedQuote && { shown: { amount: hostedQuote.amount, priceVersion: hostedQuote.priceVersion } }) } : {};const withVoiceFirst = cleanFirst ? { ...sent.request, params: { ...sent.request.params, extra: { ...sent.request.params?.extra, [VOICE_FIRST_PARAM]: true } } } : sent.request;const body = { ...withVoiceFirst, ...hosted, ...(skipGpu && { gpuCheck: "skip" }) } as typeof sent.request;create.mutate(body, {diff --git a/src/lib/catalog/palettes.ts b/src/lib/catalog/palettes.tsindex ab0d1659..aace7677 100644--- a/src/lib/catalog/palettes.ts+++ b/src/lib/catalog/palettes.ts@@ -370,8 +370,8 @@ export interface SignatureContext {caps: SignatureCaps;getModel: (id: string) => ModelDef | undefined;/**- * A guest or a free account: no palette lock. The lock is a second run on the studio's own ComfyUI- * (POST /api/palettes/lock), which only the owner starts, so a visitor's colors stay in the prompt.+ * A guest: no palette lock. The lock is a second run (POST /api/palettes/lock), which the owner or an account starts,+ * so a guest's colors stay in the prompt.*/visitor?: boolean;}diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.tsindex 80b466aa..0c681d99 100644--- a/src/lib/guest-access.ts+++ b/src/lib/guest-access.ts@@ -299,6 +299,8 @@ export const ACCOUNT_TOOL_RUNS: readonly RegExp[] = [/^\/api\/(influencer|photodump|photodump\/fashion|photodump\/character|turnaround|fly-around)$/,// Cinema Studio: a take in the account's own project, a retry and a 2K finish of one of its takes./^\/api\/cinema\/projects\/[^/]+\/(generate|items\/[^/]+\/(retry|finish))$/,+ // The Image studio's palette lock: its images, then each recoloured to the palette (src/server/palettes.ts).+ /^\/api\/palettes\/lock$/,];/**@@ -346,6 +348,21 @@ export const PLACE_ASK_HEADER = "x-fuobe-place-ask";/** Fired when a run started from a toast or a card (not from a page's own button), so the lists show it. */export const RUNS_CHANGED_EVENT = "fuobe:runs-changed";+/**+ * Where a run's client would like it to go ("own" or "pool"), as a header: for a tool whose body has no field for it.+ * A body's own `place` wins (src/server/hosted-run.ts readWishes).+ */+export const RUN_PLACE_HEADER = "x-fuobe-place";++/**+ * The price a run's client showed before Run, as a header (`{ amount, priceVersion }` as URI-encoded JSON): for a tool+ * whose body has no field for it, and for a run sent again at a changed price. A body's own `shown` wins.+ */+export const RUN_SHOWN_HEADER = "x-fuobe-shown";++/** A price shown, as RUN_SHOWN_HEADER carries it. */+export const shownHeader = (s: { amount: number; priceVersion: string }): string => encodeURIComponent(JSON.stringify({ amount: s.amount, priceVersion: s.priceVersion }));+/** Set on an account's refused run: the client shows "Connect your GPU to run this". */export const CONNECT_GPU_HEADER = "x-fuobe-connect-gpu";/** Beside it on the owner's refused run (Demo mode off, nothing connected): what would run it, "gpu", "key" or "any". */diff --git a/src/server/account-tool-run.ts b/src/server/account-tool-run.tsindex 5c232fcb..5b126f9a 100644--- a/src/server/account-tool-run.ts+++ b/src/server/account-tool-run.ts@@ -182,6 +182,7 @@ export async function toolPriceCheck(const v = toolViewer(request);if (v.kind === "owner") return null;const account = v.kind === "account" ? v.account : null;+ wish ??= headerWishes(request).place;if (!poolMayTake(account, wish)) return null;let steps: ToolStep[];try {@@ -194,15 +195,25 @@ export async function toolPriceCheck(}/**- * 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.+ * What a tool's run carries beside the tool's own fields (hosted-run.ts readWishes): the place the client prefers and+ * the price it showed before Run, from its body or, for a tool whose body has no field for them, its headers+ * (RUN_PLACE_HEADER, RUN_SHOWN_HEADER). Read from a copy, before the route reads the body itself.*/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);+ const { wish, shown } = readWishes(raw, request.headers);+ return { ...(wish && { place: wish }), shown };+}++/**+ * The place and price a run carries in its headers only (RUN_PLACE_HEADER, RUN_SHOWN_HEADER): what runAccountTool and+ * a tool's price check read when the route passed none, so a tool that reads its body itself needs no change for them.+ */+export function headerWishes(request: Request): { place?: PlaceWish; shown: { amount: number; priceVersion: string } | null } {+ const { wish, shown } = readWishes(null, request.headers);return { ...(wish && { place: wish }), shown };}@@ -290,8 +301,11 @@ function errorResponse(e: unknown): Response {* Check and start an account's tool run (see the header). The answer is the tool's own value, or the response that* refuses it. Nothing is queued unless every check passed; a refused run doesn't count against the account's hour.*/-export async function runAccountTool<T>(request: Request, account: Account, run: AccountToolRun<T>): Promise<AccountToolResult<T>> {+export async function runAccountTool<T>(request: Request, account: Account, asked: AccountToolRun<T>): Promise<AccountToolResult<T>> {const id = account.id;+ // The place and price the route didn't pass come from the request's headers (a tool that reads its body itself).+ const sent = headerWishes(request);+ const run: AccountToolRun<T> = { ...asked, place: asked.place ?? sent.place, shown: asked.shown ?? sent.shown };const no = (response: Response): AccountToolResult<T> => ({ ok: false, response });if (!diskHasRoom()) return no(refuse(503, ACCOUNT_MESSAGES.diskLow));if (accountUsage(id).total >= accountTotalBytes(id)) return no(refuse(413, filesFullMessage(id)));diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.tsindex 01bba4dd..34ea1f05 100644--- a/src/server/hosted-run.ts+++ b/src/server/hosted-run.ts@@ -25,7 +25,7 @@ import {type RunFacts,} from "./billing";import { getModel } from "@/lib/catalog";-import { PLACE_ASK_HEADER } from "@/lib/guest-access";+import { PLACE_ASK_HEADER, RUN_PLACE_HEADER, RUN_SHOWN_HEADER } from "@/lib/guest-access";import { createGenerations, outputKind, plannedSteps, previewChained, previewGeneration, type PlannedStep } from "./generations";import { loadIndex } from "./gpu/index-file";import { poolLane } from "./computer/pool";@@ -49,15 +49,29 @@ import { runAsTenant } from "./tenant";export type PlaceWish = "own" | "pool" | undefined;/** The client's preference and the price it showed, read from the body beside the request (never part of it). */-export function readWishes(body: unknown): { wish: PlaceWish; shown: { amount: number; priceVersion: string } | null } {+export function readWishes(body: unknown, headers?: Headers): { wish: PlaceWish; shown: { amount: number; priceVersion: string } | null } {const b = (body ?? {}) as { place?: unknown; shown?: unknown };- const wish = b.place === "own" || b.place === "pool" ? b.place : undefined;- const s = b.shown as { amount?: unknown; priceVersion?: unknown } | null | undefined;- const shown =- s && typeof s === "object" && Number.isFinite(s.amount) && Number(s.amount) >= 0 && typeof s.priceVersion === "string" && s.priceVersion.length <= 200- ? { amount: Math.floor(Number(s.amount)), priceVersion: s.priceVersion }- : null;- return { wish, shown };+ const wish = placeWish(b.place) ?? placeWish(headers?.get(RUN_PLACE_HEADER));+ return { wish, shown: shownPrice(b.shown) ?? shownPrice(headerJson(headers?.get(RUN_SHOWN_HEADER))) };+}++const placeWish = (v: unknown): PlaceWish => (v === "own" || v === "pool" ? v : undefined);++function shownPrice(v: unknown): { amount: number; priceVersion: string } | null {+ const s = v as { amount?: unknown; priceVersion?: unknown } | null | undefined;+ return s && typeof s === "object" && Number.isFinite(s.amount) && Number(s.amount) >= 0 && typeof s.priceVersion === "string" && s.priceVersion.length <= 200+ ? { amount: Math.floor(Number(s.amount)), priceVersion: s.priceVersion }+ : null;+}++/** A header's URI-encoded JSON (RUN_SHOWN_HEADER), or null when it isn't one. */+function headerJson(v: string | null | undefined): unknown {+ if (!v || v.length > 600) return null;+ try {+ return JSON.parse(decodeURIComponent(v));+ } catch {+ return null;+ }}/** A refusal the route sends as it is. */diff --git a/tests/hosted-surface-runs.test.ts b/tests/hosted-surface-runs.test.tsnew file mode 100644index 00000000..e16e0044--- /dev/null+++ b/tests/hosted-surface-runs.test.ts@@ -0,0 +1,280 @@+import fs from "node:fs";+import http from "node:http";+import path from "node:path";+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } 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";++vi.setConfig({ testTimeout: 120_000 });+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));++/**+ * The run surfaces beyond the studios' composer, for an account with no GPU of its own: Shorts, Cinema Studio and the+ * Image studio's palette lock reach this install's GPUs through the one gate, held once for the whole run; a tool that+ * reads its body itself gets the place and the price shown from the request's headers. With hosted runs off, and for an+ * account whose own GPU answers, nothing changes.+ */+const dir = tempDir("fuobe-hosted-surface-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: "both", delayMs: 0, loras: [] }, comfyPort);+process.env.COMFYUI_URL = comfy.url;++const auth = await import("@/server/auth");+const gpuRoute = await import("@/app/api/account/gpu/route");+const uploadsRoute = await import("@/app/api/uploads/route");+const sessionsRoute = await import("@/app/api/shorts/sessions/route");+const estimateRoute = await import("@/app/api/shorts/estimate/route");+const projectsRoute = await import("@/app/api/cinema/projects/route");+const generateRoute = await import("@/app/api/cinema/projects/[id]/generate/route");+const lockRoute = await import("@/app/api/palettes/lock/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 { clearAccountLoras } = await import("@/server/account-loras");+const access = await import("@/lib/guest-access");++const CLIP = fs.readFileSync(path.join(__dirname, "fixtures/shorts-12s.mp4"));++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(`surfaces-${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;+ for (const id of Object.values(ids)) clearAccountLoras(id);+ fake.policy = { hosted: true, pool: {}, uploads: { image: true, video: true, audio: true }, limits: { activeRuns: 7, waiting: 7, runsPerHour: 70, outputsPerRun: 4, maxMegapixels: 7, maxSeconds: 70, 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, headers: Record<string, 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] }), ...headers },+ body: text,+ });+}+const params = <T extends Record<string, string>>(p: T) => ({ params: Promise.resolve(p) }) as never;+const viaProxy = (url: string, who?: string) =>+ proxy(new NextRequest(`http://localhost:3000${url}`, { method: "POST", headers: { host: "localhost:3000", ...(who && { cookie: cookies[who] }), "content-type": "application/json" }, body: "{}" }));+const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";++async function upload(who: string, data: Buffer, type: string, name: string): Promise<string> {+ const r = await uploadsRoute.POST(new Request("http://localhost:3000/api/uploads", { method: "POST", headers: { host: "localhost:3000", cookie: cookies[who], "content-type": type, "x-file-name": name, "content-length": String(data.length) }, body: new Uint8Array(data) }));+ expect(r.status, await r.clone().text()).toBe(201);+ return ((await r.json()) as { url: string }).url;+}++/** The stored requests of an account's runs made since `since` (as the runner reads them). */+const runsSince = (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; hold?: string; modelId: string },+ );+const reserves = () => fake.calls_of("/v1/reserve").length;+const hostedOn = () => {+ process.env.FUOBE_HOSTED_RUNS = "1";+ process.env.FUOBE_BILLING_URL = fake.url;+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";+};+const shownHeaders = () => ({ [access.RUN_SHOWN_HEADER]: access.shownHeader({ amount: fake.price.amount, priceVersion: fake.price.version }) });++/** A run that names a LoRA its ComfyUI lacks is answered with the file (409): put it there, then send it again. */+async function send(call: () => Promise<Response>): Promise<Response> {+ let r = await call();+ for (let i = 0; i < 3 && r.status === 409; i++) {+ const j = (await r.clone().json()) as { code: string; fix?: { items: { file: string }[] } };+ if (j.code !== "comfy_missing_model" || !j.fix) break;+ comfy.opts.loras = [...(comfy.opts.loras ?? []), ...j.fix.items.map((x) => x.file)];+ for (const id of Object.values(ids)) clearAccountLoras(id);+ r = await call();+ }+ return r;+}++describe("the place and the price shown, from a run's headers", () => {+ it("a body's own fields win; a header fills in what the body leaves out; a broken header is ignored", () => {+ const h = new Headers({ [access.RUN_PLACE_HEADER]: "pool", [access.RUN_SHOWN_HEADER]: access.shownHeader({ amount: 3, priceVersion: "v3" }) });+ expect(hostedRun.readWishes({}, h)).toEqual({ wish: "pool", shown: { amount: 3, priceVersion: "v3" } });+ expect(hostedRun.readWishes({ place: "own", shown: { amount: 1, priceVersion: "v1" } }, h)).toEqual({ wish: "own", shown: { amount: 1, priceVersion: "v1" } });+ expect(hostedRun.readWishes({}, new Headers({ [access.RUN_PLACE_HEADER]: "elsewhere", [access.RUN_SHOWN_HEADER]: "%7Bnot json" }))).toEqual({ wish: undefined, shown: null });+ expect(hostedRun.readWishes(null)).toEqual({ wish: undefined, shown: null });+ });++ it("a tool's run reads them when its route passed none: the price shown, and its own GPU asked for", async () => {+ hostedOn();+ const steps = [{ request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox in the snow" } }];+ const account = auth.accountById(ids.none)!;+ const start = () => createGenerations(steps[0].request);+ // No price shown: the run priced higher than nothing is asked about again (the card offers the new price).+ const bare = await toolRun.runAccountTool(json("/api/x", "POST", {}, "none"), account, { tool: "test", files: [], plan: () => steps, start });+ expect(bare.ok).toBe(false);+ if (!bare.ok) expect(((await bare.response.json()) as { code: string }).code).toBe("price-changed");+ // The same run sent again with the new price in a header starts, held once.+ const before = reserves();+ const since = Date.now();+ const again = await toolRun.runAccountTool(json("/api/x", "POST", {}, "none", shownHeaders()), account, { tool: "test", files: [], plan: () => steps, start });+ expect(again.ok).toBe(true);+ expect(reserves() - before).toBe(1);+ expect(runsSince("none", since).every((q) => q.place === "pool")).toBe(true);+ // Its own GPU asked for in a header: never this install's GPUs.+ expect(await toolRun.toolPriceCheck(json("/api/x?preview=1", "POST", {}, "gpu", { [access.RUN_PLACE_HEADER]: "own" }), () => steps)).toBeNull();+ const own = await toolRun.toolPriceCheck(json("/api/x?preview=1", "POST", {}, "gpu", { [access.RUN_PLACE_HEADER]: "pool" }), () => steps);+ expect(own?.place).toBe("pool");+ });+});++describe("Shorts for an account with no GPU of its own", () => {+ it("hosted runs on: the session runs on this install's GPUs as one run, held once; its estimate names the place", async () => {+ hostedOn();+ expect(passed(await viaProxy("/api/shorts/sessions", "none"))).toBe(true);+ const clip = await upload("none", CLIP, "video/mp4", "dance.mp4");+ const body = { engine: "open", presetId: "shorts-claymation", source: { url: clip, name: "dance.mp4" }, range: { start: 0, end: 10 }, aspectRatio: "9:16", language: "auto" };+ const est = await estimateRoute.POST(json("/api/shorts/estimate", "POST", body, "none"));+ expect(est.status, await est.clone().text()).toBe(200);+ const priced = (await est.json()) as { place?: string; quote?: { allowed: boolean; amount: number; priceVersion: string }; line?: { place: number } };+ expect(priced.place).toBe("pool");+ expect(priced.quote?.allowed).toBe(true);+ expect(priced.line?.place).toBeGreaterThanOrEqual(1);+ const before = reserves();+ const since = Date.now();+ const r = await send(() => sessionsRoute.POST(json("/api/shorts/sessions", "POST", body, "none", shownHeaders())));+ expect(r.status, await r.clone().text()).toBe(201);+ expect(reserves() - before).toBe(1);+ const rows = runsSince("none", since);+ expect(rows.length).toBeGreaterThan(1);+ expect(rows.every((q) => q.place === "pool")).toBe(true);+ expect(new Set(rows.map((q) => q.hold)).size).toBe(1);+ });++ it("an account whose own GPU answers keeps it: no hold, nothing stamped for this install's GPUs", async () => {+ hostedOn();+ const clip = await upload("gpu", CLIP, "video/mp4", "dance.mp4");+ const before = reserves();+ const since = Date.now();+ const body = { engine: "open", presetId: "shorts-claymation", source: { url: clip, name: "dance.mp4" }, range: { start: 0, end: 10 }, aspectRatio: "9:16", language: "auto" };+ const r = await send(() => sessionsRoute.POST(json("/api/shorts/sessions", "POST", body, "gpu")));+ expect(r.status, await r.clone().text()).toBe(201);+ expect(reserves()).toBe(before);+ expect(runsSince("gpu", since).some((q) => q.place === "pool")).toBe(false);+ });+});++describe("Cinema Studio for an account with no GPU of its own", () => {+ const STILL = { engine: "open", mode: "image", action: "generate", prompt: "A detective under a neon sign in the rain, a wide shot", batch: 1, aspectRatio: "16:9", settings: { camera: "modern", lens: "clean-sharp", focal: "35mm" } };+ const project = async (who: string) => {+ const r = await projectsRoute.POST(json("/api/cinema/projects", "POST", { name: "Night film" }, who));+ expect(r.status, await r.clone().text()).toBe(201);+ return ((await r.json()) as { id: string }).id;+ };++ it("hosted runs on: a take runs on this install's GPUs, held once; its price check names the place", async () => {+ hostedOn();+ const id = await project("none");+ const check = await generateRoute.POST(json(`/api/cinema/projects/${id}/generate?preview=1`, "POST", { input: STILL }, "none"), params({ id }));+ expect(check.status, await check.clone().text()).toBe(200);+ const priced = (await check.json()) as { place: string; quote?: { allowed: boolean } };+ expect(priced.place).toBe("pool");+ expect(priced.quote?.allowed).toBe(true);+ const before = reserves();+ const since = Date.now();+ const r = await send(() => generateRoute.POST(json(`/api/cinema/projects/${id}/generate`, "POST", { input: STILL }, "none", shownHeaders()), params({ id })));+ expect(r.status, await r.clone().text()).toBe(201);+ expect(reserves() - before).toBe(1);+ const rows = runsSince("none", since);+ expect(rows.length).toBeGreaterThan(0);+ expect(rows.every((q) => q.place === "pool" && !!q.hold)).toBe(true);+ });++ it("an account whose own GPU answers is priced and run there, as before", async () => {+ hostedOn();+ const id = await project("gpu");+ const check = await generateRoute.POST(json(`/api/cinema/projects/${id}/generate?preview=1`, "POST", { input: STILL }, "gpu"), params({ id }));+ expect(((await check.json()) as { place: string }).place).toBe("own");+ const before = reserves();+ const since = Date.now();+ const r = await send(() => generateRoute.POST(json(`/api/cinema/projects/${id}/generate`, "POST", { input: STILL }, "gpu"), params({ id })));+ expect(r.status, await r.clone().text()).toBe(201);+ expect(reserves()).toBe(before);+ expect(runsSince("gpu", since).some((q) => q.place === "pool")).toBe(false);+ });+});++describe("the Image studio's palette lock for accounts", () => {+ const lock = (who: string | undefined, extra: Record<string, unknown> = {}) =>+ lockRoute.POST(+ json("/api/palettes/lock", "POST", { request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a silk scarf on a marble table", params: { numOutputs: 2 }, signature: {} }, colors: ["#112233", "#aabbcc"], ...extra }, who),+ );++ it("a guest signs up first; an account reaches the route", async () => {+ const guest = await viaProxy("/api/palettes/lock");+ expect(guest.status).toBe(401);+ expect(guest.headers.get(access.GUEST_HEADER)).toBe("1");+ expect((await lock(undefined)).status).toBe(401);+ expect(passed(await viaProxy("/api/palettes/lock", "gpu"))).toBe(true);+ });++ it("hosted runs off: an account with no GPU is asked to connect one; its own GPU runs it", async () => {+ const none = await lock("none");+ expect(none.status).toBe(403);+ expect(((await none.json()) as { code: string }).code).toBe("connect-gpu");+ const since = Date.now();+ const own = await send(() => lock("gpu"));+ expect(own.status, await own.clone().text()).toBe(201);+ const rows = runsSince("gpu", since);+ expect(rows.length).toBe(4);+ expect(rows.some((q) => q.place === "pool")).toBe(false);+ });++ it("hosted runs on: an account with no GPU gets both images and their recolouring as one run, held once", async () => {+ hostedOn();+ const before = reserves();+ const since = Date.now();+ const r = await send(() => lock("none", { shown: { amount: fake.price.amount, priceVersion: fake.price.version } }));+ expect(r.status, await r.clone().text()).toBe(201);+ expect(((await r.json()) as { items: unknown[] }).items.length).toBeGreaterThan(0);+ expect(reserves() - before).toBe(1);+ const rows = runsSince("none", since);+ expect(rows.length).toBe(4);+ expect(rows.every((q) => q.place === "pool")).toBe(true);+ expect(new Set(rows.map((q) => q.hold)).size).toBe(1);+ });+});++void TINY_PNG;