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: steps that can't run on this install's GPUs are refused before Run, and a run's price facts carry the size it makes
Adarsh3566b006e4fd
diff --git a/docs/billing-hook.md b/docs/billing-hook.mdindex 368ada6f..c13c467f 100644--- a/docs/billing-hook.md+++ b/docs/billing-hook.md@@ -68,16 +68,20 @@ type Policy = {};```-`megapixels` is the size of each picture or frame the run makes, about: the canvas the request names, else its aspect-ratio and resolution (the model's defaults where it names none). It is null for sound, text and 3D.+`megapixels` is the size of each picture or frame the run makes, about, as its workflow makes it: the canvas the+workflow binds (a canvas the request names counts only there; else the aspect ratio and resolution, the model's+defaults where the request names none), or for a workflow sized by its input (an edit, an upscale, a face swap) the+input's size, an upscale's times its factor, within the workflow's limits. It is null for sound, text and 3D.`steps` lists every step of the run that uses this install's GPUs, the run's own step first: a chain (a film ofseveral shots, a picture and then a step on it) is priced once, with one quote and one hold, for one press of Run.-Steps that need no model (joins, trims) and text steps are left out: they cost nothing. Every step must be one the-policy allows (`pool`, `kinds`), or the run isn't offered here.+Steps that need no model (joins, trims) are left out: they cost nothing. Every step must be one the policy allows+(`pool`, `kinds`) and one this install's GPUs can run (a ComfyUI step: not a text step, a step made in the browser or+a cloud model), or the run isn't offered here. It is refused before Run, never part way through.3D runs (Image to 3D and the other 3D tools) aren't offered on this install's GPUs yet, whatever `kinds.model3d` says.-They run on the account's own GPU, as before; an account with no GPU of its own is asked to connect one.+They run on the account's own GPU, as before. An account with no GPU of its own is told the tool isn't available here+(403, `code: "own-gpu-tool"`).The policy's limits count runs on this install's GPUs only, never runs on the account's own GPU or key (those keep theinstall's own limits). A run is one press of Run: its jobs and chain steps count once. `activeRuns` counts runs goingdiff --git a/src/server/generations.ts b/src/server/generations.tsindex f4e80cc8..47fd8c8d 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -101,7 +101,7 @@ import { blockedForAccounts, discardBody, fetchRemoteToFile, RemoteFetchError }import { accountSend } from "./account-send";import { stamped, stampOf, withoutStamp, withRunStamp } from "./run-stamp";import { POOL_WORDS, RELAY_WORDS } from "@/lib/relay";-import { placeInLine, poolWaitMs, runOnPool } from "./hosted";+import { placeInLine, poolRunsProvider, poolWaitMs, runOnPool } from "./hosted";import { poolLane } from "./computer/pool";import { runCeilingMs } from "./queue-settings";import { sweepBilling } from "./billing-outbox";@@ -1755,7 +1755,8 @@ function submit(id: string, route: ModelRoute, providerId: ProviderId, plan: Retif (!req.account) return submitNow(id, route, providerId, plan, req, index);// On this install's GPUs (hosted runs): as the account, on this install's ComfyUI server only.if (req.place === "pool") {- if (providerId !== "comfyui") {+ // (A run is checked against the same table before it is made: hosted-run.ts stepsProblem.)+ if (!poolRunsProvider(providerId)) {update(id, { status: "failed", error: OWN_GPU_ONLY, completed_at: Date.now(), message: null });submitting().delete(id);return Promise.resolve();diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.tsindex 05d3d4b5..1a896206 100644--- a/src/server/hosted-run.ts+++ b/src/server/hosted-run.ts@@ -27,7 +27,7 @@ import { PLACE_ASK_HEADER } from "@/lib/guest-access";import { createGenerations, outputKind, plannedSteps, previewGeneration, type PlannedStep } from "./generations";import { loadIndex } from "./gpu/index-file";import { poolLane } from "./computer/pool";-import { HOSTED_WORDS, inputCounts, poolAllows, poolOnWorkers, poolReady, poolTakes, poolTakesFiles, POOL_LANE, queueFacts, runFacts, runOnPool, workflowPicks } from "./hosted";+import { HOSTED_WORDS, inputCounts, poolAllows, poolOnWorkers, poolReady, poolRunsProvider, poolTakes, poolTakesFiles, POOL_LANE, queueFacts, runFacts, runOnPool, workflowPicks } from "./hosted";import { withRunStamp } from "./run-stamp";import { hostedRunsOn } from "./hosted-switch";import { checkRun, moderationConfigured } from "./moderation";@@ -100,11 +100,10 @@ const stepEndpoint = (s: PlannedStep): string | undefined => {};/**- * A step that needs no model and no graphics memory (a join, a trim, a mux): light work that costs nothing and that every- * policy allows. Text steps and steps made in the browser cost nothing either.+ * A ComfyUI step that needs no model and no graphics memory (a join, a trim, a mux): light work that costs nothing and+ * that every policy allows.*/function freeStep(s: PlannedStep): boolean {- if (s.provider === "llm" || s.provider === "local" || s.provider === "mock") return true;if (s.provider !== "comfyui") return false;const endpoint = stepEndpoint(s);if (!endpoint) return false;@@ -128,12 +127,14 @@ export function poolSteps(accountId: string, req: GenerationRequest): PlannedSte/*** The first step of a run that this install's GPUs may not take under the policy (its model or app not offered, a kind- * the policy leaves out, a model no worker is allowed, a cloud model), in words; null when every step may run there.- * A light ComfyUI step (a join) costs nothing and every policy allows it, but it still runs there: something there must- * take it, or the run's other steps would finish and their join would wait for nothing.+ * the policy leaves out, a model no worker is allowed, a cloud model, a text step or one made in the browser: steps that+ * can't run there), in words; null when every step may run there. A light ComfyUI step (a join) costs nothing and every+ * policy allows it, but it still runs there: something there must take it, or the run's other steps would finish and+ * their join would wait for nothing.*/export function stepsProblem(p: Policy, steps: PlannedStep[]): string | null {for (const s of steps) {+ if (!poolRunsProvider(s.provider)) return HOSTED_WORDS.notOffered;if (freeStep(s)) {if (s.provider === "comfyui" && !poolTakes(stepEndpoint(s))) return HOSTED_WORDS.notOffered;continue;@@ -149,7 +150,7 @@ export function stepsProblem(p: Policy, steps: PlannedStep[]): string | null {export function pricedSteps(steps: PlannedStep[]): NonNullable<RunFacts["steps"]> {const out = new Map<string, NonNullable<RunFacts["steps"]>[number]>();for (const s of steps) {- if (freeStep(s)) continue;+ if (freeStep(s) || !poolRunsProvider(s.provider)) continue;const key = `${s.modelId} ${s.op}`;const had = out.get(key);if (had) {diff --git a/src/server/hosted.ts b/src/server/hosted.tsindex 0d9859a0..d490a2b6 100644--- a/src/server/hosted.ts+++ b/src/server/hosted.ts@@ -1,6 +1,8 @@import "server-only";import { getModel } from "@/lib/catalog";-import { computeDimensions } from "@/lib/comfy";+import { computeDimensions, fitCanvas } from "@/lib/comfy";+import { h3Canvas, isH3Graph } from "@/lib/h3-prompt";+import { imageSize } from "@/lib/image-size";import type { GenerationRequest } from "@/lib/catalog/types";import { billingConfigured, type Policy, type QueueFacts, type RunFacts } from "./billing";import { lineFacts, poolLane, queueOfGeneration, workersAllowed } from "./computer/pool";@@ -8,8 +10,9 @@ import { db } from "./db";import { loadIndex } from "./gpu/index-file";import { hostedRunsOn } from "./hosted-switch";import { poolRunCounts } from "./pool-limits";-import { installComfyLocal, onInstallComfy, workerFor, workersTake } from "./providers/comfyui";+import { getWorkflow, installComfyLocal, onInstallComfy, workerFor, workersTake } from "./providers/comfyui";import { getSetting, withCandidates } from "./settings";+import { localHead, storedMedia } from "./storage";import { runAsTenant } from "./tenant";/**@@ -81,6 +84,14 @@ export function poolTakes(endpoint: string | undefined): boolean {return picks.length > 0 && picks.every((id) => workersAllowed(poolLane(id)));}+/**+ * 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.+ */+const POOL_PROVIDERS: ReadonlySet<string> = new Set(["comfyui"]);+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);@@ -195,21 +206,117 @@ export function placeInLine(generationId: string): { place: number; etaSeconds:return { place: before + 1, etaSeconds: typical === null ? null : Math.round(((before + 1) * typical) / 1000) };}+type Size = { width: number; height: number };+const megapixelsOf = (s: Size) => Math.round((s.width * s.height) / 10_000) / 100;+const positive = (v: unknown): number | null => ((typeof v === "number" || typeof v === "string") && Number.isFinite(Number(v)) && Number(v) > 0 ? Number(v) : null);++/** The size of a request's first input picture (else clip), from its file's header; null when it can't be read. */+function inputSize(req: GenerationRequest): Size | null {+ const i = req.inputs ?? {};+ const picture = i.images?.[0] ?? i.endImage;+ const head = picture ? localHead(picture) : null;+ const still = head ? imageSize(head) : null;+ if (still) return still;+ const clip = i.video ?? i.videos?.[0];+ const info = clip ? storedMedia(clip)?.info : null;+ return info?.width && info.height ? { width: info.width, height: info.height } : null;+}++/** An upscale model's own factor, from its file's name (RealESRGAN_x4plus, 4x-UltraSharp: 4). */+function modelFactor(name: unknown): number {+ const m = typeof name === "string" ? /(?:^|[^a-z0-9])x(\d)(?:[^0-9]|$)|(?:^|[^a-z0-9])(\d)x(?:[^a-z0-9]|$)/i.exec(name) : null;+ return m ? Number(m[1] ?? m[2]) : 1;+}+/**- * The megapixels of each picture or frame a request makes, about: the canvas it names (params.extra.width and height),- * else its aspect ratio and resolution (the model's defaults where it names none). Null for sound, text and 3D.+ * The size of each picture or frame a ComfyUI workflow makes, about, as the provider binds its graph (comfyui.ts+ * prepare): the canvas the graph binds (the request's own canvas only where the workflow binds one, else its aspect ratio+ * and resolution within the workflow's limits); or, for a workflow that takes its size from its input (an edit, an+ * upscale, a face swap), the input's size, an upscale's times its factor, within the workflow's limits. Undefined when+ * there's no such workflow, null when its input can't be read.*/-export function requestMegapixels(req: GenerationRequest, kind: RunFacts["kind"], modelId: string): number | null {- if (kind !== "image" && kind !== "video") return null;+function workflowSize(req: GenerationRequest, endpoint: string, modelId: string): Size | null | undefined {+ let found: ReturnType<typeof getWorkflow>;+ try {+ found = getWorkflow(endpoint);+ } catch {+ return undefined;+ }+ const { manifest, workflow } = found;+ const b = manifest.bindings as Record<string, { node: string; input: string }[] | undefined>;+ const d = (manifest.defaults ?? {}) as Record<string, unknown>;const extra = (req.params?.extra ?? {}) as Record<string, unknown>;- const w = Number(extra.width);- const h = Number(extra.height);+ // A bound value: the request's, else the workflow's default, else what its graph holds.+ const valueOf = (key: string): unknown => {+ if (extra[key] !== undefined) return extra[key];+ if (d[key] !== undefined) return d[key];+ const at = b[key]?.[0];+ return at ? (workflow[at.node]?.inputs as Record<string, unknown> | undefined)?.[at.input] : undefined;+ };+ const maxW = Number(manifest.limits?.maxWidth ?? Infinity);+ const maxH = Number(manifest.limits?.maxHeight ?? Infinity);+ const src = inputSize(req);+ if (b.width && b.height) {+ const [w, h] = [positive(extra.width), positive(extra.height)];+ if (w && h) return fitCanvas(w, h, manifest.limits);+ const model = getModel(modelId);+ const asked = req.params?.aspectRatio ?? model?.defaults?.aspectRatio;+ const h3 = isH3Graph(manifest.id);+ // "auto" (or H3 from a still) keeps the input's shape when its header says it.+ const follows = !asked || asked === "auto" || (h3 && !!b.image);+ const shape = follows && src ? `${src.width}:${src.height}` : asked === "auto" ? undefined : asked;+ if (h3) return h3Canvas(shape);+ const multiple = Number(manifest.limits?.dimensionMultiple ?? 16);+ const dims = computeDimensions(shape, req.params?.resolution ?? model?.defaults?.resolution, { width: Number(d.width ?? 1024), height: Number(d.height ?? 1024) }, multiple);+ const k = Math.min(1, maxW / dims.width, maxH / dims.height);+ return { width: Math.max(multiple, Math.floor((dims.width * k) / multiple) * multiple), height: Math.max(multiple, Math.floor((dims.height * k) / multiple) * multiple) };+ }+ if (!src) return null;+ let size: Size = { ...src };+ // What it scales its input to: so many megapixels, an upscale model's factor and a scale, a shorter side.+ const mp = b.megapixels ? positive(valueOf("megapixels")) : null;+ if (mp) {+ const k = Math.sqrt((mp * 1e6) / (size.width * size.height));+ size = { width: size.width * k, height: size.height * k };+ }+ let factor = b.upscaleModel ? modelFactor(valueOf("upscaleModel")) : 1;+ if (b.scale) {+ const scale = positive(valueOf("scale")) ?? 1;+ // SeedVR2 lowers its scale to fit its limits, to a 0.01 step (comfyui.ts); the others scale as asked.+ factor *= manifest.id === "upscale-image-seedvr2" ? Math.min(scale, Math.floor(Math.min(maxW / size.width, maxH / size.height) * 100) / 100) : scale;+ }+ size = { width: size.width * factor, height: size.height * factor };+ const short = b.shortSide ? positive(valueOf("shortSide")) : null;+ if (short) {+ const k = short / Math.min(size.width, size.height);+ size = { width: size.width * k, height: size.height * k };+ }+ // Padding out (an outpaint) adds to the canvas.+ const pad = (key: string) => (b[key] ? (positive(valueOf(key)) ?? 0) : 0);+ size = { width: size.width + pad("padLeft") + pad("padRight"), height: size.height + pad("padTop") + pad("padBottom") };+ const k = Math.min(1, maxW / size.width, maxH / size.height);+ return { width: Math.round(size.width * k), height: Math.round(size.height * k) };+}++/**+ * The megapixels of each picture or frame a run makes, about. A ComfyUI run (every run on this install's GPUs): the size+ * its workflow makes (workflowSize), never a size the request names that its workflow doesn't bind. A cloud run: the+ * canvas the request names (params.extra.width and height), else its aspect ratio and resolution (the model's defaults+ * where it names none). Null for sound, text and 3D, and for a run sized by an input that can't be read.+ */+export function requestMegapixels(req: GenerationRequest, kind: RunFacts["kind"], modelId: string, comfyEndpoint?: string): number | null {+ if (kind !== "image" && kind !== "video") return null;const model = getModel(modelId);- const size =- Number.isFinite(w) && Number.isFinite(h) && w > 0 && h > 0- ? { width: w, height: h }- : computeDimensions(req.params?.aspectRatio ?? model?.defaults?.aspectRatio, req.params?.resolution ?? model?.defaults?.resolution, {});- return Math.round((size.width * size.height) / 10_000) / 100;+ const byAsk = () => computeDimensions(req.params?.aspectRatio ?? model?.defaults?.aspectRatio, req.params?.resolution ?? model?.defaults?.resolution, {});+ if (comfyEndpoint) {+ const size = workflowSize(req, comfyEndpoint, modelId);+ if (size !== undefined) return size ? megapixelsOf(size) : null;+ // A workflow it picks at run time (a join of n clips): as asked.+ return megapixelsOf(byAsk());+ }+ const extra = (req.params?.extra ?? {}) as Record<string, unknown>;+ const [w, h] = [positive(extra.width), positive(extra.height)];+ return megapixelsOf(w && h ? { width: w, height: h } : byAsk());}/** The facts the billing service prices a run by (from a planned request: previewGeneration's answer). */@@ -232,7 +339,7 @@ export function runFacts(provider: p.providerId,jobs: p.jobs,outputsPerJob: p.jobs > 0 ? Math.max(1, Math.round(p.outputs / p.jobs)) : 1,- megapixels: requestMegapixels(req, kind, p.model.id),+ megapixels: requestMegapixels(req, kind, p.model.id, p.providerId === "comfyui" ? endpoint : undefined),seconds: req.params?.duration ?? (kind === "video" ? (model?.defaults?.duration ?? null) : null),fps: req.params?.fps ?? null,loras: p.loras.applied.length,diff --git a/tests/pool-limits.test.ts b/tests/pool-limits.test.tsindex 47b5a397..191c1cb2 100644--- a/tests/pool-limits.test.ts+++ b/tests/pool-limits.test.ts@@ -48,7 +48,8 @@ const { visitorStatus } = await import("@/server/account-gpu");const { loadManifest } = await import("@/server/providers/comfyui");const { loadIndex } = await import("@/server/gpu/index-file");const { allLanes } = await import("@/lib/lanes");-const { PLACE_ASK_HEADER } = await import("@/lib/guest-access");+const { getModel } = await import("@/lib/catalog");+const { CONNECT_GPU_HEADER, OWN_GPU_TOOL_MESSAGE, PLACE_ASK_HEADER } = await import("@/lib/guest-access");const hosted = await import("@/server/hosted");const { getGeneration } = await import("@/server/generations");const { ACCOUNT_MESSAGES } = await import("@/server/account-files");@@ -450,7 +451,7 @@ describe("where a run goes", () => {expect(hostedRun.kindAllowed({}, "model3d")).toBe(true);});- it("3D isn't offered on this install's GPUs yet, even with kinds.model3d on: an account with no GPU of its own is asked to connect one", async () => {+ it("3D isn't offered on this install's GPUs yet, even with kinds.model3d on: an account with no GPU of its own is told the tool isn't available here", async () => {withBilling({ kinds: { model3d: true }, limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });const a = account();const uploadsRoute = await import("@/app/api/uploads/route");@@ -464,6 +465,8 @@ describe("where a run goes", () => {const r = await post({ feature: "image-to-3d", modelId: "oss-pixal3d", op: "image-to-3d", inputs: { images: [url] }, ...SHOWN }, a.cookie);expect(r.status, JSON.stringify(r.body)).toBe(403);expect(r.body.code).toBe("own-gpu-tool");+ expect(r.body.error).toBe(OWN_GPU_TOOL_MESSAGE);+ expect(r.headers.get(CONNECT_GPU_HEADER)).toBeNull();expect(poolRuns(a.id)).toBe(0);expect(fake.holds.size).toBe(holds);});@@ -518,6 +521,32 @@ describe("a run's price facts", () => {expect(poolRuns(a.id)).toBe(2);});+ it("send the size a run really makes: an upscale of a large picture its upscaled size, never a size the request names that its workflow doesn't use", async () => {+ withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });+ const a = account();+ const sharp = (await import("sharp")).default;+ const big = await sharp({ create: { width: 2000, height: 1500, channels: 3, background: "#468" } })+ .png()+ .toBuffer();+ const uploadsRoute = await import("@/app/api/uploads/route");+ const up = await uploadsRoute.POST(+ new Request(`http://${HOST}/api/uploads`, { method: "POST", headers: { ...SITE_HEADERS, cookie: a.cookie, "content-type": "image/png", "x-file-name": "big.png", "content-length": String(big.length) }, body: new Uint8Array(big) }),+ );+ expect(up.status).toBe(201);+ const { url } = (await up.json()) as { url: string };+ // SeedVR2's 4x, held to its 4096 px limit (2.04x): 4080 × 3060, whatever size the request names.+ const upscale = { feature: "image", modelId: "oss-seedvr2-image", op: "upscale-image", inputs: { images: [url] }, params: { extra: { width: 64, height: 64 } }, ...SHOWN };+ const r = await post(upscale, a.cookie);+ expect(r.status, JSON.stringify(r.body)).toBe(201);+ const run = (fake.calls_of("/v1/reserve").at(-1)!.body as { run: { model: string; megapixels: number | null } }).run;+ expect(run).toMatchObject({ model: "oss-seedvr2-image", megapixels: 12.48 });+ // ESRGAN's model makes it 4 times as large: 8000 × 6000.+ expect(hosted.requestMegapixels({ ...upscale, modelId: "oss-upscale-image" } as never, "image", "oss-upscale-image", "upscale-image-esrgan")).toBe(48);+ // A workflow that binds its canvas makes the canvas the request names (a layout's), on its grid.+ const endpoint = getModel(IMAGE.modelId)!.routes.find((x) => x.provider === "comfyui")!.endpoint;+ expect(hosted.requestMegapixels({ ...IMAGE, params: { extra: { width: 1280, height: 720 } } } as never, "image", IMAGE.modelId, endpoint)).toBe(0.92);+ });+it("under the policy's cap on outputs, the price check and the run plan, price and make the same run", async () => {withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 0, outputsPerRun: 1 } });const a = account();@@ -591,9 +620,12 @@ 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; a text step costs nothing and is always allowed.+ // 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.expect(hostedRun.stepsProblem(billing.OPEN_POLICY, steps([["oss-z-image-turbo", "comfyui"], ["fal-flux", "fal"]]))).not.toBeNull();- expect(hostedRun.stepsProblem({ ...billing.OPEN_POLICY, pool: { allow: ["oss-z-image-turbo"] } }, steps([["oss-z-image-turbo", "comfyui"], ["some-llm", "llm"]]))).toBeNull();- expect(hostedRun.pricedSteps(steps([["oss-z-image-turbo", "comfyui"], ["oss-z-image-turbo", "comfyui"], ["some-llm", "llm"]]))).toEqual([expect.objectContaining({ model: "oss-z-image-turbo", jobs: 2 })]);+ for (const provider of ["llm", "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 })]);});});