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: an account's own GPU keeps every run the install's GPUs wouldn't take, and one plan for the price and the run
Adarsh9d56aa2e1874
diff --git a/docs/billing-hook.md b/docs/billing-hook.mdindex 3e9adf4f..4e97b6d3 100644--- a/docs/billing-hook.md+++ b/docs/billing-hook.md@@ -87,7 +87,9 @@ reach two servers during a deploy) never pass a limit together. They apply with`prefer: "pool"` sends a run to this install's GPUs first even when the account's own GPU is online. A place therequest names always wins, so the account can still pick its own GPU. When the account's own GPU doesn't answer and therun named no place, Fuobe asks (409, `code: "own-gpu-offline"`, header `x-fuobe-place-ask`) instead of moving the run-to this install's GPUs.+to this install's GPUs, but only for a run this install's GPUs would take. Any other run goes to the account's own GPU,+as before. While the policy is cached, a run on an account's own GPU never waits for the service; when a policy call+gets no answer, the last answer (or none) stands for 5 seconds (60 for a guest) before the service is asked again.| Call | Request | Answer ||---|---|---|@@ -103,7 +105,8 @@ to this install's GPUs.`shown` is the price the person saw before pressing Run. A service must never charge more than it: when the price wouldbe higher, it refuses with `price-changed` and the new quote, and the person sees the new price before running again.-A reserve's `text` is shown on the result once it succeeded ("7 units"). `maxWaitMs` is how long the run may wait in+A reserve's `text` is shown on the result once it succeeded ("7 units"). A run that set an `amount` above 0 aside and+then failed or was stopped says "Not charged"; a run whose hold set nothing aside says nothing about a charge. `maxWaitMs` is how long the run may wait inline before a GPU first takes it; past it the row fails and is refunded. Once a GPU has taken it, the limit is over: arun that goes back in line (a GPU paused or restarted) keeps its place and waits there.@@ -113,6 +116,8 @@ if it had come that much earlier. Both are kept for every row of the run, and aOn the workers ([gpu-workers.md](gpu-workers.md)), `queue` counts the line the way the workers serve it: `ahead` isevery task the workers that may run this one would serve first, whatever its model, and `lane` is the workflow's lane.+`mine` counts the account's runs on this install's GPUs the way the limits do: one press of Run is one run, however+many jobs or chain steps it has (`waiting`: none of its rows has started).A report's `gpuMs` is the time the workers' ComfyUI spent running the row's jobs, as they measured it (no waits, nofiles, no upload). A job that ran more than once counts once, for the attempt whose result was kept. `device` is theGPU's name. Elsewhere `gpuMs` is the row's time from its start to its end, anddiff --git a/docs/gpu-workers.md b/docs/gpu-workers.mdindex 514f9bb2..1bbbde98 100644--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@ -35,9 +35,10 @@ You do not need a start flag or a guard file. In the studio, **Connect your GPU*gets a worker token (`fuobe_wkr_…`). The studio makes the token at that moment and keeps only its SHA-256 hash.The token acts only as that person's own computer. The ComfyUI gets that person's jobs, and nobody else's. The jobs-run with no Fuobe tab open. The owner's pairing never changes where the studio's ComfyUI jobs run: the paired-ComfyUI takes the owner's jobs once the owner chooses the computer in Settings → ComfyUI. Every change of that setting-is in the admin log (`settings.comfy_where`, with the value before and after). The person can disconnect the ComfyUI in Settings → Your GPU (`DELETE /api/gpu/paired/<id>`)+run with no Fuobe tab open. When the owner pairs a ComfyUI, the studio's ComfyUI jobs move to the owner's computer, as+before, unless they run on workers or hosted runs are on (`FUOBE_HOSTED_RUNS=1`). Then the pairing changes nothing of+where they run: the paired ComfyUI takes the owner's jobs once the owner chooses the computer in Settings → ComfyUI.+Every change of that setting is in the admin log (`settings.comfy_where`, with the value before and after). The person can disconnect the ComfyUI in Settings → Your GPU (`DELETE /api/gpu/paired/<id>`)or press Disconnect in ComfyUI (`POST /api/gpu/computer/unpair`). A disconnected token gets 401 at its next call.## Workers (the owner's shared GPUs)@@ -204,11 +205,13 @@ gets 403 everywhere else. It is never the owner, and an owner API token can nevetoken on every call, so a revoked token stops at once.**A token's lifetime.** With `FUOBE_WORKER_TOKEN_DAYS` set (unset or 0: a token never expires, as before), a pool-worker's token lasts that many days. Once half of it is gone, the beat answer of a worker that speaks protocol 2 gives-it the next token (`worker.token: { value, expiresAt }`). The worker saves it and uses it from its next call on. The old+worker's token lasts that many days. A worker added before the lifetime was set gets it from its first call after. Once+half of it is gone, the beat answer of a worker that says it saves tokens (`canRotateToken: true` in its beat) gives it+the next token (`worker.token: { value, expiresAt }`). The worker saves it and uses it from its next call on. The oldtoken stops at the new one's first use. A next token that is never used is given again, as a new one, after 10-minutes. A paired ComfyUI's token keeps no lifetime. Set the lifetime only once every worker speaks protocol 2: an-older worker's token would simply expire.+minutes. A paired ComfyUI's token keeps no lifetime. Set the lifetime only once every pool worker sends+`canRotateToken: true`: the token of a worker that doesn't expires at the end of its lifetime, and the worker stops+until you rotate its token in Settings → Workers.**Where a token is used from.** For a pool worker, the studio remembers the countries (Cloudflare's `cf-ipcountry`)and the networks (an IPv4 address's /24 or an IPv6 address's /64, read only with `FUOBE_TRUST_PROXY=1`) its token was@@ -216,8 +219,8 @@ used from, as short hashes, never as addresses. A call from a new country or a nwithin 10 minutes of each other, each write an alert to the admin log (`worker.alert`, actor `system`, the worker asits target), at most once an hour each.-- `POST /api/gpu/computer/beat`: the browser's beat plus `{ protocol, version, local: { paused, why, until }, gpu: {- otherApps, tempC }, inventoryHash, warmLane }`. The answer adds `worker: { paused, pauseNow, drain, autoResume,+- `POST /api/gpu/computer/beat`: the browser's beat plus `{ protocol, version, canRotateToken?, local: { paused, why,+ until }, gpu: { otherApps, tempC }, inventoryHash, warmLane }`. The answer adds `worker: { paused, pauseNow, drain, autoResume,insideHours, nextChangeAt, lanes, minProtocol, sendInventory, token? }` (`token`: the next token, above) and`claimableNow`: how many people's jobs (anaccount's, never the owner's) this worker may claim right now by its lanes, files, VRAM and hours, its own pause aside.diff --git a/docs/public-signup.md b/docs/public-signup.mdindex ec91d109..6e66ecc4 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -363,7 +363,9 @@ With it on:- An account whose own GPU is online runs there by default, unless the billing service's policy puts the studio'sGPUs first (`prefer: "pool"`). The composer shows where a run goes ("Your GPU" or "This studio's GPUs"), and theperson can pick either. When the account's own GPU doesn't answer and the run named no place, the run is not moved- to the studio's GPUs: the page asks first, and runs it there if the person says so.+ to the studio's GPUs: the page asks first, and runs it there if the person says so. A run the studio's GPUs wouldn't+ take (a model or a kind not offered there, extra LoRAs, a file kind they don't take, Image to 3D, the billing service+ not answering) goes to the account's own GPU as before, and waits for it there.- A guest is told what the billing service's policy for guests says (without one, what any account gets).- Every other tool still needs the account's own GPU ("This tool doesn't run on your own GPU yet" stays as it is).Image to 3D and extra LoRAs added to a request stay on the account's own GPU. So do clips and sound as inputs,diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.tsindex 43525a4f..c841a6b0 100644--- a/src/app/api/generations/route.ts+++ b/src/app/api/generations/route.ts@@ -168,7 +168,7 @@ export async function POST(request: Request) {decision = await decidePlace(account, req, wish);if (decision.kind === "refuse") return refusedBy(decision.refusal);}- let onPool = decision.kind === "pool" ? decision : null;+ const onPool = decision.kind === "pool" ? decision : null;// The client's address, kept only as a salted hash for the policy's hourly count per address (null: no trusted proxy).const addr = account && onPool ? clientAddress(request) : null;if (account && onPool) {@@ -179,13 +179,10 @@ export async function POST(request: Request) {unhit(`run:${account.id}`);return refuse(over.status, over.error, { code: over.code }, { "Retry-After": String(over.retryAfterS) });}- const lim = onPool.policy.limits;- if (lim.outputsPerRun > 0 && (req.params?.numOutputs ?? 1) > lim.outputsPerRun) {- req = { ...req, params: { ...req.params, numOutputs: lim.outputsPerRun } };+ // The request as it runs there (no more outputs than the policy's cap per run): planned and priced as it is.+ if (onPool.capped) {+ req = { ...req, params: onPool.req.params };notes.push(ACCOUNT_MESSAGES.outputsCapped);- // Priced and set aside for what runs.- const capped = req;- onPool = { ...onPool, planned: runOnPool(account.id, () => previewGeneration(capped)) };}}// GPU pre-flight: a ComfyUI run that is sure to fail for something missing stops here with the plan that fixes itdiff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsxindex de6c4e78..bc576ce8 100644--- a/src/components/studio/composer.tsx+++ b/src/components/studio/composer.tsx@@ -20,6 +20,7 @@ import { 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 { composerPlace } from "@/lib/run-place";import { ExactOrbitControls } from "@/components/exact-orbit-controls";import { useFlyAround } from "@/components/fly-around-run";import { exactDefaults, takesExact, type ExactOrbit } from "@/lib/exact-orbit";@@ -594,7 +595,8 @@ export function Composer({ docked }: { docked: boolean }) {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);@@ -761,7 +763,7 @@ export function Composer({ docked }: { docked: boolean }) {model?.kind,);// Hosted runs: where it should go, and the price shown (the server checks both; a higher price comes back to confirm).- const hosted = viewerInfo?.hosted ? { place: runOn, ...(poolPrice && hostedQuote && { shown: { amount: hostedQuote.amount, priceVersion: hostedQuote.priceVersion } }) } : {};+ const hosted = viewerInfo?.hosted ? { ...(runPlace && { place: runPlace }), ...(poolPrice && hostedQuote && { shown: { amount: hostedQuote.amount, priceVersion: hostedQuote.priceVersion } }) } : {};const withVoiceFirst = cleanFirst ? { ...sent.request, params: { ...sent.request.params, extra: { ...sent.request.params?.extra, [VOICE_FIRST_PARAM]: true } } } : sent.request;const body = { ...withVoiceFirst, ...hosted, ...(skipGpu && { gpuCheck: "skip" }) } as typeof sent.request;create.mutate(body, {diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.tsindex 477198f3..7aac0285 100644--- a/src/lib/catalog/types.ts+++ b/src/lib/catalog/types.ts@@ -1116,6 +1116,8 @@ export interface GenerationRequest {place?: "pool";hold?: string;charge?: string;+ /** Server-only: the hold set an amount aside (a run that ends early then says it wasn't charged). */+ charged?: boolean;checkOutputs?: boolean;/** How long a run on this install's GPUs may wait in line (ms), when the billing service set it. */waitMs?: number;@@ -1390,9 +1392,9 @@ export interface Generation {place?: "pool";/** The billing service's words for what a run on this install's GPUs costs ("7 units"); shown when it succeeded. */charge?: string;- /** A run with a billing hold that failed or was stopped: nothing was charged. */+ /** A run whose billing hold set an amount aside, and that failed or was stopped: nothing was charged. */notCharged?: true;- /** "checking": its outputs wait for the moderation service before they show. */+ /** "checking": its outputs wait for the moderation service before they show (on this install's GPUs: "Working"). */stage?: "checking";/** A run waiting for this install's GPUs: its place in line and the wait, about (GET /api/generations/<id>). */queue?: { place: number; etaSeconds: number | null };diff --git a/src/lib/relay.ts b/src/lib/relay.tsindex 8edd5961..b7130dab 100644--- a/src/lib/relay.ts+++ b/src/lib/relay.ts@@ -186,6 +186,8 @@ export interface WorkerBeat {device: string;protocol: number;version: string;+ /** It saves the next token a beat answer gives it (`worker.token`) and uses it from its next call on. */+ canRotateToken?: boolean;ready: boolean;why: string | null;/** Its own pause switch: by hand ("here", "here-until:<ms>"), by itself ("gpu-busy:<process>", "comfy-crashes", "port-busy"). */diff --git a/src/lib/run-place.ts b/src/lib/run-place.tsindex 0445eac5..bfc1a737 100644--- a/src/lib/run-place.ts+++ b/src/lib/run-place.ts@@ -171,6 +171,18 @@ export function mainModel(steps: readonly { modelName: string; costUsd: number |return best?.modelName;}+/**+ * Where a studio composer's run goes, with hosted runs on: the person's pick, else its own GPU while that is online+ * (unless the studio puts its own GPUs first), else this studio's GPUs. `place` is what the run names beside the request:+ * none when the default is this studio's GPUs only because the studio puts them first, so the server decides, and a+ * model this studio's GPUs don't take still runs on the account's own GPU.+ */+export function composerPlace(pick: "own" | "pool" | null, ownOnline: boolean, preferPool: boolean): { runOn: "own" | "pool"; place: "own" | "pool" | undefined } {+ if (pick) return { runOn: pick, place: pick };+ if (!ownOnline) return { runOn: "pool", place: "pool" };+ return preferPool ? { runOn: "pool", place: undefined } : { runOn: "own", place: "own" };+}+/** Drawn in this browser (a Kinetic template, Click to Ad's end card): the same place and price whoever looks. */export const IN_BROWSER: RunPlace = runPlace({ audience: "guest", engine: "browser", format: String });diff --git a/src/server/billing.ts b/src/server/billing.tsindex aa2a1412..7654ff3c 100644--- a/src/server/billing.ts+++ b/src/server/billing.ts@@ -187,7 +187,7 @@ function target(): HookTarget | null {declare global {var __fuobeBillingBadUrl: boolean | undefined;- var __fuobeBillingPolicies: Map<string, { at: number; ttlMs: number; policy: Policy }> | undefined;+ var __fuobeBillingPolicies: Map<string, { at: number; ttlMs: number; policy: Policy | null }> | undefined;var __fuobeBillingBalances: Map<string, { at: number; balance: Balance }> | undefined;}@@ -219,9 +219,16 @@ export const OPEN_POLICY: Policy = {ttlS: 60,};+/**+ * After a policy call that got no answer, how long the last answer (or none) stands before the service is asked again+ * (ms). A guest's status is read on every page, so a guest's policy waits longer.+ */+export const POLICY_RETRY_MS = { account: 5_000, guest: 60_000 };+/*** The account's policy (cached for its `ttlS`), or a guest's (`accountId` null: GET /v1/policy with no account). No- * service: OPEN_POLICY. The service down: null (the caller treats runs on this install's GPUs as paused).+ * service: OPEN_POLICY. The service down: the last answer, else null (the caller treats runs on this install's GPUs as+ * paused). That stands for POLICY_RETRY_MS, so a service that doesn't answer isn't waited for on every call.*/export async function policy(accountId: string | null): Promise<Policy | null> {if (!billingConfigured()) return OPEN_POLICY;@@ -229,18 +236,33 @@ export async function policy(accountId: string | null): Promise<Policy | null> {const key = accountId ?? "";const hit = cache.get(key);if (hit && Date.now() - hit.at < hit.ttlMs) return hit.policy;+ const keep = (entry: { at: number; ttlMs: number; policy: Policy | null }) => {+ cache.set(key, entry);+ if (cache.size > 5000) cache.delete(cache.keys().next().value!);+ };try {const p = await call<Policy>("GET", accountId ? `/v1/policy?account=${encodeURIComponent(accountId)}` : "/v1/policy", undefined, BILLING_TIMEOUTS.policy);const ttlMs = Math.max(0, Math.min(3600, Number(p.ttlS) || 0)) * 1000;- cache.set(key, { at: Date.now(), ttlMs, policy: p });- if (cache.size > 5000) cache.delete(cache.keys().next().value!);+ keep({ at: Date.now(), ttlMs, policy: p });return p;} catch (e) {logDown("policy", e);- return hit?.policy ?? null;+ const last = hit?.policy ?? null;+ keep({ at: Date.now(), ttlMs: accountId ? POLICY_RETRY_MS.account : POLICY_RETRY_MS.guest, policy: last });+ return last;}}+/**+ * The policy as last read, with no call to the service: undefined when none is kept (or it is too old). No service:+ * OPEN_POLICY.+ */+export function cachedPolicy(accountId: string | null): Policy | null | undefined {+ if (!billingConfigured()) return OPEN_POLICY;+ const hit = globalThis.__fuobeBillingPolicies?.get(accountId ?? "");+ return hit && Date.now() - hit.at < hit.ttlMs ? hit.policy : undefined;+}+/** A free run's quote (no service set): Run keeps its own words. */export const FREE_QUOTE: Quote = { allowed: true, amount: 0, priceVersion: "", text: "" };diff --git a/src/server/computer/pairing-http.ts b/src/server/computer/pairing-http.tsindex de73a452..2660acf1 100644--- a/src/server/computer/pairing-http.ts+++ b/src/server/computer/pairing-http.ts@@ -2,6 +2,8 @@ import "server-only";import { clearAccountLoras } from "../account-loras";import { accountGpu, requestViewer, setAccountGpu } from "../auth";import { dropSnapshots } from "../gpu/snapshots";+import { hostedRunsOn } from "../hosted-switch";+import { getSetting, setSetting } from "../settings";import type { Principal } from "./tasks";const no = (status: number, error: string) => Response.json({ error }, { status, headers: { "Cache-Control": "no-store" } });@@ -20,11 +22,17 @@ export function pairingPrincipal(request: Request): Principal | Response {/*** A paired ComfyUI runs the person's jobs as their own computer does: an account's GPU becomes "this computer" (as when- * its browser connects). The owner's pairing changes nothing of where the studio's ComfyUI jobs run: that stays the- * owner's choice in Settings (a pairing link anyone can start must never move the studio's jobs).+ * its browser connects), and the owner's ComfyUI runs on the owner's computer, as before (the change is in the admin+ * log). While the studio's jobs run on its workers, or accounts may run on this install's GPUs, the owner's pairing+ * changes nothing of where they run: that stays the owner's choice in Settings (a pairing link anyone can start must+ * never stop the workers' jobs).*/export function runOnComputer(principal: Principal): void {- if (principal === "owner") return;+ if (principal === "owner") {+ const where = getSetting("comfyWhere");+ if (where !== "computer" && where !== "workers" && !hostedRunsOn()) setSetting("comfyWhere", "computer");+ return;+ }const id = principal.slice(5);if (accountGpu(id)?.mode !== "computer") {setAccountGpu(id, { mode: "computer" });diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.tsindex 69fcedc5..03e01de9 100644--- a/src/server/computer/pool.ts+++ b/src/server/computer/pool.ts@@ -123,6 +123,7 @@ export function cleanBeat(b: unknown): WorkerBeat {device: String(o.device ?? ""),protocol: num(o.protocol) ?? 0,version: text(o.version, 40) ?? "",+ ...(o.canRotateToken === true && { canRotateToken: true }),ready: o.ready !== false,why: text(o.why, 64),local: { paused: local.paused !== false, why: text(local.why, 96), until: num(local.until) },@@ -179,8 +180,9 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatA}const state = workerState(fresh, now);d.prepare("UPDATE relay_workers SET state = ? WHERE id = ?").run(state.state, w.id);- // A worker that can save a new token (protocol 2) gets its next one when half its token's life is gone.- const nextToken = b.protocol >= 2 ? offerNextToken(fresh, now) : null;+ // A worker that says it saves a new token (`canRotateToken` in its beat) gets its next one when half its token's life+ // is gone. (Not by its protocol number: a worker may speak a newer protocol without saving tokens.)+ const nextToken = b.canRotateToken ? offerNextToken(fresh, now) : null;const h = hoursAt(hoursOf(fresh), now);// Pool names are validated at creation (/^[a-z0-9-]{1,32}$/), so they never contain commas. INSTR on the// CSV avoids the LIKE-wildcard class of risk (%, _) entirely.@@ -596,8 +598,8 @@ export function poolFacts(lane: string | null): ComputerFacts {/*** The line for a new run of this workflow, for a quote or a reserve (the billing service's QueueFacts): how many tasks the- * workers that may run it would serve before it, about how long until it would be done, how many such workers can take- * work now, and the account's own tasks waiting and running.+ * workers that may run it would serve before it, about how long until it would be done, and how many such workers can+ * take work now. (The account's own runs, QueueFacts.mine, are counted by run in hosted.ts.)*/export function lineFacts(accountId: string | null, asked: string | null, now = Date.now()) {// A workflow that picks its graph at run time (`…-{n}`) has no lane yet: the whole line counts.@@ -608,12 +610,7 @@ export function lineFacts(accountId: string | null, asked: string | null, now =const probe = { id: "", principal: accountId ? `acct:${accountId}` : "guest", account: accountId ?? "guest", class: "free", pools: "pool", lane, needs_json: needs ? JSON.stringify(needs) : null, rank_at: now, created_at: now, stop: 0, only_worker: null, est_ms: null } as unknown as TaskRow;const p = lane ? placeInLine(probe, now) : { place: (db().prepare("SELECT COUNT(*) AS n FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting'").get() as { n: number }).n + 1, etaSeconds: null };const online = poolWorkers().filter((w) => eligible(w, now) && (!lane || fits({ ...probe, created_at: 0 }, w, now))).length;- const mine = accountId- ? (db()- .prepare("SELECT SUM(CASE WHEN state = 'waiting' THEN 1 ELSE 0 END) AS waiting, SUM(CASE WHEN state = 'waiting' THEN 0 ELSE 1 END) AS running FROM relay_tasks WHERE pools IS NOT NULL AND account = ? AND state IN ('waiting','sending','queued','running','collecting')")- .get(accountId) as { waiting: number | null; running: number | null })- : { waiting: 0, running: 0 };- return { lane: lane ?? "small", ahead: p.place - 1, etaS: p.etaSeconds, workersOnline: online, nextOpenAt: null, mine: { waiting: mine.waiting ?? 0, running: mine.running ?? 0 } };+ return { lane: lane ?? "small", ahead: p.place - 1, etaS: p.etaSeconds, workersOnline: online, nextOpenAt: null };}/**diff --git a/src/server/computer/workers.ts b/src/server/computer/workers.tsindex 7b86c08b..9f606c75 100644--- a/src/server/computer/workers.ts+++ b/src/server/computer/workers.ts@@ -83,8 +83,8 @@ const touched = new Map<string, number>();/*** How long a pool worker's token lasts (FUOBE_WORKER_TOKEN_DAYS; unset or 0: it never expires, as before). With a- * lifetime, the beat answer gives a worker that speaks protocol 2 its next token once half of it is gone, and the old- * token stops the moment the new one is first used.+ * lifetime, the beat answer gives a worker that says it saves tokens (`canRotateToken`) its next token once half of it+ * is gone, and the old token stops the moment the new one is first used.*/export function poolTokenMs(): number {const days = Number(process.env.FUOBE_WORKER_TOKEN_DAYS);@@ -106,7 +106,8 @@ export interface CallSource {/*** The worker behind an Authorization header, read now: null when the token is unknown, revoked or expired. A pool- * worker's next token (offered in a beat answer) works too, and its first use makes it the token: the old one stops.+ * worker's next token (offered in a beat answer) works too, and its first use makes it the token: the old one stops. A+ * pool worker's token with no expiry gets the lifetime (FUOBE_WORKER_TOKEN_DAYS, when set) from this call on.* Records when it was last used (at most every 30 s) and Cloudflare's country header. For a pool worker, a call from a* country or a network its token never came from before, or from a second network within minutes of another, writes an* alert to the admin log.@@ -119,6 +120,13 @@ export function workerFromAuth(header: string | null | undefined, from: CallSourlet row = db().prepare("SELECT * FROM relay_workers WHERE token_hash = ?").get(hash) as WorkerRow | undefined;if (!row) row = promoteNextToken(hash, now);if (!row || row.revoked_at || (row.expires_at && row.expires_at <= now)) return null;+ // A pool worker added before tokens had a lifetime gets one now, from its first call after: no token is left that+ // never expires and never changes.+ const life = row.kind === "pool" && !row.expires_at ? poolTokenMs() : 0;+ if (life) {+ db().prepare("UPDATE relay_workers SET expires_at = ? WHERE id = ? AND kind = 'pool' AND expires_at IS NULL").run(now + life, row.id);+ row = db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(row.id) as WorkerRow;+ }const country = source.country && /^[A-Z]{2}$/.test(source.country) ? source.country : null;if (row.kind === "pool") noteSource(row, country, source.network ?? null, now);if (now - (touched.get(row.id) ?? 0) > 30_000) {diff --git a/src/server/generations.ts b/src/server/generations.tsindex 8e6e9384..d0c27591 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -211,8 +211,10 @@ 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 }),- ...(checking && { stage: "checking" as const }),+ // (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 }),+ // 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 --git a/src/server/hosted-run.ts b/src/server/hosted-run.tsindex 5f519f04..05d3d4b5 100644--- a/src/server/hosted-run.ts+++ b/src/server/hosted-run.ts@@ -10,6 +10,7 @@ import {BILLING_HEADER,BILLING_PAUSED,billingConfigured,+ cachedPolicy,forgetBalance,policy as billingPolicy,quote as billingQuote,@@ -26,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 } from "./hosted";+import { 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";@@ -70,8 +71,17 @@ const billingRefusal = (code: RefuseCode | "price-changed", text: string, extra:type Planned = ReturnType<typeof previewGeneration>;-/** The decision for an account's run: its own GPU or key as today, this install's GPUs, or a refusal. */-export type PlaceDecision = { kind: "own" } | { kind: "pool"; planned: Planned; policy: Policy; steps: RunFacts["steps"] } | { kind: "refuse"; refusal: Refusal };+/**+ * The decision for an account's run: its own GPU or key as today, this install's GPUs, or a refusal. On this install's+ * GPUs: the request as it runs there (`req`, `capped` when the policy cut its outputs), its plan, its policy and the steps+ * it is priced for.+ */+export type PlaceDecision =+ | { kind: "own" }+ | { kind: "pool"; planned: Planned; policy: Policy; steps: RunFacts["steps"]; req: GenerationRequest; capped: boolean }+ | { kind: "refuse"; refusal: Refusal };++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.";@@ -100,11 +110,7 @@ function freeStep(s: PlannedStep): boolean {if (!endpoint) return false;// A workflow that picks its graph at run time (`video-concat-{n}`): light when every graph it may pick is.const index = loadIndex();- const [head, tail = ""] = endpoint.split("{n}");- const picks = endpoint.includes("{n}")- ? Object.keys(index.workflows).filter((id) => id.length > head.length + tail.length && id.startsWith(head) && id.endsWith(tail) && /^\d+$/.test(id.slice(head.length, id.length - tail.length)))- : [endpoint];- const needs = picks.map((id) => needsOf(index, id));+ const needs = (endpoint.includes("{") ? workflowPicks(endpoint) : [endpoint]).map((id) => needsOf(index, id));return needs.length > 0 && needs.every((x) => !!x && x.files.length === 0 && x.minVramBytes === 0);}@@ -123,10 +129,15 @@ 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.*/export function stepsProblem(p: Policy, steps: PlannedStep[]): string | null {for (const s of steps) {- if (freeStep(s)) continue;+ if (freeStep(s)) {+ if (s.provider === "comfyui" && !poolTakes(stepEndpoint(s))) return HOSTED_WORDS.notOffered;+ continue;+ }if (s.provider !== "comfyui" || s.kind === "model3d") return HOSTED_WORDS.notOffered;if (!poolAllows(p, s.modelId, s.presetId) || !kindAllowed(p, s.kind as RunFacts["kind"])) return HOSTED_WORDS.notOffered;if (!poolTakes(stepEndpoint(s))) return HOSTED_WORDS.notOffered;@@ -162,45 +173,81 @@ async function ownGpuOnline(accountId: string): Promise<boolean> {}}+/**+ * 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 { 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 (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 (!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 (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 (req.loras?.length) return notHere(HOSTED_WORDS.loras);- const inputs = inputCounts(req);- const takes = (kind: "image" | "video" | "audio") => p.uploads[kind] && poolTakesFiles(kind);+ 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);+ // 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);- return { kind: "pool", planned, policy: p, steps: steps ? pricedSteps(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 };}/** The input files of a request, for the moderation service: their kind and sha256 (pictures' previews: not sent yet). */@@ -298,6 +345,8 @@ export async function reservePool(...base,hold: a.holdId,...(a.text && { charge: a.text }),+ // Something was set aside (a free run's hold sets aside nothing): only then can a run that ends early say so.+ ...(Number(a.amount) > 0 && { charged: true }),...(a.maxWaitMs > 0 && { waitMs: a.maxWaitMs }),...(a.class === "paid" && { class: "paid" as const }),...(Number.isFinite(boost) && boost > 0 && { boostMs: Math.min(boost, 24 * 60 * 60_000) }),@@ -313,9 +362,8 @@ export async function poolQuote(account: Account | null, asked: GenerationRequesif (!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;- // 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 --git a/src/server/hosted.ts b/src/server/hosted.tsindex 9307993e..0d9859a0 100644--- a/src/server/hosted.ts+++ b/src/server/hosted.ts@@ -5,7 +5,9 @@ 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";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 { getSetting, withCandidates } from "./settings";import { runAsTenant } from "./tenant";@@ -53,17 +55,30 @@ export function poolReady(): boolean {return where === "workers" ? workersAllowed(null) : installComfyLocal();}+/**+ * The workflows a route's endpoint may run: itself, or for one that picks its graph at run time (`video-concat-{n}`)+ * every graph it may pick (one per count).+ */+export function workflowPicks(endpoint: string): string[] {+ const ids = Object.keys(loadIndex().workflows);+ if (!endpoint.includes("{")) return ids.includes(endpoint) ? [endpoint] : [];+ const re = new RegExp(`^${endpoint.replace(/[.*+?^$()|[\]\\]/g, "\\$&").replace(/\{[^}]+\}/g, "\\d+")}$`);+ return ids.filter((id) => re.test(id));+}+/*** May this install's GPUs run this workflow (planned.route.endpoint)? On the workers: one is allowed its lane (a- * workflow that picks its graph at run time, `…-{n}`, goes to any). On its own server: the isolated ComfyUI's- * workflows too only when that one is on this machine.+ * workflow that picks its graph at run time, `…-{n}`: the lane of every graph it may pick). On its own server: the+ * isolated ComfyUI's workflows too only when that one is on this machine.*/export function poolTakes(endpoint: string | undefined): boolean {if (!endpoint) return false;const isolated = workerFor(endpoint) === "isolated";if (!poolOnWorkers()) return installComfyLocal(isolated ? "isolated" : "main");if (isolated) return false;- return workersAllowed(endpoint.includes("{") ? null : poolLane(endpoint));+ if (!endpoint.includes("{")) return workersAllowed(poolLane(endpoint));+ const picks = workflowPicks(endpoint);+ return picks.length > 0 && picks.every((id) => workersAllowed(poolLane(id)));}/** May a run on this install's GPUs send them this kind of file (the workers take only the kinds the install allows)? */@@ -138,30 +153,32 @@ function typicalRunMs(): number | null {/** Rows not started yet (no provider start): they wait in line. */const WAITING = "NOT EXISTS (SELECT 1 FROM generation_runs r WHERE r.id = g.id AND r.started_at IS NOT NULL)";+/**+ * The account's runs on this install's GPUs (QueueFacts.mine), counted as the policy's limits count them: a run is one+ * press of Run, however many jobs or chain steps it has.+ */+function myRuns(accountId: string | null): QueueFacts["mine"] {+ if (!accountId) return { waiting: 0, running: 0 };+ const c = poolRunCounts(accountId);+ return { waiting: c.waiting, running: c.active - c.waiting };+}+/*** The line on this install's GPUs right now, for a quote or a reserve (QueueFacts). On the workers: their own line, as a* new run of this workflow would stand in it (every task ahead of it, whatever its lane). On its own server: its rows.*/export function queueFacts(accountId: string | null, workflowId?: string | null): QueueFacts {- if (poolOnWorkers()) return lineFacts(accountId, workflowId ?? null);+ if (poolOnWorkers()) return { ...lineFacts(accountId, workflowId ?? null), mine: myRuns(accountId) };const d = db();const ahead = (d.prepare(`SELECT COUNT(*) AS n FROM generations g WHERE ${POOL_ROWS} AND ${WAITING}`).get() as { n: number }).n;const typical = typicalRunMs();- const mine = accountId- ? (d- .prepare(- `SELECT SUM(CASE WHEN ${WAITING} THEN 1 ELSE 0 END) AS waiting, SUM(CASE WHEN ${WAITING} THEN 0 ELSE 1 END) AS running- FROM generations g WHERE ${POOL_ROWS} AND json_extract(g.request_json, '$.account') = ?`,- )- .get(accountId) as { waiting: number | null; running: number | null })- : { waiting: 0, running: 0 };return {lane: POOL_LANE,ahead,etaS: typical === null ? null : Math.round(((ahead + 1) * typical) / 1000),workersOnline: poolReady() ? 1 : 0,nextOpenAt: null,- mine: { waiting: mine.waiting ?? 0, running: mine.running ?? 0 },+ mine: myRuns(accountId),};}diff --git a/src/server/run-stamp.ts b/src/server/run-stamp.tsindex e5b18da2..dd538675 100644--- a/src/server/run-stamp.ts+++ b/src/server/run-stamp.ts@@ -10,6 +10,8 @@ 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).* - `charge`: the words the billing service gave for the charge ("7 units"), shown on the result.+ * - `charged`: the hold set an amount aside (a free run's sets aside nothing), so a run that ends early says it wasn't+ * charged.* - `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.*/@@ -17,6 +19,7 @@ export interface RunStamp {place?: "pool";hold?: string;charge?: string;+ charged?: boolean;checkOutputs?: boolean;/** How long it may wait in line on this install's GPUs (ms), from the billing service. */waitMs?: number;@@ -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", "charge", "charged", "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 {@@ -52,6 +55,7 @@ export function stamped(req: GenerationRequest): GenerationRequest {...(s.place && { place: s.place }),...(s.hold && { hold: s.hold }),...(s.charge && { charge: s.charge }),+ ...(s.charged && { charged: true }),...(s.checkOutputs && { checkOutputs: true }),...(s.waitMs && s.waitMs > 0 && { waitMs: s.waitMs }),...(s.class === "paid" && { class: "paid" as const }),@@ -65,6 +69,7 @@ export function stampOf(req: Pick<GenerationRequest, (typeof STAMP_FIELDS)[numbe...(req.place === "pool" && { place: "pool" as const }),...(req.hold && { hold: req.hold }),...(req.charge && { charge: req.charge }),+ ...(req.charged && { charged: true }),...(req.checkOutputs && { checkOutputs: true }),...(req.waitMs && { waitMs: req.waitMs }),...(req.class === "paid" && { class: "paid" as const }),diff --git a/tests/moderation-hook.test.ts b/tests/moderation-hook.test.tsindex 5ac90db3..9a96f496 100644--- a/tests/moderation-hook.test.ts+++ b/tests/moderation-hook.test.ts@@ -36,6 +36,7 @@ const checks = await import("@/server/output-checks");const { getGeneration } = await import("@/server/generations");const { fileAccount, fileHeld } = await import("@/server/account-library");const { listReports } = await import("@/server/moderation");+const { POOL_WORDS } = await import("@/lib/relay");let mod: FakeModeration;let bill: FakeBilling;@@ -141,7 +142,10 @@ describe("the output check", () => {const id = await started();await until(() => row(id).stage === "checking");const g = getGeneration(id)!;- expect(g.stage).toBe("checking");+ // A run on this install's GPUs: the check is part of "Working", with no word of its own.+ expect(g.place).toBe("pool");+ expect(g.stage).toBeUndefined();+ expect(g.message).toBe(POOL_WORDS.working);expect(g.outputs).toEqual([]);const held = (JSON.parse(row(id).outputs_json) as { url: string }[])[0].url.replace(/^\/api\/files\//, "");expect(fileHeld(held)).toBe(true);diff --git a/tests/pool-account-runs.test.ts b/tests/pool-account-runs.test.tsindex a14ed369..81301e72 100644--- a/tests/pool-account-runs.test.ts+++ b/tests/pool-account-runs.test.ts@@ -317,10 +317,34 @@ describe("an account's run on the workers", () => {it("a file input in params.extra is one the run sent, never a name in the workers' folders", async () => {standInWorker();- const r = await run({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse", params: { extra: { image: "fuobe_someone_elses.png" } } });+ const uploadsRoute = await import("@/app/api/uploads/route");+ const { TINY_PNG } = await import("./helpers/fake-comfy-runner");+ const up = await uploadsRoute.POST(+ new Request(`http://${HOST}/api/uploads`, { method: "POST", headers: { ...SITE_HEADERS, cookie, "content-type": "image/png", "x-file-name": "me.png", "content-length": String(TINY_PNG.length) }, body: new Uint8Array(TINY_PNG) }),+ );+ expect(up.status).toBe(201);+ const { url } = (await up.json()) as { url: string };+ // A workflow that loads a picture: the name in params.extra would replace the picture the run sent.+ const r = await run({ feature: "image", modelId: "oss-rmbg", op: "bg-remove", inputs: { images: [url] }, params: { extra: { image: "fuobe_someone_elses.png" } } });expect(r.status, JSON.stringify(r.body)).toBe(201);const t = await until(() => taskOf(r.body.items![0].id));- expect(t?.graph_json ?? "").not.toContain("fuobe_someone_elses.png");+ expect(t).toBeDefined();+ expect(t!.graph_json ?? "").not.toContain("fuobe_someone_elses.png");+ // The picture its graph loads is the one this run sent, kept for its task.+ const graph = JSON.parse(t!.graph_json ?? "{}") as Record<string, { class_type: string; inputs: Record<string, unknown> }>;+ const loaded = Object.values(graph)+ .filter((x) => x.class_type === "LoadImage")+ .map((x) => String(x.inputs.image));+ expect(loaded).toHaveLength(1);+ const staged = db().prepare("SELECT principal, task_id FROM relay_inputs WHERE name = ?").get(loaded[0]) as { principal: string; task_id: string | null } | undefined;+ expect(staged).toEqual({ principal: `acct:${accountId}`, task_id: t!.id });+ });++ it("a graph that names a file the run didn't send is refused before it is queued", async () => {+ const { graphProblem } = await import("@/lib/local-comfy");+ const graph = { "1": { class_type: "LoadImage", inputs: { image: "fuobe_someone_elses.png" } }, "2": { class_type: "SaveImage", inputs: { images: ["1", 0], filename_prefix: "x" } } };+ expect(graphProblem(graph as never, ["fuobe_mine.png"])).toBeTruthy();+ expect(graphProblem({ ...graph, "1": { class_type: "LoadImage", inputs: { image: "fuobe_mine.png" } } } as never, ["fuobe_mine.png"])).toBeNull();});});@@ -395,6 +419,27 @@ describe("what an account reads about its run", () => {expect(getGeneration(id)!.error).toBe("Your files have reached 3 GB. Delete some runs to make room.");});+ it("its output check is part of Working, and a stopped run says Not charged only when its hold set something aside", () => {+ const now = Date.now();+ const insert = (id: string, status: string, request: Record<string, unknown>, stage: string | null = null) =>+ db()+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, stage, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'm', 'open', 'comfyui', 't2i', 'image', ?, ?, ?, '[]', ?, ?)")+ .run(id, status, stage, JSON.stringify({ account: accountId, ...request }), now, now);+ insert(`check-pool-${now}`, "running", { place: "pool" }, "checking");+ insert(`check-own-${now}`, "running", {}, "checking");+ const pooled = getGeneration(`check-pool-${now}`)!;+ expect(pooled.stage).toBeUndefined();+ expect(pooled.message).toBe(POOL_WORDS.working);+ // On the account's own GPU, as before.+ expect(getGeneration(`check-own-${now}`)!.stage).toBe("checking");+ insert(`charged-${now}`, "canceled", { place: "pool", hold: "h_1", charged: true });+ insert(`free-${now}`, "failed", { place: "pool", hold: "h_2" });+ expect(getGeneration(`charged-${now}`)!.notCharged).toBe(true);+ expect(getGeneration(`free-${now}`)!.notCharged).toBeUndefined();+ // Neither field ever reaches the page's copy of the request.+ expect("charged" in getGeneration(`charged-${now}`)!.request).toBe(false);+ });+it("while it goes, only In line or Working, whatever the technical words were", () => {const now = Date.now();const id = `words-${now}`;diff --git a/tests/pool-limits.test.ts b/tests/pool-limits.test.tsindex 8e817532..881f5fdd 100644--- a/tests/pool-limits.test.ts+++ b/tests/pool-limits.test.ts@@ -49,6 +49,9 @@ 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 hosted = await import("@/server/hosted");+const { getGeneration } = await import("@/server/generations");+const { ACCOUNT_MESSAGES } = await import("@/server/account-files");const HOST = "localhost:3000";const SITE_HEADERS = { host: HOST, "sec-fetch-site": "same-origin", origin: `http://${HOST}` };@@ -57,6 +60,8 @@ const IMAGE = { feature: "image", modelId: "oss-z-image-turbo", prompt: "a lightlet fake: FakeBilling;let n = 0;+/** The stand-in worker of the test that runs. */+let worker: { id: string };/** A new account and its cookie (each test gets its own, so counts never carry over). */function account(o: { gpu?: "online" | "offline" } = {}) {@@ -126,9 +131,35 @@ beforeEach(() => {setSetting("engineMode", "open");setSetting("demoMode", "off");db().prepare("DELETE FROM relay_workers").run();- standInWorker();+ // Nothing of an earlier test waits in line.+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();+ worker = standInWorker();});+const tick = () => globalThis.__fuobeRunner?.tick();+async function until<T>(fn: () => T | Promise<T>, tries = 200, everyMs = 25): Promise<T> {+ let v = await fn();+ for (let i = 0; i < tries && !v; i++) {+ await tick();+ await new Promise((r) => setTimeout(r, everyMs));+ v = await fn();+ }+ return v;+}+const taskOf = (generationId: string) => db().prepare("SELECT * FROM relay_tasks WHERE generation_id = ? ORDER BY created_at DESC").get(generationId) as { id: string; state: string } | undefined;+const workerRow = () => db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(worker.id) as import("@/server/computer/workers").WorkerRow;+/** The stand-in worker takes the next task in line, as the worker program does. */+function workerTakes() {+ pool.workerBeat(workerRow(), pool.cleanBeat({ device: `wkr-${worker.id}`, protocol: 1, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [] }));+ return pool.workerClaim(workerRow(), [], Date.now());+}+const started = (generationId: string) => !!(db().prepare("SELECT started_at FROM generation_runs WHERE id = ?").get(generationId) as { started_at: number | null } | undefined)?.started_at;+const preview = async (body: Record<string, unknown>, cookie: string) => {+ const text = JSON.stringify(body);+ 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)) }, body: text }));+ return { status: r.status, body: (await r.json()) as { place?: string; quote?: { amount: number } } };+};+const SHOWN = { shown: { amount: 7, priceVersion: "v7" } };describe("runs at once on this install's GPUs", () => {@@ -194,10 +225,26 @@ describe("runs at once on this install's GPUs", () => {const a = account();const p = await billing.policy(a.id);expect(p).toBe(billing.OPEN_POLICY);- for (let i = 0; i < 4; i++) expect((await post(IMAGE, a.cookie)).status).toBe(201);- const over = await post(IMAGE, a.cookie);- expect(over.status).toBe(429);- expect(poolRuns(a.id)).toBe(4);+ // Lower than the studio's own limits, so only the policy's own count can stop these runs.+ const was = { ...billing.OPEN_POLICY.limits };+ try {+ billing.OPEN_POLICY.limits.activeRuns = 1;+ expect((await post(IMAGE, a.cookie)).status).toBe(201);+ const second = await post(IMAGE, a.cookie);+ expect(second.status).toBe(429);+ expect(second.body.error).toBe(limits.POOL_LIMIT_WORDS.active(1));+ expect(second.body.error).not.toBe(ACCOUNT_MESSAGES.activeRuns);+ billing.OPEN_POLICY.limits.activeRuns = 0;+ billing.OPEN_POLICY.limits.runsPerHour = 2;+ expect((await post(IMAGE, a.cookie)).status).toBe(201);+ const third = await post(IMAGE, a.cookie);+ expect(third.status).toBe(429);+ expect(third.body.code).toBe("limit");+ expect(third.body.error).toBe(limits.POOL_LIMIT_WORDS.hourly);+ } finally {+ Object.assign(billing.OPEN_POLICY.limits, was);+ }+ expect(poolRuns(a.id)).toBe(2);});});@@ -209,9 +256,11 @@ 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 (its run has started), the next one may wait.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());+ const t = await until(() => taskOf(id));+ expect(workerTakes()?.id).toBe(t!.id);+ expect(await until(() => started(id))).toBe(true);expect((await post({ ...IMAGE, ...SHOWN }, a.cookie)).status).toBe(201);});@@ -273,6 +322,18 @@ describe("where a run goes", () => {expect((await visitorStatus(auth.accountById(a.id)!)).viewer.prefer).toBe("pool");});+ it("with this install's GPUs first, a run that names no place and that they don't take runs on the account's own GPU", async () => {+ withBilling({ prefer: "pool", pool: { deny: ["oss-z-image-turbo"] }, limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });+ const a = account({ gpu: "online" });+ const r = await post(IMAGE, a.cookie);+ expect(r.status, JSON.stringify(r.body)).toBe(201);+ expect(r.body.items![0].place).toBeUndefined();+ // Named, it is a refusal (the person asked for that place).+ const named = await post({ ...IMAGE, place: "pool", ...SHOWN }, a.cookie);+ expect(named.status).toBe(403);+ expect(named.body.code).toBe("not-offered");+ });+it("an own GPU that doesn't answer: a run that named no place is asked about, never moved and charged", async () => {withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });const a = account({ gpu: "offline" });@@ -289,6 +350,81 @@ describe("where a run goes", () => {expect(poolRuns(a.id)).toBe(1);});+ it("an own GPU that doesn't answer: a run this install's GPUs wouldn't take goes to that GPU, as before, never asked about", async () => {+ const a = account({ gpu: "offline" });+ const own = (r: Awaited<ReturnType<typeof post>>, why: string) => {+ expect(r.body.code, why).not.toBe("own-gpu-offline");+ expect(r.headers.get(PLACE_ASK_HEADER), why).toBeNull();+ expect(r.status, `${why}: ${JSON.stringify(r.body)}`).toBe(201);+ expect(r.body.items![0].place, why).toBeUndefined();+ // Stopped, so the studio's own limit of runs at once leaves room for the next.+ db().prepare("UPDATE generations SET status = 'canceled' WHERE json_extract(request_json, '$.account') = ? AND status IN ('queued', 'running')").run(a.id);+ };+ const holds = fake.holds.size;+ // Closed to the account.+ withBilling({ hosted: false, limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });+ own(await post(IMAGE, a.cookie), "hosted runs closed");+ // A model the policy doesn't offer there.+ withBilling({ pool: { allow: ["oss-qwen-image-21-turbo"] }, limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });+ own(await post(IMAGE, a.cookie), "a model not offered");+ // A kind the policy leaves out.+ withBilling({ kinds: { image: false }, limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });+ own(await post(IMAGE, a.cookie), "a kind left out");+ // Extra LoRAs.+ withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });+ const lora = await post({ ...IMAGE, loras: [{ file: "a-look.safetensors", strength: 0.8 }] }, a.cookie);+ expect(lora.body.code).not.toBe("own-gpu-offline");+ expect(lora.status, JSON.stringify(lora.body)).not.toBe(403);+ // The billing service not answering (and no earlier answer kept).+ billing.resetBillingCache();+ fake.down = "error";+ try {+ own(await post(IMAGE, a.cookie), "the service down");+ } finally {+ fake.down = false;+ }+ expect(poolRuns(a.id)).toBe(0);+ expect(fake.holds.size).toBe(holds);+ expect(ownRuns(a.id)).toBeGreaterThanOrEqual(3);+ });++ it("asked for this install's GPUs by name while they are closed to the account: said so, never run on its own GPU", async () => {+ withBilling({ hosted: false, limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });+ const a = account({ gpu: "online" });+ const r = await post({ ...IMAGE, place: "pool", ...SHOWN }, a.cookie);+ expect(r.status).toBe(403);+ expect(r.body.code).toBe("not-offered");+ expect(ownRuns(a.id) + poolRuns(a.id)).toBe(0);+ });++ it("an own GPU that answers: its run never waits for the billing service once its policy is known", async () => {+ withBilling({ limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });+ fake.policy = { ...fake.policy, ttlS: 60 };+ const a = account({ gpu: "online" });+ await billing.policy(a.id);+ const asked = () => fake.calls_of("/v1/policy").length;+ const before = asked();+ const r = await post(IMAGE, a.cookie);+ expect(r.status).toBe(201);+ expect(r.body.items![0].place).toBeUndefined();+ expect(asked()).toBe(before);+ // A service that doesn't answer is waited for once, then not again for a while.+ billing.resetBillingCache();+ fake.down = "hang";+ try {+ const t0 = Date.now();+ expect((await post(IMAGE, a.cookie)).status).toBe(201);+ expect(Date.now() - t0).toBeLessThan(billing.BILLING_TIMEOUTS.policy + 1500);+ const after = asked();+ const t1 = Date.now();+ expect((await post(IMAGE, a.cookie)).status).toBe(201);+ expect(Date.now() - t1).toBeLessThan(billing.BILLING_TIMEOUTS.policy);+ expect(asked()).toBe(after);+ } finally {+ fake.down = false;+ }+ });+it("a kind the policy leaves out is not offered here", async () => {withBilling({ kinds: { image: false }, limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });const a = account();@@ -299,6 +435,22 @@ describe("where a run goes", () => {expect(hostedRun.kindAllowed({}, "model3d")).toBe(true);});+ it("a guest's policy that gets no answer isn't asked for again on every page for a while", async () => {+ withBilling();+ fake.down = "error";+ try {+ const before = fake.calls_of("/v1/policy").length;+ expect((await visitorStatus(null)).viewer.hosted).toBeUndefined();+ expect((await visitorStatus(null)).viewer.hosted).toBeUndefined();+ expect(fake.calls_of("/v1/policy").length).toBe(before + 1);+ expect(billing.cachedPolicy(null)).toBeNull();+ } finally {+ fake.down = false;+ }+ billing.resetBillingCache();+ expect((await visitorStatus(null)).viewer.hosted).toBe(true);+ });+it("a guest is told what the billing service's policy for guests says", async () => {withBilling();fake.guestPolicy = { ...FAKE_POLICY, hosted: false, ttlS: 0 };@@ -333,6 +485,74 @@ 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)));+ 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();+ });+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"] } };diff --git a/tests/run-place.test.ts b/tests/run-place.test.tsindex 2154b21a..b9ede31b 100644--- a/tests/run-place.test.ts+++ b/tests/run-place.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { checkedPool, IN_BROWSER, mainModel, placePrice, runPlace, type RunPlaceInput } from "@/lib/run-place";+import { checkedPool, composerPlace, IN_BROWSER, mainModel, placePrice, runPlace, type RunPlaceInput } from "@/lib/run-place";/** Where a run happens and what it costs, for each audience and engine (the composers' place chip and send button). */const fmt = (usd: number) => `$${usd.toFixed(2)}`;@@ -189,6 +189,21 @@ describe("the main model of a pipeline", () => {});});+describe("where a composer's run goes, and the place it names", () => {+ it("the person's pick, named", () => {+ expect(composerPlace("own", false, true)).toEqual({ runOn: "own", place: "own" });+ expect(composerPlace("pool", true, false)).toEqual({ runOn: "pool", place: "pool" });+ });+ it("its own GPU while online, named; this studio's GPUs when it isn't, named", () => {+ expect(composerPlace(null, true, false)).toEqual({ runOn: "own", place: "own" });+ expect(composerPlace(null, false, false)).toEqual({ runOn: "pool", place: "pool" });+ expect(composerPlace(null, false, true)).toEqual({ runOn: "pool", place: "pool" });+ });+ it("this studio's GPUs first while its own GPU is online: shown, but not named, so the server can still use its own GPU", () => {+ expect(composerPlace(null, true, true)).toEqual({ runOn: "pool", place: undefined });+ });+});+describe("checkedPool", () => {it("is this studio's GPUs only when the price check says the run goes there", () => {expect(checkedPool({ place: "pool", quote: { text: "$0.02", sub: "Billed to your balance" } })).toEqual({ text: "$0.02", sub: "Billed to your balance" });diff --git a/tests/worker-tokens.test.ts b/tests/worker-tokens.test.tsindex a527d941..dae44f3b 100644--- a/tests/worker-tokens.test.ts+++ b/tests/worker-tokens.test.ts@@ -2,8 +2,9 @@ import { afterEach, beforeAll, describe, expect, it } from "vitest";import { tempDir } from "./helpers/temp-dir";/**- * Pool worker tokens: a lifetime (FUOBE_WORKER_TOKEN_DAYS, off by default) with the next token in the beat answer, the- * old token stopping at the new one's first use; and alerts in the admin log when a token is used from a new country, a+ * Pool worker tokens: a lifetime (FUOBE_WORKER_TOKEN_DAYS, off by default) with the next token in the beat answer of a+ * worker that says it saves tokens, the old token stopping at the new one's first use, and the lifetime given to a worker+ * added before it was set; and alerts in the admin log when a token is used from a new country, a* new network, or two networks at once. The admin log and the worker's row never hold an address.*/@@ -32,8 +33,9 @@ afterEach(() => {const row = (id: string) => workers.getWorker(id)!;const bearer = (token: string) => `Bearer ${token}`;-const beat = (id: string, protocol: number, now: number) =>- pool.workerBeat(row(id), pool.cleanBeat({ device: `wkr-${id}`, protocol, version: "2.0.0", local: { paused: true, why: "here", until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [] }), now);+/** A beat; `rotate`: the worker says it saves the next token (`canRotateToken`). */+const beat = (id: string, protocol: number, now: number, rotate = true) =>+ pool.workerBeat(row(id), pool.cleanBeat({ device: `wkr-${id}`, protocol, version: "2.0.0", ...(rotate && { canRotateToken: true }), local: { paused: true, why: "here", until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [] }), now);const alerts = (id: string) =>(db().prepare("SELECT actor, target, detail_json FROM admin_audit WHERE action = 'worker.alert' AND target = ? ORDER BY id").all(id) as { actor: string; target: string; detail_json: string }[]).map((r) => ({ actor: r.actor, ...(JSON.parse(r.detail_json) as { kind: string } & Record<string, unknown>) }),@@ -46,14 +48,16 @@ describe("a pool worker's token lifetime", () => {expect(beat(w.id, 2, Date.now() + 400 * DAY).worker.token).toBeUndefined();});- it("with a lifetime: the next token once half is gone, to a worker that speaks protocol 2; the old one stops at its first use", () => {+ it("with a lifetime: the next token once half is gone, to a worker that says it saves tokens; the old one stops at its first use", () => {process.env.FUOBE_WORKER_TOKEN_DAYS = "10";const t0 = Date.now();const w = workers.createWorker({ name: `expiring-${++n}`, kind: "pool" }, t0);expect(row(w.id).expires_at).toBe(t0 + 10 * DAY);- // More than half left: nothing yet. A worker on protocol 1 never gets one.+ // More than half left: nothing yet. A worker that doesn't say it saves tokens never gets one, whatever its protocol.expect(beat(w.id, 2, t0 + 4 * DAY).worker.token).toBeUndefined();- expect(beat(w.id, 1, t0 + 6 * DAY).worker.token).toBeUndefined();+ expect(beat(w.id, 2, t0 + 6 * DAY, false).worker.token).toBeUndefined();+ expect(beat(w.id, 3, t0 + 6 * DAY, false).worker.token).toBeUndefined();+ expect(pool.cleanBeat({ protocol: 2, canRotateToken: "yes" }).canRotateToken).toBeUndefined();const offered = beat(w.id, 2, t0 + 6 * DAY).worker.token!;expect(offered.value).toMatch(/^fuobe_wkr_[A-Za-z0-9_-]{43}$/);expect(offered.expiresAt).toBe(t0 + 16 * DAY);@@ -92,11 +96,32 @@ describe("a pool worker's token lifetime", () => {expect(row(w.id).expires_at).toBe(t0 + 1.5 * DAY + MIN + 2 * DAY);});+ it("a pool worker added before the lifetime was set gets it from its first call after, then the next token as any other", () => {+ const t0 = Date.now();+ const w = workers.createWorker({ name: `older-${++n}`, kind: "pool" }, t0);+ expect(row(w.id).expires_at).toBeNull();+ process.env.FUOBE_WORKER_TOKEN_DAYS = "4";+ const t1 = t0 + 30 * DAY;+ expect(workers.workerFromAuth(bearer(w.token), null, t1)?.id).toBe(w.id);+ expect(row(w.id).expires_at).toBe(t1 + 4 * DAY);+ // A later call keeps that expiry.+ workers.workerFromAuth(bearer(w.token), null, t1 + DAY);+ expect(row(w.id).expires_at).toBe(t1 + 4 * DAY);+ const next = beat(w.id, 2, t1 + 3 * DAY).worker.token!;+ expect(next.expiresAt).toBe(t1 + 7 * DAY);+ // A worker that never takes it stops at the end of its lifetime.+ expect(workers.workerFromAuth(bearer(w.token), null, t1 + 4 * DAY + 1)).toBeNull();+ expect(workers.workerFromAuth(bearer(next.value), null, t1 + 4 * DAY + 2)?.id).toBe(w.id);+ });+it("a person's paired ComfyUI keeps its token as before", () => {process.env.FUOBE_WORKER_TOKEN_DAYS = "1";const p = workers.createWorker({ name: `paired-${++n}`, kind: "personal", principal: "owner" });expect(row(p.id).expires_at).toBeNull();expect(workers.offerNextToken(row(p.id), Date.now() + 400 * DAY)).toBeNull();+ // Its calls give it no lifetime either.+ expect(workers.workerFromAuth(bearer(p.token), null)?.id).toBe(p.id);+ expect(row(p.id).expires_at).toBeNull();});});diff --git a/tests/workers-pairing.test.ts b/tests/workers-pairing.test.tsindex b69f569b..ef135946 100644--- a/tests/workers-pairing.test.ts+++ b/tests/workers-pairing.test.ts@@ -133,6 +133,33 @@ describe("pairing a ComfyUI", () => {]);});+ it("on an install with no workers and no hosted runs, the owner's pairing runs ComfyUI on the owner's computer, as before", async () => {+ delete process.env.FUOBE_HOSTED_RUNS;+ setSetting("comfyWhere", "server");+ const logged = () => db().prepare("SELECT detail_json FROM admin_audit WHERE action = 'settings.comfy_where' ORDER BY id").all() as { detail_json: string }[];+ const before = logged().length;+ const approve = async () => {+ const s = await (await startRoute.POST(program("/api/gpu/pair/start", undefined, { body: JSON.stringify({ name: "pc" }) }))).json();+ const r = await pairRoute.POST(browser("owner", "/api/gpu/pair", { method: "POST", body: JSON.stringify({ code: s.code }) }));+ expect(r.status).toBe(200);+ return (await r.json()) as { settingsNeeded?: boolean };+ };+ expect((await approve()).settingsNeeded).toBeUndefined();+ expect(getSetting("comfyWhere")).toBe("computer");+ // The change is in the admin log.+ expect(logged().slice(before).map((r) => JSON.parse(r.detail_json))).toEqual([{ before: "server", after: "computer" }]);+ // With hosted runs on, a pairing never moves the studio's jobs: the owner is told where to choose.+ process.env.FUOBE_HOSTED_RUNS = "1";+ try {+ setSetting("comfyWhere", "server");+ expect((await approve()).settingsNeeded).toBe(true);+ expect(getSetting("comfyWhere")).toBe("server");+ } finally {+ delete process.env.FUOBE_HOSTED_RUNS;+ setSetting("comfyWhere", "server");+ }+ });+it("codes are case- and dash-blind", () => {expect(pairCode("abcd efgh")).toBe("ABCD-EFGH");expect(pairCode("abcd-efg")).toBeNull();