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: the price check and the run share one check
Adarsh678d75882e67
diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.tsindex f781c847..0268d7cc 100644--- a/src/app/api/generations/route.ts+++ b/src/app/api/generations/route.ts@@ -154,7 +154,8 @@ export async function POST(request: Request) {if (preview) {// Hosted runs: a visitor's run that would go to this install's GPUs is priced there, with the billing service's// quote (its words for Run) and where it would stand in line. Off, or a run on its own GPU or key: priced as before.- const pool = viewer.kind !== "owner" ? await poolQuote(account, req, wish, { addr: account ? clientAddress(request) : null }) : null;+ // (The client's address is read only for a policy that counts runs per address.)+ const pool = viewer.kind !== "owner" ? await poolQuote(account, req, wish, { addr: () => clientAddress(request) }) : null;if (pool) {const { model, ...p } = pool.planned;return Response.json({ ...p, modelId: model.id, modelName: model.name, engine: model.engine, kind: outputKind(p.op, model), opLabel: OPERATION_LABELS[p.op] ?? p.op, place: "pool", quote: pool.quote, line: pool.line });diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.tsindex 477198f3..c725385c 100644--- a/src/lib/catalog/types.ts+++ b/src/lib/catalog/types.ts@@ -291,6 +291,15 @@ export const OPERATION_OUTPUT: Record<Operation, MediaKind> = {"song-stems": "audio",};+/**+ * What an operation makes on a model of this kind: colour matching works on images and videos, fal renders a timeline+ * as a video, and a 3D scene is a mesh on the open engine and a depth map (an image) on the cloud, so those follow the+ * model.+ */+export function operationOutput(op: Operation, modelKind: MediaKind): MediaKind {+ return op === "color-match" || op === "timeline" || op === "scene-3d" ? modelKind : OPERATION_OUTPUT[op];+}+/*** Video codecs and containers an export or HDR job can write (params.format): H.264 MP4, 10-bit H.265* MP4, ProRes 422 HQ or 4444 in a .mov, lossless FFV1 in a .mkv, or a 16-bit EXR frame sequence.@@ -1115,6 +1124,8 @@ export interface GenerationRequest {*/place?: "pool";hold?: string;+ /** Server-only: what the billing service's hold set aside (absent: nothing). */+ heldAmount?: number;charge?: string;checkOutputs?: boolean;/** How long a run on this install's GPUs may wait in line (ms), when the billing service set it. */diff --git a/src/lib/pool-rules.ts b/src/lib/pool-rules.tsindex 0d21c4ba..162abae9 100644--- a/src/lib/pool-rules.ts+++ b/src/lib/pool-rules.ts@@ -6,7 +6,8 @@ import type { MediaKind } from "./catalog/types";* fails at Run for it. The server checks the same rules on every run (src/server/hosted.ts poolAllows).** - `allow`: only these models (absent: every model); `deny`: never these.- * - `apps`: the same for apps, camera motions and effects (by preset id).+ * - `apps`: the same for apps, camera motions and effects (by preset id). A preset whose open model (or the kind it+ * makes) the rules keep off is kept off here too, so its card never says "Try free" for a run that would be refused.* - `kinds`: a kind set to false runs on the visitor's own GPU only (absent: every kind).*/export interface PoolRules {@@ -16,8 +17,21 @@ export interface PoolRules {kinds?: Partial<Record<MediaKind, boolean>>;}-/** The rules a policy's pool lists and kinds make, or undefined when they keep nothing off. */-export function poolRulesOf(p: { pool?: { allow?: string[]; deny?: string[]; apps?: { allow?: string[]; deny?: string[] } }; kinds?: Partial<Record<MediaKind, boolean>> }): PoolRules | undefined {+/** A preset as the rules see it: its id, and the open model it runs on with the kind it makes (none: no open route). */+export interface PresetModel {+ id: string;+ model?: { id: string; kind: MediaKind };+}++/**+ * The rules a policy's pool lists and kinds make, or undefined when they keep nothing off. `presets`: the catalog's+ * presets with their open models, so a preset is kept off with its model (by id, in the app lists: the shorter of the+ * two lists when the policy has no app allow list of its own).+ */+export function poolRulesOf(+ p: { pool?: { allow?: string[]; deny?: string[]; apps?: { allow?: string[]; deny?: string[] } }; kinds?: Partial<Record<MediaKind, boolean>> },+ presets: readonly PresetModel[] = [],+): PoolRules | undefined {const list = (xs: unknown) => (Array.isArray(xs) ? xs.filter((x): x is string => typeof x === "string") : undefined);const lists = p.pool ?? {};const out: PoolRules = {};@@ -25,11 +39,18 @@ export function poolRulesOf(p: { pool?: { allow?: string[]; deny?: string[]; appconst deny = list(lists.deny);if (allow) out.allow = allow;if (deny?.length) out.deny = deny;- const appsAllow = list(lists.apps?.allow);- const appsDeny = list(lists.apps?.deny);- if (appsAllow || appsDeny?.length) out.apps = { ...(appsAllow && { allow: appsAllow }), ...(appsDeny?.length && { deny: appsDeny }) };const off = Object.entries(p.kinds ?? {}).filter(([, v]) => v === false);if (off.length) out.kinds = Object.fromEntries(off) as PoolRules["kinds"];+ let appsAllow = list(lists.apps?.allow);+ let appsDeny = list(lists.apps?.deny);+ const modelOff = new Set(presets.filter((x) => x.model && !poolRunsModel(out, { ...x.model, engine: "open" })).map((x) => x.id));+ if (modelOff.size) {+ if (appsAllow) appsAllow = appsAllow.filter((id) => !modelOff.has(id));+ // Most presets kept off: the presets still on make the shorter list.+ else if (modelOff.size * 2 > presets.length) appsAllow = presets.filter((x) => !modelOff.has(x.id)).map((x) => x.id);+ else appsDeny = [...new Set([...(appsDeny ?? []), ...modelOff])];+ }+ if (appsAllow || appsDeny?.length) out.apps = { ...(appsAllow && { allow: appsAllow }), ...(appsDeny?.length && { deny: appsDeny }) };return Object.keys(out).length ? out : undefined;}@@ -52,7 +73,8 @@ export function poolRunsPreset(rules: PoolRules | undefined, presetId: string):/*** "Try free" on preset cards: with hosted runs on, a card whose preset runs on this studio's GPUs for this viewer (a* guest, an account with no GPU of its own, or one whose runs go to this studio's GPUs first) says it can be tried there.- * Null (no card says it) with hosted runs off, for a viewer whose runs go to its own GPU, and with cloud models only.+ * The rules hold presets whose model or kind is kept off too (poolRulesOf). Null (no card says it) with hosted runs off,+ * for a viewer whose runs go to its own GPU, and with cloud models only.*/export function tryFreeFor(viewer: { hosted?: boolean; prefer?: "pool"; gpu: { connected: boolean }; pool?: PoolRules } | undefined,diff --git a/src/server/account-gpu.ts b/src/server/account-gpu.tsindex 369ae622..ec2f4bf6 100644--- a/src/server/account-gpu.ts+++ b/src/server/account-gpu.ts@@ -7,14 +7,15 @@ import { accountGpu, type Account, type AccountGpu } from "./auth";import type { OwnerGpuView } from "@/lib/connections";import { runnerFacts, type Principal } from "./computer/tasks";import { offeredSummary } from "./model-access";-import { MODELS } from "@/lib/catalog";+import { getModel, MODELS, PRESETS } from "@/lib/catalog";+import { operationOutput } from "@/lib/catalog/types";import { hostedUntestedSummary } from "@/lib/catalog/hosted-untested";import { PROVIDERS } from "./providers";import { blockedForAccounts, fetchPublic, isLoopbackGpu } from "./remote-fetch";import { isInstallHost, REFUSED_ADDRESS } from "./gpu/hosts";import { balance as billingBalance, policy as billingPolicy, type Action, type Balance } from "./billing";import { poolReady } from "./hosted";-import { poolRulesOf, type PoolRules } from "@/lib/pool-rules";+import { poolRulesOf, type PoolRules, type PresetModel } from "@/lib/pool-rules";/*** "Your GPU" (public sign-up): the ComfyUI an account connects, where its runs go. The server calls@@ -200,6 +201,17 @@ export interface VisitorView {notice?: { id: string; text: string; url?: string };}+declare global {+ var __fuobePresetModels: PresetModel[] | undefined;+}++/** Every preset with the open model it runs on and the kind it makes (for the pickers' rules): made once. */+const presetModels = (): PresetModel[] =>+ (globalThis.__fuobePresetModels ??= PRESETS.map((p) => {+ const m = p.open ? getModel(p.open.modelId) : undefined;+ return m && p.open ? { id: p.id, model: { id: m.id, kind: operationOutput(p.open.op, m.kind) } } : { id: p.id };+ }));+/*** GET /api/status for a guest or an account: ComfyUI is its own GPU (taken as there until it has one,* so the studios offer Generate and the run asks it to connect one), fal.ai and Replicate are its own@@ -224,7 +236,7 @@ export async function visitorStatus(account: Account | null) {const p = await billingPolicy(account?.id ?? null);if (p?.hosted) viewer.hosted = true;if (p?.hosted && p.prefer === "pool") viewer.prefer = "pool";- const rules = p?.hosted && !gpu ? poolRulesOf(p) : undefined;+ const rules = p?.hosted && !gpu ? poolRulesOf(p, presetModels()) : undefined;if (rules) viewer.pool = rules;if (account && p?.links?.length) viewer.links = p.links;if (account && p?.notice) viewer.notice = p.notice;diff --git a/src/server/generations.ts b/src/server/generations.tsindex 8e6e9384..41fdbc1b 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -34,7 +34,7 @@ import { h3Frames, h3Prompt } from "@/lib/h3-prompt";import {CHAIN_LIST_SLACK,LAST_FRAME_CHAIN,- OPERATION_OUTPUT,+ operationOutput,type ChainSlot,type Engine,type Generation,@@ -157,6 +157,8 @@ export function toGeneration(r: Row): Generation {// 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 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.@@ -190,7 +192,7 @@ export function toGeneration(r: Row): Generation {request,// Held for the moderation service's check: nothing of it is shown until it passes.outputs: checking ? [] : (JSON.parse(r.outputs_json) as OutputFile[]),- error: pool ? poolError(r.id, r.error) : r.error,+ error: pool ? poolError(r.id, r.error, charged) : r.error,costUsd: r.cost_usd,favorite: !!r.favorite,createdAt: r.created_at,@@ -211,7 +213,7 @@ export function toGeneration(r: Row): Generation {// 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 }),- ...(hold && (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 }),// 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)),@@ -228,13 +230,15 @@ function poolMessage(r: Pick<Row, "status" | "message">): string | null {/*** A pool row's failure as the account reads it: Fuobe's own plain words about the account's side (its files are full, a* picture it can't use, it stopped the run) and the output check's words (a result it removed) as they are; anything- * else (whatever the GPUs, ComfyUI or a worker said) one plain sentence.+ * else (whatever the GPUs, ComfyUI or a worker said) one plain sentence. "Not charged" stays only on a run that had+ * something set aside (`charged`).*/-function poolError(id: string, error: string | null): string | null {+function poolError(id: string, error: string | null, charged: boolean): string | null {if (!error) return error;if (PLAIN_POOL_ERRORS().has(error) || /^Your files have reached \d+ GB\b/.test(error)) return error;const checked = db().prepare("SELECT 1 FROM output_checks WHERE generation_id = ? AND state IN ('hidden', 'unchecked') LIMIT 1").get(id);- return checked ? error : POOL_WORDS.failed;+ if (!checked) return POOL_WORDS.failed;+ return charged ? error : error.replace(/\s*Not charged\.$/, "");}const PLAIN_POOL_ERRORS = (() => {@@ -647,10 +651,9 @@ export class ConnectComfyError extends Error {/** Text steps depend on which LLM the route may use (the open model never calls Claude). */const routeReady = (r: ModelRoute) => (r.provider === "llm" ? llmBackends(r).length > 0 : provider(r.provider).isConfigured());-/** What a run produces: colour matching works on images and videos, and fal renders a timeline as a video, so those follow the model. */+/** What a run produces (operationOutput: some operations follow the model's kind). */export function outputKind(op: Generation["op"], model: { kind: MediaKind }): MediaKind {- // A 3D scene is a mesh on the open engine and a depth map (an image) on the cloud.- return op === "color-match" || op === "timeline" || op === "scene-3d" ? model.kind : OPERATION_OUTPUT[op];+ return operationOutput(op, model.kind);}// Live updates: every write to the table becomes an event (src/server/live.ts). A trashed rowdiff --git a/src/server/hosted-run.ts b/src/server/hosted-run.tsindex 07ea2c8c..f2090697 100644--- a/src/server/hosted-run.ts+++ b/src/server/hosted-run.ts@@ -26,7 +26,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 } from "./hosted";+import { HOSTED_GUEST_WORDS, HOSTED_WORDS, inputCounts, poolAllows, poolOnWorkers, poolReady, poolTakes, poolTakesFiles, POOL_LANE, queueFacts, runFacts, runOnPool } from "./hosted";import { withRunStamp } from "./run-stamp";import { hostedRunsOn } from "./hosted-switch";import { checkRun, moderationConfigured } from "./moderation";@@ -152,6 +152,54 @@ export function pricedSteps(steps: PlannedStep[]): NonNullable<RunFacts["steps"]return [...out.values()];}+/** Why this install's GPUs won't take a run: a 3D model, a model or kind not offered there, LoRAs, or a kind of file. */+export type GateReason = "model3d" | "notOffered" | "loras" | "inputs";++/** The words for a gate's reason: an account may connect its own GPU in Settings, a guest has nowhere to do that yet. */+export function gateWords(reason: GateReason, guest: boolean): string {+ if (reason === "model3d") return OWN_GPU_TOOL_MESSAGE;+ return (guest ? HOSTED_GUEST_WORDS : HOSTED_WORDS)[reason];+}++/**+ * The one check of whether this install's GPUs take a run, shared by the run itself (decidePlace) and the price check+ * before Run (poolQuote), so the two always agree: its output kind (no 3D there), the policy's model, app and kind+ * lists, a worker allowed its lane, LoRAs, the kinds of file it sends, and every later step of a chain (planned only+ * once the cheaper checks pass). `p` null: the billing service didn't answer, so only what needs no policy is checked.+ * Passed, it gives the planned steps for the run's one price.+ */+export function poolGate(+ p: Policy | null,+ planned: Planned,+ req: GenerationRequest,+ planSteps: () => PlannedStep[] | null,+): { ok: true; steps: PlannedStep[] | null } | { ok: false; reason: GateReason } {+ const kind = outputKind(planned.op, planned.model);+ if (kind === "model3d") return { ok: false, reason: "model3d" };+ if (p && (!poolAllows(p, planned.model.id, req.presetId) || !kindAllowed(p, kind))) return { ok: false, reason: "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 { ok: false, reason: "notOffered" };+ if (req.loras?.length) return { ok: false, reason: "loras" };+ if (p) {+ const inputs = inputCounts(req);+ const takes = (k: "image" | "video" | "audio") => p.uploads[k] && poolTakesFiles(k);+ if ((inputs.image && !takes("image")) || (inputs.video && !takes("video")) || (inputs.audio && !takes("audio"))) return { ok: false, reason: "inputs" };+ }+ // Every step of a chain, not only its first: each one the policy must allow, and the run is priced for all of them.+ const steps = planSteps();+ if (steps && p && stepsProblem(p, steps)) return { ok: false, reason: "notOffered" };+ return { ok: true, steps };+}++/**+ * The account a guest's price check plans a chain's later steps under: no real account has it (account ids hold no+ * colon), and nothing planned under it is kept (plannedSteps throws every row away).+ */+const GUEST_PLAN = "guest:plan";++/** Every row a run would make on this install's GPUs, for an account or (planned as nobody's) for a guest's price check. */+const stepsFor = (account: Account | null, req: GenerationRequest) => poolSteps(account?.id ?? GUEST_PLAN, req);+/** Is the account's own GPU there to run now? */async function ownGpuOnline(accountId: string): Promise<boolean> {const gpu = accountGpu(accountId);@@ -187,21 +235,15 @@ export async function decidePlace(account: Account, req: GenerationRequest, wishif (!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.- const notHere = (error: string): PlaceDecision => (hasGpu && wish !== "pool" ? { kind: "own" } : { kind: "refuse", refusal: { status: 403, body: { error, code: "not-offered" }, headers: { [BILLING_HEADER]: "not-offered" } } });- if (outputKind(planned.op, planned.model) === "model3d") return hasGpu && wish !== "pool" ? { kind: "own" } : { kind: "refuse", refusal: { status: 403, body: { error: OWN_GPU_TOOL_MESSAGE, code: "own-gpu-tool" }, headers: {} } };- if (!poolAllows(p, planned.model.id, req.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 (req.loras?.length) return notHere(HOSTED_WORDS.loras);- const inputs = inputCounts(req);- const takes = (kind: "image" | "video" | "audio") => p.uploads[kind] && poolTakesFiles(kind);- if ((inputs.image && !takes("image")) || (inputs.video && !takes("video")) || (inputs.audio && !takes("audio"))) return notHere(HOSTED_WORDS.inputs);- // Every step of a chain, not only its first: each one the policy must allow, and the run is priced for all of them.- const steps = poolSteps(account.id, req);- const problem = steps && stepsProblem(p, steps);- if (problem) return notHere(problem);- return { kind: "pool", planned, policy: p, steps: steps ? pricedSteps(steps) : undefined };+ const gate = poolGate(p, planned, req, () => stepsFor(account, req));+ if (!gate.ok) {+ if (hasGpu && wish !== "pool") return { kind: "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 { kind: "pool", planned, policy: p, steps: gate.steps ? pricedSteps(gate.steps) : undefined };}/** The input files of a request, for the moderation service: their kind and sha256 (pictures' previews: not sent yet). */@@ -293,11 +335,14 @@ export async function reservePool(forgetBalance(account.id);// Its class and head start in the line come from the answer too (a paid run goes before every free one).const boost = Number(a.boostMs);+ // What the hold set aside: a run that can't finish says it wasn't charged only when something could have been.+ const amount = Number(a.amount);return {ok: true,stamp: {...base,hold: a.holdId,+ ...(Number.isFinite(amount) && amount > 0 && { heldAmount: amount }),...(a.text && { charge: a.text }),...(a.maxWaitMs > 0 && { waitMs: a.maxWaitMs }),...(a.class === "paid" && { class: "paid" as const }),@@ -320,16 +365,18 @@ const notOfferedQuote = (text: string): Quote => ({ allowed: false, amount: 0, p* 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 (decidePlace and the route's limits), so- * Run is off and says why instead of failing once pressed: a model, a kind, LoRAs or files 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. `addr`: the client's address as the hourly count keeps it (pool-limits.ts clientAddress).+ * 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,- o: { addr?: string | null } = {},+ 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).@@ -350,22 +397,13 @@ export async function poolQuote(const line = (facts: { ahead: number; etaS: number | null }, q?: Quote): PoolLine => ({ place: Math.max(0, facts.ahead) + 1, etaSeconds: q?.etaS ?? facts.etaS ?? null });// What this install's GPUs won't take goes to the viewer's own GPU when it has one (as the run would); otherwise the// price check says so, and Run stays off.- const notHere = (text: string) => (hasGpu && wish !== "pool" ? null : { planned, quote: notOfferedQuote(text), line: line(queueFacts(account?.id ?? null, planned.route.endpoint)) });- const kind = outputKind(planned.op, planned.model);- if (kind === "model3d") return notHere(OWN_GPU_TOOL_MESSAGE);- if (p && (!poolAllows(p, planned.model.id, req.presetId) || !kindAllowed(p, kind))) return notHere(HOSTED_WORDS.notOffered);- if (!poolTakes(planned.route.endpoint)) return notHere(HOSTED_WORDS.notOffered);- if (req.loras?.length) return notHere(HOSTED_WORDS.loras);- if (p) {- const inputs = inputCounts(req);- const takes = (k: "image" | "video" | "audio") => p.uploads[k] && poolTakesFiles(k);- if ((inputs.image && !takes("image")) || (inputs.video && !takes("video")) || (inputs.audio && !takes("audio"))) return notHere(HOSTED_WORDS.inputs);+ const gate = poolGate(p, planned, req, () => stepsFor(account, req));+ if (!gate.ok) {+ if (hasGpu && wish !== "pool") return null;+ return { planned, quote: notOfferedQuote(gateWords(gate.reason, !account)), line: line(queueFacts(account?.id ?? null, planned.route.endpoint)) };}- // Priced once for every step of a chain that uses this install's GPUs (a step it can't take there: not offered here).- const steps = account ? poolSteps(account.id, req) : null;- const problem = steps && p ? stepsProblem(p, steps) : null;- if (problem) return notHere(problem);- const facts = { ...runFacts(req, planned, kind), ...(steps && { steps: pricedSteps(steps) }) };+ // Priced once for every step of a chain that uses this install's GPUs.+ const facts = { ...runFacts(req, planned, outputKind(planned.op, planned.model)), ...(gate.steps && { steps: pricedSteps(gate.steps) }) };const queue = queueFacts(account?.id ?? null, planned.route.endpoint);let q = await billingQuote(account ? accountFacts(account) : null, facts, queue);// The policy's limits on this account's runs here, as the run would meet them (pool-limits.ts): said before Run.diff --git a/src/server/hosted.ts b/src/server/hosted.tsindex 9307993e..1ee87905 100644--- a/src/server/hosted.ts+++ b/src/server/hosted.ts@@ -87,6 +87,13 @@ export const HOSTED_WORDS = {waitedTooLong: "This studio's GPUs were busy, so it didn't run. Not charged.",};+/** The same refusals for a guest, who has no Settings to connect a GPU in yet. */+export const HOSTED_GUEST_WORDS = {+ notOffered: "This one isn't offered here. Pick another model.",+ loras: "Extra LoRAs aren't offered here. Run without them.",+ inputs: "This kind of file can't be used here. Use a picture instead.",+};+/** May this model (and app) run on this install's GPUs under this policy? */export function poolAllows(p: Pick<Policy, "pool">, modelId: string, presetId?: string | null): boolean {const m = p.pool ?? {};diff --git a/src/server/pool-limits.ts b/src/server/pool-limits.tsindex 389817b9..ae8b1547 100644--- a/src/server/pool-limits.ts+++ b/src/server/pool-limits.ts@@ -63,11 +63,26 @@ export function poolRunCounts(accountId: string): { active: number; waiting: numreturn { active: r.active, waiting: r.waiting };}-/** The salt the client addresses are kept under: made once per install, never sent anywhere. */+declare global {+ var __fuobeAddressSalt: { db: unknown; salt: string } | undefined;+}++/**+ * The salt the client addresses are kept under: made once per install, never sent anywhere. Read (and made, the first+ * time) once per process and database, so counting an address never takes the database's write lock again.+ */function salt(): string {const d = db();- d.prepare("INSERT OR IGNORE INTO settings (key, value) VALUES ('pool.addressSalt', ?)").run(crypto.randomBytes(32).toString("hex"));- return (d.prepare("SELECT value FROM settings WHERE key = 'pool.addressSalt'").get() as { value: string }).value;+ const kept = globalThis.__fuobeAddressSalt;+ if (kept?.db === d) return kept.salt;+ const read = () => (d.prepare("SELECT value FROM settings WHERE key = 'pool.addressSalt'").get() as { value: string } | undefined)?.value;+ let value = read();+ if (!value) {+ d.prepare("INSERT OR IGNORE INTO settings (key, value) VALUES ('pool.addressSalt', ?)").run(crypto.randomBytes(32).toString("hex"));+ value = read()!;+ }+ globalThis.__fuobeAddressSalt = { db: d, salt: value };+ return value;}/**@@ -86,8 +101,11 @@ const since = (column: "account" | "addr", value: string, from: number) =>/** Seconds until the oldest of an hour's runs leaves the hour. */const retryAfter = (oldest: number | null, now: number) => Math.max(60, Math.ceil(((oldest ?? now) + HOUR - now) / 1000));-/** The first of the policy's limits this run would pass, or null. */-export function poolLimitRefusal(accountId: string, policy: Pick<Policy, "limits">, addr: string | null, now = Date.now()): LimitRefusal | null {+/**+ * The first of the policy's limits this run would pass, or null. `addr` may be a function: it is asked only when the+ * policy counts runs per address.+ */+export function poolLimitRefusal(accountId: string, policy: Pick<Policy, "limits">, addr: string | null | (() => string | null), now = Date.now()): LimitRefusal | null {const lim = policy.limits ?? ({} as Policy["limits"]);const positive = (v: unknown) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? Math.floor(v) : 0);const activeMax = positive(lim.activeRuns);@@ -103,8 +121,9 @@ export function poolLimitRefusal(accountId: string, policy: Pick<Policy, "limitsconst h = since("account", accountId, now - HOUR);if (h.n >= hourMax) return { status: 429, error: POOL_LIMIT_WORDS.hourly, code: "limit", retryAfterS: retryAfter(h.oldest, now) };}- if (addrMax && addr) {- const h = since("addr", addr, now - HOUR);+ const address = addrMax ? (typeof addr === "function" ? addr() : addr) : null;+ if (address) {+ const h = since("addr", address, now - HOUR);if (h.n >= addrMax) return { status: 429, error: POOL_LIMIT_WORDS.address, code: "limit", retryAfterS: retryAfter(h.oldest, now) };}return null;diff --git a/src/server/run-stamp.ts b/src/server/run-stamp.tsindex e5b18da2..4c4e6aa2 100644--- a/src/server/run-stamp.ts+++ b/src/server/run-stamp.ts@@ -9,6 +9,7 @@ import type { GenerationRequest } from "@/lib/catalog/types";** - `place: "pool"`: the run goes to this install's GPUs (hosted runs, hosted.ts), not the account's own.* - `hold`: the billing service's hold for the run (billing.ts reserve); every row reports to it once (billing-outbox.ts).+ * `heldAmount`: what the hold set aside (absent: nothing was).* - `charge`: the words the billing service gave for the charge ("7 units"), shown on the result.* - `checkOutputs`: the moderation service asked to see this run's outputs before they show (moderation.ts).* - `class` and `boostMs`: its class in the line ("paid" before "free") and its head start inside that class.@@ -16,6 +17,8 @@ import type { GenerationRequest } from "@/lib/catalog/types";export interface RunStamp {place?: "pool";hold?: string;+ /** What the hold set aside, when it set anything aside (a run that can't finish then says it wasn't charged). */+ heldAmount?: number;charge?: string;checkOutputs?: boolean;/** How long it may wait in line on this install's GPUs (ms), from the billing service. */@@ -39,7 +42,7 @@ export const withRunStamp = <T,>(stamp: RunStamp, fn: () => T): T => store().runexport const runStamp = (): RunStamp | undefined => store().getStore();/** The server-only fields of a request. */-export const STAMP_FIELDS = ["place", "hold", "charge", "checkOutputs", "waitMs", "class", "boostMs"] as const;+export const STAMP_FIELDS = ["place", "hold", "heldAmount", "charge", "checkOutputs", "waitMs", "class", "boostMs"] as const;/** A request with the current stamp's fields, and none of a stored request's own. */export function stamped(req: GenerationRequest): GenerationRequest {@@ -51,6 +54,7 @@ export function stamped(req: GenerationRequest): GenerationRequest {...out,...(s.place && { place: s.place }),...(s.hold && { hold: s.hold }),+ ...(s.heldAmount && s.heldAmount > 0 && { heldAmount: s.heldAmount }),...(s.charge && { charge: s.charge }),...(s.checkOutputs && { checkOutputs: true }),...(s.waitMs && s.waitMs > 0 && { waitMs: s.waitMs }),@@ -64,6 +68,7 @@ export function stampOf(req: Pick<GenerationRequest, (typeof STAMP_FIELDS)[numbereturn {...(req.place === "pool" && { place: "pool" as const }),...(req.hold && { hold: req.hold }),+ ...(req.heldAmount && req.heldAmount > 0 && { heldAmount: req.heldAmount }),...(req.charge && { charge: req.charge }),...(req.checkOutputs && { checkOutputs: true }),...(req.waitMs && { waitMs: req.waitMs }),diff --git a/tests/hosted-pickers.test.ts b/tests/hosted-pickers.test.tsindex 4be1441e..60e0e2da 100644--- a/tests/hosted-pickers.test.ts+++ b/tests/hosted-pickers.test.ts@@ -46,6 +46,54 @@ describe("what pickers leave out for a visitor with no GPU of its own", () => {});});+describe("presets kept off with their model or the kind they make", () => {+ const presets = [+ { id: "app-face", model: { id: "oss-face", kind: "image" as const } },+ { id: "app-portrait", model: { id: "oss-portrait", kind: "image" as const } },+ { id: "motion-orbit", model: { id: "oss-clip", kind: "video" as const } },+ { id: "effect-melt", model: { id: "oss-clip", kind: "video" as const } },+ { id: "app-cloud-only" },+ ];+ const tryFree = (pool: Parameters<typeof poolRulesOf>[0]) => tryFreeFor({ hosted: true, gpu: { connected: false }, pool: poolRulesOf(pool, presets) }, "both")!;++ it("a preset on a model the policy denies, or of a kind it keeps off, says no Try free and leaves the pickers", () => {+ const denied = tryFree({ pool: { deny: ["oss-face"] } });+ expect(denied({ id: "app-face", open: true })).toBe(false);+ expect(denied({ id: "app-portrait", open: true })).toBe(true);+ expect(denied({ id: "motion-orbit", open: true })).toBe(true);+ const noVideo = tryFree({ pool: {}, kinds: { video: false } });+ expect(noVideo({ id: "motion-orbit", open: true })).toBe(false);+ expect(noVideo({ id: "effect-melt", open: true })).toBe(false);+ expect(noVideo({ id: "app-face", open: true })).toBe(true);+ // The rules the gallery and the motion and effect pickers filter by say the same.+ const rules = poolRulesOf({ pool: { deny: ["oss-face"] }, kinds: { video: false } }, presets);+ expect(presets.filter((p) => poolRunsPreset(rules, p.id)).map((p) => p.id)).toEqual(["app-portrait", "app-cloud-only"]);+ });++ it("keeps the shorter list, and the policy's own app lists", () => {+ // Most presets kept off: the ones still on are listed instead.+ expect(poolRulesOf({ pool: { allow: ["oss-portrait"] } }, presets)?.apps).toEqual({ allow: ["app-portrait", "app-cloud-only"] });+ // An app allow list of the policy's own only loses what its models keep off.+ expect(poolRulesOf({ pool: { deny: ["oss-face"], apps: { allow: ["app-face", "motion-orbit"] } } }, presets)?.apps).toEqual({ allow: ["motion-orbit"] });+ expect(poolRulesOf({ pool: { deny: ["oss-face"], apps: { deny: ["effect-melt"] } } }, presets)?.apps).toEqual({ deny: ["effect-melt", "app-face"] });+ // Nothing kept off: nothing to send.+ expect(poolRulesOf({ pool: { deny: [] } }, presets)).toBeUndefined();+ });++ it("agree with the server: a preset says Try free only when the run it makes would be taken", async () => {+ const { poolAllows } = await import("@/server/hosted");+ const { kindAllowed } = await import("@/server/hosted-run");+ const policies = [{ pool: {} }, { pool: { deny: ["oss-face"] } }, { pool: { allow: ["oss-clip"] } }, { pool: {}, kinds: { video: false } }, { pool: { apps: { deny: ["app-portrait"] } } }];+ for (const p of policies) {+ const free = tryFreeFor({ hosted: true, gpu: { connected: false }, pool: poolRulesOf(p, presets) }, "both")!;+ for (const preset of presets.filter((x) => x.model)) {+ const server = poolAllows(p, preset.model!.id, preset.id) && kindAllowed(p, preset.model!.kind);+ expect(free({ id: preset.id, open: true }), JSON.stringify({ p, preset: preset.id })).toBe(server);+ }+ }+ });+});+describe("Try free on preset cards", () => {const card = { id: "app-x", open: true };it("only with hosted runs on, for a viewer whose runs go to this studio's GPUs, on presets they run", () => {diff --git a/tests/hosted-price-check.test.ts b/tests/hosted-price-check.test.tsindex 690ea1f6..1414227f 100644--- a/tests/hosted-price-check.test.ts+++ b/tests/hosted-price-check.test.ts@@ -226,7 +226,13 @@ describe("what this install's GPUs keep off, in the status", () => {expect((await visitorStatus(auth.accountById(a)!)).viewer.pool).toBeUndefined();process.env.FUOBE_HOSTED_RUNS = "1";const s = await visitorStatus(auth.accountById(a)!);- expect(s.viewer.pool).toEqual({ deny: ["oss-z-image-turbo"], apps: { deny: ["app-x"] }, kinds: { model3d: false } });+ expect(s.viewer.pool).toMatchObject({ deny: ["oss-z-image-turbo"], kinds: { model3d: false } });+ // The policy's own app list, and every preset whose open model (or the kind it makes) is kept off with it.+ const { PRESETS, getModel } = await import("@/lib/catalog");+ const offWithModel = PRESETS.filter((p) => p.open && (p.open.modelId === "oss-z-image-turbo" || getModel(p.open.modelId)?.kind === "model3d")).map((p) => p.id);+ expect(offWithModel.length).toBeGreaterThan(0);+ expect(s.viewer.pool?.apps?.deny).toEqual(expect.arrayContaining(["app-x", ...offWithModel]));+ expect(s.viewer.pool?.apps?.deny).not.toContain(PRESETS.find((p) => p.open && !offWithModel.includes(p.id))!.id);expect((await visitorStatus(null)).viewer.pool).toEqual(s.viewer.pool);// Its own GPU runs what this install's GPUs don't: nothing is left out of its pickers.auth.setAccountGpu(a, { mode: "computer" });diff --git a/tests/hosted-run-tiles.test.ts b/tests/hosted-run-tiles.test.tsindex 0823da73..fb9f74a9 100644--- a/tests/hosted-run-tiles.test.ts+++ b/tests/hosted-run-tiles.test.ts@@ -72,6 +72,11 @@ describe("a run's tile on this studio's GPUs", () => {expect(html).toContain(POOL_WORDS.failed.replace("'", "'"));expect(html).not.toContain("Couldn't generate this one");expect(html).toContain("Retry");+ // Nothing set aside for it (every run free): only the sentence and Retry, with nothing about a charge.+ const free = render(createElement(FailedTile, { g: gen({ place: "pool", status: "failed", error: POOL_WORDS.failed }), ratio: 1, onRetry: () => {} }));+ expect(free).toContain(POOL_WORDS.failed.replace("'", "'"));+ expect(free).toContain("Retry");+ expect(free).not.toMatch(/charged/i);});it("every other run's tiles are as before", () => {const own = render(createElement(PendingTile, { g: gen({ status: "running", message: "Generating", progress: 0.4 }), ratio: 1 }));diff --git a/tests/moderation-hook.test.ts b/tests/moderation-hook.test.tsindex 5ac90db3..be7557db 100644--- a/tests/moderation-hook.test.ts+++ b/tests/moderation-hook.test.ts@@ -188,7 +188,9 @@ describe("the output check", () => {await checks.sweepOutputChecks(Date.now() + 25 * 3_600_000);expect(row(id).status).toBe("failed");expect(row(id).error).toBe(checks.UNCHECKED_WORDS);- expect(getGeneration(id)!.error).toBe(checks.UNCHECKED_WORDS);+ // Nothing was set aside for it (no billing service): the account reads the sentence without the charge.+ expect(getGeneration(id)!.error).toBe(checks.UNCHECKED_WORDS.replace(/ Not charged\.$/, ""));+ expect(getGeneration(id)!.error).not.toContain("charged");expect(db().prepare("SELECT 1 FROM assets WHERE id = ?").get(file)).toBeUndefined();});});diff --git a/tests/pool-limits.test.ts b/tests/pool-limits.test.tsindex 8e817532..c8bdc68f 100644--- a/tests/pool-limits.test.ts+++ b/tests/pool-limits.test.ts@@ -76,6 +76,15 @@ const post = async (body: Record<string, unknown>, cookie: string, headers: Recoreturn { 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> {+ 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;@@ -209,9 +218,15 @@ describe("runs waiting, runs an hour, runs from one address", () => {const second = await post({ ...IMAGE, ...SHOWN }, a.cookie);expect(second.status).toBe(429);expect(second.body.error).toBe(limits.POOL_LIMIT_WORDS.waiting(1));- // Once it has started, the next one may wait.+ // Once a worker has taken it, the next one may wait. Its submit runs in the background and notes the submission+ // (clearing any start): the worker takes it only after that, and the start is noted as the runner notes it.const id = (db().prepare("SELECT id FROM generations WHERE json_extract(request_json, '$.account') = ?").get(a.id) as { id: string }).id;- db().prepare("INSERT OR REPLACE INTO generation_runs (id, submitted_at, started_at) VALUES (?, ?, ?)").run(id, Date.now(), Date.now());+ await until(() => !!db().prepare("SELECT 1 FROM generation_runs WHERE id = ? AND submitted_at IS NOT NULL").get(id));+ const w = db().prepare("SELECT * FROM relay_workers LIMIT 1").get() as Parameters<typeof pool.workerBeat>[0];+ pool.workerBeat(w, pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 1, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [] }));+ const now = Date.now();+ db().prepare("UPDATE relay_tasks SET state = 'running', worker_id = ?, device = ?, claimed_at = ?, started_at = ? WHERE generation_id = ?").run(w.id, `wkr-${w.id}`, now, now, id);+ db().prepare("UPDATE generation_runs SET started_at = ? WHERE id = ?").run(now, id);expect((await post({ ...IMAGE, ...SHOWN }, a.cookie)).status).toBe(201);});@@ -246,7 +261,8 @@ describe("runs waiting, runs an hour, runs from one address", () => {expect((await post({ ...IMAGE, ...SHOWN }, b.cookie, { "x-forwarded-for": "198.51.100.4" })).status).toBe(201);const kept = db().prepare("SELECT addr FROM pool_admissions WHERE addr IS NOT NULL").all() as { addr: string }[];expect(kept.length).toBeGreaterThan(0);- expect(kept.every((r) => /^[0-9a-f]{32}$/.test(r.addr) && !r.addr.includes("203"))).toBe(true);+ // A salted hash, never the address itself (a hash's hex digits may hold "203" by chance: the address never).+ expect(kept.every((r) => /^[0-9a-f]{32}$/.test(r.addr) && !r.addr.includes("203.0.113.9"))).toBe(true);});});@@ -344,3 +360,140 @@ describe("a run's price facts", () => {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);+ });+});