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: account runs go through the workers' line
Adarsh40ce8540509c
diff --git a/docs/SELF-HOSTING.md b/docs/SELF-HOSTING.mdindex 42284eae..6f140447 100644--- a/docs/SELF-HOSTING.md+++ b/docs/SELF-HOSTING.md@@ -114,9 +114,10 @@ Don't copy `auth.json.migrated-<…>` back instead. It lacks the accounts made s| `FUOBE_ENGINE_MODE`, `FUOBE_CLOUD_PROVIDER`, `FUOBE_ENHANCE_PROVIDER`, `FUOBE_LLM_PROVIDER` | The Settings choices above || `FUOBE_LLM_CONTEXT` | Tokens of context for the local model (default `16384`): Ollama's `num_ctx`, and the context LM Studio loads a model with. `0` leaves it to the server || `OPENAI_API_KEY`, `GEMINI_API_KEY` | Read into Settings; no feature uses them yet |-| `FUOBE_HOSTED_RUNS=1` | With public sign-up: accounts with no GPU of their own may run on this install's ComfyUI ([Hosted runs](public-signup.md#hosted-runs)). Off by default |-| `FUOBE_POOL_WAIT_MIN` | How long a hosted run may wait in line, in minutes (default `30`) |-| `FUOBE_BILLING_URL`, `FUOBE_BILLING_TOKEN` | An optional external billing service for hosted runs ([billing-hook.md](billing-hook.md)). None: hosted runs are free |+| `FUOBE_HOSTED_RUNS=1` | With public sign-up: accounts with no GPU of their own may run on this install's GPUs: its workers, or its own ComfyUI when that is on this machine ([Hosted runs](public-signup.md#hosted-runs)). Off by default. A billing service or `FUOBE_HOSTED_FREE=1` must answer for these runs |+| `FUOBE_HOSTED_FREE=1` | With no billing service: hosted runs are free for every account, within the install's own limits. Without it (and without a billing service) hosted runs stay closed |+| `FUOBE_POOL_WAIT_MIN` | How long a hosted run may wait in line before a GPU first takes it, in minutes (default `30`) |+| `FUOBE_BILLING_URL`, `FUOBE_BILLING_TOKEN` | An optional external billing service for hosted runs ([billing-hook.md](billing-hook.md)). None: hosted runs are closed, or free with `FUOBE_HOSTED_FREE=1` || `FUOBE_MODERATION_URL`, `FUOBE_MODERATION_TOKEN`, `FUOBE_MODERATION_MAX_WAIT_H` | An optional external moderation service ([moderation-hook.md](moderation-hook.md)). None: nothing is checked |Uploads up to 200 MB work with sign-in on; Split soundtrack's Export mix sends its WAV in 16 MB parts, up to 2 GiB. Inputs given as URLs are fetched only from public addresses unless `FUOBE_ALLOW_PRIVATE_URLS=1`.diff --git a/docs/admin-api.md b/docs/admin-api.mdindex 26e3f77f..e78a71a2 100644--- a/docs/admin-api.md+++ b/docs/admin-api.md@@ -98,7 +98,7 @@ Times are epoch milliseconds and sizes are bytes. Every answer is `Cache-Control| `GET /api/admin/accounts/{id}` | | one account with its numbers; 404 `No such account` || `PATCH /api/admin/accounts/{id}` | exactly one of `{ disabled: boolean }` or `{ signOut: true }` | the account (no numbers) || `DELETE /api/admin/accounts/{id}` | | 204 |-| `GET /api/admin/generations` | `account`, `status` (`finished`, `running`, `failed`), `kind` (`image`, `video`, `audio`, `model3d`, `text`), `before` (the last page's `next`), `limit` (1 to 100, default 30) | `{ items, next }`; `next` is null on the last page. Each output has a `state`: `shown`, `held` (hidden, or waiting for its check) or `removed` (its file is gone) |+| `GET /api/admin/generations` | `account`, `status` (`finished`, `running`, `failed`), `kind` (`image`, `video`, `audio`, `model3d`, `text`), `before` (the last page's `next`), `limit` (1 to 100, default 30) | `{ items, next }`; `next` is null on the last page. Each output has a `state`: `shown`, `held` (hidden, or waiting for its check) or `removed` (its file is gone). A failed run on this install's GPUs also has `detail`: the technical reason, which the account never sees || `DELETE /api/admin/generations/{id}` | | 204; 404 for an unknown run or the owner's own || `POST /api/admin/outputs/hide` | `{ assetIds?, generationIds? }` (up to 500 each) | `{ hidden }` || `POST /api/admin/outputs/unhide` | the same | `{ shown }` |diff --git a/docs/billing-hook.md b/docs/billing-hook.mdindex 94e4f110..b898740b 100644--- a/docs/billing-hook.md+++ b/docs/billing-hook.md@@ -2,8 +2,8 @@An install can connect an external billing service at `FUOBE_BILLING_URL`. Fuobe sends facts about each run that goesto this install's GPUs (hosted runs, see [public-signup.md](public-signup.md#hosted-runs)); the service answers with what-the person sees and whether the run may start. With no service set, every run is free and allowed, and Fuobe makes no-call at all.+the person sees and whether the run may start. With no service set, Fuobe makes no call at all, and runs on this+install's GPUs stay closed unless `FUOBE_HOSTED_FREE=1` makes them free for every account.Fuobe has no words of its own for prices or balances. Every word on screen about them (the price on Run, the balance inthe top bar and the account menu, a refusal's text, a link, an offer) comes from the service's answers at runtime.@@ -15,6 +15,7 @@ the top bar and the account menu, a refusal's text, a link, an offer) comes from| `FUOBE_BILLING_URL` | The service: `https://billing.example.com/base`, `http://…`, or a Unix socket on this machine, `unix:/path/to/billing.sock` | none: no billing || `FUOBE_BILLING_TOKEN` | Sent as `Authorization: Bearer <token>` with every call | none || `FUOBE_HOSTED_RUNS` | `1` lets accounts run on this install's GPUs (the only runs the service prices) | off |+| `FUOBE_HOSTED_FREE` | `1` opens those runs with no service set: free for every account, within the install's own limits | off || `FUOBE_POOL_WAIT_MIN` | How long a run may wait in line on this install's GPUs when the service doesn't say | 30 |## When Fuobe calls the service@@ -129,7 +130,7 @@ report from what is stored. A run whose rows couldn't be made after its reserve| Situation | What happens ||---|---|-| No `FUOBE_BILLING_URL` | No call. Every run is free and allowed. |+| No `FUOBE_BILLING_URL` | No call. Runs on this install's GPUs are closed, or free and allowed with `FUOBE_HOSTED_FREE=1`. || Set, and it answers | As above. || Set, and no answer in time | Runs on this install's GPUs are refused (503, "Runs are paused for a moment. Try again soon."). Run shows "Price unavailable". Runs on the account's own GPU or key go on. Reports wait in the outbox and are sent when it is back. Runs that already have a hold keep running. |diff --git a/docs/gpu-workers.md b/docs/gpu-workers.mdindex c7bbda75..9922a14f 100644--- a/docs/gpu-workers.md+++ b/docs/gpu-workers.md@@ -104,7 +104,10 @@ The worker obeys any one of these pauses. One pause never ends another pause.### The queue-A job for the workers belongs to the owner. It names the pools that may take it (`pool` by default). It also keeps:+A job for the workers belongs to the owner or, with hosted runs on ([public-signup.md](public-signup.md#hosted-runs)),+to an account. An account's job is the account's task (`acct:<id>`): only a worker of its pool takes it, and the+account's own session never reaches it through the computer routes. It names the pools that may take it (`pool` by+default). It also keeps:- its lane: the first 12 hex digits of the SHA-256 of the sorted names of the workflow's files over 2 GB. A workflowwith no big file is in the lane `small`.@@ -163,8 +166,12 @@ Before its ComfyUI gets a graph, the worker checks all of these. The studio cannAfter each job, the worker deletes the job's inputs and results from its folders and deletes the prompt from itsComfyUI's history. At start, it empties its folders.-Pictures for workers are made again from their pixels on the studio (no EXIF, no GPS). Clips and sound go to workers-only when `FUOBE_POOL_MEDIA_INPUTS` allows them (`image` by default; `image,video,audio` for all).+Pictures for workers are made again from their pixels on the studio (no EXIF, no GPS), the owner's and accounts'+alike. Clips and sound go to workers only when `FUOBE_POOL_MEDIA_INPUTS` allows them (`image` by default;+`image,video,audio` for all); an account's run with a kind it doesn't allow is refused before it is queued. Every+VideoHelperSuite save node of a graph for the workers is sent with `save_metadata` off, so no prompt rides inside a+result. An account's run is shaped by the workers' own facts (the least VRAM and RAM of the workers allowed its lane),+never by the account's own computer.### The protocol@@ -206,7 +213,8 @@ routes.## Tests-- `pnpm test` (`tests/workers-pool.test.ts`, `tests/workers-pairing.test.ts`, `tests/worker-program.test.ts`)+- `pnpm test` (`tests/workers-pool.test.ts`, `tests/workers-pairing.test.ts`, `tests/worker-program.test.ts`,+ `tests/worker-queue.test.ts`, `tests/pool-account-runs.test.ts`)- `node tests/e2e/worker.mjs` and `node tests/e2e/fuobe-connect.mjs` (after `pnpm build`, or with `E2E_DEV=1`). Theseuse a stand-in ComfyUI and a stand-in `nvidia-smi` on ports 3361 and 3362. They never touch a real GPU or ComfyUI.- `python -m unittest discover -s tests` in `integrations/fuobe-connect`diff --git a/docs/public-signup.md b/docs/public-signup.mdindex 086788dc..a7934070 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -339,35 +339,59 @@ account with that provider. The studio's own keys are never used for an account'## Hosted runsBy default an account runs only on its own GPU or its own key. An owner who wants accounts to run on the studio's own-ComfyUI instead sets `FUOBE_HOSTED_RUNS=1`. It is off unless set, and with it off nothing below changes.+GPUs instead sets `FUOBE_HOSTED_RUNS=1`. It is off unless set, and with it off nothing below changes.++Something must answer for these runs. Either a billing service is set (`FUOBE_BILLING_URL`, below), or+`FUOBE_HOSTED_FREE=1` says that they are free for every account. With neither, hosted runs stay closed even when the+switch is on.++Where the runs go:++- **The workers** ([gpu-workers.md](gpu-workers.md)), when Settings sends this studio's ComfyUI jobs to them+ (`comfyWhere=workers`). Each job of an account's run becomes a task for the workers that belongs to that account.+ It waits in one line with every other task, and the server never sends it to a ComfyUI address. Hosted runs are open+ while at least one worker is added and allowed a lane, even when it is paused: a run then waits in line for it. A run+ that no worker is allowed to run is refused before it is queued.+- **This install's own ComfyUI server** (the address in Settings), only when that address is on the same machine+ (`127.0.0.1` or `localhost`). An address on another machine is never used for accounts' runs. Pictures are made+ again from their pixels first (no EXIF, no GPS).+- An install whose ComfyUI runs on the owner's computer doesn't offer hosted runs.With it on:-- An account with no GPU of its own can run in the studios (generations, camera motions, effects, apps). The run goes- to this install's ComfyUI server (the address in Settings). An install whose ComfyUI runs on the owner's computer- doesn't offer hosted runs.+- An account with no GPU of its own can run in the studios (generations, camera motions, effects, apps).- An account whose own GPU is online runs there by default. The composer shows where a run goes ("Your GPU" or "Thisstudio's GPUs"), and the person can pick either.- 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, extra LoRAs added to a request, and clips and sound as inputs stay on the account's own GPU.-- An account can upload pictures for these runs. Clips and sound still need its own GPU or key.+ Image to 3D and extra LoRAs added to a request stay on the account's own GPU. So do clips and sound as inputs,+ unless the policy and the studio's GPUs both take them.+- An account can upload the kinds of file its policy allows for these runs (pictures without a billing service), and+ only those the studio's GPUs take (`FUOBE_POOL_MEDIA_INPUTS` on the workers). Others still need its own GPU or key.- A new account goes back to where it was after sign-up, not to "Connect your GPU". Connecting a GPU stays inSettings → Your GPU and at `/connect`; the account menu says "Your GPU · Optional".-- A run waiting for the studio's GPUs shows its place in line ("In line · 3rd · about 40 s"). A run may wait- `FUOBE_POOL_WAIT_MIN` minutes (30 by default); past that it fails.+- A run on the studio's GPUs shows only where it is: "In line" with its place ("In line · 3rd · about 40 s"),+ "Working" with its progress, then its result. The place counts every run ahead of it that the same GPUs serve+ first, whatever its model. When a worker pauses, goes quiet or restarts, the run is "In line" again in the same+ place. A run that can't finish shows one plain sentence; the owner reads the technical reason in the accounts' runs+ (`detail` in `GET /api/admin/generations`). A failed run on the studio's GPUs never offers "Fix it".+- A run may wait `FUOBE_POOL_WAIT_MIN` minutes (30 by default, or what the billing service says) before a worker+ first takes it; past that it fails, not charged. Once a worker took it, that limit is over.+- In a run's `params.extra`, a file input is used only when the run sent that file itself. A name of a file in the+ GPUs' folders is dropped. The graph is checked before it is queued or sent: it reads only the files this run sent.- The account's usual limits apply: runs at once, runs per hour, outputs per run, and its space.Two optional services can go with it:- a **billing service** ([billing-hook.md](billing-hook.md)): prices runs on this install's GPUs, sets the price aside- before a run starts, and shows the person a balance. Without one, these runs are free.+ before a run starts, and shows the person a balance. Without one, these runs are closed unless `FUOBE_HOSTED_FREE=1`+ makes them free.- a **moderation service** ([moderation-hook.md](moderation-hook.md)): checks a run before it starts and, when it asksto, its outputs before they show. Without one, nothing is checked.The code is `src/server/hosted.ts` (the switch, the place, the line), `src/server/hosted-run.ts` (the run route's side),`src/server/run-stamp.ts` (what every row of a run carries) and `src/lib/hosted.ts` (the browser's side). The tests are-`tests/hosted-runs.test.ts`, `tests/billing-hook.test.ts`, `tests/billing-release.test.ts` and-`tests/moderation-hook.test.ts`.+`tests/hosted-runs.test.ts`, `tests/pool-account-runs.test.ts` (runs on the workers), `tests/billing-hook.test.ts`,+`tests/billing-release.test.ts` and `tests/moderation-hook.test.ts`.## Uploadsdiff --git a/src/app/api/uploads/route.ts b/src/app/api/uploads/route.tsindex eaeee6a1..ce26b4f3 100644--- a/src/app/api/uploads/route.ts+++ b/src/app/api/uploads/route.ts@@ -4,7 +4,7 @@ import { nanoid } from "nanoid";import { CONNECT_GPU_HEADER, CONNECT_GPU_UPLOAD_MESSAGE, CONNECT_GPU_UPLOAD_OPEN_MESSAGE, KINETIC_UPLOAD_HEADER } from "@/lib/guest-access";import { accountProviders, paidAllowed } from "@/server/account-keys";import { policy as billingPolicy } from "@/server/billing";-import { poolReady } from "@/server/hosted";+import { poolReady, poolTakesFiles } from "@/server/hosted";import { imageSize } from "@/lib/image-size";import { sniffMedia, type SniffKind } from "@/lib/sniff";import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "@/server/account-files";@@ -178,12 +178,16 @@ type Kinds = { image: boolean; video: boolean; audio: boolean };*/type Without = { hosted: Kinds | null; kinetic: boolean };-/** The kinds of file an account with no GPU or key of its own may add for runs on this install's GPUs (hosted runs). */+/**+ * The kinds of file an account with no GPU or key of its own may add for runs on this install's GPUs (hosted runs): the+ * policy's, and only those this install's GPUs take.+ */async function hostedUploads(accountId: string): Promise<Kinds | null> {if (!poolReady()) return null;const p = await billingPolicy(accountId);- if (!p?.hosted || !(p.uploads.image || p.uploads.video || p.uploads.audio)) return null;- return p.uploads;+ if (!p?.hosted) return null;+ const kinds: Kinds = { image: p.uploads.image && poolTakesFiles("image"), video: p.uploads.video && poolTakesFiles("video"), audio: p.uploads.audio && poolTakesFiles("audio") };+ return kinds.image || kinds.video || kinds.audio ? kinds : null;}async function accountUpload(request: Request, account: Account): Promise<Response> {diff --git a/src/lib/relay.ts b/src/lib/relay.tsindex 36cc01da..99a3148c 100644--- a/src/lib/relay.ts+++ b/src/lib/relay.ts@@ -338,6 +338,18 @@ export const RELAY_WORDS = {computerAway: "Waiting for your computer. Open Fuobe there to finish this run.",} as const;+/**+ * What a run on this install's GPUs (hosted runs) shows an account: in line (with its place and wait, the row's queue+ * block), working on it, then its result. Every recovery (a worker that paused, went quiet or restarted, a retry) is+ * "in line" again in the same place. A run that can't finish says one plain sentence; the technical reason is kept for+ * the owner only.+ */+export const POOL_WORDS = {+ inLine: "In line",+ working: "Working",+ failed: "This one couldn't be made. Press Retry to try again.",+} as const;+/** A script's open-source run (an API token) while the owner's ComfyUI is on the owner's computer. */export const RUNS_ON_COMPUTER_NOTE = "Runs when Fuobe is open on your computer.";diff --git a/src/server/account-admin.ts b/src/server/account-admin.tsindex 83600f73..2b26d203 100644--- a/src/server/account-admin.ts+++ b/src/server/account-admin.ts@@ -129,8 +129,12 @@ export function accountRunOptions(sp: URLSearchParams): ListOptions | { error: s*/export type OutputState = "shown" | "held" | "removed";-/** An account's run as the owner sees it: whose it is (null email: the account was deleted), and each result's state. */-export type AccountRun = Omit<Generation, "outputs"> & { outputs: (OutputFile & { state: OutputState })[]; account: { id: string; email: string | null } };+/**+ * An account's run as the owner sees it: whose it is (null email: the account was deleted), and each result's state. A+ * run on this install's GPUs also carries `detail`: the technical reason it failed, which the account never sees (its+ * own page shows one plain sentence).+ */+export type AccountRun = Omit<Generation, "outputs"> & { outputs: (OutputFile & { state: OutputState })[]; account: { id: string; email: string | null }; detail?: string };/** Each result's state, read from its stored file (its asset row; none: removed). An output that isn't a stored file is shown. */function withStates(outputs: OutputFile[]): (OutputFile & { state: OutputState })[] {@@ -152,8 +156,14 @@ export function listAccountRuns(o: ListOptions): { items: AccountRun[]; next: st// The WHERE already leaves the owner's runs out; this keeps them out whatever a caller passes.const found = listGenerations(opts).filter((g) => g.request.account);const last = found.at(-1);+ const raw = db().prepare("SELECT error FROM generations WHERE id = ?");+ const detail = (g: Generation) => {+ if (g.place !== "pool" || !g.error) return {};+ const e = (raw.get(g.id) as { error: string | null } | undefined)?.error;+ return e && e !== g.error ? { detail: e } : {};+ };return {- items: found.map((g) => ({ ...g, outputs: withStates(g.outputs), account: { id: g.request.account!, email: emails.get(g.request.account!) ?? null } })),+ items: found.map((g) => ({ ...g, outputs: withStates(g.outputs), account: { id: g.request.account!, email: emails.get(g.request.account!) ?? null }, ...detail(g) })),next: last && found.length === limit ? `${last.createdAt}:${last.id}` : null,};}diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.tsindex 6092ac54..29791c34 100644--- a/src/server/computer/pool.ts+++ b/src/server/computer/pool.ts@@ -403,27 +403,140 @@ setPoolClocks((t, now) => {// ---------------------------------------------------------------------------// Place in line and the wait (4.4)-/** Where a waiting task is in its lane's line, and about how long until it is done. */+/** Tasks looked at for a place in line, at most (a longer line counts as this long). */+const LOOK_AHEAD = 2000;++const poolWorkers = () => db().prepare("SELECT * FROM relay_workers WHERE kind = 'pool' AND revoked_at IS NULL").all() as WorkerRow[];++/** Do two tasks share a pool (the same workers may serve both)? */+const sharePool = (a: Pick<TaskRow, "pools">, b: Pick<TaskRow, "pools">) => (a.pools ?? "").split(",").some((p) => !!p && (b.pools ?? "").split(",").includes(p));++/**+ * A lane's typical run on the workers: the median measured time of its last 20 finished jobs (the worker's own+ * execution time), else of any lane's, else null before any.+ */+export function typicalPoolMs(lane: string | null): number | null {+ const d = db();+ const of = (rows: { ms: number }[]) => (rows.length ? rows.map((r) => r.ms).sort((a, b) => a - b)[Math.floor(rows.length / 2)] : null);+ const q = (where: string, ...args: unknown[]) =>+ d.prepare(`SELECT exec_ms AS ms FROM worker_jobs WHERE event = 'finished' AND exec_ms > 0 ${where} ORDER BY id DESC LIMIT 20`).all(...args) as { ms: number }[];+ return (lane ? of(q("AND lane = ?", lane)) : null) ?? of(q(""));+}++/** How long a task should take: its lane's bench on the quickest of these workers, its own estimate, or the lane's typical run. */+function estFor(t: Pick<TaskRow, "lane" | "est_ms">, workers: WorkerRow[], typical: (lane: string | null) => number | null): number {+ const bench = workers.map((w) => (t.lane && benchOf(w)[t.lane]?.medianMs) || 0).filter((ms) => ms > 0);+ return (bench.length ? Math.min(...bench) : 0) || t.est_ms || typical(t.lane) || 60_000;+}++/**+ * Where a waiting task is in line, and about how long until it is done. Every task ahead of it counts, whatever its lane,+ * in the order the workers serve them (LINE_ORDER), when a worker that may run this one may run that one too: one GPU+ * serves every lane it has in that order. The wait adds what is left of the jobs those workers are running now, the+ * load of its lane when none has it warm, and its own run. No worker able to run it right now (paused, outside its+ * hours): its place, with no estimate.+ */export function placeInLine(t: TaskRow, now = Date.now()): { place: number; etaSeconds: number | null } {const d = db();- const ahead = d.prepare("SELECT est_ms FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND lane IS ? AND rank_at < ?").all(t.lane, t.rank_at ?? now) as { est_ms: number | null }[];- const workers = (d.prepare("SELECT * FROM relay_workers WHERE kind = 'pool' AND revoked_at IS NULL").all() as WorkerRow[]).filter((w) => eligible(w, now) && fits({ ...t, created_at: 0 }, w, now));+ const all = poolWorkers().filter((w) => sharePool({ pools: w.pool }, t));+ const workers = all.filter((w) => eligible(w, now) && fits({ ...t, created_at: 0 }, w, now));+ const rank = t.rank_at ?? t.created_at;+ const before = d+ .prepare(+ `SELECT ${LINE_COLS} FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND id != ?+ AND (rank_at < ? OR (rank_at = ? AND (created_at < ? OR (created_at = ? AND id < ?))))+ ORDER BY ${LINE_ORDER} LIMIT ?`,+ )+ .all(t.id, rank, rank, t.created_at, t.created_at, t.id, LOOK_AHEAD) as TaskRow[];+ // Ahead of it: a task the same workers would serve first (with none able to run it now, any that could run it at all).+ const able = workers.length ? workers : all.filter((w) => fits({ ...t, created_at: 0 }, w, now));+ const ahead = before.filter((x) => sharePool(x, t) && (!able.length || able.some((w) => fits({ ...x, created_at: 0 }, w, now))));if (!workers.length) return { place: ahead.length + 1, etaSeconds: null };- const own = t.est_ms ?? 60_000;+ const typical = memo(typicalPoolMs);+ const own = estFor(t, workers, typical);const warm = workers.some((w) => w.warm_lane === t.lane);const load = warm ? 0 : Math.max(0, ...workers.map((w) => (t.lane && benchOf(w)[t.lane]?.loadMs) || 0));- const sum = ahead.reduce((s, r) => s + (r.est_ms ?? own), 0);- return { place: ahead.length + 1, etaSeconds: Math.round((sum / workers.length + load + own) / 1000) };+ const sum = ahead.reduce((s, x) => s + estFor(x, workers, typical), 0);+ // The jobs these workers hold now: what is left of each.+ const ids = new Set(workers.map((w) => w.id));+ const running = (d.prepare(`SELECT ${LINE_COLS} FROM relay_tasks WHERE pools IS NOT NULL AND state IN ('sending','queued','running','collecting') AND worker_id IS NOT NULL`).all() as TaskRow[]).filter((x) => ids.has(x.worker_id!));+ const left = running.reduce((s, x) => s + Math.max(0, estFor(x, workers, typical) - (now - (x.claimed_at ?? now))), 0);+ return { place: ahead.length + 1, etaSeconds: Math.round(((sum + left) / workers.length + load + own) / 1000) };+}++/** A one-argument function whose answers are kept for this call's life. */+function memo<A, R>(fn: (a: A) => R): (a: A) => R {+ const seen = new Map<A, R>();+ return (a) => {+ if (!seen.has(a)) seen.set(a, fn(a));+ return seen.get(a)!;+ };}// ---------------------------------------------------------------------------// Making tasks for workers+/** The lane a workflow's tasks go in (a workflow the catalog doesn't know: the small lane). */+export function poolLane(workflowId: string): string {+ return allLanes(loadIndex(), sha).find((l) => l.workflows.includes(workflowId))?.lane ?? "small";+}++/**+ * Is there a worker for this lane: one the owner added and didn't revoke, allowed the lane (any lane: `lane` null),+ * whether it is paused, outside its hours or offline right now (a run then waits in line for it).+ */+export function workersAllowed(lane: string | null): boolean {+ return poolWorkers().some((w) => {+ const allow = allowOf(w);+ return lane === null ? Object.keys(allow).length > 0 : lane in allow;+ });+}++/**+ * What the workers allowed a lane have (any lane: `lane` null), for shaping a graph that each of them can run: the least+ * VRAM and RAM among those that said, and their device when they all name the same kind. Nothing known: empty.+ */+export function poolFacts(lane: string | null): ComputerFacts {+ const facts = poolWorkers()+ .filter((w) => lane === null || lane in allowOf(w))+ .map((w) => json<ComputerFacts>(w.facts_json, {}));+ const least = (k: "vramBytes" | "ramBytes") => {+ const v = facts.map((f) => f[k]).filter((n): n is number => typeof n === "number" && n > 0);+ return v.length ? Math.min(...v) : undefined;+ };+ const kinds = new Set(facts.map((f) => /^[a-z]+/i.exec(f.device ?? "")?.[0].toLowerCase()).filter(Boolean));+ const vramBytes = least("vramBytes");+ const ramBytes = least("ramBytes");+ const device = kinds.size === 1 ? facts.find((f) => f.device)?.device : undefined;+ return { ...(vramBytes && { vramBytes }), ...(ramBytes && { ramBytes }), ...(device && { device }) };+}++/**+ * 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.+ */+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.+ const workflowId = asked && !asked.includes("{") ? asked : null;+ const lane = workflowId ? poolLane(workflowId) : null;+ const needs = workflowId ? needsOf(loadIndex(), workflowId) : null;+ const probe = { id: "", 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 } };+}+/** What a task for workers stores: its lane, its needs, and its place in line. */export function poolFields(workflowId: string, o: { account?: string; boostMs?: number; waitMs?: number; onlyWorker?: string } = {}, now = Date.now()) {const index = loadIndex();const needs = needsOf(index, workflowId);- const lane = allLanes(index, sha).find((l) => l.workflows.includes(workflowId))?.lane ?? "small";+ const lane = poolLane(workflowId);return {pools: ["pool"],account: o.account,diff --git a/src/server/computer/tasks.ts b/src/server/computer/tasks.tsindex 1c1e9265..b4463813 100644--- a/src/server/computer/tasks.ts+++ b/src/server/computer/tasks.ts@@ -154,8 +154,9 @@ export function setTask(id: string, fields: Partial<TaskRow>): void {}/**- * A principal's task, or null (another principal's task is no task at all). A pool's: a task for workers that this pool- * may take.+ * A task as a caller of the computer routes reaches it, or null (another principal's task is no task at all). A pool's:+ * a task for workers that this pool may take. The owner's or an account's: a task for its own computer only, never a+ * task for workers, even one of its own runs (only a worker of its pool takes that, and only the server reads it).*/export function getTask(principal: Principal, id: string): TaskRow | null {if (typeof id !== "string" || !/^[A-Za-z0-9_-]{16}$/.test(id)) return null;@@ -163,6 +164,15 @@ export function getTask(principal: Principal, id: string): TaskRow | null {const t = rdb().prepare("SELECT * FROM relay_tasks WHERE id = ? AND pools IS NOT NULL").get(id) as TaskRow | undefined;return t && poolsOf(t).includes(principal.slice(5)) ? t : null;}+ return (rdb().prepare("SELECT * FROM relay_tasks WHERE id = ? AND principal = ? AND pools IS NULL").get(id, principal) as TaskRow | undefined) ?? null;+}++/**+ * A task of one of this principal's runs, wherever it runs (its own computer, or the workers): the server's own reads as+ * the run's principal (a poll, a cancel, a result). Never what a route's caller reaches (that is getTask).+ */+export function ownTask(principal: Principal, id: string): TaskRow | null {+ if (isPool(principal) || typeof id !== "string" || !/^[A-Za-z0-9_-]{16}$/.test(id)) return null;return (rdb().prepare("SELECT * FROM relay_tasks WHERE id = ? AND principal = ?").get(id, principal) as TaskRow | undefined) ?? null;}@@ -293,6 +303,8 @@ export interface NewTask {made?: string;/** The run's LoRAs (for the words of a refusal). */loras?: { file: string; url?: string }[];+ /** How many results its workflow says one job makes (an owner's job keeps no more than that, and at least 16). */+ outputs?: number;/** For workers (pool.ts): the pools that may take it, and what they need to. */pool?: { pools: string[]; account?: string; rankAt: number; lane: string; needs: unknown; estMs?: number; notAfter?: number; onlyWorker?: string };}@@ -320,7 +332,7 @@ export function createTask(t: NewTask): { id: string; promptId: string } {t.metaBatch ? 1 : 0,t.preview ? 1 : 0,t.workflowId ?? null,- JSON.stringify({ made: t.made, loras: t.loras ?? [] }),+ JSON.stringify({ made: t.made, loras: t.loras ?? [], ...(t.outputs && { outputs: t.outputs }) }),now,now,pool?.account ?? null,@@ -339,6 +351,10 @@ export function createTask(t: NewTask): { id: string; promptId: string } {return { id, promptId };}+/** The names of the inputs a principal staged that no task has taken yet (its next task's files). */+export const freeInputs = (principal: Principal): string[] =>+ (rdb().prepare("SELECT name FROM relay_inputs WHERE principal = ? AND task_id IS NULL").all(principal) as { name: string }[]).map((r) => r.name);+export const inputsOf = (taskId: string) => rdb().prepare("SELECT * FROM relay_inputs WHERE task_id = ? ORDER BY n").all(taskId) as InputRow[];// ---------------------------------------------------------------------------@@ -456,7 +472,7 @@ export function beat(principal: Principal, b: BeatInput, now = Date.now()): Beatif (t?.device === b.device) setTask(t.id, { stop: 0 });}const stops = (- d.prepare("SELECT id, prompt_id, prefix FROM relay_tasks WHERE principal = ? AND device = ? AND stop = 1").all(principal, b.device) as { id: string; prompt_id: string; prefix: string | null }[]+ d.prepare("SELECT id, prompt_id, prefix FROM relay_tasks WHERE principal = ? AND pools IS NULL AND device = ? AND stop = 1").all(principal, b.device) as { id: string; prompt_id: string; prefix: string | null }[]).map((s) => ({ task: s.id, promptId: s.prompt_id, ...(s.prefix && { prefix: s.prefix }) }));const waiting = (d.prepare("SELECT COUNT(*) AS n FROM relay_tasks WHERE principal = ? AND pools IS NULL AND state = 'waiting'").get(principal) as { n: number }).n;return { runner: free, heldElsewhere: !free && elsewhere, waiting, stops };@@ -789,7 +805,7 @@ export function release(t: TaskRow): void {* ComfyUI at the computer's next beat.*/export function requestStop(principal: Principal, id: string): void {- const t = getTask(principal, id);+ const t = ownTask(principal, id);if (!t || !(ACTIVE_STATES as readonly string[]).includes(t.state)) return;endTask(t.id, "canceled", { error: "Stopped" });}@@ -888,7 +904,7 @@ export const setPoolClocks = (fn: (t: TaskRow, now: number) => TaskRow) => (pool/** The file of a received output, for the principal whose task it is (anyone else: null). */export function receivedFile(principal: Principal, taskId: string, n: number): { path: string; contentType?: string } | null {- const t = getTask(principal, taskId);+ const t = ownTask(principal, taskId);if (!t) return null;const r = json<Received[]>(t.received_json, []).find((x) => x.n === n);if (!r?.done) return null;@@ -899,6 +915,6 @@ export function receivedFile(principal: Principal, taskId: string, n: number): {export const wantedOf = (t: TaskRow) => json<WantedFile[]>(t.wanted_json, []);export const receivedOf = (t: TaskRow) => json<Received[]>(t.received_json, []);export const resultOf = <T,>(t: TaskRow) => json<T[]>(t.result_json, []);-export const extraOf = (t: TaskRow) => json<{ made?: string; loras?: { file: string; url?: string }[]; budget?: number }>(t.extra_json, {});+export const extraOf = (t: { extra_json?: string | null }) => json<{ made?: string; loras?: { file: string; url?: string }[]; budget?: number; outputs?: number }>(t.extra_json ?? null, {});export const refusalOf = (t: TaskRow) => json<{ status: number; body: unknown } | null>(t.refusal_json, null);export const inputKinds = (t: TaskRow) => (rdb().prepare("SELECT content_type FROM relay_inputs WHERE task_id = ?").all(t.id) as { content_type: string }[]).map((r) => r.content_type);diff --git a/src/server/generations.ts b/src/server/generations.tsindex 5b0345b9..d4dcbef5 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -98,6 +98,7 @@ import { engineMode, getSetting, withCandidates, withoutCandidates } from "./setimport { blockedForAccounts, discardBody, fetchRemoteToFile, RemoteFetchError } from "./remote-fetch";import { accountSend } from "./account-send";import { stamped, stampOf, withRunStamp } from "./run-stamp";+import { POOL_WORDS, RELAY_WORDS } from "@/lib/relay";import { placeInLine, poolWaitMs, runOnPool } from "./hosted";import { sweepBilling } from "./billing-outbox";import { inDemoScope } from "./demo-scope";@@ -152,6 +153,9 @@ export function toGeneration(r: Row): Generation {const stored = JSON.parse(r.request_json) as GenerationRequest;// The billing hold is the server's: never sent to a browser or a script.const { hold, ...request } = 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.+ const pool = stored.place === "pool";const checking = r.stage === "checking";const model = getModel(r.model_id);const ar = request.params?.aspectRatio ?? model?.defaults?.aspectRatio;@@ -176,12 +180,12 @@ export function toGeneration(r: Row): Generation {kind: r.kind,status: r.status,progress: r.progress,- message: r.message,+ message: pool ? poolMessage(r) : r.message,prompt: r.prompt,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: r.error,+ error: pool ? poolError(r.id, r.error) : r.error,costUsd: r.cost_usd,favorite: !!r.favorite,createdAt: r.created_at,@@ -196,7 +200,7 @@ export function toGeneration(r: Row): Generation {folderId: lib.folder_id ?? null,pinnedAt: r.pinned_at ?? null,review: isReviewStatus(r.review) ? r.review : null,- ...(r.status === "failed" && r.fix_json && { fix: parseFix(r.fix_json) }),+ ...(r.status === "failed" && r.fix_json && !pool && { fix: parseFix(r.fix_json) }),// Failed or stopped before a paid provider took the job (a refused key, an empty balance): nothing was billed....((r.status === "failed" || r.status === "canceled") && !r.external_id && (r.provider === "fal" || r.provider === "replicate") && { notBilled: true as const }),// On this install's GPUs (hosted runs): what it cost, or that it cost nothing.@@ -209,6 +213,39 @@ export function toGeneration(r: Row): Generation {};}+/** A pool row's words while it goes: in line, or working on it. */+function poolMessage(r: Pick<Row, "status" | "message">): string | null {+ if (r.status === "queued") return POOL_WORDS.inLine;+ if (r.status === "running") return POOL_WORDS.working;+ return 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.+ */+function poolError(id: string, error: string | null): 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;+}++const PLAIN_POOL_ERRORS = (() => {+ let set: Set<string> | undefined;+ return () =>+ (set ??= new Set<string>([+ ...Object.values(ACCOUNT_MESSAGES),+ RELAY_WORDS.stopped,+ POOL_WORDS.failed,+ BLOCKED_CARD_MESSAGE,+ NO_SUBJECT_MESSAGE,+ WATERMARK_COPY.rejected,+ WATERMARK_COPY.scanFailed,+ ]));+})();+/** A pool row's place in line, as the Generation field (none once it has started). */function poolQueue(id: string): { queue: { place: number; etaSeconds: number | null } } | Record<string, never> {const q = placeInLine(id);@@ -2169,9 +2206,16 @@ async function pollOne(r: Row): Promise<void> {recordSubmission(r.id, res.sentAt);run = { submitted_at: res.sentAt, started_at: null };}+ // A job for the workers keeps its task's own clocks (its wait limit until a worker first takes it): back in line+ // after an attempt, its next attempt gets its own running time, and no wait limit of the runner's ends it.+ const ownClocks = !!res && (res.state === "queued" || res.state === "running") && !!res.ownClocks;+ if (ownClocks && res?.state === "queued" && run.started_at) {+ db().prepare("UPDATE generation_runs SET started_at = NULL WHERE id = ?").run(r.id);+ run = { ...run, started_at: null };+ }// A job that has just left the queue gets its full running time from now.const startsNow = res?.state === "running" && !run.started_at;- const overdue = run.started_at ? now - run.started_at > TIMEOUT_MS : !startsNow && now - run.submitted_at > queueMs;+ const overdue = run.started_at ? now - run.started_at > TIMEOUT_MS : !ownClocks && !startsNow && now - run.submitted_at > queueMs;if (overdue) {// Stop the provider's job too, so it doesn't keep rendering (or billing) for nothing.await adapterFor(r.provider, account)@@ -2201,7 +2245,8 @@ async function pollOne(r: Row): Promise<void> {if (res.state === "failed") {// What the GPU was missing (a model, a node class): the tile offers "Fix it", and the GPU's check counts as stale.update(r.id, { status: "failed", error: res.error, completed_at: Date.now(), message: null, ...(res.fix && { fix_json: JSON.stringify(res.fix) }) });- if (res.fix) markStale(account ? `acct:${account}` : "install");+ // (A run on this install's GPUs says nothing about the account's own GPU.)+ if (res.fix && !onPool) markStale(account ? `acct:${account}` : "install");return;}// The Watermark Remover gave the original back (no clean repair was possible): no new result, the run says what to try.diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.tsindex 75aef48f..61d9cf38 100644--- a/src/server/hosted-run.ts+++ b/src/server/hosted-run.ts@@ -21,7 +21,7 @@ import {type RunFacts,} from "./billing";import { outputKind, previewGeneration } from "./generations";-import { HOSTED_WORDS, inputCounts, poolAllows, poolReady, queueFacts, runFacts, runOnPool } from "./hosted";+import { HOSTED_WORDS, inputCounts, poolAllows, poolReady, poolTakes, poolTakesFiles, queueFacts, runFacts, runOnPool } from "./hosted";import { hostedRunsOn } from "./hosted-switch";import { checkRun, moderationConfigured } from "./moderation";import type { RunStamp } from "./run-stamp";@@ -100,9 +100,12 @@ export async function decidePlace(account: Account, req: GenerationRequest, wishconst 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);+ // 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);- if ((inputs.image && !p.uploads.image) || (inputs.video && !p.uploads.video) || (inputs.audio && !p.uploads.audio)) return notHere(HOSTED_WORDS.inputs);+ 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);return { kind: "pool", planned, policy: p };}@@ -178,7 +181,7 @@ export async function reservePool(account: Account, req: GenerationRequest, planrequestId: nanoid(16),account: accountFacts(account),run: runFacts(req, planned, kind),- queue: queueFacts(account.id),+ queue: queueFacts(account.id, planned.route.endpoint),shown: shown ?? { amount: 0, priceVersion: "" },});if (!a) return { ok: true, stamp: base };@@ -208,7 +211,8 @@ export async function poolQuote(account: Account | null, asked: GenerationRequesif (planned.route.provider !== "comfyui") return null;if (account && wish !== "pool" && accountGpu(account.id) && (await ownGpuOnline(account.id))) return null;if (p && (!p.hosted || !poolAllows(p, planned.model.id, req.presetId))) return null;+ if (!poolTakes(planned.route.endpoint)) return null;const kind = outputKind(planned.op, planned.model);- const q = await billingQuote(account ? accountFacts(account) : null, runFacts(req, planned, kind), queueFacts(account?.id ?? null));+ const q = await billingQuote(account ? accountFacts(account) : null, runFacts(req, planned, kind), queueFacts(account?.id ?? null, planned.route.endpoint));return { planned, quote: q };}diff --git a/src/server/hosted.ts b/src/server/hosted.tsindex 043fe2fd..36683e2d 100644--- a/src/server/hosted.ts+++ b/src/server/hosted.ts@@ -1,12 +1,13 @@import "server-only";import { getModel } from "@/lib/catalog";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 { hostedRunsOn } from "./hosted-switch";-import { onInstallComfy } from "./providers/comfyui";+import { installComfyLocal, onInstallComfy, workerFor, workersTake } from "./providers/comfyui";import { getSetting, withCandidates } from "./settings";import { runAsTenant } from "./tenant";-import type { Policy, QueueFacts, RunFacts } from "./billing";/*** Hosted runs (FUOBE_HOSTED_RUNS=1; docs/public-signup.md "Hosted runs"): an account with no GPU of its own may run on@@ -20,19 +21,53 @@ import type { Policy, QueueFacts, RunFacts } from "./billing";* when a billing service is set (billing.ts), free otherwise;* 4. otherwise today's answer ("Connect your GPU", "Add your key").*- * This install's GPUs are its own ComfyUI server (Settings → ComfyUI address). An install whose ComfyUI is on the+ * This install's GPUs are its workers (Settings: ComfyUI runs on "workers", docs/gpu-workers.md): each job of the run is+ * a task for them, in one line with every other, and nothing reaches a ComfyUI address from here. Otherwise its own+ * ComfyUI server (Settings → ComfyUI address), only when that is on this machine. An install whose ComfyUI is on the* owner's computer (a browser tab) doesn't offer hosted runs: that computer is the owner's alone.+ *+ * Runs here need someone to answer for them: a billing service (billing.ts), whose policy then says who may run what;+ * or FUOBE_HOSTED_FREE=1, which says this install's runs are free for every account (within its own limits). With+ * neither, hosted runs stay closed even when switched on.*/export const hostedRuns = hostedRunsOn;-/** Hosted runs are on and this install has a ComfyUI server they can use. */+/** FUOBE_HOSTED_FREE=1: with no billing service, runs on this install's GPUs are free for accounts (within its limits). */+export const hostedFree = (): boolean => process.env.FUOBE_HOSTED_FREE === "1";++/** This install's GPUs are its workers (Settings: ComfyUI runs on "workers"). */+export const poolOnWorkers = (): boolean => getSetting("comfyWhere") === "workers";++/**+ * Hosted runs are on, something answers for them (a billing service, or FUOBE_HOSTED_FREE=1), and this install has GPUs+ * for them: a worker the owner added and allowed a lane (paused or not: a paused worker means the run waits in line),+ * or its own ComfyUI server on this machine.+ */export function poolReady(): boolean {if (!hostedRunsOn()) return false;- if (getSetting("comfyWhere") === "computer") return false;- return !!getSetting("comfyUrl").trim();+ if (!billingConfigured() && !hostedFree()) return false;+ const where = getSetting("comfyWhere");+ if (where === "computer") return false;+ return where === "workers" ? workersAllowed(null) : installComfyLocal();}+/**+ * 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.+ */+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));+}++/** May a run on this install's GPUs send them this kind of file (the workers take only the kinds the install allows)? */+export const poolTakesFiles = (kind: "image" | "video" | "audio"): boolean => !poolOnWorkers() || workersTake(kind);+/*** Run `fn` as an account's run on this install's GPUs: as the account (its own files and runs only), on this install's* ComfyUI server, the open engine, no demo outputs.@@ -102,8 +137,12 @@ 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 line on this install's GPUs right now, for a quote or a reserve (QueueFacts). */-export function queueFacts(accountId: string | null): QueueFacts {+/**+ * 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);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();@@ -127,6 +166,9 @@ export function queueFacts(accountId: string | null): QueueFacts {/** A waiting row's place in line on this install's GPUs (1: next), and the wait, about. Null when it isn't waiting there. */export function placeInLine(generationId: string): { place: number; etaSeconds: number | null } | null {+ // On the workers: its task's place in their line (back in line after an attempt, the same place).+ const task = queueOfGeneration(generationId);+ if (task || poolOnWorkers()) return task;const d = db();const row = d.prepare(`SELECT g.created_at FROM generations g WHERE g.id = ? AND ${POOL_ROWS} AND ${WAITING}`).get(generationId) as { created_at: number } | undefined;if (!row) return null;@@ -138,10 +180,11 @@ export function placeInLine(generationId: string): { place: number; etaSeconds:/** The facts the billing service prices a run by (from a planned request: previewGeneration's answer). */export function runFacts(req: GenerationRequest,- p: { model: { id: string; kind: string; engine: "open" | "cloud" }; op: string; jobs: number; outputs: number; providerId: string; costUsd: number | null; loras: { applied: unknown[] } },+ p: { model: { id: string; kind: string; engine: "open" | "cloud" }; op: string; jobs: number; outputs: number; providerId: string; costUsd: number | null; loras: { applied: unknown[] }; route?: { endpoint?: string } },kind: RunFacts["kind"],): RunFacts {const model = getModel(p.model.id);+ const endpoint = p.route?.endpoint;return {place: "pool",model: p.model.id,@@ -159,7 +202,7 @@ export function runFacts(fps: req.params?.fps ?? null,loras: p.loras.applied.length,inputs: inputCounts(req),- lane: POOL_LANE,+ lane: poolOnWorkers() && endpoint && !endpoint.includes("{") ? poolLane(endpoint) : POOL_LANE,providerUsd: p.costUsd,};}diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex 8137c6da..d86dbeea 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -81,23 +81,27 @@ import { probeAvi } from "../avi-probe";import { probeWebm } from "../webm-probe";import { adoptFile, contentTypeFor, readRef, saveFile, scratchDir } from "../storage";import { CONNECT_GPU_MESSAGE } from "@/lib/guest-access";+import { addressKind } from "@/lib/page-place";+import { graphProblem } from "@/lib/local-comfy";+import { runStamp } from "../run-stamp";import { discardBody, fetchPublic, RemoteFetchError } from "../remote-fetch";import { zipToFile } from "../zip";-import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "../account-files";+import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskFloorBytes, diskFreeBytes, diskHasRoom, filesFullMessage } from "../account-files";import { accountSend } from "../account-send";import { outsideTenant, runAsTenant, tenantAccount } from "../tenant";import { ask, checkReach, reachSync, sharedCheck, type Reach } from "./reach";import { ProviderError, type PollResult, type ProviderAdapter, type RemoteOutput } from "./types";import { isOutOfMemory } from "@/lib/gpu/fix-codes";-import { makingWords, queueWords, RELAY_TIMES, RELAY_WORDS, savingWords, sendingWords, tabFailureWords, type HistoryEntryLike, type TabFailure, type WantedFile } from "@/lib/relay";+import { makingWords, POOL_WORDS, queueWords, RELAY_TIMES, RELAY_WORDS, savingWords, sendingWords, tabFailureWords, type ComputerFacts, type HistoryEntryLike, type TabFailure, type WantedFile } from "@/lib/relay";import type { GenerationFix } from "@/lib/catalog/types";import {checkClocks,createTask,extraOf,- getTask,inputKinds,+ ownTask,receivedFile,+ freeInputs,receivedOf,refusalOf,requestStop,@@ -109,7 +113,7 @@ import {type Principal,type TaskRow,} from "../computer/tasks";-import { OWNER_BOOST_MS, poolFields, poolWaitMs, poolWaitWords } from "../computer/pool";+import { OWNER_BOOST_MS, poolFacts, poolFields, poolLane, poolWaitMs, poolWaitWords } from "../computer/pool";export const WORKFLOW_DIR = path.join(process.cwd(), "workflows", "comfyui");@@ -177,14 +181,38 @@ export const outsideOwnGpu = <T,>(fn: () => T): T => ownGpuStore.exit(fn);export function computerScope(): Principal | undefined {const own = ownGpu();if (own) return own.kind === "computer" ? own.principal : undefined;+ // An account's run on this install's workers: its jobs are tasks for the workers, as the account's own.+ if (poolScope.getStore()) {+ const account = tenantAccount();+ return account ? `acct:${account}` : undefined;+ }if (serverScope.getStore()) return undefined;const where = getSetting("comfyWhere");// Workers (docs/gpu-workers.md) take the owner's jobs the way the owner's own computer would: staged here, run there.return where === "computer" || where === "workers" ? "owner" : undefined;}-/** The owner's ComfyUI jobs go to the workers (Settings: ComfyUI runs on "workers"), not to one computer. */-const onWorkers = (computer: Principal | undefined) => computer === "owner" && !ownGpu() && getSetting("comfyWhere") === "workers";+/**+ * The jobs of this principal go to the workers: the owner's while Settings says ComfyUI runs on "workers", and an+ * account's run on this install's GPUs then (never one computer's tab).+ */+const onWorkers = (computer: Principal | undefined) => {+ if (!computer || ownGpu()) return false;+ if (computer === "owner") return getSetting("comfyWhere") === "workers";+ return !!poolScope.getStore() && computer.startsWith("acct:");+};++/**+ * What a computer's jobs are shaped by (its VRAM, RAM, device, LoRA files): what its tab last said. An account's run on+ * the workers reads theirs instead (those allowed the workflow's lane), never the account's own computer.+ */+function factsOf(computer: Principal, endpoint?: string): ComputerFacts | null {+ if (computer !== "owner" && onWorkers(computer)) return poolFacts(endpoint && !endpoint.includes("{") ? poolLane(endpoint) : null);+ return runnerFacts(computer);+}++/** Inside a run on this install's GPUs (hosted runs): the account's jobs are tasks for the workers. */+export const onPoolWorkers = (): boolean => !!poolScope.getStore();/*** FUOBE_POOL_MEDIA_INPUTS: what a job for workers may send them ("image" unless set; "image,video,audio" for all).@@ -192,6 +220,9 @@ const onWorkers = (computer: Principal | undefined) => computer === "owner" && !*/const poolMedia = () => new Set((process.env.FUOBE_POOL_MEDIA_INPUTS ?? "image").split(",").map((s) => s.trim()).filter(Boolean));+/** May a job for workers send them files of this kind ("image", "video", "audio")? */+export const workersTake = (kind: "image" | "video" | "audio"): boolean => poolMedia().has(kind);+export async function forWorkers(data: Buffer, contentType: string, name: string): Promise<{ data: Buffer; contentType: string; name: string }> {const kind = contentType.split("/")[0];if (!poolMedia().has(kind)) throw new ProviderError(kind === "video" ? "The shared GPUs don't take clips yet." : kind === "audio" ? "The shared GPUs don't take sound yet." : "The shared GPUs don't take this kind of file.");@@ -201,14 +232,55 @@ export async function forWorkers(data: Buffer, contentType: string, name: stringreturn { data: png, contentType: "image/png", name: name.replace(/\.[^.]*$/, "") + ".png" };}-/** A run the owner sent to the studio's own ComfyUI before Settings moved ComfyUI to the owner's computer. */-const serverScope = new AsyncLocalStorage<true>();+/**+ * A run on this install's own ComfyUI server (an account's run on this install's GPUs, or one the owner sent there+ * before Settings moved ComfyUI): the names of the files this run uploaded there, so its graph is checked to read+ * only those (never another run's leftovers in the same input folder).+ */+const serverScope = new AsyncLocalStorage<{ uploads: Set<string> }>();++/** An account's run on this install's workers (hosted runs while Settings says ComfyUI runs on "workers"). */+const poolScope = new AsyncLocalStorage<true>();++/**+ * Run `fn` on this install's own ComfyUI server, whatever Settings says now: a run sent there before ComfyUI moved (to a+ * computer, or to the workers) is followed and stopped there.+ */+const onInstallServer = <T,>(fn: () => T): T => poolScope.exit(() => serverScope.run({ uploads: new Set() }, fn));++/**+ * Run `fn` as a run on this install's GPUs (hosted runs, src/server/hosted.ts), never an account's own GPU and never a+ * computer's tab. While Settings says ComfyUI runs on "workers", each job is a task for the workers that belongs to the+ * account (staged here, run there, as the owner's jobs are). Otherwise the install's own ComfyUI server, which then must+ * be on this machine (installComfyLocal).+ */+export const onInstallComfy = <T,>(fn: () => T): T => outsideOwnGpu(() => (getSetting("comfyWhere") === "workers" ? serverScope.exit(() => poolScope.run(true, fn)) : onInstallServer(fn)));++/**+ * The install's own ComfyUI address is on this machine (loopback). Runs of accounts on this install's GPUs go straight+ * to it only then: an address elsewhere would send accounts' files and prompts over a network to a ComfyUI nothing+ * cleans, and its errors would name it.+ */+export function installComfyLocal(worker: ComfyWorker = "main"): boolean {+ const url = getSetting(worker === "isolated" ? "comfyIsolatedUrl" : "comfyUrl").trim();+ return !!url && addressKind(url) === "loopback";+}++/** Said when a run on this install's GPUs can't go where it was planned (its row's own words then say it plainly). */+export const POOL_NOT_LOCAL = "This install's ComfyUI address isn't on this machine, so runs of accounts don't go to it.";/**- * Run `fn` on this install's own ComfyUI server (Settings → ComfyUI address), never an account's own GPU and never a- * computer's tab: an account's run on this install's GPUs (hosted runs, src/server/hosted.ts).+ * Every VideoHelperSuite save node of a graph for the workers saves no metadata: the prompt and the machine's own clock never+ * travel inside a result. Returns the graph changed in place.*/-export const onInstallComfy = <T,>(fn: () => T): T => outsideOwnGpu(() => serverScope.run(true, fn));+export function withoutSaveMetadata(wf: ComfyWorkflow): ComfyWorkflow {+ for (const node of Object.values(wf)) {+ const cls = typeof node?.class_type === "string" ? node.class_type : "";+ if (!node?.inputs || !cls.startsWith("VHS_")) continue;+ if (cls === "VHS_VideoCombine" || "save_metadata" in node.inputs) node.inputs.save_metadata = false;+ }+ return wf;+}/*** Whose computer a run sent there belongs to, whatever ComfyUI's place is now: the account's (as its tenant), or the@@ -280,7 +352,8 @@ export const PROMPT_ID = /^[\w-]{1,64}$/;function baseUrl(worker: ComfyWorker = "main"): string {const own = ownGpu();if (own) return own.kind === "computer" ? "" : own.url;- if (computerScope()) return "";+ // A run on this install's workers never has an address of its own (its jobs are tasks for the workers).+ if (computerScope() || onPoolWorkers()) return "";return getSetting(worker === "isolated" ? "comfyIsolatedUrl" : "comfyUrl").replace(/\/+$/, "");}@@ -306,8 +379,8 @@ function authHeaders(worker: ComfyWorker = "main"): Record<string, string> {async function comfyFetch(p: string, init: RequestInit = {}, worker: ComfyWorker = "main"): Promise<Response> {// A ComfyUI on someone's own computer is never called from here: not the install's, not a link (every caller in that- // scope goes through its task instead; this is the last guard).- if (computerScope()) throw new ProviderError(ON_COMPUTER_ONLY);+ // scope goes through its task instead; this is the last guard). Nor is any from a run on this install's workers.+ if (computerScope() || onPoolWorkers()) throw new ProviderError(ON_COMPUTER_ONLY);const base = baseUrl(worker);if (ownGpu()) {// A visitor without a GPU of its own (a price check): nothing to reach, and never the install's.@@ -396,7 +469,8 @@ function setSocket(worker: ComfyWorker, s: ComfySocket | undefined) {function ensureSocket(worker: ComfyWorker = "main"): { clientId: string; progress: Map<string, Progress> } {// An account's own ComfyUI: no socket (the install's stays as it is); its progress comes from polling, or from its tab.- if (ownGpu() || computerScope()) return { clientId: "fuobe-account", progress: new Map() };+ // Nor for a run on this install's workers (its jobs are tasks for them).+ if (ownGpu() || computerScope() || onPoolWorkers()) return { clientId: "fuobe-account", progress: new Map() };const url = baseUrl(worker);const cur = socketOf(worker);if (cur && cur.url === url && cur.ws.readyState <= 1) return cur;@@ -709,7 +783,7 @@ async function checkComfy(url: string): Promise<boolean> {export async function probeComfy(force = false): Promise<boolean> {// An account's own ComfyUI is taken as there: its run says so when it isn't (the install's state stays its own). So is// one on a computer: its runs wait for a tab there.- if (ownGpu() || computerScope()) return true;+ if (ownGpu() || computerScope() || onPoolWorkers()) return true;const url = baseUrl();const cur = globalThis.__fuobeComfyReach;if (!force && cur && cur.url === url && Date.now() - cur.at < 10_000) return cur.ok;@@ -743,7 +817,7 @@ declare global {export async function comfyDevice(worker: ComfyWorker = "main"): Promise<string | undefined> {// On someone's computer: what its Fuobe tab last said ("cuda:0 NVIDIA …").const computer = computerScope();- if (computer) return /^[a-z]+/i.exec(runnerFacts(computer)?.device ?? "")?.[0].toLowerCase();+ if (computer) return /^[a-z]+/i.exec(factsOf(computer)?.device ?? "")?.[0].toLowerCase();const url = baseUrl(worker);if (!url) return undefined;const cache = (globalThis.__fuobeComfyDevice ??= new Map());@@ -862,7 +936,7 @@ export async function comfyReuseModels(worker: ComfyWorker = "main", maxAgeMs =/** The connected ComfyUI's RAM in bytes, as the last reachability check read it (whole-clip tools' budget). */export function comfyRam(): number | undefined {const computer = computerScope();- if (computer) return runnerFacts(computer)?.ramBytes;+ if (computer) return factsOf(computer)?.ramBytes;if (ownGpu()) return undefined;const cur = globalThis.__fuobeComfyReach;return cur?.ok && cur.url === baseUrl() ? cur.ram : undefined;@@ -874,7 +948,7 @@ export function comfyRam(): number | undefined {* the background to say for sure.*/export function probeComfySync(timeoutMs = 1500): boolean {- if (ownGpu() || computerScope()) return true;+ if (ownGpu() || computerScope() || onPoolWorkers()) return true;const url = baseUrl();const { reach, sure } = reachSync(url, `${url}/system_stats`, timeoutMs, authHeaders());globalThis.__fuobeComfyReach = reach;@@ -1223,8 +1297,10 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,if (audio2) delete extra.audio2;// Media refs in params.extra (e.g. a background stem for "audio2") are uploaded like regular inputs.+ const sentHere = new Set<string>();for (const [k, v] of Object.entries(extra)) {if (!isMediaRef(v)) continue;+ sentHere.add(k);// An account's file is read and sent when it may send (account-send.ts), as the run's other inputs are.const send = async () => {const f = await readRef(v);@@ -1801,6 +1877,11 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,reviewInputs = { video: values.video, image: values.image, prefix: values.filenamePrefix };}}+ // An account's run on this install's GPUs never names a file there itself: a file input in params.extra is one this+ // run sent (a media ref, uploaded above), else it is dropped (it could name another run's file in the same folder).+ if (tenantAccount() && (poolScope.getStore() || serverScope.getStore())) {+ for (const k of mediaKeys(manifest, workflow)) if (k in extra && !sentHere.has(k)) delete extra[k];+ }for (const [k, v] of Object.entries(extra)) values[k as BindingKey] = v;// SeedVR2's `scale` multiplies the picture before one diffusion pass over all of it, and its graph is made for up to// limits.maxWidth × maxHeight: the multiplier comes down to fit the picture (a 3000 × 2000 photo at the template's 4x@@ -2156,6 +2237,16 @@ async function uploadTo(worker: ComfyWorker, data: Buffer, contentType: string,rememberSent(staged, sent.data, sent.contentType, sent.name);return staged;}+ // A run on this install's workers with no account behind it (a guest's price check) never sends anything.+ if (onPoolWorkers()) throw new ProviderError(ON_COMPUTER_ONLY);+ // An account's run on this install's own ComfyUI server: only one on this machine, and its pictures made again from+ // their pixels (no EXIF, no GPS), as for the workers.+ const server = serverScope.getStore();+ const account = server ? tenantAccount() : undefined;+ if (account) {+ if (!installComfyLocal(worker)) throw new ProviderError(POOL_NOT_LOCAL);+ if (contentType.startsWith("image/")) ({ data, contentType, name } = await forWorkers(data, contentType, name));+ }const form = new FormData();const ext = name.includes(".") ? name.split(".").pop() : contentType.split("/")[1];form.append("image", new Blob([new Uint8Array(data)], { type: contentType }), `fuobe_${nanoid(8)}.${ext}`);@@ -2176,6 +2267,7 @@ async function uploadTo(worker: ComfyWorker, data: Buffer, contentType: string,const uploaded = j.subfolder ? `${j.subfolder}/${j.name}` : j.name;// Remember a clip's / track's header facts (length, size, fps, audio) for prepareWorkflow.rememberSent(uploaded, data, contentType, name);+ server?.uploads.add(uploaded);return uploaded;}@@ -2247,6 +2339,8 @@ export function onComputer<T>(principal: Principal, fn: () => T): T {/** The most one result may weigh when it comes from a computer: an account's 1 GB (less when its files are fuller); the owner's 8 GB. */const OWNER_RESULT_BYTES = 8 * 2 ** 30;+/** The free space the owner's results never use (less than accounts keep free: the owner's own work goes on longer). */+const OWNER_DISK_FLOOR_BYTES = 2 * 2 ** 30;/** A text result (a transcript, captions). */const TEXT_RESULT_BYTES = 8 * 2 ** 20;@@ -2255,7 +2349,7 @@ const TEXT_RESULT_BYTES = 8 * 2 ** 20;* own run would collect them (collectOutputs), each one a file the tab uploads under its number. An account keeps up to* 16 results and 1,800 EXR frames, never more than its files have room for. Call it as the task's principal (onComputer).*/-export function planRelayOutputs(t: Pick<TaskRow, "id" | "workflow_id" | "meta_batch" | "prefix">, entries: HistoryEntryLike[], passes: boolean): FinishedPlan {+export function planRelayOutputs(t: Pick<TaskRow, "id" | "workflow_id" | "meta_batch" | "prefix"> & Partial<Pick<TaskRow, "extra_json" | "pools">>, entries: HistoryEntryLike[], passes: boolean): FinishedPlan {let manifest: ManifestWorkflow | undefined;try {manifest = t.workflow_id ? getWorkflow(t.workflow_id).manifest : undefined;@@ -2280,8 +2374,20 @@ export function planRelayOutputs(t: Pick<TaskRow, "id" | "workflow_id" | "meta_bif (frames.length > ACCOUNT_LIMITS.framesPerJob) return { error: `Your ComfyUI made ${frames.length} EXR frames. A run on your GPU keeps up to ${ACCOUNT_LIMITS.framesPerJob}: export a shorter clip.` };outputs = [...outputs.filter((o) => o.meta?.role !== "frames").slice(0, ACCOUNT_LIMITS.outputsPerJob), ...frames];if (!diskHasRoom()) return { error: ACCOUNT_MESSAGES.diskLow };- budget = accountTotalBytes(account) - accountUsage(account).total;+ budget = Math.min(accountTotalBytes(account) - accountUsage(account).total, diskFreeBytes() - diskFloorBytes());if (budget <= 0) return { error: filesFullMessage(account) };+ } else {+ // The owner's job: never past the disk's free floor. On the workers also never more results than its workflow says+ // it makes (at least 16), and EXR frames up to the same number as an account's: a worker token that reports a+ // made-up history can't fill the server's disk. (The owner's own computer keeps every result, as before.)+ if (t.pools) {+ const frames = outputs.filter((o) => o.meta?.role === "frames");+ if (frames.length > ACCOUNT_LIMITS.framesPerJob) return { error: `ComfyUI made ${frames.length} EXR frames. A run keeps up to ${ACCOUNT_LIMITS.framesPerJob}: export a shorter clip.` };+ const declared = extraOf(t).outputs ?? 0;+ outputs = [...outputs.filter((o) => o.meta?.role !== "frames").slice(0, Math.max(ACCOUNT_LIMITS.outputsPerJob, declared)), ...frames];+ }+ budget = diskFreeBytes() - Math.min(diskFloorBytes(), OWNER_DISK_FLOOR_BYTES);+ if (budget <= 0) return { error: "There's no room on this server's disk to keep this result. Free some space, then press Retry." };}const wanted: WantedFile[] = [];outputs = outputs.map((o) => {@@ -2318,12 +2424,23 @@ function relayFailure(t: TaskRow, manifest: ManifestWorkflow | undefined): { err/** A run on someone's computer: where its task is, in the words its tile shows. */async function pollComputer(principal: Principal, meta: Record<string, unknown>, manifest: ManifestWorkflow | undefined, made: string | undefined): Promise<PollResult> {- const found = typeof meta.relay === "string" ? getTask(principal, meta.relay) : null;+ const found = typeof meta.relay === "string" ? ownTask(principal, meta.relay) : null;if (!found) return { state: "failed", error: "This run was lost. Press Retry." };const t = checkClocks(found);+ if (!t.pools) return pollTask(principal, t, meta, manifest, made);// A run on the workers: while it waits, its place in line; once a worker has it, that worker's reports (a worker that- // goes quiet gives it back to the line, pool.ts, so no "open Fuobe on your computer").- if (t.pools && t.state === "waiting") return { state: "queued", message: t.note === "resent" ? "Back in line for another GPU" : poolWaitWords(t) };+ // goes quiet gives it back to the line, pool.ts, so no "open Fuobe on your computer"). It keeps its task's clocks+ // (pool.ts): its wait limit until a worker first takes it, then each attempt's own running time; back in line after+ // an attempt (a worker paused, went quiet, restarted), it keeps its place.+ const res: PollResult = t.state === "waiting" ? { state: "queued", message: t.note === "resent" ? "Back in line for another GPU" : poolWaitWords(t) } : await pollTask(principal, t, meta, manifest, made);+ if (res.state !== "queued" && res.state !== "running") return res;+ // An account's run says only where it is: in line, or working on it (the owner's own runs keep the workers' words).+ if (!tenantAccount()) return { state: res.state, progress: res.progress, message: res.message, ownClocks: true };+ return t.state === "waiting" ? { state: "queued", message: POOL_WORDS.inLine, ownClocks: true } : { state: "running", progress: res.progress, message: POOL_WORDS.working, ownClocks: true };+}++/** Where a task is (on someone's computer, or with a worker), in the words its tile shows. */+async function pollTask(principal: Principal, t: TaskRow, meta: Record<string, unknown>, manifest: ManifestWorkflow | undefined, made: string | undefined): Promise<PollResult> {const p = taskProgress(t.id);const kind = extraOf(t).made ?? made ?? "image";const waitMs = tenantAccount() ? ACCOUNT_LIMITS.queueMs : 4 * 3_600_000;@@ -2380,7 +2497,7 @@ export const comfyProvider: ProviderAdapter = {id: "comfyui",label: "ComfyUI",isConfigured: () => {- if (ownGpu() || computerScope()) return true;+ if (ownGpu() || computerScope() || onPoolWorkers()) return true;const cur = globalThis.__fuobeComfyReach;// First check for this server: wait for the answer, so a request right after start isn't sent to demo.if (!cur || cur.url !== baseUrl()) return probeComfySync();@@ -2406,14 +2523,14 @@ export const comfyProvider: ProviderAdapter = {media: mediaInfoFor,serverRam: async () => {const computer = computerScope();- if (computer) return runnerFacts(computer)?.ramBytes;+ if (computer) return factsOf(computer, route.endpoint)?.ramBytes;return (await comfyJson<{ system?: { ram_total?: number } }>("/system_stats", worker).catch(() => undefined))?.system?.ram_total;},device: () => comfyDevice(worker),modelPath: (folder, name) => comfyModelPath(folder, name, worker),vram: async () => {const computer = computerScope();- if (computer) return runnerFacts(computer)?.vramBytes;+ if (computer) return factsOf(computer, route.endpoint)?.vramBytes;const s = await comfyJson<{ devices?: { vram_total?: unknown }[] }>("/system_stats", worker).catch(() => undefined);const v = s?.devices?.[0]?.vram_total;return typeof v === "number" && v > 0 ? v : undefined;@@ -2425,23 +2542,42 @@ export const comfyProvider: ProviderAdapter = {// On someone's computer: the job waits for their Fuobe tab, which sends exactly this graph under the prompt id minted// here. A refusal comes back in its report, and the poll explains it as below.const computer = computerScope();+ // An account's run on this install's GPUs: its graph reads only the files this run sent, checked here before it is+ // queued or sent (the workers check again; this install's own ComfyUI doesn't).+ const server = serverScope.getStore();+ const account = tenantAccount();+ if (account && (onPoolWorkers() || server)) {+ if (!computer && !installComfyLocal(worker)) throw new ProviderError(POOL_NOT_LOCAL);+ const problem = graphProblem(wf, computer ? freeInputs(computer) : [...(server?.uploads ?? [])]);+ if (problem) throw new ProviderError(problem);+ }if (computer) {const metaBatch = !!meta.metaBatch;+ const forPool = onWorkers(computer);const task = createTask({principal: computer,generationId,- graph: wf,+ graph: forPool ? withoutSaveMetadata(wf) : wf,prefix: typeof meta.prefix === "string" ? meta.prefix : undefined,metaBatch,preview: true,workflowId: manifest.id,made: model?.kind,loras: (input.loras ?? []).map((l) => ({ file: l.file, ...(l.url && { url: l.url }) })),- // The owner's jobs on the workers: the lane and files they need, ahead of everyone else's, with a wait limit.- ...(onWorkers(computer) && { pool: poolFields(manifest.id, { boostMs: OWNER_BOOST_MS, waitMs: poolWaitMs() }) }),+ outputs: Math.max(1, manifest.outputs.length) * Math.max(1, Math.round(Number(input.numOutputs) || 1)),+ ...(forPool && {+ pool:+ computer === "owner"+ ? // The owner's jobs on the workers: the lane and files they need, ahead of everyone else's, with a wait limit.+ poolFields(manifest.id, { boostMs: OWNER_BOOST_MS, waitMs: poolWaitMs() })+ : // An account's: the lane and files they need, in the order they came, with the wait set for the run.+ poolFields(manifest.id, { account: computer.slice(5), waitMs: runStamp()?.waitMs || poolWaitMs() }),+ }),});return { externalId: task.promptId, meta: { ...meta, generationId, relay: task.id }, payload: wf };}+ // A run on this install's workers with no account behind it is never sent anywhere.+ if (onPoolWorkers()) throw new ProviderError(ON_COMPUTER_ONLY);const { clientId } = ensureSocket(worker);const res = await comfyFetch("/prompt",@@ -2477,7 +2613,7 @@ export const comfyProvider: ProviderAdapter = {if (computerScope()) {// Sent to a link before the account chose this computer: that link is gone.if (ownGpu()) return { state: "failed", error: RELAY_WORDS.switched };- return serverScope.run(true, () => comfyProvider.poll({ externalId, meta, model, ...rest }));+ return onInstallServer(() => comfyProvider.poll({ externalId, meta, model, ...rest }));}const finished = async (entry: HistoryEntry) => {// A Context Loop job (Group swap, Scene edit): its clips and checkpoints under output/h3_chains go once it ends (the@@ -2549,7 +2685,7 @@ export const comfyProvider: ProviderAdapter = {if (typeof meta?.relay === "string") return requestStop(relayPrincipal(), meta.relay);if (computerScope()) {// Sent before ComfyUI moved to a computer: the owner's goes off the studio's own ComfyUI (a link is gone).- if (!ownGpu()) await serverScope.run(true, () => comfyProvider.cancel!(ctx));+ if (!ownGpu()) await onInstallServer(() => comfyProvider.cancel!(ctx));return;}const worker: ComfyWorker = meta?.worker === "isolated" ? "isolated" : "main";@@ -2609,7 +2745,7 @@ export const comfyProvider: ProviderAdapter = {export async function comfyLoraFiles(route?: ModelRoute): Promise<string[] | null> {// On someone's computer: the list its tab last sent (null: it can't say, and ComfyUI's own check has the last word).const computer = computerScope();- if (computer) return runnerFacts(computer)?.loras ?? null;+ if (computer) return factsOf(computer)?.loras ?? null;try {const res = await comfyFetch("/models/loras", {}, workerFor(route?.endpoint));if (!res.ok) discardBody(res);diff --git a/src/server/providers/types.ts b/src/server/providers/types.tsindex 3cde0f8e..259b09ed 100644--- a/src/server/providers/types.ts+++ b/src/server/providers/types.ts@@ -31,11 +31,12 @@ export interface RemoteOutput {/*** What a poll found. A job on someone's own computer (comfyui.ts) also says when it reached their ComfyUI (`sentAt`: the* queue clock starts there, not while it waited for their tab), what to say if it waits too long (`timeoutError`), and- * what was missing when it failed (`fix`: the tile's "Fix it").+ * what was missing when it failed (`fix`: the tile's "Fix it"). A job for the workers keeps its task's own clocks+ * (`ownClocks`): the runner then sets no wait limit of its own, and its running time counts from the attempt now running.*/export type PollResult =- | { state: "queued"; progress?: number; message?: string; sentAt?: number; timeoutError?: string }- | { state: "running"; progress?: number; message?: string; sentAt?: number }+ | { state: "queued"; progress?: number; message?: string; sentAt?: number; timeoutError?: string; ownClocks?: true }+ | { state: "running"; progress?: number; message?: string; sentAt?: number; ownClocks?: true }| { state: "succeeded"; outputs: RemoteOutput[]; message?: string }| { state: "failed"; error: string; fix?: GenerationFix };diff --git a/tests/billing-hook.test.ts b/tests/billing-hook.test.tsindex e48f4847..c5f40eb6 100644--- a/tests/billing-hook.test.ts+++ b/tests/billing-hook.test.ts@@ -109,17 +109,30 @@ describe("the billing hook with no service set", () => {expect(await billing.reserve({ requestId: "r", account: billing.accountFacts({ id: a, email: "[email protected]", createdAt: 1 }), run: {} as never, queue: null, shown: { amount: 0, priceVersion: "" } })).toBeNull();});- it("with hosted runs on and no billing service, a run on this install's GPUs is free, with no hold", async () => {+ it("with hosted runs on and no billing service, they stay closed unless they are free for everyone", async () => {delete process.env.FUOBE_BILLING_URL;- const r = await post(run());- expect(r.status).toBe(201);- const { items } = (await r.json()) as { items: { id: string; place?: string }[] };- expect(items[0].place).toBe("pool");- expect(holdOf(items[0].id)).toBeNull();- await until(() => statusOf(items[0].id).status !== "queued" && statusOf(items[0].id).status !== "running");- expect(statusOf(items[0].id).status).toBe("succeeded");+ const closed = await post(run());+ expect(closed.status).toBe(403);+ expect(((await closed.json()) as { code: string }).code).toBe("connect-gpu");expect(fake.calls).toEqual([]);});++ it("with hosted runs on, no billing service and FUOBE_HOSTED_FREE=1, a run on this install's GPUs is free, with no hold", async () => {+ delete process.env.FUOBE_BILLING_URL;+ process.env.FUOBE_HOSTED_FREE = "1";+ try {+ const r = await post(run());+ expect(r.status).toBe(201);+ const { items } = (await r.json()) as { items: { id: string; place?: string }[] };+ expect(items[0].place).toBe("pool");+ expect(holdOf(items[0].id)).toBeNull();+ await until(() => statusOf(items[0].id).status !== "queued" && statusOf(items[0].id).status !== "running");+ expect(statusOf(items[0].id).status).toBe("succeeded");+ expect(fake.calls).toEqual([]);+ } finally {+ delete process.env.FUOBE_HOSTED_FREE;+ }+ });});describe("the billing hook with a service", () => {diff --git a/tests/hosted-runs.test.ts b/tests/hosted-runs.test.tsindex 4099a198..a088a983 100644--- a/tests/hosted-runs.test.ts+++ b/tests/hosted-runs.test.ts@@ -42,7 +42,7 @@ beforeAll(async () => {});afterAll(async () => {globalThis.__fuobeTestDiskFree = undefined;- for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN"]) delete process.env[k];+ for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_HOSTED_FREE", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN"]) delete process.env[k];await fake.close();await comfy.close();});@@ -50,6 +50,7 @@ beforeEach(() => {resetRates();billing.resetBillingCache();delete process.env.FUOBE_HOSTED_RUNS;+ delete process.env.FUOBE_HOSTED_FREE;delete process.env.FUOBE_BILLING_URL;fake.policy = { hosted: true, pool: {}, uploads: { image: true, video: false, audio: false }, limits: { activeRuns: 7, waiting: 7, runsPerHour: 70, outputsPerRun: 2, maxMegapixels: 7, maxSeconds: 7, keepDays: 7, spaceBytes: 7 }, ttlS: 0 };});@@ -78,6 +79,17 @@ describe("hosted runs off (the default)", () => {describe("hosted runs on", () => {beforeEach(() => {process.env.FUOBE_HOSTED_RUNS = "1";+ // Free for every account here: no billing service answers for these runs unless a test sets one.+ process.env.FUOBE_HOSTED_FREE = "1";+ });++ it("stay closed with nothing to answer for them: no billing service, and not free", async () => {+ delete process.env.FUOBE_HOSTED_FREE;+ const r = await post({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" });+ expect(r.status).toBe(403);+ expect(((await r.json()) as { code: string }).code).toBe("connect-gpu");+ expect((await visitorStatus(auth.accountById(a)!)).viewer.hosted).toBeUndefined();+ expect((await upload(TINY_PNG, "image/png", "me.png")).status).toBe(403);});it("a studio run reaches the route; other tools still need the account's own GPU", async () => {diff --git a/tests/moderation-hook.test.ts b/tests/moderation-hook.test.tsindex 84c7591a..5ac90db3 100644--- a/tests/moderation-hook.test.ts+++ b/tests/moderation-hook.test.ts@@ -13,6 +13,8 @@ delete process.env.FUOBE_PASSWORD;delete process.env.FUOBE_BILLING_URL;delete process.env.FUOBE_MODERATION_URL;process.env.FUOBE_HOSTED_RUNS = "1";+// Free for every account unless a test sets a billing service: something answers for runs on this install's GPUs.+process.env.FUOBE_HOSTED_FREE = "1";globalThis.__fuobeTestDiskFree = 1e13;const probe = http.createServer();@@ -48,7 +50,7 @@ beforeAll(async () => {});afterAll(async () => {globalThis.__fuobeTestDiskFree = undefined;- for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_MODERATION_URL", "FUOBE_MODERATION_TOKEN", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN"]) delete process.env[k];+ for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_HOSTED_FREE", "FUOBE_MODERATION_URL", "FUOBE_MODERATION_TOKEN", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN"]) delete process.env[k];await mod.close();await bill.close();await comfy.close();@@ -169,6 +171,8 @@ describe("the output check", () => {const id = await started({ ...run, shown: { amount: 7, priceVersion: "v7" } });await until(() => row(id).status === "failed");expect(row(id).error).toBe("Removed by the checks. Not charged.");+ // The account reads the check's own words (a run on this install's GPUs hides only technical reasons).+ expect(getGeneration(id)!.error).toBe("Removed by the checks. Not charged.");expect(getGeneration(id)!.notCharged).toBe(true);await outbox.sweepBilling();const hold = [...bill.holds.entries()].find(([, h]) => h.reports.has(id));@@ -184,6 +188,7 @@ 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);expect(db().prepare("SELECT 1 FROM assets WHERE id = ?").get(file)).toBeUndefined();});});diff --git a/tests/pool-account-runs.test.ts b/tests/pool-account-runs.test.tsnew file mode 100644index 00000000..a14ed369--- /dev/null+++ b/tests/pool-account-runs.test.ts@@ -0,0 +1,570 @@+import crypto from "node:crypto";+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { startFakeBilling, type FakeBilling } from "./helpers/fake-billing";+import { startLocalComfy, type LocalComfy } from "./helpers/fake-local-comfy";+import { apiAs, loadRoutes, sha256, type ComputerRoutes } from "./helpers/computer-tab";+import { tempDir } from "./helpers/temp-dir";++/**+ * Account runs on this install's GPUs go through the workers' line: each job of an account's run is a task for the+ * workers that belongs to the account, never a request to a ComfyUI address. The account sees only "In line", "Working"+ * and its result; an account's own session can never take or read such a task; a task back in line keeps its place and+ * shows "In line" again; and with hosted runs off nothing changes. (The line's own rules for every job, one job per+ * worker among them: tests/worker-queue.test.ts.)+ */++vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));+vi.setConfig({ testTimeout: 60_000 });++const dir = tempDir("fuobe-pool-account-runs-");+process.env.FUOBE_DATA_DIR = dir;+// Nothing answers here: no test may reach a real ComfyUI on this machine. (Not port 9: the tests point local AI+// helpers there.)+const DEAD = "http://127.0.0.1:7";+process.env.COMFYUI_URL = DEAD;+process.env.FUOBE_PUBLIC_SIGNUP = "1";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_HOSTED_RUNS;+delete process.env.FUOBE_HOSTED_FREE;+delete process.env.FUOBE_BILLING_URL;+delete process.env.FUOBE_MODERATION_URL;+globalThis.__fuobeTestDiskFree = 1e13;++// The server's own fetch: recorded. Anything but the stand-ins answers 599 at once (no real network).+const realFetch = globalThis.fetch;+const fetched: string[] = [];+let allowed: string[] = [];+globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input instanceof Request ? input.url : input);+ fetched.push(url);+ if (allowed.some((a) => url.startsWith(a))) return realFetch(input, init);+ return new Response("not reachable in this test", { status: 599 });+}) as typeof fetch;++const auth = await import("@/server/auth");+const generationsRoute = await import("@/app/api/generations/route");+const { db } = await import("@/server/db");+const { resetRates } = await import("@/server/rate");+const { setSetting } = await import("@/server/settings");+const { getGeneration, toGeneration } = await import("@/server/generations");+const tasks = await import("@/server/computer/tasks");+const pool = await import("@/server/computer/pool");+const hosted = await import("@/server/hosted");+const billing = await import("@/server/billing");+const { listAccountRuns } = await import("@/server/account-admin");+const { loadManifest, withoutSaveMetadata, planRelayOutputs, onComputer } = await import("@/server/providers/comfyui");+const { loadIndex } = await import("@/server/gpu/index-file");+const { allLanes } = await import("@/lib/lanes");+const { ComputerRunner } = await import("@/lib/computer-runner");+const { POOL_WORDS } = await import("@/lib/relay");++const HOST = "localhost:3000";+const SITE_HEADERS = { host: HOST, "sec-fetch-site": "same-origin", origin: `http://${HOST}` };+const MIN = 60_000;+const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");++let comfy: LocalComfy;+let routes: ComputerRoutes;+let fake: FakeBilling;+let accountId = "";+let cookie = "";+let computerAccount = "";+let computerCookie = "";++beforeAll(async () => {+ comfy = await startLocalComfy({ cors: "*", steps: 2, stepMs: 10, latencyMs: 10 });+ allowed = [comfy.url];+ routes = await loadRoutes();+ fake = await startFakeBilling();+ allowed.push(fake.url);+ auth.setPassword("install password");+ accountId = auth.createAccount("[email protected]", "long enough").id;+ cookie = `${auth.SESSION_COOKIE}=${auth.createSession(accountId).value}`;+ // An account whose own GPU is "this computer": its session reaches the computer routes as acct:<id>.+ computerAccount = auth.createAccount("[email protected]", "long enough").id;+ auth.setAccountGpu(computerAccount, { mode: "computer" });+ computerCookie = `${auth.SESSION_COOKIE}=${auth.createSession(computerAccount).value}`;+});+afterAll(async () => {+ globalThis.fetch = realFetch;+ globalThis.__fuobeTestDiskFree = undefined;+ for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_HOSTED_FREE", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN"]) delete process.env[k];+ await comfy.close();+ await fake.close();+});+beforeEach(() => {+ resetRates();+ billing.resetBillingCache();+ process.env.FUOBE_HOSTED_RUNS = "1";+ process.env.FUOBE_HOSTED_FREE = "1";+ delete process.env.FUOBE_BILLING_URL;+ process.env.COMFYUI_URL = DEAD;+ setSetting("comfyWhere", "workers");+ setSetting("comfyUrl", "");+ setSetting("engineMode", "open");+ setSetting("demoMode", "off");+ db().prepare("DELETE FROM relay_workers").run();+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();+ fetched.length = 0;+});++/** A worker the owner added and resumed, allowed every lane, able to run every workflow. */+function standInWorker(name = "stand-in", o: { paused?: boolean } = {}) {+ const w = pool.addWorker(name);+ const lanes = allLanes(loadIndex(), sha);+ pool.patchWorker(w.id, { paused: !!o.paused, hours: { always: true }, allow: Object.fromEntries(lanes.map((l) => [l.lane, { delayMs: 0 }])), claimAfterMs: 0 });+ db()+ .prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ? WHERE id = ?")+ .run(JSON.stringify({ lanes: lanes.map((l) => l.lane), workflows: loadManifest().workflows.map((x) => x.id) }), JSON.stringify({ vramBytes: 96 * 2 ** 30 }), w.id);+ return w;+}++/** The worker program's side, as `fuobe worker run` drives it: the shared runner with the worker's token and its own ComfyUI. */+function workerRunner(token: string) {+ const api = apiAs(routes, null, { authorization: `Bearer ${token}` });+ return new ComputerRunner(+ {+ api,+ local: (url, init) => realFetch(url, init),+ socket: (url) => new WebSocket(url) as never,+ sha256,+ origin: "http://localhost:3000",+ sleep: (ms) => new Promise((r) => setTimeout(r, Math.min(ms, 50))),+ beatExtra: () => ({ protocol: 1, version: "test", local: { paused: false, why: null, until: null }, gpu: { otherApps: [], tempC: null }, inventoryHash: null, warmLane: null }),+ },+ { device: "worker", port: comfy.port, clientId: "worker-test" },+ );+}++const request = (url: string, o: { method?: string; body?: unknown; cookie?: string | null; headers?: Record<string, string> } = {}) => {+ const text = o.body === undefined ? undefined : JSON.stringify(o.body);+ const headers: Record<string, string> = { ...SITE_HEADERS, ...(o.cookie !== null && { cookie: o.cookie ?? cookie }), ...(text && { "content-type": "application/json", "content-length": String(Buffer.byteLength(text)) }), ...o.headers };+ return new Request(`http://${HOST}${url}`, { method: o.method ?? (text ? "POST" : "GET"), headers, body: text });+};+const run = async (body: Record<string, unknown>, c = cookie) => {+ const r = await generationsRoute.POST(request("/api/generations", { body, cookie: c }));+ return { status: r.status, body: (await r.json()) as { items?: { id: string }[]; code?: string; error?: string } };+};+const tick = () => globalThis.__fuobeRunner?.tick();+const taskOf = (generationId: string) => db().prepare("SELECT * FROM relay_tasks WHERE generation_id = ? ORDER BY created_at DESC").get(generationId) as import("@/server/computer/tasks").TaskRow | undefined;+const rowOf = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as import("@/server/computer/tasks").TaskRow;+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;+}+/** Requests to a ComfyUI address the server made itself (the stand-in worker's own ComfyUI is the worker's, not the server's). */+const serverComfyCalls = () => fetched.filter((u) => u.startsWith(`${DEAD}/`) || /:818[89]\b|:819[01]\b/.test(u) || /\/(prompt|upload\/image|system_stats|history|view|queue|object_info)\b/.test(u));++/** An account's task made straight in the line (no run route), for the queue's own rules. */+let gens = 0;+function accountTask(o: { lane?: string; account?: string; rankAt?: number; notAfter?: number; workflow?: string } = {}) {+ const gid = `pool-gen-${++gens}`;+ const now = Date.now();+ db()+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'm', 'open', 'comfyui', 't2i', 'image', 'queued', ?, '[]', ?, ?)")+ .run(gid, JSON.stringify({ account: o.account ?? accountId, place: "pool" }), now, now);+ const lanes = allLanes(loadIndex(), sha);+ const t = tasks.createTask({+ principal: `acct:${o.account ?? accountId}`,+ generationId: gid,+ graph: { "1": { class_type: "SaveImage", inputs: { filename_prefix: "x" } } },+ pool: { pools: ["pool"], account: o.account ?? accountId, rankAt: o.rankAt ?? now, lane: o.lane ?? lanes[0]?.lane ?? "small", needs: { workflowId: o.workflow ?? loadManifest().workflows[0].id, files: [], packs: [], minVramBytes: 0 }, notAfter: o.notAfter },+ });+ return { id: t.id, generationId: gid };+}++type WorkerRow = import("@/server/computer/workers").WorkerRow;+const workerRow = (w: { id: string }) => db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as WorkerRow;+const beatAs = (w: { id: string }, now = Date.now()) =>+ pool.workerBeat(workerRow(w), pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 1, version: "1", local: { paused: false, why: null, until: null }, gpu: {}, inventoryHash: null, running: [], stopped: [] }), now);+const claimAs = (w: { id: string }, running: string[] = [], now = Date.now()) => pool.workerClaim(workerRow(w), running, now);++describe("with hosted runs off, nothing changes", () => {+ it("an account with no GPU of its own gets today's answer, and no task is made", async () => {+ delete process.env.FUOBE_HOSTED_RUNS;+ standInWorker();+ expect(hosted.poolReady()).toBe(false);+ const before = (db().prepare("SELECT COUNT(*) AS n FROM relay_tasks").get() as { n: number }).n;+ const r = await run({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse" });+ expect(r.status).toBe(403);+ expect(r.body.code).toBe("connect-gpu");+ expect((db().prepare("SELECT COUNT(*) AS n FROM relay_tasks").get() as { n: number }).n).toBe(before);+ expect(serverComfyCalls()).toEqual([]);+ });++ it("switched on with nothing to answer for the runs (no billing service, no free runs), they stay closed", async () => {+ delete process.env.FUOBE_HOSTED_FREE;+ standInWorker();+ expect(hosted.poolReady()).toBe(false);+ const r = await run({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse" });+ expect(r.status).toBe(403);+ expect(r.body.code).toBe("connect-gpu");+ // A billing service that answers opens them.+ process.env.FUOBE_BILLING_URL = fake.url;+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";+ expect(hosted.poolReady()).toBe(true);+ });+});++describe("where hosted runs may go", () => {+ it("on the workers: a worker the owner allowed a lane, paused or not; none at all closes them", () => {+ expect(hosted.poolReady()).toBe(false);+ const w = standInWorker("paused one", { paused: true });+ expect(hosted.poolReady()).toBe(true);+ pool.patchWorker(w.id, { revoke: true });+ expect(hosted.poolReady()).toBe(false);+ });++ it("on this install's own ComfyUI server: only an address on this machine", () => {+ setSetting("comfyWhere", "server");+ setSetting("comfyUrl", "http://127.0.0.1:3399");+ expect(hosted.poolReady()).toBe(true);+ for (const url of ["http://10.0.0.5:8188", "https://comfy.example.com", "http://studio:3399"]) {+ setSetting("comfyUrl", url);+ expect(hosted.poolReady(), url).toBe(false);+ }+ setSetting("comfyWhere", "computer");+ setSetting("comfyUrl", "http://127.0.0.1:3399");+ expect(hosted.poolReady()).toBe(false);+ });+});++describe("an account's run on the workers", () => {+ it("with no ComfyUI address the server could reach, it becomes the account's task, and a stand-in worker renders it", async () => {+ const w = standInWorker();+ const r = await run({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse at dusk" });+ expect(r.status, JSON.stringify(r.body)).toBe(201);+ const id = r.body.items![0].id;+ const t = await until(() => taskOf(id));+ expect(t).toBeDefined();+ expect(t!.principal).toBe(`acct:${accountId}`);+ expect(t!.pools).toBe("pool");+ expect(t!.account).toBe(accountId);+ // It waits in line, in plain words, with its place.+ await until(() => getGeneration(id)?.message === POOL_WORDS.inLine);+ const waiting = getGeneration(id)!;+ expect(waiting.message).toBe(POOL_WORDS.inLine);+ expect(waiting.queue?.place).toBe(1);+ expect(waiting.place).toBe("pool");++ // The worker takes it through the same routes as every worker, and renders it on its own ComfyUI.+ const worker = workerRunner(w.token);+ const beat = await worker.beat();+ expect(beat?.claimableNow).toBe(1);+ await worker.claimAndRun();+ expect(rowOf(t!.id).state).toBe("done");+ const g = await until(() => {+ const x = getGeneration(id);+ return x && x.status !== "queued" && x.status !== "running" ? x : null;+ });+ expect(g?.status, g?.error ?? "").toBe("succeeded");+ expect(g!.outputs.length).toBeGreaterThan(0);+ // The server never called a ComfyUI address for it.+ expect(serverComfyCalls()).toEqual([]);+ // The workers' log: who took it, and how it ended.+ const log = db().prepare("SELECT event, worker_id, principal FROM worker_jobs WHERE task_id = ? ORDER BY id").all(t!.id) as { event: string; worker_id: string; principal: string }[];+ expect(log.map((x) => x.event)).toEqual(["claimed", "finished", "done"]);+ expect(log.every((x) => x.worker_id === w.id && x.principal === `acct:${accountId}`)).toBe(true);+ });++ it("an account's own session can never claim or read a task for the workers, even one of its own runs", async () => {+ standInWorker();+ const mine = accountTask({ account: computerAccount });+ const api = apiAs(routes, computerCookie);+ // Claim: nothing (a task for the workers is never a computer's own).+ const claim = await api("/api/gpu/computer/claim", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ device: "device-own-1", running: [] }) });+ expect(claim.status).toBe(204);+ // A worker takes it; the account then names it with any lease: unknown.+ const w = db().prepare("SELECT * FROM relay_workers LIMIT 1").get() as { id: string };+ beatAs(w);+ const got = claimAs(w)!;+ expect(got.id).toBe(mine.id);+ for (const [path, init] of [+ [`/api/gpu/computer/tasks/${mine.id}/report`, { method: "POST", headers: { "x-fuobe-lease": got.lease, "Content-Type": "application/json" }, body: JSON.stringify({ event: "running", value: 1, max: 2 }) }],+ [`/api/gpu/computer/tasks/${mine.id}/inputs/0`, { headers: { "x-fuobe-lease": got.lease } }],+ [`/api/gpu/computer/tasks/${mine.id}/outputs/0`, { headers: { "x-fuobe-lease": got.lease } }],+ [`/api/gpu/computer/tasks/${mine.id}/release`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ lease: got.lease }) }],+ ] as [string, RequestInit][]) {+ const res = await api(path, init);+ expect(res.status, path).toBe(404);+ }+ // A beat that names it (even under the worker's device) touches nothing of it, and hears no stop of it.+ tasks.setTask(mine.id, { stop: 1 });+ const beat = await api("/api/gpu/computer/beat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ device: `wkr-${w.id}`, running: [{ task: mine.id, value: 9, max: 9 }], stopped: [mine.id] }) });+ expect(beat.status).toBe(200);+ expect(((await beat.json()) as { stops: unknown[] }).stops).toEqual([]);+ expect(rowOf(mine.id).stop).toBe(1);+ expect(tasks.getTask(`acct:${computerAccount}`, mine.id)).toBeNull();+ // The server's own reads, as the run's account, still find it.+ expect(tasks.ownTask(`acct:${computerAccount}`, mine.id)?.id).toBe(mine.id);+ });++ it("refuses a run that no worker would ever take, before anything is queued", async () => {+ const w = standInWorker();+ pool.patchWorker(w.id, { allow: {} });+ pool.addWorker("lane-less");+ const before = (db().prepare("SELECT COUNT(*) AS n FROM relay_tasks").get() as { n: number }).n;+ const r = await run({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse" });+ expect(r.status).toBe(403);+ expect((db().prepare("SELECT COUNT(*) AS n FROM relay_tasks").get() as { n: number }).n).toBe(before);+ });++ 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" } } });+ 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");+ });+});++describe("the line", () => {+ it("a requeue keeps the run's place (rank_at), it shows In line again, and its wait limit is over", async () => {+ const w = standInWorker();+ const first = accountTask({ rankAt: Date.now() - 5 * MIN, notAfter: Date.now() + MIN });+ const later = accountTask({ rankAt: Date.now() });+ const rank = rowOf(first.id).rank_at;+ beatAs(w);+ expect(claimAs(w)?.id).toBe(first.id);+ // The worker pauses at once (another program on the GPU): the job goes back in line at no cost.+ pool.workerBeat(+ db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as never,+ pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 1, version: "1", local: { paused: true, why: "gpu-busy:game.exe", until: null }, gpu: {}, running: [{ task: first.id }], stopped: [] }),+ );+ const back = rowOf(first.id);+ expect(back.state).toBe("waiting");+ expect(back.rank_at).toBe(rank);+ expect(back.requeues).toBe(0);+ // First in line again, ahead of the later run, and past its wait limit it still waits: a worker took it once.+ expect(pool.queueOfGeneration(first.generationId)?.place).toBe(1);+ expect(pool.queueOfGeneration(later.generationId)?.place).toBe(2);+ pool.sweepPool(Date.now() + 10 * MIN);+ expect(rowOf(first.id).state).toBe("waiting");+ // A run no worker has taken yet still fails at its wait limit, not charged.+ const never = accountTask({ notAfter: Date.now() + MIN });+ pool.sweepPool(Date.now() + 2 * MIN);+ expect(rowOf(never.id).state).toBe("failed");+ // Its row says In line, never a pause or a GPU word.+ const g = toGeneration(db().prepare("SELECT * FROM generations WHERE id = ?").get(first.generationId) as never);+ expect(g.message).toBe(POOL_WORDS.inLine);+ });++ it("place and wait count every task ahead in the order the workers serve them, whatever its lane", () => {+ const w = standInWorker();+ const lanes = allLanes(loadIndex(), sha).map((l) => l.lane);+ expect(lanes.length).toBeGreaterThan(1);+ const now = Date.now();+ accountTask({ lane: lanes[0], rankAt: now - 3 * MIN });+ accountTask({ lane: lanes[1], rankAt: now - 2 * MIN });+ const mine = accountTask({ lane: lanes[0], rankAt: now - MIN });+ beatAs(w);+ const place = pool.queueOfGeneration(mine.generationId);+ expect(place?.place).toBe(3);+ expect(place?.etaSeconds).toBeGreaterThan(0);+ // The billing service's line facts read the same line.+ const facts = hosted.queueFacts(accountId, loadManifest().workflows[0].id);+ expect(facts.ahead).toBe(3);+ expect(facts.workersOnline).toBe(1);+ expect(facts.mine.waiting).toBe(3);+ });++});++describe("what an account reads about its run", () => {+ it("a failed run on this install's GPUs shows one plain sentence and no Fix it; the owner reads the reason", () => {+ const now = Date.now();+ const id = `plain-${now}`;+ db()+ .prepare(+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, error, fix_json, created_at, updated_at) VALUES (?, 'image', 'oss-z-image-turbo', 'open', 'comfyui', 't2i', 'image', 'failed', ?, '[]', ?, ?, ?, ?)",+ )+ .run(id, JSON.stringify({ account: accountId, place: "pool", feature: "image", modelId: "oss-z-image-turbo" }), "Can't reach ComfyUI at http://10.0.0.5:8188 (C:\\Users\\x\\ComfyUI)", JSON.stringify({ code: "comfy_missing_node", items: [] }), now, now);+ const g = getGeneration(id)!;+ expect(g.error).toBe(POOL_WORDS.failed);+ expect(g.fix).toBeUndefined();+ const owner = listAccountRuns({ account: accountId }).items.find((x) => x.id === id);+ expect(owner?.detail).toContain("Can't reach ComfyUI");+ // Fuobe's own words about the account's side stay as they are.+ db().prepare("UPDATE generations SET error = ? WHERE id = ?").run("Your files have reached 3 GB. Delete some runs to make room.", id);+ expect(getGeneration(id)!.error).toBe("Your files have reached 3 GB. Delete some runs to make room.");+ });++ it("while it goes, only In line or Working, whatever the technical words were", () => {+ const now = Date.now();+ const id = `words-${now}`;+ db()+ .prepare("INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, message, created_at, updated_at) VALUES (?, 'image', 'm', 'open', 'comfyui', 't2i', 'image', 'running', ?, '[]', ?, ?, ?)")+ .run(id, JSON.stringify({ account: accountId, place: "pool" }), "In ComfyUI's queue · 2 ahead", now, now);+ expect(getGeneration(id)!.message).toBe(POOL_WORDS.working);+ db().prepare("UPDATE generations SET status = 'queued', message = 'Back in line for another GPU' WHERE id = ?").run(id);+ expect(getGeneration(id)!.message).toBe(POOL_WORDS.inLine);+ });+});++describe("graphs and results for the workers", () => {+ it("every VideoHelperSuite save node saves no metadata", () => {+ const wf = withoutSaveMetadata({+ "1": { class_type: "VHS_VideoCombine", inputs: { save_metadata: true, filename_prefix: "x" } },+ "2": { class_type: "VHS_VideoCombine", inputs: {} },+ "3": { class_type: "SaveImage", inputs: {} },+ "4": { class_type: "VHS_SaveImageSequence", inputs: { save_metadata: true } },+ "5": { class_type: "VHS_LoadVideo", inputs: { video: "x.mp4" } },+ "6": { class_type: "SomeOtherSave", inputs: { save_metadata: true } },+ } as never) as unknown as Record<string, { inputs: Record<string, unknown> }>;+ expect(wf["1"].inputs.save_metadata).toBe(false);+ expect(wf["2"].inputs.save_metadata).toBe(false);+ expect(wf["3"].inputs.save_metadata).toBeUndefined();+ expect(wf["4"].inputs.save_metadata).toBe(false);+ expect(wf["5"].inputs).toEqual({ video: "x.mp4" });+ expect(wf["6"].inputs.save_metadata).toBe(true);+ });++ it("an account's clip run on the workers is queued with no metadata in its clip saves", async () => {+ standInWorker();+ const { comfyProvider } = await import("@/server/providers/comfyui");+ const { TINY_MP4 } = await import("./helpers/fake-comfy-runner");+ const prior = process.env.FUOBE_POOL_MEDIA_INPUTS;+ process.env.FUOBE_POOL_MEDIA_INPUTS = "image,video";+ try {+ const route = { provider: "comfyui", endpoint: "interpolate-rife-vfi", op: "interpolate" } as never;+ const sent = await hosted.runOnPool(accountId, async () => {+ const video = (await comfyProvider.prepareFile!(TINY_MP4, "video/mp4", "clip.mp4", route))!;+ return comfyProvider.submit({ route, input: { video, extra: { multiplier: 2 } } as never, generationId: `vhs-${Date.now()}` } as never);+ });+ const t = rowOf(String((sent.meta as { relay: string }).relay));+ expect(t.principal).toBe(`acct:${accountId}`);+ expect(t.pools).toBe("pool");+ const graph = JSON.parse(t.graph_json ?? "{}") as Record<string, { class_type: string; inputs: Record<string, unknown> }>;+ const saves = Object.values(graph).filter((n) => n.class_type === "VHS_VideoCombine");+ expect(saves.length).toBeGreaterThan(0);+ for (const node of saves) expect(node.inputs.save_metadata).toBe(false);+ expect(serverComfyCalls()).toEqual([]);+ } finally {+ if (prior === undefined) delete process.env.FUOBE_POOL_MEDIA_INPUTS;+ else process.env.FUOBE_POOL_MEDIA_INPUTS = prior;+ }+ });++ it("an owner's job on the workers keeps no more results than its workflow makes, and nothing past the disk's free floor", () => {+ const entry = { status: { status_str: "success", completed: true }, outputs: { "9": { images: Array.from({ length: 40 }, (_, i) => ({ filename: `x_${i}.png`, subfolder: "", type: "output" })) } } };+ const t = { id: "owner-task-0001x", workflow_id: loadManifest().workflows.find((x) => x.outputs.length === 1)!.id, meta_batch: 0, prefix: null, extra_json: JSON.stringify({ outputs: 1 }), pools: "pool" };+ const plan = onComputer("owner", () => planRelayOutputs(t, [entry], false));+ expect("wanted" in plan && plan.wanted.length).toBe(16);+ // The owner's own computer keeps every result, as before.+ const own = onComputer("owner", () => planRelayOutputs({ ...t, pools: null }, [entry], false));+ expect("wanted" in own && own.wanted.length).toBe(40);+ globalThis.__fuobeTestDiskFree = 1;+ try {+ const full = onComputer("owner", () => planRelayOutputs(t, [entry], false));+ expect("error" in full && full.error).toMatch(/no room/);+ } finally {+ globalThis.__fuobeTestDiskFree = 1e13;+ }+ });+});++describe("nothing of a run on the workers goes to a ComfyUI address", () => {+ it("an account's picture is made again from its pixels (no EXIF) and kept for its task", async () => {+ const sharp = (await import("sharp")).default;+ const jpeg = await sharp({ create: { width: 8, height: 8, channels: 3, background: "#c33" } })+ .jpeg()+ .withExif({ IFD0: { Copyright: "private note", Artist: "someone" } })+ .toBuffer();+ expect((await sharp(jpeg).metadata()).exif).toBeDefined();+ const { comfyProvider } = await import("@/server/providers/comfyui");+ const staged = await hosted.runOnPool(accountId, () => comfyProvider.prepareFile!(jpeg, "image/jpeg", "me.jpg"));+ const row = db().prepare("SELECT principal, content_type FROM relay_inputs WHERE name = ?").get(staged) as { principal: string; content_type: string };+ expect(row).toEqual({ principal: `acct:${accountId}`, content_type: "image/png" });+ const fs = await import("node:fs");+ const path = await import("node:path");+ const kept = fs.readFileSync(path.join(dir, "relay", "in", staged));+ const meta = await sharp(kept).metadata();+ expect(meta.format).toBe("png");+ expect(meta.exif).toBeUndefined();+ expect(serverComfyCalls()).toEqual([]);+ });++ it("a run on the workers with no account behind it never sends a file or a prompt", async () => {+ const { comfyProvider } = await import("@/server/providers/comfyui");+ const png = Buffer.from("89504e470d0a1a0a", "hex");+ await expect(hosted.runOnPool(null, () => comfyProvider.prepareFile!(png, "image/png", "x.png"))).rejects.toThrow();+ const route = { provider: "comfyui", endpoint: loadManifest().workflows[0].id, op: "t2i" } as never;+ await expect(hosted.runOnPool(null, () => comfyProvider.submit({ route, input: { prompt: "a lighthouse" } as never, generationId: "guest-run-0001" } as never))).rejects.toThrow();+ expect(serverComfyCalls()).toEqual([]);+ });++ it("a run sent to this install's own ComfyUI before Settings moved to the workers is still followed there", async () => {+ const { comfyProvider } = await import("@/server/providers/comfyui");+ setSetting("comfyUrl", DEAD);+ // (It answers nothing here: the poll says so, and never goes round in circles.)+ await hosted+ .runOnPool(accountId, () => comfyProvider.poll({ externalId: crypto.randomUUID(), meta: { workflowId: loadManifest().workflows[0].id, generationId: "moved-0001" }, model: undefined } as never))+ .catch((e: Error) => expect(e.message).not.toMatch(/call stack/i));+ // Asked of the address it was sent to, not of the workers' line.+ expect(fetched.some((u) => u.startsWith(`${DEAD}/`))).toBe(true);+ });+});++describe("what a run on the workers is shaped by", () => {+ it("the workers' facts (the least VRAM and RAM of those allowed its lane), never the account's own computer's", async () => {+ const big = standInWorker("big");+ const small = standInWorker("small");+ const facts = (w: { id: string }, f: Record<string, unknown>) => db().prepare("UPDATE relay_workers SET facts_json = ? WHERE id = ?").run(JSON.stringify(f), w.id);+ facts(big, { vramBytes: 96 * 2 ** 30, ramBytes: 128 * 2 ** 30, device: "cuda:0 Test GPU" });+ facts(small, { vramBytes: 24 * 2 ** 30, ramBytes: 64 * 2 ** 30, device: "cuda:0 Other GPU" });+ expect(pool.poolFacts(null)).toEqual({ vramBytes: 24 * 2 ** 30, ramBytes: 64 * 2 ** 30, device: "cuda:0 Test GPU" });+ // A lane only the big one is allowed: its facts alone.+ const lane = allLanes(loadIndex(), sha)[0].lane;+ pool.patchWorker(small.id, { allow: {} });+ expect(pool.poolFacts(lane).vramBytes).toBe(96 * 2 ** 30);+ // Workers that name different kinds of device: none is assumed.+ pool.patchWorker(small.id, { allow: { [lane]: { delayMs: 0 } } });+ facts(small, { vramBytes: 24 * 2 ** 30, device: "mps" });+ expect(pool.poolFacts(null).device).toBeUndefined();+ facts(small, { vramBytes: 24 * 2 ** 30, ramBytes: 64 * 2 ** 30, device: "cuda:0 Other GPU" });++ // The account's own computer said something else: a run on the workers never reads it; a run on that computer does.+ tasks.beat(`acct:${computerAccount}`, { device: "device-own-facts", takeover: true, facts: { ramBytes: 2 ** 30, vramBytes: 2 ** 30, device: "mps" } });+ const { comfyRam, comfyDevice } = await import("@/server/providers/comfyui");+ expect(hosted.runOnPool(computerAccount, () => comfyRam())).toBe(64 * 2 ** 30);+ expect(await hosted.runOnPool(computerAccount, () => comfyDevice())).toBe("cuda");+ expect(onComputer(`acct:${computerAccount}`, () => comfyRam())).toBe(2 ** 30);+ expect(await onComputer(`acct:${computerAccount}`, () => comfyDevice())).toBe("mps");+ expect(serverComfyCalls()).toEqual([]);+ });+});++describe("files for runs on the workers", () => {+ it("an account may add only the kinds of file the workers take, whatever the policy allows", async () => {+ const uploadsRoute = await import("@/app/api/uploads/route");+ const { TINY_MP4, TINY_PNG } = await import("./helpers/fake-comfy-runner");+ standInWorker();+ process.env.FUOBE_BILLING_URL = fake.url;+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";+ const before = fake.policy;+ fake.policy = { ...before, hosted: true, uploads: { image: true, video: true, audio: true }, ttlS: 0 };+ const prior = process.env.FUOBE_POOL_MEDIA_INPUTS;+ delete process.env.FUOBE_POOL_MEDIA_INPUTS;+ try {+ const up = (bytes: Buffer, type: string, name: string) =>+ uploadsRoute.POST(new Request(`http://${HOST}/api/uploads`, { method: "POST", headers: { ...SITE_HEADERS, cookie, "content-type": type, "x-file-name": name, "content-length": String(bytes.length) }, body: new Uint8Array(bytes) }));+ expect((await up(TINY_PNG, "image/png", "me.png")).status).toBe(201);+ expect((await up(TINY_MP4, "video/mp4", "me.mp4")).status).toBe(403);+ // The workers take clips too: so may the account.+ process.env.FUOBE_POOL_MEDIA_INPUTS = "image,video";+ expect((await up(TINY_MP4, "video/mp4", "me.mp4")).status).toBe(201);+ } finally {+ fake.policy = before;+ if (prior === undefined) delete process.env.FUOBE_POOL_MEDIA_INPUTS;+ else process.env.FUOBE_POOL_MEDIA_INPUTS = prior;+ delete process.env.FUOBE_BILLING_URL;+ delete process.env.FUOBE_BILLING_TOKEN;+ }+ });+});