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
Merge one-click render: the price check before Run, the place in line, pickers and the guest draft
Adarshac1cfc0a9ed8
diff --cc src/components/studio/composer.tsxindex bc576ce8,e7c99ac5..744a2b27--- a/src/components/studio/composer.tsx+++ b/src/components/studio/composer.tsx@@@ -19,8 -19,12 +19,13 @@@ import { dualEngine } from "@/lib/catalimport { locksByDefault } from "@/lib/catalog/palettes";import { DEFAULT_LOOK, lookCard } from "@/lib/catalog/soul-cards";import { formatsOf } from "@/lib/av/formats";- import { quoteBody, useHostedQuote, useSettled, type RunOn } from "@/lib/hosted";+ import { poolRunState, quoteBody, useHostedQuote, useSettled, type RunOn } from "@/lib/hosted";+import { composerPlace } from "@/lib/run-place";+ import { PoolNote } from "./pool-note";+ import { poolRunsModel } from "@/lib/pool-rules";+ import { HoldFilesCtx } from "@/lib/held-files";+ import { pendingStep } from "@/lib/guest-draft";+ import { useGuestDraft } from "./guest-draft";import { ExactOrbitControls } from "@/components/exact-orbit-controls";import { useFlyAround } from "@/components/fly-around-run";import { exactDefaults, takesExact, type ExactOrbit } from "@/lib/exact-orbit";@@@ -595,13 -620,20 +621,21 @@@ export function Composer({ docked }: {const viewerInfo = status?.viewer;const ownOnline = !!viewerInfo?.gpu.connected && !!viewerInfo.gpu.online;const [runOnPick, setRunOn] = useState<RunOn | null>(null);- const runOn: RunOn = runOnPick ?? (ownOnline && viewerInfo?.prefer !== "pool" ? "own" : "pool");+ // (The place the run names: none when the default is the studio's GPUs only because the studio puts them first.)+ const { runOn, place: runPlace } = composerPlace(runOnPick, ownOnline, viewerInfo?.prefer === "pool");const hostedHere = !!viewerInfo?.hosted && model?.engine === "open";const poolPrice = hostedHere && runOn === "pool";- const priceBody = useSettled(poolPrice ? quoteBody(signed.request, runOn) : null);- const hostedQuote = useHostedQuote(priceBody).data?.quote;- const priceUnavailable = poolPrice && hostedQuote?.code === "paused";+ const wantPrice = poolPrice ? quoteBody(signed.request, runOn) : null;+ const priceBody = useSettled(wantPrice);+ const priceQuery = useHostedQuote(priceBody);+ const hostedCheck = priceQuery.data;+ // The price check has answered for the draft as it is now (not one typed a moment ago).+ const priceSettled = !wantPrice || (priceBody === wantPrice && priceQuery.isFetched && !priceQuery.isFetching);+ const hostedQuote = hostedCheck?.quote;+ // The price check's answer: refused (busy, a limit, not offered here, paused…), Run is off and says why; otherwise+ // the price, and where the run would stand in line with the wait.+ const poolState = poolPrice ? poolRunState(hostedCheck) : null;+ const poolRefused = !!poolState?.refused;const resolvesOnServer = mentions.mentioned.length > 0 || !!draft.slots.mask?.ref || !!draft.slots.sketch?.ref;// Plan with stand-ins for attachments that are missing or still uploading, so the cost and thediff --cc src/server/generations.tsindex 8e0657d3,41fdbc1b..8533cd61--- a/src/server/generations.ts+++ b/src/server/generations.ts@@@ -157,6 -157,8 +157,8 @@@ export function toGeneration(r: Row): G// The run's stamp is the server's (its place, the billing hold, its class in the line): never sent to a browser or a// script, so a retry that sends the request back never says where the last attempt ran.const hold = stored.hold;+ // Its hold set an amount aside: only then does a run that can't finish say it wasn't charged.- const charged = !!hold && Number(stored.heldAmount) > 0;++ const charged = !!hold && !!stored.charged;const request = withoutStamp(stored);// A run on this install's GPUs shows the account only where it is (in line, working) and its result, or one plain// sentence when it can't finish: never the technical reason, which the owner reads in the accounts' runs.@@@ -212,10 -213,8 +214,10 @@@// On this install's GPUs (hosted runs): what it cost, or that it cost nothing....(stored.place === "pool" && { place: "pool" as const }),...(stored.charge && r.status === "succeeded" && { charge: stored.charge }),+ // (Only when its hold set an amount aside: a free run's hold has nothing to give back, so nothing is said.)- ...(hold && stored.charged && (r.status === "failed" || r.status === "canceled") && { notCharged: true as const }),+ ...(charged && (r.status === "failed" || r.status === "canceled") && { notCharged: true as const }),- ...(checking && { stage: "checking" as const }),+ // On this install's GPUs the output check is part of "Working": no word of its own.+ ...(checking && !pool && { stage: "checking" as const }),// Waiting in line on this install's GPUs: its place and the wait, about....(stored.place === "pool" && (r.status === "queued" || r.status === "running") && !checking && poolQueue(r.id)),};diff --cc src/server/hosted-run.tsindex 05d3d4b5,f2090697..093ed90e--- a/src/server/hosted-run.ts+++ b/src/server/hosted-run.ts@@@ -27,7 -26,7 +27,7 @@@ import { PLACE_ASK_HEADER } from "@/libimport { 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_GUEST_WORDS, HOSTED_WORDS, inputCounts, poolAllows, poolOnWorkers, poolReady, poolTakes, poolTakesFiles, POOL_LANE, queueFacts, runFacts, runOnPool } from "./hosted";++import { HOSTED_GUEST_WORDS, HOSTED_WORDS, inputCounts, poolAllows, poolOnWorkers, poolReady, 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";@@@ -86,6 -77,6 +87,9 @@@ const OWN: PlaceDecision = { kind: "own/** What an account whose own GPU didn't answer is asked, when its run named no place (never moved and charged unasked). */export const OWN_GPU_QUIET = "Your GPU isn't answering right now. Run this on this studio's GPUs instead, or try again when your GPU is back.";++/** A run this install's GPUs won't take, refused in the words the price check before Run gives too. */++const notOffered = (error: string): PlaceDecision => ({ kind: "refuse", refusal: { status: 403, body: { error, code: "not-offered" }, headers: { [BILLING_HEADER]: "not-offered" } } });++const askPlace = (): Refusal => ({ status: 409, body: { error: OWN_GPU_QUIET, code: "own-gpu-offline" }, headers: { [PLACE_ASK_HEADER]: "1" } });/** Does the policy put runs on this install's GPUs first, before the account's own GPU? */@@@ -173,81 -211,39 +225,74 @@@ async function ownGpuOnline(accountId:}}+/**+ * A request as it runs on this install's GPUs: no more outputs than the studio's cap per run, and the policy's when lower+ * (`capped`: fewer than it asked). The price check and the run plan and price this same request.+ */+export function poolRequest(req: GenerationRequest, p: Pick<Policy, "limits"> | null): { req: GenerationRequest; capped: boolean } {+ const policyCap = p && p.limits.outputsPerRun > 0 ? [Math.floor(p.limits.outputsPerRun)] : [];+ const cap = Math.min(ACCOUNT_LIMITS.outputsPerRun, ...policyCap);+ if ((req.params?.numOutputs ?? 1) <= cap) return { req, capped: false };+ return { req: { ...req, params: { ...req.params, numOutputs: cap } }, capped: true };+}+/*** Where an account's run goes (hosted.ts has the order). Only with hosted runs on; otherwise always "own" (today).+ *+ * An account with a GPU of its own keeps it as before: its own GPU first (unless the policy puts this install's first),+ * and every run this install's GPUs wouldn't take (the service down, hosted runs closed to it, a model or a kind not+ * offered, LoRAs, inputs, a step no worker takes, 3D) goes to its own GPU, even while that GPU doesn't answer. Only a run+ * this install's GPUs would take, that named no place, whose own GPU doesn't answer, is asked about (never moved there,+ * and charged, unasked).*/-export async function decidePlace(account: Account, req: GenerationRequest, wish: PlaceWish): Promise<PlaceDecision> {- if (!hostedRunsOn() || wish === "own" || !poolReady()) return { kind: "own" };+export async function decidePlace(account: Account, asked: GenerationRequest, wish: PlaceWish): Promise<PlaceDecision> {+ if (!hostedRunsOn() || wish === "own" || !poolReady()) return OWN;let planned: Planned;try {- planned = runOnPool(account.id, () => previewGeneration(req));+ planned = runOnPool(account.id, () => previewGeneration(asked));} catch {// A paid model, a model switched off, a request with something wrong: today's path says what.- return { kind: "own" };+ return OWN;+ }+ if (planned.route.provider !== "comfyui") return OWN;+ // What this install's GPUs can't take goes to the account's own GPU when it has one and didn't ask for this install's.+ const ownFallback = !!accountGpu(account.id) && wish !== "pool";+ // Its own GPU first, unless the policy puts this install's first. The policy as last read is enough to know that (no+ // call to the billing service); when none is kept, it is read while the GPU is checked.+ let p = cachedPolicy(account.id);+ let ownOffline = false;+ if (ownFallback && !prefersPool(p)) {+ const [online, read] = await Promise.all([ownGpuOnline(account.id), p === undefined ? billingPolicy(account.id) : Promise.resolve(p)]);+ p = read;+ if (!prefersPool(p)) {+ if (online) return OWN;+ ownOffline = true;+ }}- if (planned.route.provider !== "comfyui") return { kind: "own" };- const hasGpu = !!accountGpu(account.id);- const p = await billingPolicy(account.id);- // Its own GPU first, unless the policy puts this install's first (a place the request names always wins).- if (hasGpu && wish !== "pool" && !prefersPool(p)) {- if (await ownGpuOnline(account.id)) return { kind: "own" };- // Its GPU didn't answer the check: asked, never moved to this install's GPUs (and charged) without a word.- if (!wish) return { kind: "refuse", refusal: askPlace() };+ if (p === undefined) p = await billingPolicy(account.id);+ if (!p) return ownFallback ? OWN : { kind: "refuse", refusal: billingRefusal("paused", BILLING_PAUSED) };- const notHere = (error: string): PlaceDecision => (ownFallback ? OWN : { kind: "refuse", refusal: { status: 403, body: { error, code: "not-offered" }, headers: { [BILLING_HEADER]: "not-offered" } } });+ // Closed to this account: its own GPU (or today's "Connect your GPU"); asked for by name, said so.- if (!p.hosted) return wish === "pool" ? notHere(HOSTED_WORDS.notHosted) : OWN;- if (outputKind(planned.op, planned.model) === "model3d") return ownFallback ? OWN : { kind: "refuse", refusal: { status: 403, body: { error: OWN_GPU_TOOL_MESSAGE, code: "own-gpu-tool" }, headers: {} } };- if (!poolAllows(p, planned.model.id, asked.presetId)) return notHere(HOSTED_WORDS.notOffered);- if (!kindAllowed(p, outputKind(planned.op, planned.model))) return notHere(HOSTED_WORDS.notOffered);- // Nothing of this install's would ever run it (no worker is allowed its lane): never a run that waits for nothing.- if (!poolTakes(planned.route.endpoint)) return notHere(HOSTED_WORDS.notOffered);- if (asked.loras?.length) return notHere(HOSTED_WORDS.loras);- const inputs = inputCounts(asked);- const policy = p;- const takes = (kind: "image" | "video" | "audio") => policy.uploads[kind] && poolTakesFiles(kind);- if ((inputs.image && !takes("image")) || (inputs.video && !takes("video")) || (inputs.audio && !takes("audio"))) return notHere(HOSTED_WORDS.inputs);++ if (!p.hosted) return wish === "pool" ? notOffered(HOSTED_WORDS.notHosted) : OWN;+ // Planned, checked and priced for the outputs it would make there (the policy's cap per run).+ const { req, capped } = poolRequest(asked, p);+ if (capped) {+ try {+ planned = runOnPool(account.id, () => previewGeneration(req));+ } catch {+ return OWN;+ }}- // Every step of a chain, not only its first: each one the policy must allow, and the run is priced for all of them.- const steps = poolSteps(account.id, req);- const problem = steps && stepsProblem(p, steps);- if (problem) return notHere(problem);- if (!p) return { kind: "refuse", refusal: billingRefusal("paused", BILLING_PAUSED) };- if (!p.hosted) return { kind: "own" };- // From here on the run would be this install's: what it can't take there goes to the account's own GPU when it has one.++ // The same check as the price check before Run (poolGate): what this install's GPUs can't take goes to the account's++ // own GPU when it has one and didn't ask for this install's; otherwise it is refused in the same words.+ const gate = poolGate(p, planned, req, () => stepsFor(account, req));+ if (!gate.ok) {- if (hasGpu && wish !== "pool") return { kind: "own" };++ if (ownFallback) return OWN;+ const error = gateWords(gate.reason, false);- return gate.reason === "model3d"- ? { kind: "refuse", refusal: { status: 403, body: { error, code: "own-gpu-tool" }, headers: {} } }- : { kind: "refuse", refusal: { status: 403, body: { error, code: "not-offered" }, headers: { [BILLING_HEADER]: "not-offered" } } };++ return gate.reason === "model3d" ? { kind: "refuse", refusal: { status: 403, body: { error, code: "own-gpu-tool" }, headers: {} } } : notOffered(error);+ }- return { kind: "pool", planned, policy: p, steps: gate.steps ? pricedSteps(gate.steps) : undefined };+ // Its own GPU didn't answer the check: asked, never moved to this install's GPUs (and charged) without a word.+ if (ownOffline) return { kind: "refuse", refusal: askPlace() };- return { kind: "pool", planned, policy: p, steps: steps ? pricedSteps(steps) : undefined, req, capped };++ return { kind: "pool", planned, policy: p, steps: gate.steps ? pricedSteps(gate.steps) : undefined, req, capped };}/** The input files of a request, for the moderation service: their kind and sha256 (pictures' previews: not sent yet). */@@@ -354,16 -351,39 +399,38 @@@ export async function reservePool};}+ /** Where a new run would stand in line on this install's GPUs right now (1: next), and the wait, about (null: unknown). */+ export interface PoolLine {+ place: number;+ etaSeconds: number | null;+ }++ /** A price check's answer for a run this install's GPUs won't take, in the words the run itself would get. */+ const notOfferedQuote = (text: string): Quote => ({ allowed: false, amount: 0, priceVersion: "", text, code: "not-offered" });+/**- * A price check on this install's GPUs (hosted runs on): the plan there and the billing service's quote (no service:- * free, and Run keeps its own words). Null when the run wouldn't go there (its own GPU, its own key, today's answer).+ * A price check on this install's GPUs (hosted runs on): the plan there, the billing service's quote (no service: free,+ * and Run keeps its own words) and where the run would stand in line. Null when the run wouldn't go there (its own GPU,+ * its own key, today's answer).+ *+ * The quote is refused before Run for what the run itself would be refused for (the same poolGate as decidePlace, and+ * the route's limits), so Run is off and says why instead of failing once pressed: a model, a kind, LoRAs, files or a+ * chain's later step this install's GPUs don't take (for a viewer with no GPU of its own to send them to instead), and+ * the policy's limits on runs at once, runs in line and runs an hour. A guest's refusal names nothing it can't do yet.+ * `addr`: the client's address as the hourly count keeps it (pool-limits.ts clientAddress), asked for only when the+ * policy counts runs per address.*/- export async function poolQuote(account: Account | null, asked: GenerationRequest, wish: PlaceWish): Promise<{ planned: Planned; quote: Quote } | null> {+ export async function poolQuote(+ account: Account | null,+ asked: GenerationRequest,+ wish: PlaceWish,+ o: { addr?: () => string | null } = {},+ ): Promise<{ planned: Planned; quote: Quote; line: PoolLine } | null> {if (!hostedRunsOn() || wish === "own" || !poolReady()) return null;// A guest is priced under the billing service's policy for guests (none set: as an account would be, once signed up).- const p = account ? await billingPolicy(account.id) : billingConfigured() ? await billingPolicy(null) : null;+ const p = await billingPolicy(account?.id ?? null);- // Priced for the outputs it would make: the studio's cap per run, and the billing service's when lower.- const cap = Math.min(ACCOUNT_LIMITS.outputsPerRun, ...(billingConfigured() && p && p.limits.outputsPerRun > 0 ? [p.limits.outputsPerRun] : []));- const req = (asked.params?.numOutputs ?? 1) > cap ? { ...asked, params: { ...asked.params, numOutputs: cap } } : asked;+ // Priced for the outputs it would make: the studio's cap per run, and the policy's when lower (as the run is).+ const { req } = poolRequest(asked, p);let planned: Planned;try {planned = runOnPool(account?.id ?? null, () => previewGeneration(req));diff --cc tests/pool-limits.test.tsindex c8a753d9,c8bdc68f..675d49ba--- a/tests/pool-limits.test.ts+++ b/tests/pool-limits.test.ts@@@ -81,6 -76,15 +81,15 @@@ const post = async (body: Record<stringreturn { status: r.status, headers: r.headers, body: (await r.json()) as { items?: { id: string; place?: string }[]; code?: string; error?: string } };};+ /** Wait (up to 5 s) until `ok` holds: work the route left running in the background has landed. */-async function until(ok: () => boolean): Promise<void> {++async function waitFor(ok: () => boolean): Promise<void> {+ const end = Date.now() + 5000;+ while (!ok()) {+ if (Date.now() > end) throw new Error("timed out waiting");+ await new Promise((r) => setTimeout(r, 10));+ }+ }+/** Runs on this install's GPUs an account has made. */const poolRuns = (id: string) =>(db().prepare("SELECT COUNT(DISTINCT COALESCE(batch_id, id)) AS n FROM generations WHERE json_extract(request_json, '$.account') = ? AND json_extract(request_json, '$.place') = 'pool'").get(id) as { n: number }).n;@@@ -485,74 -349,6 +495,75 @@@ describe("a run's price facts", () =>expect(poolRuns(a.id)).toBe(2);});+ 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();+ const asked = { ...IMAGE, params: { numOutputs: 4 } };+ const q = await preview(asked, a.cookie);+ expect(q.body.place).toBe("pool");+ const quoted = (fake.calls_of("/v1/quote").at(-1)!.body as { run: { jobs: number; steps?: { jobs: number }[] } }).run;+ const r = await post({ ...asked, ...SHOWN }, a.cookie);+ expect(r.status, JSON.stringify(r.body)).toBe(201);+ const reserved = (fake.calls_of("/v1/reserve").at(-1)!.body as { run: { jobs: number; steps?: { jobs: number }[] } }).run;+ expect(quoted.jobs).toBe(1);+ expect(reserved.jobs).toBe(1);+ expect(reserved.steps).toEqual(quoted.steps);+ expect(reserved.steps?.[0].jobs).toBe(1);+ expect(r.body.items).toHaveLength(1);+ expect((r.body as { notes?: string[] }).notes).toContain(ACCOUNT_MESSAGES.outputsCapped);+ });++ it("the account's runs in the line facts count one per press of Run, however many jobs", async () => {+ withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });+ const a = account();+ const r = await post({ ...IMAGE, params: { numOutputs: 3 }, ...SHOWN }, a.cookie);+ expect(r.status, JSON.stringify(r.body)).toBe(201);+ expect(r.body.items!.length).toBeGreaterThan(1);- await until(() => r.body.items!.every((g) => taskOf(g.id)));++ await waitFor(() => r.body.items!.every((g) => !!taskOf(g.id)));+ expect(hosted.queueFacts(a.id, "z-image-turbo-t2i").mine).toEqual({ waiting: 1, running: 0 });+ expect((await post({ ...IMAGE, ...SHOWN }, a.cookie)).status).toBe(201);+ const sent = (fake.calls_of("/v1/reserve").at(-1)!.body as { queue: { mine: { waiting: number } } }).queue;+ expect(sent.mine.waiting).toBe(1);+ });++ it("a run whose hold set nothing aside never says it wasn't charged", async () => {+ withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });+ const a = account();+ const stopped = async () => {+ const r = await post({ ...IMAGE, ...SHOWN }, a.cookie);+ expect(r.status, JSON.stringify(r.body)).toBe(201);+ const id = r.body.items![0].id;+ db().prepare("UPDATE generations SET status = 'canceled', completed_at = ? WHERE id = ?").run(Date.now(), id);+ return getGeneration(id)!;+ };+ expect((await stopped()).notCharged).toBe(true);+ fake.price = { amount: 0, version: "v0" };+ const free = await stopped();+ expect(free.place).toBe("pool");+ expect(free.notCharged).toBeUndefined();+ });++ it("a chain whose join no worker takes is refused before anything is made", async () => {+ withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });+ const a = account();+ const film = { feature: "video", modelId: "oss-wan22-14b-fast", prompt: "x", params: { aspectRatio: "16:9", shots: [{ prompt: "wide shot", duration: 3 }, { prompt: "close-up", duration: 3 }] }, ...SHOWN };+ // Every lane but the joins'.+ const joins = new Set(hosted.workflowPicks("video-concat-{n}").map((id) => pool.poolLane(id)));+ expect(joins.size).toBeGreaterThan(0);+ const lanes = allLanes(loadIndex(), sha).map((l) => l.lane);+ expect(lanes.some((l) => !joins.has(l))).toBe(true);+ pool.patchWorker(worker.id, { allow: Object.fromEntries(lanes.filter((l) => !joins.has(l)).map((l) => [l, { delayMs: 0 }])) });+ const holds = fake.holds.size;+ const r = await post(film, a.cookie);+ expect(r.status, JSON.stringify(r.body)).toBe(403);+ expect(r.body.code).toBe("not-offered");+ expect(poolRuns(a.id)).toBe(0);+ expect(fake.holds.size).toBe(holds);- // Its price check says the same: not here.- expect((await preview(film, a.cookie)).body.place).toBeUndefined();++ // Its price check says the same before Run: not offered here, so Run stays off.++ const check = (await preview(film, a.cookie)).body as { quote?: { allowed: boolean; code?: string } };++ expect(check.quote).toMatchObject({ allowed: false, code: "not-offered" });+ });+it("every step must be one the policy allows: a later step's model it leaves out stops the run before anything is made", () => {const steps = (models: [string, string][]) => models.map(([modelId, provider], i) => ({ id: `s${i}`, modelId, op: "t2i", provider, kind: "image", presetId: null, waits: i > 0 }));const p = { ...billing.OPEN_POLICY, pool: { deny: ["oss-qwen-image-edit"] } };@@@ -564,3 -360,140 +575,140 @@@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 })]);});});++ describe("the price check before Run and the run itself", async () => {+ const { PLACEHOLDER } = await import("@/lib/composer");+ const { HOSTED_GUEST_WORDS, HOSTED_WORDS } = await import("@/server/hosted");+ const { OWN_GPU_TOOL_MESSAGE } = await import("@/lib/guest-access");+ /** A Fuobe DoP effect: its start frame is made first on another model, then animated. */+ const EFFECT = { feature: "video", presetId: "effect-acid", modelId: "fuobe-dop", op: "i2v", prompt: "a dancer", inputs: { images: [PLACEHOLDER.image] } };+ const LORAS = { ...IMAGE, loras: [{ file: "x.safetensors", url: "https://huggingface.co/x/x.safetensors" }] };+ const THREE_D = { feature: "3d", modelId: "oss-pixal3d", op: "image-to-3d", prompt: "", inputs: { images: [PLACEHOLDER.image] } };+ const NO_LIMITS = { activeRuns: 0, waiting: 0, runsPerHour: 0 };++ it("agree on every case: what the run would be refused for, the price check refuses before Run, in the same words", async () => {+ const cases: { name: string; req: Record<string, unknown>; policy?: Record<string, unknown>; refused?: string }[] = [+ { name: "taken", req: IMAGE },+ { name: "a chain, every step taken", req: EFFECT },+ { name: "a model the policy denies", req: IMAGE, policy: { pool: { deny: ["oss-z-image-turbo"] } }, refused: HOSTED_WORDS.notOffered },+ { name: "a kind the policy keeps off", req: IMAGE, policy: { kinds: { image: false } }, refused: HOSTED_WORDS.notOffered },+ { name: "extra LoRAs", req: LORAS, refused: HOSTED_WORDS.loras },+ { name: "a kind of file the policy keeps off", req: EFFECT, policy: { uploads: { image: false, video: false, audio: false } }, refused: HOSTED_WORDS.inputs },+ { name: "a chain whose later step the policy denies", req: EFFECT, policy: { pool: { deny: ["fuobe-mixed-media"] } }, refused: HOSTED_WORDS.notOffered },+ { name: "a 3D model", req: THREE_D, refused: OWN_GPU_TOOL_MESSAGE },+ ];+ const a = account();+ const acct = auth.accountById(a.id)!;+ for (const c of cases) {+ withBilling({ limits: NO_LIMITS, ...(c.policy ?? {}) });+ const req = { ...c.req, account: a.id } as never;+ const run = await hostedRun.decidePlace(acct, req, undefined);+ const check = await hostedRun.poolQuote(acct, req, undefined);+ if (!c.refused) {+ expect(run.kind, c.name).toBe("pool");+ expect(check?.quote.allowed, c.name).toBe(true);+ continue;+ }+ expect(run.kind, c.name).toBe("refuse");+ expect(run.kind === "refuse" && run.refusal.body.error, c.name).toBe(c.refused);+ expect(check?.quote, c.name).toMatchObject({ allowed: false, text: c.refused });+ }+ });++ it("a guest's price check plans every step of a chain too, and words its refusals for someone with no Settings yet", async () => {+ withBilling({ limits: NO_LIMITS });+ expect((await hostedRun.poolQuote(null, EFFECT as never, undefined))?.quote.allowed).toBe(true);+ // A later step this install's GPUs don't take: refused before Run, never only once the run starts after sign-up.+ withBilling({ limits: NO_LIMITS, pool: { deny: ["fuobe-mixed-media"] } });+ expect((await hostedRun.poolQuote(null, EFFECT as never, undefined))?.quote).toMatchObject({ allowed: false, code: "not-offered", text: HOSTED_GUEST_WORDS.notOffered });+ withBilling({ limits: NO_LIMITS, pool: { deny: ["oss-z-image-turbo"] } });+ const denied = await hostedRun.poolQuote(null, IMAGE as never, undefined);+ expect(denied?.quote).toMatchObject({ allowed: false, text: HOSTED_GUEST_WORDS.notOffered });+ expect(denied?.quote.text).not.toMatch(/Settings|your own GPU/);+ withBilling({ limits: NO_LIMITS });+ expect((await hostedRun.poolQuote(null, LORAS as never, undefined))?.quote.text).toBe(HOSTED_GUEST_WORDS.loras);+ // Planned as nobody's: nothing of the plan is kept.+ expect((db().prepare("SELECT COUNT(*) AS n FROM generations WHERE json_extract(request_json, '$.account') = 'guest:plan'").get() as { n: number }).n).toBe(0);+ });++ it("asks for the client's address only when the policy counts runs per address, and keeps its salt without writing again", async () => {+ const salted = () => !!db().prepare("SELECT 1 FROM settings WHERE key = 'pool.addressSalt'").get();+ const from = "203.0.113.20";+ const preview = async (cookie: string) => {+ const text = JSON.stringify(IMAGE);+ const r = await generationsRoute.POST(+ new Request(`http://${HOST}/api/generations?preview=1`, {+ method: "POST",+ headers: { ...SITE_HEADERS, cookie, "content-type": "application/json", "content-length": String(Buffer.byteLength(text)), "x-forwarded-for": from },+ body: text,+ }),+ );+ return (await r.json()) as { quote?: { allowed: boolean } };+ };+ db().prepare("DELETE FROM settings WHERE key = 'pool.addressSalt'").run();+ globalThis.__fuobeAddressSalt = undefined;+ process.env.FUOBE_TRUST_PROXY = "1";+ const a = account();+ // Hosted runs off: nothing of it at all.+ delete process.env.FUOBE_HOSTED_RUNS;+ await preview(a.cookie);+ expect(salted()).toBe(false);+ process.env.FUOBE_HOSTED_RUNS = "1";+ // No count per address in the policy: the address isn't read.+ withBilling({ limits: NO_LIMITS });+ expect((await preview(a.cookie)).quote?.allowed).toBe(true);+ expect(salted()).toBe(false);+ // Counted per address: read, under a salt made once.+ withBilling({ limits: { ...NO_LIMITS, addressRunsPerHour: 5 } });+ expect((await preview(a.cookie)).quote?.allowed).toBe(true);+ expect(salted()).toBe(true);+ const ask = () => limits.clientAddress(new Request("http://x/", { headers: { "x-forwarded-for": from } }));+ const first = ask();+ // Kept in memory after that: the settings row isn't written (nor read) for each check.+ db().prepare("DELETE FROM settings WHERE key = 'pool.addressSalt'").run();+ expect(ask()).toBe(first);+ expect(salted()).toBe(false);+ });+ });++ describe("a run on this install's GPUs that can't finish", async () => {+ const { getGeneration } = await import("@/server/generations");+ const { POOL_WORDS } = await import("@/lib/relay");+ const { HIDDEN_WORDS } = await import("@/server/output-checks");+ const fail = (id: string, error: string) => db().prepare("UPDATE generations SET status = 'failed', error = ?, completed_at = ? WHERE id = ?").run(error, Date.now(), id);+ const hide = (id: string) => {+ fail(id, HIDDEN_WORDS);+ db().prepare("INSERT INTO output_checks (asset_id, generation_id, state, asked_at, tries, next_at) VALUES (?, ?, 'hidden', ?, 0, ?)").run(`asset-${id}`, id, Date.now(), Date.now());+ };+ const FREE = { shown: { amount: 0, priceVersion: "v0" } };++ it("says Not charged only when its hold set an amount aside", async () => {+ withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });+ fake.price = { amount: 0, version: "v0" };+ const a = account();+ const free = await post({ ...IMAGE, ...FREE }, a.cookie);+ expect(free.status, JSON.stringify(free.body)).toBe(201);+ const freeId = free.body.items![0].id;+ fail(freeId, "the worker stopped");+ const g = getGeneration(freeId)!;+ expect(g.place).toBe("pool");+ expect(g.notCharged).toBeUndefined();+ expect(g.error).toBe(POOL_WORDS.failed);+ // Removed by the output checks: their sentence, without the charge.+ const hidden = await post({ ...IMAGE, ...FREE }, a.cookie);+ const hiddenId = hidden.body.items![0].id;+ hide(hiddenId);+ expect(getGeneration(hiddenId)!.error).toBe("This result was removed by the studio's checks.");+ expect(getGeneration(hiddenId)!.notCharged).toBeUndefined();+ // Something set aside: it says so.+ fake.price = { amount: 7, version: "v7" };+ const paid = await post({ ...IMAGE, ...SHOWN }, a.cookie);+ expect(paid.status, JSON.stringify(paid.body)).toBe(201);+ const paidId = paid.body.items![0].id;+ hide(paidId);+ expect(getGeneration(paidId)).toMatchObject({ notCharged: true, error: HIDDEN_WORDS });- // What the hold set aside stays the server's: never sent with the request.- expect(getGeneration(paidId)!.request.heldAmount).toBeUndefined();- expect((JSON.parse((db().prepare("SELECT request_json FROM generations WHERE id = ?").get(paidId) as { request_json: string }).request_json) as { heldAmount?: number }).heldAmount).toBe(7);++ // That the hold set something aside stays the server's: never sent with the request.++ expect("charged" in getGeneration(paidId)!.request).toBe(false);++ expect((JSON.parse((db().prepare("SELECT request_json FROM generations WHERE id = ?").get(paidId) as { request_json: string }).request_json) as { charged?: boolean }).charged).toBe(true);+ });+ });