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: Video tools, Audio tools and Translate & dub price checks name their place on this install's GPUs
Adarsh64a8499493fa
diff --git a/src/app/api/audio-tools/route.ts b/src/app/api/audio-tools/route.tsindex 2dfa5112..5062ad61 100644--- a/src/app/api/audio-tools/route.ts+++ b/src/app/api/audio-tools/route.ts@@ -1,7 +1,8 @@-import { bodyTooBig, guestRun, onceForAccount, priceAsRun, runAccountTool, toolViewer } from "@/server/account-tool-run";+import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";import { AudioToolBody, AudioToolError, audioToolFiles, audioToolSteps, planAudioTool, previewAudioTool, runAudioTool, startAudioTool, type AudioToolPlan } from "@/server/audio-tools";import { connectRefusal } from "@/server/connect-refusal";import { ConnectComfyError } from "@/server/generations";+import { poolPricedCheck } from "@/server/tool-runs";/** What a field that doesn't check out means, in words the page shows. */const MESSAGES: Record<string, string> = {@@ -83,5 +84,6 @@ export async function POST(request: Request) {const big = bodyTooBig(request);if (big) return big;}- return preview ? priceAsRun(request, () => post(request, true)) : post(request, false);+ // With hosted runs on, a run that would go to this install's GPUs adds its place, price and line (poolPricedCheck).+ return preview ? poolPricedCheck(request, () => post(request, true), (raw) => audioToolSteps(planAudioTool(AudioToolBody.parse(raw)))) : post(request, false);}diff --git a/src/app/api/dub/[id]/voice/route.ts b/src/app/api/dub/[id]/voice/route.tsindex 225aae1c..e09e5a17 100644--- a/src/app/api/dub/[id]/voice/route.ts+++ b/src/app/api/dub/[id]/voice/route.ts@@ -1,6 +1,7 @@import { z } from "zod";-import { asViewer, bodyTooBig, guestRun, onceForAccount, priceAsRun, runAccountTool, toolViewer } from "@/server/account-tool-run";+import { asViewer, bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";import { CueSchema, getDubSession, planVoiceDub, previewVoiceDub, startVoiceDub, voiceDub, voicePlanSteps, type VoicePlan } from "@/server/dub";+import { poolPricedCheck } from "@/server/tool-runs";const Body = z.object({lang: z.string().min(2).max(12),@@ -55,5 +56,15 @@ export async function POST(request: Request, ctx: RouteContext<"/api/dub/[id]/voconst big = bodyTooBig(request);if (big) return big;}- return preview ? priceAsRun(request, () => post(request, ctx, true)) : post(request, ctx, false);+ if (!preview) return post(request, ctx, false);+ // With hosted runs on, a run that would go to this install's GPUs adds its place, price and line (poolPricedCheck).+ const { id } = await ctx.params;+ return poolPricedCheck(+ request,+ () => post(request, ctx, true),+ (raw) => {+ const b = Body.parse(raw);+ return voicePlanSteps(planVoiceDub(id, b.lang, { cues: b.cues, lipsync: b.lipsync }));+ },+ );}diff --git a/src/app/api/dub/route.ts b/src/app/api/dub/route.tsindex 5e04f889..cd4bb5ec 100644--- a/src/app/api/dub/route.ts+++ b/src/app/api/dub/route.ts@@ -1,10 +1,11 @@import { connection } from "next/server";import { z } from "zod";import { ONE_SHOT_MODELS, VOICE_SPLIT_IDS, type VoiceSplit } from "@/lib/av/dub";-import { asViewer, bodyTooBig, guestRun, onceForAccount, priceAsRun, runAccountTool, toolViewer } from "@/server/account-tool-run";+import { asViewer, bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";import { createDubSession, dubPlanSteps, dubRoomProblem, listDubSessions, planDub, previewDub, startDub, type DubPlan } from "@/server/dub";import { connectRefusal } from "@/server/connect-refusal";import { ShortsError } from "@/server/shorts";+import { poolPricedCheck } from "@/server/tool-runs";const Body = z.object({engine: z.enum(["cloud", "open"]),@@ -82,5 +83,6 @@ export async function POST(request: Request) {const big = bodyTooBig(request);if (big) return big;}- return preview ? priceAsRun(request, () => post(request, true)) : post(request, false);+ // With hosted runs on, a run that would go to this install's GPUs adds its place, price and line (poolPricedCheck).+ return preview ? poolPricedCheck(request, () => post(request, true), (raw) => dubPlanSteps(planDub(Body.parse(raw)))) : post(request, false);}diff --git a/src/app/api/evolution/estimate/route.ts b/src/app/api/evolution/estimate/route.tsindex 05c8adab..9d072c3d 100644--- a/src/app/api/evolution/estimate/route.ts+++ b/src/app/api/evolution/estimate/route.ts@@ -1,5 +1,5 @@-import { priceAsRun } from "@/server/account-tool-run";-import { estimateEvolution, EvolutionEstimateSchema } from "@/server/evolution";+import { estimateEvolution, EvolutionEstimateSchema, evolutionSteps, planEvolutionRun } from "@/server/evolution";+import { poolPricedCheck } from "@/server/tool-runs";import { body, handle } from "@/server/shorts-schemas";/** The price, the pieces and the notes for the current settings, before anything runs ("Free" on your GPU). */@@ -10,7 +10,10 @@ async function post(request: Request) {});}-/** Priced as the asker's run would go: an account's on its own GPU or key, a guest's on the open engine, never a demo. */+/**+ * Priced as the asker's run would go: an account's on its own GPU or key, a guest's on the open engine, never a demo;+ * with its place, price and line on this install's GPUs when the run would go there (poolPricedCheck).+ */export async function POST(request: Request) {- return priceAsRun(request, () => post(request));+ return poolPricedCheck(request, () => post(request), async (raw) => evolutionSteps(await planEvolutionRun(EvolutionEstimateSchema.parse(raw))));}diff --git a/src/app/api/fly-around/route.ts b/src/app/api/fly-around/route.tsindex 8cc3e88e..40b54f06 100644--- a/src/app/api/fly-around/route.ts+++ b/src/app/api/fly-around/route.ts@@ -1,7 +1,7 @@-import { bodyTooBig, guestRun, onceForAccount, priceAsRun, runAccountTool, toolViewer } from "@/server/account-tool-run";+import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";import { body, handle, once } from "@/server/shorts-schemas";import { createFlyAround, flyAroundSteps, FlyAroundSchema, planFlyAroundRun, previewFlyAround, startFlyAround, type FlyAroundRun } from "@/server/fly-around";-import { withPlanPrice } from "@/server/tool-runs";+import { poolPricedCheck } from "@/server/tool-runs";import { worldcastContextNow } from "@/server/worldcast-on";/**@@ -16,8 +16,7 @@ async function post(request: Request) {// The WorldCast worker's answer, fresh, before the plan reads it (N7-9). An account's run never uses it.// An account's run never uses the studio's WorldCast worker, nor asks it anything.if (toolViewer(request).kind !== "account") await worldcastContextNow();- // With hosted runs on, a run that would go to this install's GPUs adds its place, price and line.- if (new URL(request.url).searchParams.get("preview")) return Response.json(await withPlanPrice(request, previewFlyAround(input), () => flyAroundSteps(planFlyAroundRun(input))));+ if (new URL(request.url).searchParams.get("preview")) return Response.json(previewFlyAround(input));const viewer = toolViewer(request);if (viewer.kind !== "account") {// A plan that can't run (FlyAroundError) is a 422 with its reason, as any planner's error is.@@ -41,10 +40,13 @@ async function post(request: Request) {}, request);}-/** A price check (`?preview=1`) is priced as the asker's run would go; a guest's run signs up first. */+/**+ * A price check (`?preview=1`) is priced as the asker's run would go, with its place, price and line on this install's+ * GPUs when it would go there (src/server/tool-runs.ts poolPricedCheck); a guest's run signs up first.+ */export async function POST(request: Request) {const viewer = toolViewer(request);- if (new URL(request.url).searchParams.get("preview")) return priceAsRun(request, () => post(request));+ if (new URL(request.url).searchParams.get("preview")) return poolPricedCheck(request, () => post(request), (raw) => flyAroundSteps(planFlyAroundRun(FlyAroundSchema.parse(raw))));if (viewer.kind === "guest") return guestRun();if (viewer.kind === "account") {const big = bodyTooBig(request);diff --git a/src/app/api/katana/route.ts b/src/app/api/katana/route.tsindex 9f907e2e..69318f46 100644--- a/src/app/api/katana/route.ts+++ b/src/app/api/katana/route.ts@@ -1,8 +1,9 @@import { connection } from "next/server";-import { bodyTooBig, guestRun, onceForAccount, priceAsRun, runAccountTool, toolViewer } from "@/server/account-tool-run";+import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";import { asAccount } from "@/server/generations";import { createKatana, KatanaBody, katanaRoom, katanaRunSteps, listKatana, planKatanaRun, previewKatana, startKatana, type KatanaRun } from "@/server/katana";import { connectRefusal } from "@/server/connect-refusal";+import { poolPricedCheck } from "@/server/tool-runs";/*** Recent Katana runs with the state of every step: the owner's, or a signed-in account's own (its jobs are its own@@ -31,7 +32,8 @@ const badBody = (path: string) =>export async function POST(request: Request) {const preview = new URL(request.url).searchParams.get("preview") === "1";const viewer = toolViewer(request);- if (preview) return priceAsRun(request, () => post(request, true));+ // With hosted runs on, a run that would go to this install's GPUs adds its place, price and line (poolPricedCheck).+ if (preview) return poolPricedCheck(request, () => post(request, true), (raw) => katanaRunSteps(planKatanaRun(KatanaBody.parse(raw))));if (viewer.kind === "guest") return guestRun();if (viewer.kind === "owner") return post(request, false);const big = bodyTooBig(request);diff --git a/src/app/api/mixed-media/estimate/route.ts b/src/app/api/mixed-media/estimate/route.tsindex 920c5f1a..aaa9d194 100644--- a/src/app/api/mixed-media/estimate/route.ts+++ b/src/app/api/mixed-media/estimate/route.ts@@ -1,5 +1,5 @@-import { priceAsRun } from "@/server/account-tool-run";-import { estimateMixed } from "@/server/mixed-media";+import { estimateMixed, mixedSteps, planMixedRun } from "@/server/mixed-media";+import { poolPricedCheck } from "@/server/tool-runs";import { MixedEstimateSchema, body, handle } from "@/server/shorts-schemas";/** Frames, cost of the render and of a preview frame, and notes for the current settings. */@@ -10,7 +10,10 @@ async function post(request: Request) {});}-/** Priced as the asker's run would go: an account's on its own GPU or key, a guest's on the open engine, never a demo. */+/**+ * Priced as the asker's run would go: an account's on its own GPU or key, a guest's on the open engine, never a demo;+ * with its place, price and line on this install's GPUs when the run would go there (poolPricedCheck).+ */export async function POST(request: Request) {- return priceAsRun(request, () => post(request));+ return poolPricedCheck(request, () => post(request), async (raw) => mixedSteps(await planMixedRun(MixedEstimateSchema.parse(raw))));}diff --git a/src/app/api/remove-object/estimate/route.ts b/src/app/api/remove-object/estimate/route.tsindex 1ed99f61..208fe8f6 100644--- a/src/app/api/remove-object/estimate/route.ts+++ b/src/app/api/remove-object/estimate/route.ts@@ -1,5 +1,5 @@-import { priceAsRun } from "@/server/account-tool-run";-import { estimateRemoval, RemovalEstimateSchema } from "@/server/remove-object";+import { estimateRemoval, planRemovalRun, RemovalEstimateSchema, removalSteps } from "@/server/remove-object";+import { poolPricedCheck } from "@/server/tool-runs";import { body, handle } from "@/server/shorts-schemas";/** The price, the pieces and the notes for the current settings, before anything runs. */@@ -10,7 +10,10 @@ async function post(request: Request) {});}-/** Priced as the asker's run would go: an account's on its own GPU or key, a guest's on the open engine, never a demo. */+/**+ * Priced as the asker's run would go: an account's on its own GPU or key, a guest's on the open engine, never a demo;+ * with its place, price and line on this install's GPUs when the run would go there (poolPricedCheck).+ */export async function POST(request: Request) {- return priceAsRun(request, () => post(request));+ return poolPricedCheck(request, () => post(request), async (raw) => removalSteps(await planRemovalRun(RemovalEstimateSchema.parse(raw))));}diff --git a/src/app/api/turnaround/estimate/route.ts b/src/app/api/turnaround/estimate/route.tsindex c87fc8aa..9a5a348a 100644--- a/src/app/api/turnaround/estimate/route.ts+++ b/src/app/api/turnaround/estimate/route.ts@@ -1,8 +1,8 @@import { requestViewer } from "@/server/auth";-import { priceAsRun } from "@/server/account-tool-run";import { recordExists } from "@/server/records";import { body, handle } from "@/server/shorts-schemas";-import { previewTurnaround, TurnaroundBodySchema, turnaroundRun } from "@/server/turnaround";+import { planTurnaroundRun, previewTurnaround, TurnaroundBodySchema, turnaroundRun, turnaroundSteps } from "@/server/turnaround";+import { poolPricedCheck } from "@/server/tool-runs";import { worldcastContextNow } from "@/server/worldcast-on";/**@@ -23,7 +23,15 @@ async function post(request: Request) {});}-/** Priced as the asker's run would go: an account's on its own GPU or key, a guest's on the open engine, never a demo. */+/**+ * Priced as the asker's run would go: an account's on its own GPU or key, a guest's on the open engine, never a demo;+ * with its place, price and line on this install's GPUs when the run would go there (poolPricedCheck).+ */export async function POST(request: Request) {- return priceAsRun(request, () => post(request));+ return poolPricedCheck(request, () => post(request), (raw) => {+ const input = TurnaroundBodySchema.parse(raw);+ delete input.requestId;+ if (input.elementId) throw new Error("Character not found");+ return turnaroundSteps(planTurnaroundRun(turnaroundRun(input)));+ });}diff --git a/src/app/api/turnaround/route.ts b/src/app/api/turnaround/route.tsindex 33950f2c..fa1998eb 100644--- a/src/app/api/turnaround/route.ts+++ b/src/app/api/turnaround/route.ts@@ -1,9 +1,9 @@import { requestViewer } from "@/server/auth";-import { bodyTooBig, guestRun, onceForAccount, priceAsRun, runAccountTool, toolViewer } from "@/server/account-tool-run";+import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";import { recordExists } from "@/server/records";import { body, handle, once } from "@/server/shorts-schemas";import { createTurnaround, planTurnaroundRun, previewTurnaround, startTurnaround, TurnaroundBodySchema, turnaroundRun, turnaroundSteps, type TurnaroundRun } from "@/server/turnaround";-import { withPlanPrice } from "@/server/tool-runs";+import { poolPricedCheck } from "@/server/tool-runs";import { worldcastContextNow } from "@/server/worldcast-on";/**@@ -22,8 +22,7 @@ async function post(request: Request) {// An account's run never uses the studio's WorldCast worker, nor asks it anything.if (toolViewer(request).kind !== "account") await worldcastContextNow();const run = turnaroundRun(input);- // With hosted runs on, a run that would go to this install's GPUs adds its place, price and line.- if (new URL(request.url).searchParams.get("preview")) return Response.json(await withPlanPrice(request, previewTurnaround(run), () => turnaroundSteps(planTurnaroundRun(run))));+ if (new URL(request.url).searchParams.get("preview")) return Response.json(previewTurnaround(run));const viewer = toolViewer(request);if (viewer.kind !== "account") {const result = await once("turnaround", requestId, () => createTurnaround(run));@@ -46,11 +45,22 @@ async function post(request: Request) {});}-/** A price check (`?preview=1`) is priced as the asker's run would go; a guest's run signs up first. */+/** The steps a turnaround's body would make (a character from the library is never planned for a visitor). */+function turnaroundPlan(raw: unknown) {+ const input = TurnaroundBodySchema.parse(raw);+ delete input.requestId;+ if (input.elementId) throw new Error("Character not found");+ return turnaroundSteps(planTurnaroundRun(turnaroundRun(input)));+}++/**+ * A price check (`?preview=1`) is priced as the asker's run would go, with its place, price and line on this install's+ * GPUs when it would go there (src/server/tool-runs.ts poolPricedCheck); a guest's run signs up first.+ */export async function POST(request: Request) {const viewer = toolViewer(request);const preview = !!new URL(request.url).searchParams.get("preview");- if (preview) return priceAsRun(request, () => post(request));+ if (preview) return poolPricedCheck(request, () => post(request), turnaroundPlan);if (viewer.kind === "guest") return guestRun();if (viewer.kind === "account") {const big = bodyTooBig(request);diff --git a/src/server/tool-runs.ts b/src/server/tool-runs.tsindex 0dd6a887..134e2a68 100644--- a/src/server/tool-runs.ts+++ b/src/server/tool-runs.ts@@ -1,10 +1,10 @@import "server-only";-import { onceForAccount, runAccountTool, toolPriceCheck, toolViewer, toolWishes, type ToolStep } from "./account-tool-run";+import { onceForAccount, priceAsRun, runAccountTool, toolPriceCheck, toolViewer, toolWishes, type ToolStep } from "./account-tool-run";import type { Account } from "./auth";import { db } from "./db";import { captureRun } from "./generations";import type { GenerationRequest } from "@/lib/catalog/types";-import type { PlaceWish } from "./hosted-run";+import { runOnPool } from "./hosted";import { withoutStamp } from "./run-stamp";/**@@ -80,35 +80,28 @@ export async function runToolForAccount<T>(request: Request, account: Account, o}/**- * A tool's price check (`?preview=1`) with its place on this install's GPUs added when the run would go there:- * `{ place: "pool", quote, line }` beside the tool's own answer (an account's or a guest's; the owner's as always).+ * A tool's price check (`?preview=1` or its estimate route) as one answer: the tool's own, priced as the asker's run+ * would go (priceAsRun), with `{ place: "pool", quote, line }` added when the run would go to this install's GPUs (an+ * account with no GPU of its own, or one whose runs go there first; a guest). Then the tool's own answer is made as a+ * run there too (runOnPool), so an account with no GPU of its own is priced instead of asked to connect one. The+ * owner's as always.+ *+ * `plan` gets the request's body (read from a copy, before `preview` reads it) and gives the run's steps; a body or a+ * plan that doesn't check out adds nothing here (the tool's own answer says why).*/-export async function withPoolPrice(request: Request, answer: object, start: () => unknown, wish?: PlaceWish): Promise<object> {- if (toolViewer(request).kind === "owner" || "error" in answer) return answer;- const pool = await toolPriceCheck(request, () => dryRunSteps(start), wish);- return pool ? { ...answer, ...pool } : answer;-}--/**- * The same, for a tool that plans its steps itself (turnaroundSteps, flyAroundSteps…): `plan` gives the run's steps as- * the viewer's run plans them. The place and price come from the request's headers when the body has no field for them.- */-export async function withPlanPrice(request: Request, answer: unknown, plan: () => ToolStep[] | Promise<ToolStep[]>): Promise<unknown> {- if (toolViewer(request).kind === "owner" || !answer || typeof answer !== "object" || "error" in answer) return answer;- const pool = await toolPriceCheck(request, plan);- return pool ? { ...answer, ...pool } : answer;-}--/** Every stored file a body names (`/api/files/…`), wherever it sits: the files an account's run must own. */-export function bodyFiles(value: unknown): string[] {- const out = new Set<string>();- const walk = (v: unknown, depth: number) => {- if (depth > 8) return;- if (typeof v === "string") {- if (v.startsWith("/api/files/")) out.add(v);- } else if (Array.isArray(v)) for (const x of v) walk(x, depth + 1);- else if (v && typeof v === "object") for (const x of Object.values(v)) walk(x, depth + 1);- };- walk(value, 0);- return [...out];+export async function poolPricedCheck(+ request: Request,+ preview: () => Response | Promise<Response>,+ plan: (body: unknown) => ToolStep[] | Promise<ToolStep[]>,+): Promise<Response> {+ const viewer = toolViewer(request);+ if (viewer.kind === "owner") return preview();+ let body: Promise<unknown> | null = null;+ const read = () => (body ??= request.clone().json().catch(() => null));+ const pool = await toolPriceCheck(request, async () => plan(await read()));+ if (!pool) return priceAsRun(request, preview);+ const res = await runOnPool(viewer.kind === "account" ? viewer.account.id : null, preview);+ const answer: unknown = res.ok ? await res.clone().json().catch(() => null) : null;+ if (!answer || typeof answer !== "object" || Array.isArray(answer) || "error" in answer) return res;+ return Response.json({ ...answer, ...pool }, { status: res.status, headers: { "Cache-Control": "no-store" } });}diff --git a/tests/hosted-video-audio-tools.test.ts b/tests/hosted-video-audio-tools.test.tsnew file mode 100644index 00000000..5e5ccecd--- /dev/null+++ b/tests/hosted-video-audio-tools.test.ts@@ -0,0 +1,234 @@+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 { 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 Video tools (Remove object, Evolution, Mixed Media, Katana, Turnaround's estimate), the Audio tools and Translate &+ * dub for an account with no GPU of its own: with hosted runs on, each price check names its place on this install's+ * GPUs with the price and the line, and the run goes there through the one gate, held once for the whole run. With+ * hosted runs off, and for an account whose own GPU answers, nothing changes.+ */+const dir = tempDir("fuobe-hosted-video-audio-tools-");+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 routes = {+ removeEstimate: await import("@/app/api/remove-object/estimate/route"),+ remove: await import("@/app/api/remove-object/route"),+ evolutionEstimate: await import("@/app/api/evolution/estimate/route"),+ evolution: await import("@/app/api/evolution/route"),+ mixedEstimate: await import("@/app/api/mixed-media/estimate/route"),+ mixed: await import("@/app/api/mixed-media/route"),+ katana: await import("@/app/api/katana/route"),+ turnaroundEstimate: await import("@/app/api/turnaround/estimate/route"),+ audio: await import("@/app/api/audio-tools/route"),+ dub: await import("@/app/api/dub/route"),+};+const { db } = await import("@/server/db");+const { resetRates } = await import("@/server/rate");+const billing = await import("@/server/billing");+const { clearAccountLoras } = await import("@/server/account-loras");+const { HOSTED_WORDS } = await import("@/server/hosted");++const CLIP = fs.readFileSync(path.join(__dirname, "fixtures/shorts-12s.mp4"));+const src = { duration: 12, fps: 16, width: 72, height: 128, hasAudio: true };++let fake: FakeBilling;+const ids: Record<string, string> = {};+const cookies: Record<string, string> = {};+beforeAll(async () => {+ fake = await startFakeBilling();+ fake.price = { amount: 0, version: "free" };+ auth.setPassword("install password");+ for (const who of ["none", "gpu"]) {+ ids[who] = auth.createAccount(`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_BILLING_URL", "FUOBE_BILLING_TOKEN", "FUOBE_POOL_MEDIA_INPUTS"]) delete process.env[k];+ await fake.close();+ await comfy.close();+});+beforeEach(() => {+ resetRates();+ billing.resetBillingCache();+ for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN"]) delete process.env[k];+ 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): Request {+ const text = JSON.stringify(body);+ return new Request(`http://localhost:3000${url}`, {+ method,+ headers: { host: "localhost:3000", "content-type": "application/json", "content-length": String(Buffer.byteLength(text)), ...(who && { cookie: cookies[who] }) },+ body: text,+ });+}+async function upload(who: string, 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;+}+const hostedOn = () => {+ process.env.FUOBE_HOSTED_RUNS = "1";+ process.env.FUOBE_BILLING_URL = fake.url;+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";+};+const places = (who: string, since: number) =>+ (db().prepare("SELECT request_json FROM generations WHERE json_extract(request_json, '$.account') = ? AND created_at >= ? ORDER BY created_at").all(ids[who], since) as { request_json: string }[]).map(+ (r) => (JSON.parse(r.request_json) as { place?: string }).place ?? "own",+ );+const reserves = () => fake.calls_of("/v1/reserve").length;++/** 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;+}++type Tool = {+ name: string;+ /** The price check: its route and body. */+ check: (files: Files) => [{ POST: (r: Request) => Promise<Response> }, string, unknown];+ /** The run itself (none: the price check only). */+ run?: (files: Files) => [{ POST: (r: Request) => Promise<Response> }, string, unknown];+ /** A step this install's GPUs don't carry yet (the tool's own LoRAs): refused there before Run. */+ ownOnly?: boolean;+};+type Files = { clip: string; pic: string };++const removal = (f: Files) => ({ engine: "open", mode: "type", prompt: "the skateboard", source: { url: f.clip, name: "skate.mp4", ...src }, range: { start: 0, end: 3 } });+const evolution = (f: Files) => ({ engine: "open", source: { url: f.clip, ...src }, range: { start: 0, end: 6 }, direction: "A paper world." });+const mixed = (f: Files) => ({ engine: "open", presetId: "mixed-sketch", source: { url: f.clip, ...src }, range: { start: 0, end: 1 }, fps: 4, resolution: "1K" });+const katana = (f: Files) => ({ engine: "open", reference: f.clip, photos: [f.pic], segments: [{ start: 0, end: 3 }], duration: 12 });+const split = (f: Files) => ({ tool: "split", engine: "open", media: f.clip, kind: "video" });+const dub = (f: Files) => ({ engine: "open", mode: "steps", video: f.clip, targets: ["es"] });++const TOOLS: Tool[] = [+ { name: "Remove object", check: (f) => [routes.removeEstimate, "/api/remove-object/estimate", removal(f)], run: (f) => [routes.remove, "/api/remove-object", removal(f)] },+ { name: "Evolution", check: (f) => [routes.evolutionEstimate, "/api/evolution/estimate", evolution(f)], run: (f) => [routes.evolution, "/api/evolution", evolution(f)] },+ { name: "Mixed Media", check: (f) => [routes.mixedEstimate, "/api/mixed-media/estimate", mixed(f)], run: (f) => [routes.mixed, "/api/mixed-media", mixed(f)], ownOnly: true },+ { name: "Katana", check: (f) => [routes.katana, "/api/katana?preview=1", katana(f)], run: (f) => [routes.katana, "/api/katana", katana(f)] },+ { name: "Turnaround", check: (f) => [routes.turnaroundEstimate, "/api/turnaround/estimate", { engine: "open", views: { front: f.pic, back: f.pic } }], ownOnly: true },+ { name: "Split soundtrack", check: (f) => [routes.audio, "/api/audio-tools?preview=1", split(f)], run: (f) => [routes.audio, "/api/audio-tools", split(f)] },+ { name: "Translate & dub", check: (f) => [routes.dub, "/api/dub?preview=1", dub(f)], run: (f) => [routes.dub, "/api/dub", dub(f)] },+];++const filesOf = async (who: string): Promise<Files> => ({ clip: await upload(who, CLIP, "video/mp4", "clip.mp4"), pic: await upload(who, TINY_PNG, "image/png", "me.png") });+const call = (who: string, [route, url, body]: [{ POST: (r: Request) => Promise<Response> }, string, unknown]) => route.POST(json(url, "POST", body, who));++describe("hosted runs on: an account with no GPU of its own runs them on this install's GPUs", () => {+ beforeEach(hostedOn);+ for (const t of TOOLS) {+ it(`${t.name}: its price check names the place, and its run is held once with every step there`, async () => {+ const f = await filesOf("none");+ const check = await call("none", t.check(f));+ expect(check.status, await check.clone().text()).toBe(200);+ const priced = (await check.json()) as { place?: string; quote?: { allowed: boolean; text: string }; line?: { place: number } };+ expect(priced.place, JSON.stringify(priced)).toBe("pool");+ expect(priced.line?.place).toBeGreaterThan(0);+ if (t.ownOnly) {+ // A step this install's GPUs don't carry yet (its own LoRAs): Run stays off and says so; pressed anyway, nothing is held or made.+ expect(priced.quote).toMatchObject({ allowed: false, text: HOSTED_WORDS.notOffered });+ if (!t.run) return;+ const before = reserves();+ const since = Date.now();+ const r = await call("none", t.run(f));+ expect(r.status).toBe(403);+ expect(((await r.json()) as { error: string }).error).toBe(HOSTED_WORDS.notOffered);+ expect(reserves()).toBe(before);+ expect(places("none", since)).toEqual([]);+ return;+ }+ expect(priced.quote?.allowed, JSON.stringify(priced.quote)).toBe(true);+ if (!t.run) return;+ const before = reserves();+ const since = Date.now();+ const r = await send(() => call("none", t.run!(f)));+ expect(r.status, await r.clone().text()).toBe(201);+ expect(reserves() - before).toBe(1);+ const made = places("none", since);+ expect(made.length).toBeGreaterThan(0);+ expect(made.every((p) => p === "pool")).toBe(true);+ });+ }++ it("an account whose own GPU answers keeps it: no place in its price check, and its run stays on its GPU", async () => {+ const f = await filesOf("gpu");+ for (const t of TOOLS) {+ const check = await call("gpu", t.check(f));+ expect(((await check.json()) as { place?: string }).place, t.name).toBeUndefined();+ }+ const since = Date.now();+ const before = reserves();+ for (const t of TOOLS.filter((x) => x.run && !x.ownOnly)) {+ // One at a time, as the account's limit on runs going at once asks.+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();+ const r = await send(() => call("gpu", t.run!(f)));+ expect(r.status, `${t.name}: ${await r.clone().text()}`).toBe(201);+ }+ expect(reserves()).toBe(before);+ const made = places("gpu", since);+ expect(made.length).toBeGreaterThan(0);+ expect(made.every((p) => p === "own")).toBe(true);+ });+});++describe("hosted runs off: as today", () => {+ it("no price check names a place, and an account with no GPU of its own is asked to connect one", async () => {+ // Its files were uploaded while hosted runs were on (with them off, it can't upload any).+ hostedOn();+ const f = await filesOf("none");+ for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN"]) delete process.env[k];+ billing.resetBillingCache();+ const calls = fake.calls_of("/v1/reserve").length + fake.calls_of("/v1/quote").length;+ for (const t of TOOLS) {+ const check = await call("none", t.check(f));+ expect(((await check.clone().json()) as { place?: string }).place, `${t.name}: ${await check.clone().text()}`).toBeUndefined();+ }+ const since = Date.now();+ for (const t of TOOLS.filter((x) => x.run)) {+ const r = await call("none", t.run!(f));+ expect(r.status, t.name).toBe(403);+ expect(((await r.json()) as { code?: string }).code, t.name).toBe("connect-gpu");+ }+ expect(places("none", since)).toEqual([]);+ expect(fake.calls_of("/v1/reserve").length + fake.calls_of("/v1/quote").length).toBe(calls);+ });+});