Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

Workers: share your GPUs with other machines (the studio's side)

Adarshebabeed31423
diff --git a/src/app/(studio)/settings/workers/page.tsx b/src/app/(studio)/settings/workers/page.tsx
new file mode 100644
index 00000000..ae4fcdfd
--- /dev/null
+++ b/src/app/(studio)/settings/workers/page.tsx
@@ -0,0 +1,20 @@
+import { ArrowLeft } from "lucide-react";
+import type { Metadata } from "next";
+import Link from "next/link";
+import { PageHeader, PageShell } from "@/components/page-shell";
+import { WorkersAdmin } from "@/components/workers-admin";
+
+export const metadata: Metadata = { title: "Workers" };
+
+/** Settings → Workers (the owner only): the GPUs on other machines that run this studio's ComfyUI jobs. */
+export default function Page() {
+ return (
+ <PageShell>
+ <Link href="/settings" className="mb-3 inline-flex items-center gap-1.5 rounded-md text-[13px] text-muted-foreground hover:text-foreground">
+ <ArrowLeft className="size-3.5" /> Settings
+ </Link>
+ <PageHeader title="Workers" description="Share your GPUs with other machines." />
+ <WorkersAdmin />
+ </PageShell>
+ );
+}
diff --git a/src/app/api/admin/queue/route.ts b/src/app/api/admin/queue/route.ts
new file mode 100644
index 00000000..a4c3b390
--- /dev/null
+++ b/src/app/api/admin/queue/route.ts
@@ -0,0 +1,10 @@
+import { connection } from "next/server";
+import { isOwnerRequest, sessionCookieOf } from "@/server/auth";
+import { queueView } from "@/server/computer/pool";
+
+/** The line for workers (owner only): per lane, how many wait, the oldest, the estimate, and which workers have it warm. */
+export async function GET(request: Request) {
+ await connection();
+ if (!isOwnerRequest(request, sessionCookieOf(request))) return Response.json({ error: "Only the studio's owner sees the queue" }, { status: 403 });
+ return Response.json(queueView(), { headers: { "Cache-Control": "no-store" } });
+}
diff --git a/src/app/api/admin/workers/[id]/route.ts b/src/app/api/admin/workers/[id]/route.ts
new file mode 100644
index 00000000..a5097829
--- /dev/null
+++ b/src/app/api/admin/workers/[id]/route.ts
@@ -0,0 +1,23 @@
+import { isOwnerRequest, sessionCookieOf } from "@/server/auth";
+import { patchWorker, type WorkerPatch } from "@/server/computer/pool";
+
+const NO_STORE = { "Cache-Control": "no-store" };
+
+/**
+ * Change a worker (owner only): `{ paused, pauseNow, drain, hours, allow, claimAfterMs, switchAfterMs, rotate, revoke }`.
+ * Each reaches the worker at its next beat. Rotate answers with the new token, once; revoke stops the old token at once
+ * and puts its job back in line.
+ */
+export async function PATCH(request: Request, ctx: RouteContext<"/api/admin/workers/[id]">) {
+ if (!isOwnerRequest(request, sessionCookieOf(request))) return Response.json({ error: "Only the studio's owner manages workers" }, { status: 403, headers: NO_STORE });
+ const { id } = await ctx.params;
+ const body = (await request.json().catch(() => null)) as WorkerPatch | null;
+ if (!body || typeof body !== "object") return Response.json({ error: "Say what to change" }, { status: 400, headers: NO_STORE });
+ try {
+ const r = patchWorker(id, body);
+ if (!r.view && !body.revoke) return Response.json({ error: "Not found" }, { status: 404, headers: NO_STORE });
+ return Response.json({ worker: r.view, ...(r.token && { token: r.token }) }, { headers: NO_STORE });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: 400, headers: NO_STORE });
+ }
+}
diff --git a/src/app/api/admin/workers/route.ts b/src/app/api/admin/workers/route.ts
new file mode 100644
index 00000000..b1e29420
--- /dev/null
+++ b/src/app/api/admin/workers/route.ts
@@ -0,0 +1,27 @@
+import { connection } from "next/server";
+import { isOwnerRequest, sessionCookieOf } from "@/server/auth";
+import { addWorker, lanesCatalog, listWorkers } from "@/server/computer/pool";
+
+const NO_STORE = { "Cache-Control": "no-store" };
+
+/**
+ * Settings → Workers (owner only, docs/gpu-workers.md): the shared GPUs with their state in words, and the lanes this
+ * studio's catalog has (to allow per worker). POST `{ name, pool? }` adds one: paused, with no hours and no lanes; its
+ * token is in this answer only.
+ */
+export async function GET(request: Request) {
+ await connection();
+ if (!isOwnerRequest(request, sessionCookieOf(request))) return Response.json({ error: "Only the studio's owner manages workers" }, { status: 403, headers: NO_STORE });
+ return Response.json({ workers: listWorkers(), lanes: lanesCatalog() }, { headers: NO_STORE });
+}
+
+export async function POST(request: Request) {
+ if (!isOwnerRequest(request, sessionCookieOf(request))) return Response.json({ error: "Only the studio's owner manages workers" }, { status: 403, headers: NO_STORE });
+ const body = (await request.json().catch(() => null)) as { name?: unknown; pool?: unknown } | null;
+ try {
+ const w = addWorker(typeof body?.name === "string" ? body.name.slice(0, 48) : "", typeof body?.pool === "string" ? body.pool : undefined);
+ return Response.json(w, { status: 201, headers: NO_STORE });
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: 400, headers: NO_STORE });
+ }
+}
diff --git a/src/app/api/gpu/computer/beat/route.ts b/src/app/api/gpu/computer/beat/route.ts
index 5ce8bad3..835abc6d 100644
--- a/src/app/api/gpu/computer/beat/route.ts
+++ b/src/app/api/gpu/computer/beat/route.ts
@@ -1,5 +1,6 @@
-import { principalOf, rateOf, relayAnswer, requestWorker } from "@/server/computer/http";
+import { callerKey, principalOf, rateOf, relayAnswer, requestWorker } from "@/server/computer/http";
import { beat, cleanFacts, type BeatInput } from "@/server/computer/tasks";
+import { cleanBeat, workerBeat } from "@/server/computer/pool";
import { noteWorkerFacts } from "@/server/computer/workers";
/** What a beat may weigh: the facts, with up to 20,000 LoRA names. */
@@ -14,7 +15,7 @@ const MAX_BYTES = 3 * 2 ** 20;
export async function POST(request: Request) {
const principal = principalOf(request);
if (principal instanceof Response) return principal;
- const limited = rateOf(principal, "beat", 30);
+ const limited = rateOf(callerKey(request, principal), "beat", 30);
if (limited) return limited;
const text = await request.text().catch(() => "");
if (text.length > MAX_BYTES) return Response.json({ error: "Too much at once" }, { status: 413 });
@@ -24,8 +25,16 @@ export async function POST(request: Request) {
} catch {
return Response.json({ error: "Send JSON" }, { status: 400 });
}
- // A paired ComfyUI's facts are kept with it too (the person's list of paired ComfyUIs shows its GPU).
const worker = requestWorker(request);
+ // One of the owner's shared GPUs: its own beat (pool.ts).
+ if (worker?.kind === "pool") {
+ try {
+ return Response.json(workerBeat(worker, cleanBeat(body)), { headers: { "Cache-Control": "no-store" } });
+ } catch (e) {
+ return relayAnswer(e);
+ }
+ }
+ // A paired ComfyUI's facts are kept with it too (the person's list of paired ComfyUIs shows its GPU).
if (worker && body?.facts !== undefined) {
const facts = cleanFacts(body.facts);
delete facts.loras;
diff --git a/src/app/api/gpu/computer/bench/route.ts b/src/app/api/gpu/computer/bench/route.ts
new file mode 100644
index 00000000..db6071dd
--- /dev/null
+++ b/src/app/api/gpu/computer/bench/route.ts
@@ -0,0 +1,18 @@
+import { callerKey, principalOf, rateOf, requestWorker } from "@/server/computer/http";
+import { benchTasks } from "@/server/computer/bench";
+
+/**
+ * `fuobe worker bench`: small fixed jobs, one per lane this worker is allowed, for this worker only and never billed.
+ * Their times become the worker's wait estimates and run limits. `{ lanes?: string[] }` narrows them.
+ */
+export async function POST(request: Request) {
+ const principal = principalOf(request);
+ if (principal instanceof Response) return principal;
+ const worker = requestWorker(request);
+ if (worker?.kind !== "pool") return Response.json({ error: "Only a worker benchmarks itself" }, { status: 403 });
+ const limited = rateOf(callerKey(request, principal), "bench", 2);
+ if (limited) return limited;
+ const body = (await request.json().catch(() => null)) as { lanes?: unknown } | null;
+ const lanes = Array.isArray(body?.lanes) ? body.lanes.filter((x): x is string => typeof x === "string").slice(0, 64) : undefined;
+ return Response.json({ tasks: await benchTasks(worker, lanes) }, { headers: { "Cache-Control": "no-store" } });
+}
diff --git a/src/app/api/gpu/computer/claim/route.ts b/src/app/api/gpu/computer/claim/route.ts
index 875bcf5a..09a31ee9 100644
--- a/src/app/api/gpu/computer/claim/route.ts
+++ b/src/app/api/gpu/computer/claim/route.ts
@@ -1,4 +1,5 @@
-import { principalOf, rateOf, relayAnswer } from "@/server/computer/http";
+import { callerKey, principalOf, rateOf, relayAnswer, requestWorker } from "@/server/computer/http";
+import { workerClaim } from "@/server/computer/pool";
import { claim } from "@/server/computer/tasks";
/**
@@ -10,12 +11,14 @@ import { claim } from "@/server/computer/tasks";
export async function POST(request: Request) {
const principal = principalOf(request);
if (principal instanceof Response) return principal;
- const limited = rateOf(principal, "claim", 60);
+ const limited = rateOf(callerKey(request, principal), "claim", 60);
if (limited) return limited;
const body = (await request.json().catch(() => null)) as { device?: unknown; running?: unknown } | null;
const running = Array.isArray(body?.running) ? body.running.filter((x): x is string => typeof x === "string").slice(0, 32) : [];
try {
- const task = claim(principal, String(body?.device ?? ""), running);
+ const worker = requestWorker(request);
+ // A shared GPU takes the best task it can run from its pool (pool.ts); a person's computer, their own oldest.
+ const task = worker?.kind === "pool" ? workerClaim(worker, running) : claim(principal, String(body?.device ?? ""), running);
if (!task) return new Response(null, { status: 204, headers: { "Cache-Control": "no-store" } });
return Response.json({ task }, { headers: { "Cache-Control": "no-store" } });
} catch (e) {
diff --git a/src/app/api/gpu/computer/inventory/route.ts b/src/app/api/gpu/computer/inventory/route.ts
new file mode 100644
index 00000000..e3de5ad1
--- /dev/null
+++ b/src/app/api/gpu/computer/inventory/route.ts
@@ -0,0 +1,27 @@
+import { callerKey, principalOf, rateOf, requestWorker } from "@/server/computer/http";
+import { saveInventory } from "@/server/computer/pool";
+
+/** What an inventory may weigh: 20,000 files with their names and hashes. */
+const MAX_BYTES = 8 * 2 ** 20;
+
+/**
+ * A worker's verified model files and node packs (docs/gpu-workers.md): the answer is the lanes it can run now, and what
+ * each other lane lacks. Only a shared GPU's worker sends one.
+ */
+export async function PUT(request: Request) {
+ const principal = principalOf(request);
+ if (principal instanceof Response) return principal;
+ const worker = requestWorker(request);
+ if (worker?.kind !== "pool") return Response.json({ error: "Only a worker sends its files" }, { status: 403 });
+ const limited = rateOf(callerKey(request, principal), "inventory", 6);
+ if (limited) return limited;
+ const text = await request.text().catch(() => "");
+ if (text.length > MAX_BYTES) return Response.json({ error: "Too much at once" }, { status: 413 });
+ let body: unknown;
+ try {
+ body = JSON.parse(text);
+ } catch {
+ return Response.json({ error: "Send JSON" }, { status: 400 });
+ }
+ return Response.json({ ok: true, ...saveInventory(worker, body) }, { headers: { "Cache-Control": "no-store" } });
+}
diff --git a/src/app/api/gpu/computer/tasks/[id]/inputs/[n]/route.ts b/src/app/api/gpu/computer/tasks/[id]/inputs/[n]/route.ts
index 097e5ce7..810aed49 100644
--- a/src/app/api/gpu/computer/tasks/[id]/inputs/[n]/route.ts
+++ b/src/app/api/gpu/computer/tasks/[id]/inputs/[n]/route.ts
@@ -1,7 +1,7 @@
import fs from "node:fs";
import { Readable } from "node:stream";
import { connection } from "next/server";
-import { principalOf, rateOf, relayAnswer } from "@/server/computer/http";
+import { callerKey, principalOf, rateOf, relayAnswer } from "@/server/computer/http";
import { inputFor, leased } from "@/server/computer/tasks";
/**
@@ -13,7 +13,7 @@ export async function GET(request: Request, ctx: RouteContext<"/api/gpu/computer
await connection();
const principal = principalOf(request);
if (principal instanceof Response) return principal;
- const limited = rateOf(principal, "input", 120);
+ const limited = rateOf(callerKey(request, principal), "input", 120);
if (limited) return limited;
const { id, n } = await ctx.params;
try {
diff --git a/src/app/api/gpu/computer/tasks/[id]/outputs/[n]/route.ts b/src/app/api/gpu/computer/tasks/[id]/outputs/[n]/route.ts
index c35e2cb0..57eda8ca 100644
--- a/src/app/api/gpu/computer/tasks/[id]/outputs/[n]/route.ts
+++ b/src/app/api/gpu/computer/tasks/[id]/outputs/[n]/route.ts
@@ -2,7 +2,7 @@ import fs from "node:fs";
import { connection } from "next/server";
import { RELAY_LIMITS } from "@/lib/relay";
import { gateAsProxy } from "@/server/direct-gate";
-import { isUtf8File, outputType, principalOf, rateOf, relayAnswer } from "@/server/computer/http";
+import { callerKey, isUtf8File, outputType, principalOf, rateOf, relayAnswer } from "@/server/computer/http";
import { failTask, getTask, leased, outputFile, outputStatus, receivePart, RelayError, SNIFF_BYTES, wantedOf, type TaskRow } from "@/server/computer/tasks";
import { enter } from "@/server/rate";
@@ -62,7 +62,7 @@ export async function PUT(request: Request, ctx: RouteContext<"/api/gpu/computer
if (denied) return denied;
const principal = principalOf(request);
if (principal instanceof Response) return principal;
- const limited = rateOf(principal, "output", 600);
+ const limited = rateOf(callerKey(request, principal), "output", 600);
if (limited) return limited;
const declared = request.headers.get("content-length");
if (declared === null || !/^\d+$/.test(declared)) return no(411, "Send the part with its size (Content-Length).");
@@ -80,7 +80,7 @@ export async function PUT(request: Request, ctx: RouteContext<"/api/gpu/computer
} catch (e) {
return relayAnswer(e);
}
- const mine = enter(`relay-out:${principal}`, 1);
+ const mine = enter(`relay-out:${callerKey(request, principal)}`, 1);
if (!mine) return no(429, "Another result of yours is uploading. Fuobe tries again by itself.", { "Retry-After": "2" });
const all = enter("relay-out", AT_ONCE);
if (!all) {
@@ -88,7 +88,7 @@ export async function PUT(request: Request, ctx: RouteContext<"/api/gpu/computer
return no(429, "The studio is busy saving other results. Fuobe tries again by itself.", { "Retry-After": "3" });
}
try {
- const owner = principal === "owner";
+ const owner = t.principal === "owner";
const r = await receivePart(t, n, { offset, total, length }, (file, append) => writeBody(request, file, append, length), (head, w) => outputType(head, w, owner));
// A text result is UTF-8 through to its end.
const w = wantedOf(t).find((x) => x.n === n);
diff --git a/src/app/api/gpu/computer/tasks/[id]/report/route.ts b/src/app/api/gpu/computer/tasks/[id]/report/route.ts
index 9919ad37..c4a322d7 100644
--- a/src/app/api/gpu/computer/tasks/[id]/report/route.ts
+++ b/src/app/api/gpu/computer/tasks/[id]/report/route.ts
@@ -1,6 +1,7 @@
import { RELAY_LIMITS, TAB_FAILURES, type ReportEvent } from "@/lib/relay";
import { gateAsProxy, readBodyWithin } from "@/server/direct-gate";
-import { principalOf, rateOf, relayAnswer } from "@/server/computer/http";
+import { callerKey, principalOf, rateOf, relayAnswer } from "@/server/computer/http";
+import { noteFinished } from "@/server/computer/bench";
import { leased, report, type TaskRow } from "@/server/computer/tasks";
import { onComputer, planRelayOutputs } from "@/server/providers/comfyui";
import { enter } from "@/server/rate";
@@ -27,7 +28,7 @@ function eventOf(b: Record<string, unknown>): ReportEvent | null {
case "running":
return { event: e, value: num(b.value), max: num(b.max), nodesDone: num(b.nodesDone), ...(typeof b.node === "string" && { node: b.node }) };
case "finished":
- return b.entry && typeof b.entry === "object" ? { event: e, entry: b.entry as never } : null;
+ return b.entry && typeof b.entry === "object" ? { event: e, entry: b.entry as never, ...(num(b.peakVramBytes) !== undefined && { peakVramBytes: num(b.peakVramBytes) }) } : null;
case "passes":
return Array.isArray(b.entries) && b.entries.length <= 64 ? { event: e, running: b.running === true, entries: b.entries as never } : null;
case "failed":
@@ -58,7 +59,7 @@ export async function POST(request: Request, ctx: RouteContext<"/api/gpu/compute
if (denied) return denied;
const principal = principalOf(request);
if (principal instanceof Response) return principal;
- const limited = rateOf(principal, "report", 300);
+ const limited = rateOf(callerKey(request, principal), "report", 300);
if (limited) return limited;
const { id } = await ctx.params;
const lease = request.headers.get("x-fuobe-lease");
@@ -71,10 +72,10 @@ export async function POST(request: Request, ctx: RouteContext<"/api/gpu/compute
const declared = Number(request.headers.get("content-length") ?? NaN);
if (Number.isFinite(declared) && declared > cap) return no(413, "That report is too large");
if (cap > LARGE_BYTES && !(declared <= LARGE_BYTES)) {
- const big = rateOf(principal, "report-large", 30);
+ const big = rateOf(callerKey(request, principal), "report-large", 30);
if (big) return big;
}
- const mine = enter(`relay-report:${principal}`, AT_ONCE.person);
+ const mine = enter(`relay-report:${callerKey(request, principal)}`, AT_ONCE.person);
if (!mine) return no(429, "Too many at once. Fuobe tries again by itself.", { "Retry-After": "1" });
const all = enter("relay-report", AT_ONCE.all);
if (!all) {
@@ -93,10 +94,10 @@ export async function POST(request: Request, ctx: RouteContext<"/api/gpu/compute
if (!LARGE_EVENTS.has(event.event) && raw!.length > RELAY_LIMITS.smallReportBytes) return no(413, "That report is too large");
// Where the job is now (it may have moved while the body arrived).
const t = leased(principal, id, lease);
- return Response.json(
- report(t, event, (entries, passes) => onComputer(principal, () => planRelayOutputs(t, entries, passes))),
- { headers: { "Cache-Control": "no-store" } },
- );
+ const answer = report(t, event, (entries, passes) => onComputer(t.principal, () => planRelayOutputs(t, entries, passes)));
+ // A worker's finished job counts toward its lane's times there.
+ if (t.pools && (event.event === "finished" || event.event === "passes") && answer.state !== "running") noteFinished(t, Date.now(), event.event === "finished" ? event.peakVramBytes : undefined);
+ return Response.json(answer, { headers: { "Cache-Control": "no-store" } });
} catch (e) {
return relayAnswer(e);
} finally {
diff --git a/src/components/settings-form.tsx b/src/components/settings-form.tsx
index 5fed27c0..e6a14529 100644
--- a/src/components/settings-form.tsx
+++ b/src/components/settings-form.tsx
@@ -7,6 +7,7 @@ import { useEffect, useState, useSyncExternalStore } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { ConnectChoice, OwnerComfyWhere } from "@/components/gpu/connect-choice";
+import { WorkersChip } from "@/components/workers-admin";
import { usePagePlace } from "@/components/gpu/use-local-comfy";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
@@ -476,6 +477,8 @@ function LocalComfy({ get, onWhere }: { get: (n: string) => PublicSetting | unde
return (
<>
<OwnerComfyWhere value={get("comfyWhere")?.value || "server"} onChange={onWhere} />
+ {get("comfyWhere")?.value === "workers" && <p className="text-[13px] text-muted-foreground">ComfyUI jobs run on your workers now.</p>}
+ <WorkersChip />
<ConnectField name="comfyUrl" setting={get("comfyUrl")} provider="comfyui" label="ComfyUI server URL" placeholder="http://127.0.0.1:8188" hint="Where ComfyUI listens; a local install is http://127.0.0.1:8188." />
<ConnectField name="comfyToken" setting={get("comfyToken")} provider="comfyui" label="Auth token (optional)" hint="Sent as a Bearer token, for ComfyUI behind a proxy." />
<ConnectField
diff --git a/src/components/workers-admin.tsx b/src/components/workers-admin.tsx
new file mode 100644
index 00000000..57491267
--- /dev/null
+++ b/src/components/workers-admin.tsx
@@ -0,0 +1,318 @@
+"use client";
+
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { Copy, Cpu, KeyRound, Pause, Play, Plus, RotateCw, Square, Trash2 } from "lucide-react";
+import Link from "next/link";
+import { useState } from "react";
+import { toast } from "sonner";
+import { useSettings } from "@/components/connect-field";
+import { gib } from "@/components/gpu/comfy-finder";
+import { useNow } from "@/components/studio/use-now";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { useHydrated, useViewer } from "@/lib/api";
+import { copyWithToast } from "@/lib/clipboard";
+import { deviceLabel } from "@/lib/gpu/readiness";
+import { cn } from "@/lib/utils";
+
+/**
+ * Settings → Workers (the owner only, docs/gpu-workers.md): the GPUs on other machines that run this studio's ComfyUI
+ * jobs. Each says its state in words; the owner adds one (its token is shown once), pauses it, stops its job now, lets
+ * it finish then pause, sets its hours and the lanes it may run, gives it a new token or revokes it. Works on a phone.
+ */
+
+type Hours = { always: true } | { tz: string; days: Record<string, [string, string][]> };
+
+interface WorkerView {
+ id: string;
+ name: string;
+ pool: string;
+ state: string;
+ words: string;
+ pausedServer: boolean;
+ pausedLocal: boolean;
+ drain: boolean;
+ hours: Hours | null;
+ allow: Record<string, { delayMs: number }>;
+ lanes: string[];
+ warmLane: string | null;
+ facts: { device?: string; vramBytes?: number; version?: string };
+ seenAt: number | null;
+ version: string | null;
+ current: { taskId: string; lane: string | null; startedAt: number | null } | null;
+}
+interface Lane {
+ lane: string;
+ label: string;
+ workflows: number;
+}
+
+async function call<T>(method: string, url: string, body?: unknown): Promise<T> {
+ const res = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
+ const j = (await res.json().catch(() => ({}))) as T & { error?: string };
+ if (!res.ok) throw new Error(j.error ?? `Request failed (${res.status})`);
+ return j;
+}
+
+const DAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
+const zone = () => Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
+
+function hoursWords(h: Hours | null): string {
+ if (!h) return "No hours yet: it takes nothing";
+ if ("always" in h) return "All day, every day";
+ const first = Object.values(h.days).find((w) => w?.length)?.[0];
+ return first ? `Every day ${first[0]}–${first[1]} (${h.tz})` : "No hours yet: it takes nothing";
+}
+
+function TokenOnce({ token, onDone }: { token: string; onDone: () => void }) {
+ return (
+ <div className="space-y-2 rounded-xl border border-amber-500/40 bg-amber-500/5 p-3 text-[13px]">
+ <p className="flex items-center gap-2 font-medium">
+ <KeyRound className="size-4" /> The worker&apos;s token. It is shown only now.
+ </p>
+ <div className="flex items-center gap-2 rounded-lg bg-muted px-2.5 py-2">
+ <code className="min-w-0 flex-1 overflow-x-auto font-mono text-[12px] whitespace-nowrap">{token}</code>
+ <button type="button" onClick={() => void copyWithToast(token)} aria-label="Copy the token" className="grid size-7 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-background">
+ <Copy className="size-3.5" />
+ </button>
+ </div>
+ <p className="text-muted-foreground">
+ On the GPU&apos;s PC, run <code className="font-mono">node bin/fuobe.mjs worker setup</code> and paste it when asked. See{" "}
+ <a className="text-brand-text underline-offset-4 hover:underline" href="https://github.com/workingprototype/Fuobe/blob/main/docs/gpu-workers.md" target="_blank" rel="noreferrer">
+ the workers guide
+ </a>
+ .
+ </p>
+ <Button size="sm" variant="secondary" onClick={onDone}>
+ I saved it
+ </Button>
+ </div>
+ );
+}
+
+function HoursEditor({ w, onSave }: { w: WorkerView; onSave: (hours: Hours | null) => void }) {
+ const cur = w.hours && "days" in w.hours ? Object.values(w.hours.days).find((x) => x?.length)?.[0] : undefined;
+ const [from, setFrom] = useState(cur?.[0] ?? "01:00");
+ const [to, setTo] = useState(cur?.[1] ?? "09:00");
+ return (
+ <div className="flex flex-wrap items-center gap-2 text-[13px]">
+ <span className="text-muted-foreground">Hours:</span>
+ <Button size="sm" variant={w.hours && "always" in w.hours ? "secondary" : "ghost"} className="h-8" onClick={() => onSave({ always: true })}>
+ All day
+ </Button>
+ <span className="text-muted-foreground">or every day</span>
+ <Input aria-label="From" value={from} onChange={(e) => setFrom(e.target.value)} className="h-8 w-20" />
+ <span>–</span>
+ <Input aria-label="To" value={to} onChange={(e) => setTo(e.target.value)} className="h-8 w-20" />
+ <Button size="sm" variant="secondary" className="h-8" onClick={() => onSave({ tz: zone(), days: Object.fromEntries(DAYS.map((d) => [d, [[from, to]]])) as Record<string, [string, string][]> })}>
+ Set
+ </Button>
+ <Button size="sm" variant="ghost" className="h-8" onClick={() => onSave(null)}>
+ None
+ </Button>
+ </div>
+ );
+}
+
+function LanesEditor({ w, lanes, onSave }: { w: WorkerView; lanes: Lane[]; onSave: (allow: Record<string, { delayMs: number }>) => void }) {
+ const [allow, setAllow] = useState(w.allow);
+ const capable = new Set(w.lanes);
+ const sorted = [...lanes].sort((a, b) => Number(capable.has(b.lane)) - Number(capable.has(a.lane)) || a.label.localeCompare(b.label));
+ return (
+ <details className="text-[13px]">
+ <summary className="cursor-pointer text-muted-foreground">
+ Lanes it may run: {Object.keys(w.allow).length} of {lanes.length} ({w.lanes.length} it has the files for)
+ </summary>
+ <ul className="mt-2 max-h-72 space-y-1 overflow-y-auto">
+ {sorted.map((l) => (
+ <li key={l.lane} className="flex flex-wrap items-center gap-2">
+ <label className="flex min-w-0 flex-1 items-center gap-2">
+ <input
+ type="checkbox"
+ checked={l.lane in allow}
+ onChange={(e) => {
+ const next = { ...allow };
+ if (e.target.checked) next[l.lane] = { delayMs: 0 };
+ else delete next[l.lane];
+ setAllow(next);
+ }}
+ />
+ <span className={cn("truncate", !capable.has(l.lane) && "text-muted-foreground")}>{l.label}</span>
+ {!capable.has(l.lane) && <span className="text-[11px] text-muted-foreground">(files missing)</span>}
+ </label>
+ {l.lane in allow && (
+ <label className="flex items-center gap-1 text-[12px] text-muted-foreground">
+ wait
+ <Input
+ aria-label={`Delay for ${l.label}`}
+ className="h-7 w-14"
+ inputMode="numeric"
+ value={String(Math.round((allow[l.lane]?.delayMs ?? 0) / 1000))}
+ onChange={(e) => setAllow({ ...allow, [l.lane]: { delayMs: Math.max(0, Number(e.target.value) || 0) * 1000 } })}
+ />
+ s first
+ </label>
+ )}
+ </li>
+ ))}
+ </ul>
+ <Button size="sm" variant="secondary" className="mt-2 h-8" onClick={() => onSave(allow)}>
+ Save lanes
+ </Button>
+ </details>
+ );
+}
+
+function WorkerCard({ w, lanes, onToken }: { w: WorkerView; lanes: Lane[]; onToken: (t: string) => void }) {
+ const qc = useQueryClient();
+ const now = useNow(10_000);
+ const patch = useMutation({
+ mutationFn: (body: Record<string, unknown>) => call<{ worker: WorkerView | null; token?: string }>("PATCH", `/api/admin/workers/${encodeURIComponent(w.id)}`, body),
+ onSuccess: (r) => {
+ if (r.token) onToken(r.token);
+ void qc.invalidateQueries({ queryKey: ["admin", "workers"] });
+ },
+ onError: (e) => toast.error((e as Error).message),
+ });
+ const gpu = [w.facts.device && deviceLabel(w.facts.device), gib(w.facts.vramBytes), w.version && `worker ${w.version}`].filter(Boolean).join(" · ");
+ const seen = w.seenAt ? `${Math.max(0, Math.round((now - w.seenAt) / 1000))} s ago` : "never";
+ return (
+ <li className="space-y-2 rounded-xl border p-3">
+ <div className="flex flex-wrap items-start justify-between gap-2">
+ <div className="min-w-0">
+ <p className="flex items-center gap-2 text-[14px] font-medium">
+ <Cpu className="size-4 text-brand-text" /> {w.name}
+ </p>
+ <p className="text-[13px]">{w.words}</p>
+ <p className="truncate text-[12px] text-muted-foreground">{[gpu, `heard from ${seen}`].filter(Boolean).join(" · ")}</p>
+ </div>
+ <div className="flex flex-wrap gap-1.5">
+ {w.pausedServer ? (
+ <Button size="sm" className="h-8" disabled={patch.isPending} onClick={() => patch.mutate({ paused: false })}>
+ <Play /> Resume
+ </Button>
+ ) : (
+ <>
+ <Button size="sm" variant="secondary" className="h-8" disabled={patch.isPending} onClick={() => patch.mutate({ paused: true })}>
+ <Pause /> Pause
+ </Button>
+ <Button size="sm" variant="ghost" className="h-8" disabled={patch.isPending || !w.current} onClick={() => patch.mutate({ pauseNow: true })}>
+ <Square /> Pause now
+ </Button>
+ <Button size="sm" variant="ghost" className="h-8" disabled={patch.isPending || w.drain} onClick={() => patch.mutate({ drain: true })}>
+ Finish, then pause
+ </Button>
+ </>
+ )}
+ </div>
+ </div>
+ <p className="text-[12px] text-muted-foreground">{hoursWords(w.hours)}</p>
+ <HoursEditor w={w} onSave={(hours) => patch.mutate({ hours })} />
+ <LanesEditor key={JSON.stringify(w.allow)} w={w} lanes={lanes} onSave={(allow) => patch.mutate({ allow })} />
+ <div className="flex flex-wrap gap-1.5 border-t pt-2">
+ <Button size="sm" variant="ghost" className="h-8" disabled={patch.isPending} onClick={() => patch.mutate({ rotate: true })}>
+ <RotateCw /> New token
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ className="h-8 text-destructive"
+ disabled={patch.isPending}
+ onClick={() => {
+ if (window.confirm(`Revoke ${w.name}? Its token stops at once, and its job goes back in line.`)) patch.mutate({ revoke: true });
+ }}
+ >
+ <Trash2 /> Revoke
+ </Button>
+ </div>
+ </li>
+ );
+}
+
+export function useWorkers(enabled: boolean) {
+ return useQuery({
+ queryKey: ["admin", "workers"],
+ queryFn: () => call<{ workers: WorkerView[]; lanes: Lane[] }>("GET", "/api/admin/workers"),
+ enabled,
+ refetchInterval: 10_000,
+ });
+}
+
+/** The whole Workers screen. */
+export function WorkersAdmin() {
+ const hydrated = useHydrated();
+ const owner = useViewer().data?.owner;
+ const q = useWorkers(!!owner);
+ const qc = useQueryClient();
+ const [name, setName] = useState("");
+ const [token, setToken] = useState<string | null>(null);
+ const add = useMutation({
+ mutationFn: () => call<{ id: string; token: string }>("POST", "/api/admin/workers", { name }),
+ onSuccess: (r) => {
+ setToken(r.token);
+ setName("");
+ void qc.invalidateQueries({ queryKey: ["admin", "workers"] });
+ },
+ onError: (e) => toast.error((e as Error).message),
+ });
+ const where = useSettings(!!owner);
+ const onWorkers = where.data?.find((s) => s.name === "comfyWhere")?.value === "workers";
+ const setWhere = useMutation({
+ mutationFn: (v: string) => call("PUT", "/api/settings", { comfyWhere: v }),
+ onSuccess: () => void qc.invalidateQueries({ queryKey: ["settings"] }),
+ onError: (e) => toast.error((e as Error).message),
+ });
+ if (!hydrated) return null;
+ if (!owner) return <p className="text-[14px] text-muted-foreground">Only the studio&apos;s owner manages workers.</p>;
+ const workers = q.data?.workers ?? [];
+ return (
+ <div className="space-y-6">
+ <div className="space-y-2">
+ <p className="max-w-2xl text-[14px] text-muted-foreground">
+ A worker is a program on another PC with a GPU. It takes this studio&apos;s ComfyUI jobs over HTTPS and runs them on its own ComfyUI, so you can share GPUs with your team or
+ your other machines. It opens no port. A new worker starts paused, with no hours and no lanes.
+ </p>
+ <label className="flex items-center gap-2 text-[14px]">
+ <input type="checkbox" checked={onWorkers} disabled={setWhere.isPending || !where.data} onChange={(e) => setWhere.mutate(e.target.checked ? "workers" : "server")} />
+ Run this studio&apos;s ComfyUI jobs on the workers
+ </label>
+ </div>
+ {token && <TokenOnce token={token} onDone={() => setToken(null)} />}
+ <form
+ className="flex flex-wrap items-center gap-2"
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (name.trim()) add.mutate();
+ }}
+ >
+ <Input aria-label="Worker name" placeholder="A name, like pc-3060ti" value={name} onChange={(e) => setName(e.target.value)} className="h-9 w-56" />
+ <Button size="sm" className="h-9" disabled={!name.trim() || add.isPending}>
+ <Plus /> Add a worker
+ </Button>
+ </form>
+ {q.isError && <p className="text-[13px] text-destructive">{(q.error as Error).message}</p>}
+ {workers.length ? (
+ <ul className="space-y-3">
+ {workers.map((w) => (
+ <WorkerCard key={w.id} w={w} lanes={q.data?.lanes ?? []} onToken={setToken} />
+ ))}
+ </ul>
+ ) : (
+ q.data && <p className="text-[13px] text-muted-foreground">No workers yet.</p>
+ )}
+ </div>
+ );
+}
+
+/** The Workers line in Settings: how many, and the way in. */
+export function WorkersChip() {
+ const owner = useViewer().data?.owner;
+ const q = useWorkers(!!owner);
+ if (!owner) return null;
+ const n = q.data?.workers.length ?? 0;
+ return (
+ <Link href="/settings/workers" className="text-[13px] text-brand-text underline-offset-4 hover:underline">
+ {n ? `Workers: ${n}` : "Workers: share your GPUs with other machines"}
+ </Link>
+ );
+}
diff --git a/src/lib/lanes.ts b/src/lib/lanes.ts
new file mode 100644
index 00000000..228ff3e7
--- /dev/null
+++ b/src/lib/lanes.ts
@@ -0,0 +1,123 @@
+/**
+ * Lanes: the jobs that load the same big model files, so a worker that has them loaded runs the next one with no reload
+ * (docs/gpu-workers.md). A lane is named by its files, never by hand: the first 12 hex digits of the SHA-256 of the
+ * sorted names of a workflow's files over 2 GB in workflows/comfyui/requirements.json. Two workflows that load the same
+ * diffusion model and text encoder share a lane. A workflow with no big file has the lane "small".
+ *
+ * Pure: the server, the worker program and the tests share it. `sha256hex` is passed in (node:crypto on the server).
+ */
+import type { IndexWorkflow, RequirementIndex } from "./gpu/types";
+
+export const BIG_FILE_BYTES = 2 * 2 ** 30;
+export const SMALL_LANE = "small";
+
+export interface FileNeed {
+ folder: string;
+ name: string;
+ size: number;
+ sha256: string | null;
+}
+
+/** What a task needs from the worker that takes it. */
+export interface Needs {
+ workflowId: string;
+ files: FileNeed[];
+ packs: string[];
+ minVramBytes: number;
+}
+
+type Sha = (text: string) => string;
+
+const bigFiles = (index: RequirementIndex, wf: IndexWorkflow) =>
+ wf.files
+ .map((k) => index.files[k])
+ .filter((f) => f && f.sizeBytes > BIG_FILE_BYTES)
+ .map((f) => `${f.folder}/${f.file}`)
+ .sort();
+
+/** A workflow's lane key, or "small". Null: no such workflow. */
+export function laneOf(index: RequirementIndex, workflowId: string, sha: Sha): string | null {
+ const wf = index.workflows[workflowId];
+ if (!wf) return null;
+ const big = bigFiles(index, wf);
+ return big.length ? sha(big.join("\n")).slice(0, 12) : SMALL_LANE;
+}
+
+/** A readable name for a lane: its biggest file's name, cleaned ("wan2.2 i2v high noise 14B fp8"). */
+export function laneLabel(index: RequirementIndex, lane: string, sha: Sha): string {
+ if (lane === SMALL_LANE) return "Small jobs";
+ for (const [id, wf] of Object.entries(index.workflows)) {
+ if (laneOf(index, id, sha) !== lane) continue;
+ const biggest = wf.files.map((k) => index.files[k]).filter(Boolean).sort((a, b) => b.sizeBytes - a.sizeBytes)[0];
+ if (biggest) return biggest.file.replace(/\.(safetensors|gguf|pth|ckpt)$/i, "").replace(/[_-]+/g, " ");
+ }
+ return lane;
+}
+
+/** Every lane in the index, with its label and the workflows in it. */
+export function allLanes(index: RequirementIndex, sha: Sha): { lane: string; label: string; workflows: string[] }[] {
+ const by = new Map<string, string[]>();
+ for (const id of Object.keys(index.workflows)) {
+ const lane = laneOf(index, id, sha)!;
+ by.set(lane, [...(by.get(lane) ?? []), id]);
+ }
+ return [...by].map(([lane, workflows]) => ({ lane, label: laneLabel(index, lane, sha), workflows })).sort((a, b) => a.label.localeCompare(b.label));
+}
+
+/** What a workflow's task needs: its default files (folder, name, exact size, sha256 when pinned), packs and VRAM. */
+export function needsOf(index: RequirementIndex, workflowId: string): Needs | null {
+ const wf = index.workflows[workflowId];
+ if (!wf) return null;
+ const files = wf.files
+ .map((k) => index.files[k])
+ .filter(Boolean)
+ .map((f) => ({ folder: f.folder, name: f.file, size: f.sizeBytes, sha256: f.sha256 ?? null }));
+ return { workflowId, files, packs: Object.keys(wf.packs).sort(), minVramBytes: Math.round((wf.vramGb || 0) * 2 ** 30) };
+}
+
+/** A worker's verified files and node packs (PUT /api/gpu/computer/inventory). */
+export interface Inventory {
+ files: FileNeed[];
+ nodePacks: { name: string; commit: string | null }[];
+}
+
+const fileKey = (f: Pick<FileNeed, "folder" | "name">) => `${f.folder}/${f.name}`;
+
+/** Has the worker this file: folder, name and exact size always; the SHA-256 too when the index pins one. */
+export function hasFile(inv: Inventory, need: FileNeed): boolean {
+ return inv.files.some((f) => fileKey(f) === fileKey(need) && f.size === need.size && (!need.sha256 || f.sha256 === need.sha256));
+}
+
+/**
+ * What a worker can run with what it has: the workflows whose files and packs are all there, the lanes whose every
+ * workflow runs, and, for the other lanes, what it lacks. A task goes only to a worker that can run its workflow.
+ */
+export function lanesFor(
+ index: RequirementIndex,
+ inv: Inventory,
+ sha: Sha,
+): { lanes: string[]; workflows: string[]; missing: { lane: string; label: string; files: string[]; bytes: number }[] } {
+ const packs = new Set(inv.nodePacks.map((p) => p.name));
+ const ok = new Map<string, boolean>();
+ const workflows: string[] = [];
+ const lacking = new Map<string, Map<string, number>>();
+ for (const id of Object.keys(index.workflows)) {
+ if (index.workflows[id].isolated) continue;
+ const lane = laneOf(index, id, sha)!;
+ const n = needsOf(index, id)!;
+ const missingFiles = n.files.filter((f) => !hasFile(inv, f));
+ const missingPacks = n.packs.filter((p) => !packs.has(p));
+ const fine = !missingFiles.length && !missingPacks.length;
+ if (fine) workflows.push(id);
+ ok.set(lane, (ok.get(lane) ?? true) && fine);
+ if (!fine) {
+ const m = lacking.get(lane) ?? new Map<string, number>();
+ for (const f of missingFiles) m.set(fileKey(f), f.size);
+ for (const p of missingPacks) m.set(`pack:${p}`, 0);
+ lacking.set(lane, m);
+ }
+ }
+ const lanes = [...ok].filter(([, v]) => v).map(([k]) => k).sort();
+ const missing = [...lacking].map(([lane, m]) => ({ lane, label: laneLabel(index, lane, sha), files: [...m.keys()].sort(), bytes: [...m.values()].reduce((a, b) => a + b, 0) }));
+ return { lanes, workflows: workflows.sort(), missing };
+}
diff --git a/src/lib/relay.ts b/src/lib/relay.ts
index f046f23b..8ceebe13 100644
--- a/src/lib/relay.ts
+++ b/src/lib/relay.ts
@@ -24,7 +24,7 @@ export interface HistoryEntryLike {
}
/** Why the tab gave up on a task by itself (the server says it in plain words). */
-export const TAB_FAILURES = ["input-too-big", "input-changed", "unsafe-graph", "output-missing", "comfy-error", "save-failed"] as const;
+export const TAB_FAILURES = ["input-too-big", "input-changed", "unsafe-graph", "output-missing", "comfy-error", "save-failed", "unknown-node", "unsafe-path", "model-unverified"] as const;
export type TabFailure = (typeof TAB_FAILURES)[number];
/** What the tab reports about one task. */
@@ -37,8 +37,8 @@ export type ReportEvent =
| { event: "queued"; position: number }
/** Running: the sampler's steps, and the node. */
| { event: "running"; value?: number; max?: number; node?: string; nodesDone?: number }
- /** Finished: its /history entry. */
- | { event: "finished"; entry: HistoryEntryLike }
+ /** Finished: its /history entry (a worker adds the most VRAM it took, for the benchmarks). */
+ | { event: "finished"; entry: HistoryEntryLike; peakVramBytes?: number }
/** A meta-batch job (VHS re-queues it pass by pass): whether a pass is still queued, and the passes' entries so far. */
| { event: "passes"; running: boolean; entries: HistoryEntryLike[] }
/** ComfyUI has no trace of it (restarted): the server sends it again once. */
@@ -109,6 +109,13 @@ export interface ClaimedTask {
/** Collecting: the files still to upload, and how far each got. */
wanted?: WantedFile[];
received?: { n: number; bytes: number; done: boolean }[];
+ /** A worker's task (docs/gpu-workers.md): its lane, how long it should take there, when to stop it, and its files. */
+ lane?: string;
+ estMs?: number | null;
+ runLimitMs?: number;
+ notAfter?: number | null;
+ attempt?: number;
+ models?: { folder: string; name: string; size: number; sha256: string | null }[];
}
/** The tab's facts about its ComfyUI (never its command line: that holds paths and user names). */
@@ -140,6 +147,43 @@ export interface BeatAnswer {
waiting: number;
/** Prompts to take off this computer's ComfyUI. */
stops: { task: string; promptId: string; prefix?: string }[];
+ /** A worker's own (docs/gpu-workers.md): what the studio says about it now. */
+ worker?: WorkerAnswer;
+}
+
+/** The beat's answer for a worker. */
+export interface WorkerAnswer {
+ /** Paused on the website. */
+ paused: boolean;
+ /** Stop the current job now (it went back in line). */
+ pauseNow: boolean;
+ /** Finish the current job, then take nothing new. */
+ drain: boolean;
+ insideHours: boolean;
+ /** When its hours start or end next. */
+ nextChangeAt: number | null;
+ /** Lanes the owner allows it. */
+ lanes: string[];
+ minProtocol: number;
+ /** Its inventory is unknown or changed: send it (PUT /api/gpu/computer/inventory). */
+ sendInventory: boolean;
+}
+
+/** What a worker says in its beat, on top of a browser's. */
+export interface WorkerBeat {
+ device: string;
+ protocol: number;
+ version: string;
+ ready: boolean;
+ why: string | null;
+ /** Its own pause switch: by hand ("here", "here-until:<ms>"), by itself ("gpu-busy:<process>", "comfy-crashes", "port-busy"). */
+ local: { paused: boolean; why: string | null; until: number | null };
+ gpu: { otherApps: { pid: number; name: string; vramBytes: number }[]; tempC: number | null };
+ facts?: ComputerFacts;
+ inventoryHash: string | null;
+ warmLane: string | null;
+ running: { task: string; position?: number; value?: number; max?: number; node?: string; nodesDone?: number }[];
+ stopped: string[];
}
/** Task timings (DESIGN 5.5): the runner lease, how often the tab beats, when a computer counts as gone. */
@@ -157,6 +201,10 @@ export const RELAY_TIMES = {
keepMs: 24 * 60 * 60_000,
/** An input staged for a task that never came. */
stagedMs: 60 * 60_000,
+ /** A worker silent this long (no beat) gives its task back to the line. */
+ poolSilentMs: 2 * 60_000,
+ /** A worker's ComfyUI down this long gives its task back to the line. */
+ poolComfyDownMs: 2 * 60_000,
};
/**
@@ -299,6 +347,12 @@ export function tabFailureWords(reason: TabFailure, status?: number): string {
return "Your ComfyUI no longer has this run's result. Press Retry.";
case "save-failed":
return "Saving the result to Fuobe failed three times. Check your connection, then press Retry.";
+ case "unknown-node":
+ return "The GPU that took this run refused it: it uses a node that GPU doesn't allow.";
+ case "unsafe-path":
+ return "The GPU that took this run refused it: it names a file path.";
+ case "model-unverified":
+ return "The GPU that took this run refused it: it needs a model file that GPU couldn't verify.";
default:
return `Your ComfyUI answered HTTP ${Number.isInteger(status) ? status : "?"}. Check that it's running, then press Retry.`;
}
diff --git a/src/lib/worker-hours.ts b/src/lib/worker-hours.ts
new file mode 100644
index 00000000..b8743068
--- /dev/null
+++ b/src/lib/worker-hours.ts
@@ -0,0 +1,104 @@
+/**
+ * A worker's allowed hours (docs/gpu-workers.md): a time zone and weekly windows, as the owner sets them in Settings →
+ * Workers. `{ "tz": "Asia/Kolkata", "days": { "mon": [["01:00", "09:00"]], … } }`; `{ "always": true }` for all day,
+ * every day. No hours at all: never (a new worker takes nothing until the owner sets them). A window whose end is not
+ * after its start runs past midnight ("22:00"–"06:00"). "24:00" is the end of the day.
+ *
+ * Pure: the server and the tests share it. Daylight-saving jumps move a window by the jump at most.
+ */
+
+export const DAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"] as const;
+export type Day = (typeof DAYS)[number];
+
+export type Hours = { always: true } | { tz: string; days: Partial<Record<Day, [string, string][]>> };
+
+const HHMM = /^([01]\d|2[0-4]):([0-5]\d)$/;
+const minutes = (t: string) => {
+ const m = HHMM.exec(t);
+ if (!m) return null;
+ const v = Number(m[1]) * 60 + Number(m[2]);
+ return v <= 24 * 60 ? v : null;
+};
+
+/** Hours as stored, checked: null when they are not valid. */
+export function parseHours(value: unknown): Hours | null {
+ if (!value || typeof value !== "object") return null;
+ const v = value as Record<string, unknown>;
+ if (v.always === true) return { always: true };
+ if (typeof v.tz !== "string" || !validZone(v.tz) || !v.days || typeof v.days !== "object") return null;
+ const days: Partial<Record<Day, [string, string][]>> = {};
+ for (const [d, list] of Object.entries(v.days as Record<string, unknown>)) {
+ if (!(DAYS as readonly string[]).includes(d) || !Array.isArray(list) || list.length > 8) return null;
+ const ok = list.every((w) => Array.isArray(w) && w.length === 2 && typeof w[0] === "string" && typeof w[1] === "string" && minutes(w[0]) !== null && minutes(w[1]) !== null && w[0] !== w[1]);
+ if (!ok) return null;
+ days[d as Day] = list as [string, string][];
+ }
+ return { tz: v.tz, days };
+}
+
+export function validZone(tz: string): boolean {
+ try {
+ new Intl.DateTimeFormat("en-US", { timeZone: tz });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** The weekday (0 = Sunday) and minute of the day at `now` in `tz`. */
+function local(now: number, tz: string): { day: number; minute: number } {
+ const parts = new Intl.DateTimeFormat("en-US", { timeZone: tz, weekday: "short", hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).formatToParts(new Date(now));
+ const get = (t: string) => parts.find((p) => p.type === t)?.value ?? "";
+ const day = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].indexOf(get("weekday"));
+ return { day, minute: Number(get("hour")) * 60 + Number(get("minute")) };
+}
+
+/** Every window as [start, end) in minutes from the start of this local week (Sunday 00:00), over two weeks. */
+function spans(h: Exclude<Hours, { always: true }>): [number, number][] {
+ const out: [number, number][] = [];
+ for (let week = 0; week < 2; week++) {
+ DAYS.forEach((d, i) => {
+ for (const [a, b] of h.days[d] ?? []) {
+ const s = minutes(a)!;
+ let e = minutes(b)!;
+ if (e <= s) e += 24 * 60;
+ const base = (week * 7 + i) * 24 * 60;
+ out.push([base + s, base + e]);
+ }
+ });
+ }
+ // Windows that touch become one (Monday until 24:00 and Tuesday from 00:00).
+ out.sort((x, y) => x[0] - y[0]);
+ const merged: [number, number][] = [];
+ for (const w of out) {
+ const last = merged.at(-1);
+ if (last && w[0] <= last[1]) last[1] = Math.max(last[1], w[1]);
+ else merged.push([...w]);
+ }
+ return merged;
+}
+
+/** Where `now` is: inside a window (and when it ends), or outside (and when the next one starts). Null hours: never. */
+export function hoursAt(hours: Hours | null, now: number): { inside: boolean; endsAt: number | null; nextChangeAt: number | null } {
+ if (!hours) return { inside: false, endsAt: null, nextChangeAt: null };
+ if ("always" in hours) return { inside: true, endsAt: null, nextChangeAt: null };
+ const { day, minute } = local(now, hours.tz);
+ // Minutes since the start of this local week; also look at last week's windows that run into this one.
+ const at = day * 24 * 60 + minute;
+ const all = spans(hours);
+ const shifted = all.flatMap(([s, e]) => [[s, e] as [number, number], [s - 7 * 24 * 60, e - 7 * 24 * 60] as [number, number]]);
+ const nowMs = now - (now % 60_000);
+ const toMs = (m: number) => nowMs + (m - at) * 60_000;
+ const cur = shifted.find(([s, e]) => s <= at && at < e);
+ if (cur) {
+ // An all-week window never ends.
+ return cur[1] - cur[0] >= 7 * 24 * 60 ? { inside: true, endsAt: null, nextChangeAt: null } : { inside: true, endsAt: toMs(cur[1]), nextChangeAt: toMs(cur[1]) };
+ }
+ const next = shifted.filter(([s]) => s > at).sort((x, y) => x[0] - y[0])[0];
+ return { inside: false, endsAt: null, nextChangeAt: next ? toMs(next[0]) : null };
+}
+
+/** "back at 01:00" in the worker's own zone. */
+export function clock(ms: number, tz?: string): string {
+ return new Intl.DateTimeFormat("en-GB", { timeZone: tz, hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).format(new Date(ms));
+}
diff --git a/src/server/computer/bench.ts b/src/server/computer/bench.ts
new file mode 100644
index 00000000..eb974aff
--- /dev/null
+++ b/src/server/computer/bench.ts
@@ -0,0 +1,58 @@
+import "server-only";
+import { db } from "../db";
+import { json, type TaskRow } from "./tasks";
+import type { WorkerRow } from "./workers";
+
+/**
+ * Benchmarks for workers (docs/gpu-workers.md): how long each lane takes on each worker. Every job a worker finishes
+ * counts (its last 20 per lane give the median and the 90th percentile), so the numbers follow real work. Bench jobs
+ * (one small fixed job per lane, made for one worker only, never billed) fill them in before any real work; a lane
+ * gets one once the catalog defines it (BENCH_JOBS, empty until then).
+ */
+
+export interface LaneBench {
+ medianMs?: number;
+ p90Ms?: number;
+ loadMs?: number;
+ peakVramBytes?: number;
+ /** The last durations, newest last. */
+ runs?: number[];
+}
+
+/** Workflow id → the fixed input of its bench job. Filled in by the catalog's bench definitions. */
+export const BENCH_JOBS: Record<string, { prompt: string; seed: number }> = {};
+
+const KEEP = 20;
+
+const percentile = (sorted: number[], p: number) => sorted[Math.min(sorted.length - 1, Math.floor(p * sorted.length))];
+
+/** A worker finished a task: its time (from start to finish) and peak VRAM count for its lane there. */
+export function noteFinished(t: Pick<TaskRow, "worker_id" | "lane" | "started_at" | "sent_at">, now = Date.now(), peakVramBytes?: number): void {
+ if (!t.worker_id || !t.lane) return;
+ const from = t.started_at ?? t.sent_at;
+ if (!from || now <= from) return;
+ const w = db().prepare("SELECT bench_json FROM relay_workers WHERE id = ?").get(t.worker_id) as { bench_json: string | null } | undefined;
+ if (!w) return;
+ const all = json<Record<string, LaneBench>>(w.bench_json, {});
+ const lane = all[t.lane] ?? {};
+ const runs = [...(lane.runs ?? []), now - from].slice(-KEEP);
+ const sorted = [...runs].sort((a, b) => a - b);
+ all[t.lane] = {
+ ...lane,
+ runs,
+ medianMs: percentile(sorted, 0.5),
+ p90Ms: percentile(sorted, 0.9),
+ ...(peakVramBytes && peakVramBytes > 0 && { peakVramBytes: Math.max(peakVramBytes, lane.peakVramBytes ?? 0) }),
+ };
+ db().prepare("UPDATE relay_workers SET bench_json = ? WHERE id = ?").run(JSON.stringify(all), t.worker_id);
+}
+
+/** Bench tasks for this worker's allowed lanes (or the ones asked for): how many were made. */
+export async function benchTasks(w: WorkerRow, lanes?: string[]): Promise<number> {
+ const allowed = Object.keys(json<Record<string, unknown>>(w.allow_json, {}));
+ const want = lanes ? allowed.filter((l) => lanes.includes(l)) : allowed;
+ if (!want.length || !Object.keys(BENCH_JOBS).length) return 0;
+ // The catalog defines no bench job yet; when it does, each runs through the owner's normal run path with
+ // only_worker set to this worker (pool.ts poolFields).
+ return 0;
+}
diff --git a/src/server/computer/http.ts b/src/server/computer/http.ts
index 2643bfd4..0e3142e1 100644
--- a/src/server/computer/http.ts
+++ b/src/server/computer/http.ts
@@ -46,10 +46,12 @@ export function principalOf(request: Request): Principal | Response {
function workerPrincipal(request: Request, auth: string, no: (status: number, error: string, extra?: Record<string, unknown>) => Response): Principal | Response {
const w = workerFromAuth(auth, request.headers.get("cf-ipcountry"));
if (!w) return no(401, "This ComfyUI isn't paired with this studio any more. Pair it again from Fuobe Connect.", { code: "worker-token" });
- if (w.kind !== "personal" || !w.principal) return no(403, "Shared workers aren't switched on for this studio.", { code: "pool-off" });
const host = request.headers.get("host") ?? new URL(request.url).host;
if (!authEnabled() && !hostAllowed(host)) return no(403, "Blocked a request for an address this studio isn't reached at.");
workerOfRequest.set(request, w);
+ // One of the owner's shared GPUs (docs/gpu-workers.md): it takes tasks for its pool, never a person's own.
+ if (w.kind === "pool") return `pool:${w.pool}`;
+ if (!w.principal) return no(401, "This worker's token isn't valid.", { code: "worker-token" });
if (w.principal === "owner") {
return getSetting("comfyWhere") === "computer" ? "owner" : no(409, "This studio's ComfyUI runs on its server.", { code: "server-mode" });
}
@@ -66,9 +68,18 @@ function workerPrincipal(request: Request, auth: string, no: (status: number, er
const workerOfRequest = new WeakMap<Request, WorkerRow>();
export const requestWorker = (request: Request): WorkerRow | null => workerOfRequest.get(request) ?? null;
-/** At most `limit` calls a minute of one kind for a principal. */
-export function rateOf(principal: Principal, what: string, limit: number): Response | null {
- const r = hit(`relay-${what}:${principal}`, limit, 60_000);
+/**
+ * Whose limits a call counts against: a principal's (a person's computers share them), or one worker's own (three
+ * workers of one pool that beat every 5 seconds are never held up by each other).
+ */
+export function callerKey(request: Request, principal: Principal): string {
+ const w = workerOfRequest.get(request);
+ return w ? `${principal}:${w.id}` : principal;
+}
+
+/** At most `limit` calls a minute of one kind for a caller (callerKey). */
+export function rateOf(caller: string, what: string, limit: number): Response | null {
+ const r = hit(`relay-${what}:${caller}`, limit, 60_000);
return r.ok ? null : Response.json({ error: "Too many at once. Fuobe tries again by itself." }, { status: 429, headers: { "Retry-After": String(r.retryAfterS), "Cache-Control": "no-store" } });
}
diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.ts
new file mode 100644
index 00000000..d83de66f
--- /dev/null
+++ b/src/server/computer/pool.ts
@@ -0,0 +1,560 @@
+import "server-only";
+import crypto from "node:crypto";
+import { allLanes, laneLabel, lanesFor, needsOf, type Inventory, type Needs } from "@/lib/lanes";
+import { RELAY_TIMES, SENT_STATES, type BeatAnswer, type ClaimedTask, type ComputerFacts, type WorkerAnswer, type WorkerBeat } from "@/lib/relay";
+import { clock, hoursAt, parseHours, type Hours } from "@/lib/worker-hours";
+import { db } from "../db";
+import { loadIndex } from "../gpu/index-file";
+import { cleanFacts, endTask, getTask, json, noteProgress, setPoolClocks, setTask, takeTask, type TaskRow } from "./tasks";
+import { createWorker, revokeWorker, rotateWorker, type WorkerRow } from "./workers";
+
+/**
+ * Workers (docs/gpu-workers.md): the owner's GPUs on other machines, each running `fuobe worker`, which pulls jobs from
+ * this studio over HTTPS and runs them on its own ComfyUI. A task for workers belongs to the owner (or, later, an
+ * account) and names the pools that may take it. This file is the queue's side: the beat, the claim (in one SQLite
+ * transaction, so two workers never take the same task), putting a silent worker's task back in line, inventory and
+ * lanes, and the owner's controls. Nothing here runs unless the owner adds a worker.
+ */
+
+/** The oldest worker program this studio still talks to. */
+export const MIN_PROTOCOL = 1;
+/** A task avoids workers that lost or failed it, unless no other worker that can run it beat this recently. */
+export const RETRY_WINDOW_MS = 10 * 60_000;
+/** Attempts in all before a task fails. */
+export const MAX_ATTEMPTS = 3;
+/** A worker that beat this recently may claim. */
+const FRESH_BEAT_MS = 30_000;
+/** The run limit: 3 × the lane's p90 on that worker, at least 5 minutes, at most 45. */
+export const runLimitMs = (p90?: number | null) => Math.min(45 * 60_000, Math.max(5 * 60_000, 3 * (p90 ?? 0)));
+/** The owner's own tasks go ahead of everyone else's by this much (rank_at = created_at - boost). */
+export const OWNER_BOOST_MS = 24 * 60 * 60_000;
+
+const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
+
+const MAX_RUNNING = 32;
+
+// ---------------------------------------------------------------------------
+// What a worker is now
+
+interface Allow {
+ delayMs: number;
+}
+
+const allowOf = (w: WorkerRow) => json<Record<string, Allow>>(w.allow_json, {});
+const capableOf = (w: WorkerRow) => json<{ lanes: string[]; workflows: string[] }>(w.lanes_json, { lanes: [], workflows: [] });
+const factsOf = (w: WorkerRow) => json<ComputerFacts>(w.facts_json, {});
+const hoursOf = (w: WorkerRow): Hours | null => parseHours(json<unknown>(w.hours_json, null));
+const benchOf = (w: WorkerRow) => json<Record<string, { medianMs?: number; p90Ms?: number; loadMs?: number; peakVramBytes?: number }>>(w.bench_json, {});
+
+export type WorkerState = "new" | "idle" | "busy" | "draining" | "paused" | "outside-hours" | "gpu-busy" | "comfy-down" | "offline";
+
+/** The state in one word, and in words for the owner ("Paused here until 16:30", "Your GPU is busy (blender.exe)"). */
+export function workerState(w: WorkerRow, now = Date.now()): { state: WorkerState; words: string } {
+ const tz = hoursOf(w) && "tz" in hoursOf(w)! ? (hoursOf(w) as { tz: string }).tz : undefined;
+ if (!w.seen_at) return { state: "new", words: "Not connected yet" };
+ if (now - w.seen_at > RELAY_TIMES.poolSilentMs) return { state: "offline", words: "Offline" };
+ const why = w.local_why ?? "";
+ if (w.paused_local) {
+ if (why.startsWith("gpu-busy")) return { state: "gpu-busy", words: `Your GPU is busy${why.includes(":") ? ` (${why.split(":").slice(1).join(":")})` : ""}` };
+ if (why === "comfy-crashes") return { state: "comfy-down", words: "ComfyUI keeps stopping" };
+ if (why === "port-busy") return { state: "comfy-down", words: "Its ComfyUI port is taken by another program" };
+ return { state: "paused", words: w.local_until ? `Paused here until ${clock(w.local_until, tz)}` : "Paused here" };
+ }
+ if (w.paused_server) return { state: "paused", words: "Paused on the website" };
+ const h = hoursAt(hoursOf(w), now);
+ if (!h.inside) return { state: "outside-hours", words: h.nextChangeAt ? `Outside its hours (back at ${clock(h.nextChangeAt, tz)})` : "No hours set" };
+ const busy = (db().prepare(`SELECT COUNT(*) AS n FROM relay_tasks WHERE worker_id = ? AND state IN ('sending','queued','running','collecting')`).get(w.id) as { n: number }).n > 0;
+ if (w.drain) return busy ? { state: "draining", words: "Finishing its job, then pausing" } : { state: "paused", words: "Paused after its last job" };
+ return busy ? { state: "busy", words: "Running a job" } : { state: "idle", words: "Ready" };
+}
+
+/** May this worker take a new task now (4.3: paused in neither place, not draining, inside its hours, new enough, heard from)? */
+export function eligible(w: WorkerRow, now = Date.now()): boolean {
+ return (
+ w.kind === "pool" &&
+ !w.revoked_at &&
+ !(w.expires_at && w.expires_at <= now) &&
+ !w.paused_server &&
+ !w.paused_local &&
+ !w.drain &&
+ (w.protocol ?? 0) >= MIN_PROTOCOL &&
+ !!w.seen_at &&
+ now - w.seen_at <= FRESH_BEAT_MS &&
+ hoursAt(hoursOf(w), now).inside
+ );
+}
+
+// ---------------------------------------------------------------------------
+// The beat
+
+const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : null);
+const text = (v: unknown, max: number) => (typeof v === "string" && v ? v.slice(0, max) : null);
+
+/** A worker's beat as it may be kept: known fields, capped. */
+export function cleanBeat(b: unknown): WorkerBeat {
+ const o = (b && typeof b === "object" ? b : {}) as Record<string, unknown>;
+ const local = (o.local && typeof o.local === "object" ? o.local : {}) as Record<string, unknown>;
+ const gpu = (o.gpu && typeof o.gpu === "object" ? o.gpu : {}) as Record<string, unknown>;
+ const apps = Array.isArray(gpu.otherApps) ? gpu.otherApps.slice(0, 16) : [];
+ return {
+ device: String(o.device ?? ""),
+ protocol: num(o.protocol) ?? 0,
+ version: text(o.version, 40) ?? "",
+ ready: o.ready !== false,
+ why: text(o.why, 64),
+ local: { paused: local.paused !== false, why: text(local.why, 96), until: num(local.until) },
+ gpu: {
+ otherApps: apps.map((a) => ({ pid: num((a as Record<string, unknown>)?.pid) ?? 0, name: text((a as Record<string, unknown>)?.name, 64) ?? "?", vramBytes: num((a as Record<string, unknown>)?.vramBytes) ?? 0 })),
+ tempC: num(gpu.tempC),
+ },
+ ...(o.facts !== undefined && { facts: cleanFacts(o.facts) }),
+ inventoryHash: text(o.inventoryHash, 80),
+ warmLane: text(o.warmLane, 16),
+ running: Array.isArray(o.running) ? (o.running.slice(0, MAX_RUNNING) as WorkerBeat["running"]) : [],
+ stopped: Array.isArray(o.stopped) ? o.stopped.filter((x): x is string => typeof x === "string").slice(0, 64) : [],
+ };
+}
+
+/**
+ * A worker says it is here: its own pause and why, its GPU, its facts, what it runs. The answer: whether it is paused on
+ * the website, a stop-now, drain, its hours, the lanes it is allowed, and the prompts to take off its ComfyUI.
+ */
+export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatAnswer & { worker: WorkerAnswer } {
+ const d = db();
+ const device = `wkr-${w.id}`;
+ return d.transaction(() => {
+ // A worker back after going silent finds its task back in line first (its lease no longer works).
+ sweepPool(now);
+ const facts = b.facts ? { ...b.facts, loras: undefined } : undefined;
+ d.prepare(
+ `UPDATE relay_workers SET seen_at = ?, device = ?, protocol = ?, version = ?, paused_local = ?, local_why = ?, local_until = ?,
+ warm_lane = ?, facts_json = COALESCE(?, facts_json) WHERE id = ?`,
+ ).run(now, device, b.protocol, b.version, b.local.paused ? 1 : 0, b.local.why, b.local.until, b.warmLane, facts ? JSON.stringify(facts) : null, w.id);
+ for (const r of b.running) {
+ const t = typeof r?.task === "string" ? (d.prepare("SELECT * FROM relay_tasks WHERE id = ? AND worker_id = ?").get(r.task, w.id) as TaskRow | undefined) : undefined;
+ if (!t || !(SENT_STATES as readonly string[]).includes(t.state)) continue;
+ setTask(t.id, { device_seen_at: now });
+ noteProgress(t.id, r as unknown as Record<string, unknown>, now);
+ }
+ for (const id of b.stopped) d.prepare("UPDATE relay_tasks SET stop = 0 WHERE id = ? AND device = ?").run(id, device);
+ const stops = (d.prepare("SELECT id, prompt_id, prefix FROM relay_tasks WHERE device = ? AND stop = 1").all(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 fresh = d.prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as WorkerRow;
+ // Stop now (the website, or the worker paused itself with --now / a busy GPU): its jobs go back in line at no cost,
+ // and the worker takes their prompts off its ComfyUI.
+ const stopNow = !!fresh.stop_now || (b.local.paused && !!b.local.why && (b.local.why === "here-now" || b.local.why.startsWith("gpu-busy")));
+ if (stopNow) {
+ for (const t of d.prepare("SELECT * FROM relay_tasks WHERE worker_id = ? AND state IN ('sending','queued','running','collecting')").all(w.id) as TaskRow[]) {
+ if (t.state === "collecting") continue; // Its result is being saved: let it finish.
+ backInLine(t, { blame: false });
+ stops.push({ task: t.id, promptId: t.prompt_id, ...(t.prefix && { prefix: t.prefix }) });
+ }
+ d.prepare("UPDATE relay_workers SET stop_now = 0 WHERE id = ?").run(w.id);
+ }
+ const state = workerState(fresh, now);
+ d.prepare("UPDATE relay_workers SET state = ? WHERE id = ?").run(state.state, w.id);
+ const h = hoursAt(hoursOf(fresh), now);
+ const waiting = (d.prepare("SELECT COUNT(*) AS n FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND (',' || pools || ',') LIKE ?").get(`%,${fresh.pool},%`) as { n: number }).n;
+ return {
+ runner: eligible(fresh, now),
+ heldElsewhere: false,
+ waiting,
+ stops,
+ worker: {
+ paused: !!fresh.paused_server,
+ pauseNow: stopNow,
+ drain: !!fresh.drain,
+ insideHours: h.inside,
+ nextChangeAt: h.nextChangeAt,
+ lanes: Object.keys(allowOf(fresh)),
+ minProtocol: MIN_PROTOCOL,
+ sendInventory: !fresh.inventory_hash || fresh.inventory_hash !== b.inventoryHash,
+ },
+ };
+ })();
+}
+
+// ---------------------------------------------------------------------------
+// Inventory
+
+/** The worker's verified files and node packs: what it can run now, and what each other lane lacks. */
+export function saveInventory(w: WorkerRow, raw: unknown): { lanes: string[]; workflows: string[]; missing: { lane: string; label: string; files: string[]; bytes: number }[] } {
+ const o = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>;
+ const files = (Array.isArray(o.files) ? o.files : []).slice(0, 20_000).flatMap((f) => {
+ const x = f as Record<string, unknown>;
+ const folder = text(x?.folder, 64);
+ const name = text(x?.name, 256);
+ const size = num(x?.size);
+ const sha256 = typeof x?.sha256 === "string" && /^[0-9a-f]{64}$/.test(x.sha256) ? x.sha256 : null;
+ return folder && name && size !== null && !/[\\/]|\.\./.test(name) ? [{ folder, name, size, sha256 }] : [];
+ });
+ const nodePacks = (Array.isArray(o.nodePacks) ? o.nodePacks : []).slice(0, 500).flatMap((p) => {
+ const x = p as Record<string, unknown>;
+ const name = text(x?.name, 128);
+ return name ? [{ name, commit: text(x?.commit, 64) }] : [];
+ });
+ const inv: Inventory = { files, nodePacks };
+ const r = lanesFor(loadIndex(), inv, sha);
+ const invHash = inventoryHash(inv);
+ db()
+ .prepare("UPDATE relay_workers SET inventory_json = ?, inventory_hash = ?, lanes_json = ? WHERE id = ?")
+ .run(JSON.stringify(inv), invHash, JSON.stringify({ lanes: r.lanes, workflows: r.workflows }), w.id);
+ return r;
+}
+
+/** The hash a worker sends with each beat, so the studio asks for the whole list only when it changed. */
+export function inventoryHash(inv: Inventory): string {
+ const files = [...inv.files].map((f) => `${f.folder}/${f.name}:${f.size}:${f.sha256 ?? ""}`).sort();
+ const packs = [...inv.nodePacks].map((p) => `${p.name}@${p.commit ?? ""}`).sort();
+ return sha(JSON.stringify({ files, packs }));
+}
+
+// ---------------------------------------------------------------------------
+// The claim (4.3)
+
+/** Tasks for workers that wait, best first, at most this many looked at per claim. */
+const LOOK_AT = 200;
+
+/**
+ * A worker asks for work, inside one transaction: first a task it had and lost track of; then, if it may take work, the
+ * best waiting task it can run (its pool, its allowed lanes and their delays, the files and VRAM it needs, the retry
+ * rule, and the end of its hours). Sticky lanes: its warm lane goes first until another lane's best task has waited
+ * longer than switch_after_ms (and is older).
+ */
+export function workerClaim(w: WorkerRow, running: string[], now = Date.now()): ClaimedTask | null {
+ const d = db();
+ const device = `wkr-${w.id}`;
+ return d.transaction((): ClaimedTask | null => {
+ sweepPool(now);
+ const fresh = d.prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as WorkerRow;
+ const mine = (d.prepare(`SELECT * FROM relay_tasks WHERE worker_id = ? AND device = ? AND state IN ('sending','queued','running','collecting') AND stop = 0 ORDER BY rank_at`).all(fresh.id, device) as TaskRow[]).find(
+ (t) => !running.includes(t.id),
+ );
+ if (mine) return claimed(mine, fresh, device, now);
+ if (!eligible(fresh, now)) return null;
+ const t = pick(fresh, now);
+ return t ? claimed(t, fresh, device, now) : null;
+ })();
+}
+
+function claimed(t: TaskRow, w: WorkerRow, device: string, now: number): ClaimedTask {
+ const needs = json<Needs | null>(t.needs_json, null);
+ const p90 = t.lane ? benchOf(w)[t.lane]?.p90Ms : undefined;
+ const c = takeTask(t, device, now, { worker_id: w.id });
+ return {
+ ...c,
+ lane: t.lane ?? undefined,
+ estMs: estOn(t, w),
+ runLimitMs: runLimitMs(p90),
+ notAfter: t.not_after,
+ attempt: t.requeues + 1,
+ models: needs?.files ?? [],
+ };
+}
+
+/** How long a task should take on this worker: the lane's bench median there, or the task's own estimate. */
+function estOn(t: TaskRow, w: WorkerRow): number | null {
+ return (t.lane && benchOf(w)[t.lane]?.medianMs) || t.est_ms || null;
+}
+
+/** May this worker run this task: its pool, its lane allowed and capable, its files, its VRAM, and the delays. */
+function fits(t: TaskRow, w: WorkerRow, now: number): boolean {
+ if (!(t.pools ?? "").split(",").includes(w.pool)) return false;
+ if (t.only_worker && t.only_worker !== w.id) return false;
+ if (t.stop) return false;
+ const allow = allowOf(w);
+ const lane = t.lane ?? "";
+ if (!(lane in allow)) return false;
+ const cap = capableOf(w);
+ const needs = json<Needs | null>(t.needs_json, null);
+ if (needs?.workflowId ? !cap.workflows.includes(needs.workflowId) : !cap.lanes.includes(lane)) return false;
+ const vram = factsOf(w).vramBytes ?? 0;
+ if ((needs?.minVramBytes ?? 0) > vram) return false;
+ if (now - t.created_at < w.claim_after_ms + (allow[lane]?.delayMs ?? 0)) return false;
+ return true;
+}
+
+/** The retry rule: a worker that lost or failed this task takes it again only when no other capable worker is about. */
+function retryOk(t: TaskRow, w: WorkerRow, now: number): boolean {
+ const tried = json<string[]>(t.tried_json, []);
+ if (!tried.includes(w.id)) return true;
+ const others = db().prepare("SELECT * FROM relay_workers WHERE kind = 'pool' AND revoked_at IS NULL AND id != ? AND seen_at > ?").all(w.id, now - RETRY_WINDOW_MS) as WorkerRow[];
+ return !others.some((o) => !tried.includes(o.id) && fits(t, o, now + RETRY_WINDOW_MS));
+}
+
+/** Near the end of its hours, only a task that ends before they do. */
+function beforeWindowEnds(t: TaskRow, w: WorkerRow, now: number): boolean {
+ const h = hoursAt(hoursOf(w), now);
+ if (h.endsAt === null) return true;
+ return now + (estOn(t, w) ?? 0) <= h.endsAt;
+}
+
+function pick(w: WorkerRow, now: number): TaskRow | null {
+ const rows = db()
+ .prepare("SELECT * FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND stop = 0 AND (',' || pools || ',') LIKE ? ORDER BY rank_at LIMIT ?")
+ .all(`%,${w.pool},%`, LOOK_AT) as TaskRow[];
+ const ok = rows.filter((t) => fits(t, w, now) && retryOk(t, w, now) && beforeWindowEnds(t, w, now));
+ if (!ok.length) return null;
+ const warm = w.warm_lane ? ok.find((t) => t.lane === w.warm_lane) : undefined;
+ const other = ok.find((t) => t.lane !== w.warm_lane);
+ if (!warm) return other ?? null;
+ if (other && (other.rank_at ?? 0) < now - w.switch_after_ms && (other.rank_at ?? 0) < (warm.rank_at ?? 0)) return other;
+ return warm;
+}
+
+// ---------------------------------------------------------------------------
+// Back in line, and the clocks
+
+/**
+ * A task goes back in line: its worker let it go (`blame: false`: a pause, at no cost to anyone) or lost it (silent,
+ * its ComfyUI down: the worker is noted in tried_json and it counts as an attempt). The third lost attempt fails it.
+ * The old worker's lease stops working, so its late calls get 409.
+ */
+export function backInLine(t: TaskRow, o: { blame: boolean; why?: string }): void {
+ const tried = json<string[]>(t.tried_json, []);
+ const requeues = t.requeues + (o.blame ? 1 : 0);
+ if (o.blame && requeues >= MAX_ATTEMPTS) {
+ endTask(t.id, "failed", { error: o.why ?? "The GPUs couldn't finish this run. Press Retry.", requeues, tried_json: JSON.stringify([...new Set([...tried, t.worker_id ?? ""])].filter(Boolean)) }, true);
+ return;
+ }
+ // A live worker that let it go hears the stop in its beat answer; one that went silent finds its lease gone when it
+ // comes back (409), and takes the prompt off its own ComfyUI.
+ setTask(t.id, {
+ state: "waiting",
+ lease_hash: null,
+ worker_id: null,
+ requeues,
+ sent_at: null,
+ started_at: null,
+ down_at: null,
+ down_why: null,
+ note: "resent",
+ ...(o.blame && t.worker_id && { tried_json: JSON.stringify([...new Set([...tried, t.worker_id])]) }),
+ });
+ db().prepare("UPDATE relay_inputs SET reads = 0 WHERE task_id = ?").run(t.id);
+}
+
+/**
+ * The workers' clocks: a task whose worker went silent for 2 minutes (or was revoked), or whose ComfyUI was down for 2
+ * minutes, goes back in line; a task still waiting past its wait limit fails, not charged.
+ */
+export function sweepPool(now = Date.now()): void {
+ const d = db();
+ const held = d
+ .prepare(
+ `SELECT t.*, w.seen_at AS w_seen, w.revoked_at AS w_revoked FROM relay_tasks t LEFT JOIN relay_workers w ON w.id = t.worker_id
+ WHERE t.pools IS NOT NULL AND t.state IN ('sending','queued','running','collecting')`,
+ )
+ .all() as (TaskRow & { w_seen: number | null; w_revoked: number | null })[];
+ for (const t of held) {
+ const silent = !t.w_seen || now - t.w_seen > RELAY_TIMES.poolSilentMs || !!t.w_revoked;
+ const down = !!t.down_at && now - t.down_at > RELAY_TIMES.poolComfyDownMs;
+ if (silent || down) backInLine(t, { blame: true, why: silent ? "The GPU running this stopped answering, three times. Press Retry." : "ComfyUI kept stopping on the GPUs. Press Retry." });
+ }
+ const late = d.prepare("SELECT id FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND not_after IS NOT NULL AND not_after < ?").all(now) as { id: string }[];
+ for (const t of late) endTask(t.id, "failed", { error: "The GPUs were busy. Not charged." });
+}
+
+setPoolClocks((t, now) => {
+ sweepPool(now);
+ return getTask(t.principal, t.id) ?? t;
+});
+
+// ---------------------------------------------------------------------------
+// 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. */
+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));
+ if (!workers.length) return { place: ahead.length + 1, etaSeconds: null };
+ const own = t.est_ms ?? 60_000;
+ 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) };
+}
+
+// ---------------------------------------------------------------------------
+// Making tasks for workers
+
+/** 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";
+ return {
+ pools: ["pool"],
+ account: o.account,
+ rankAt: now - (o.boostMs ?? 0),
+ lane,
+ needs: needs ?? { workflowId, files: [], packs: [], minVramBytes: 0 },
+ notAfter: o.waitMs ? now + o.waitMs : undefined,
+ onlyWorker: o.onlyWorker,
+ };
+}
+
+/** FUOBE_POOL_WAIT_MIN: how long a task for workers waits before it fails (30 minutes). */
+export const poolWaitMs = () => {
+ const m = Number(process.env.FUOBE_POOL_WAIT_MIN);
+ return (Number.isFinite(m) && m > 0 ? m : 30) * 60_000;
+};
+
+/** The waiting words of a task for workers ("Waiting for a GPU · 2 ahead", "No GPU is on now"). */
+export function poolWaitWords(t: TaskRow, now = Date.now()): string {
+ const p = placeInLine(t, now);
+ if (p.etaSeconds === null) return "Waiting for a GPU to come on";
+ return p.place > 1 ? `Waiting for a GPU · ${p.place - 1} ahead` : "Next for a GPU";
+}
+
+// ---------------------------------------------------------------------------
+// The owner's controls (Settings → Workers, /api/admin/workers)
+
+export interface WorkerView {
+ id: string;
+ name: string;
+ pool: string;
+ state: WorkerState;
+ words: string;
+ pausedServer: boolean;
+ pausedLocal: boolean;
+ localWhy: string | null;
+ drain: boolean;
+ hours: Hours | null;
+ allow: Record<string, Allow>;
+ claimAfterMs: number;
+ switchAfterMs: number;
+ warmLane: string | null;
+ lanes: string[];
+ facts: ComputerFacts;
+ bench: ReturnType<typeof benchOf>;
+ seenAt: number | null;
+ version: string | null;
+ lastCountry: string | null;
+ createdAt: number;
+ current: { taskId: string; generationId: string; lane: string | null; startedAt: number | null } | null;
+}
+
+export function workerView(w: WorkerRow, now = Date.now()): WorkerView {
+ const s = workerState(w, now);
+ const cur = db().prepare("SELECT id, generation_id, lane, started_at FROM relay_tasks WHERE worker_id = ? AND state IN ('sending','queued','running','collecting') LIMIT 1").get(w.id) as
+ | { id: string; generation_id: string; lane: string | null; started_at: number | null }
+ | undefined;
+ return {
+ id: w.id,
+ name: w.name,
+ pool: w.pool,
+ state: s.state,
+ words: s.words,
+ pausedServer: !!w.paused_server,
+ pausedLocal: !!w.paused_local,
+ localWhy: w.local_why,
+ drain: !!w.drain,
+ hours: hoursOf(w),
+ allow: allowOf(w),
+ claimAfterMs: w.claim_after_ms,
+ switchAfterMs: w.switch_after_ms,
+ warmLane: w.warm_lane,
+ lanes: capableOf(w).lanes,
+ facts: factsOf(w),
+ bench: benchOf(w),
+ seenAt: w.seen_at,
+ version: w.version,
+ lastCountry: w.last_country,
+ createdAt: w.created_at,
+ current: cur ? { taskId: cur.id, generationId: cur.generation_id, lane: cur.lane, startedAt: cur.started_at } : null,
+ };
+}
+
+export function listWorkers(now = Date.now()): WorkerView[] {
+ return (db().prepare("SELECT * FROM relay_workers WHERE kind = 'pool' AND revoked_at IS NULL ORDER BY created_at").all() as WorkerRow[]).map((w) => workerView(w, now));
+}
+
+/** Add a worker: paused on the website, with no hours and no lanes. Its token is shown once. */
+export function addWorker(name: string, pool = "pool"): { id: string; token: string } {
+ if (!/^[a-z0-9-]{1,32}$/.test(pool)) throw new Error("A pool's name is lower-case letters, digits and hyphens");
+ const clean = name.trim();
+ if (!clean) throw new Error("Name the worker");
+ if (db().prepare("SELECT 1 FROM relay_workers WHERE kind = 'pool' AND revoked_at IS NULL AND name = ?").get(clean)) throw new Error("A worker with that name exists");
+ return createWorker({ name: clean, kind: "pool", pool });
+}
+
+export interface WorkerPatch {
+ paused?: boolean;
+ pauseNow?: boolean;
+ drain?: boolean;
+ hours?: unknown;
+ allow?: unknown;
+ claimAfterMs?: number;
+ switchAfterMs?: number;
+ rotate?: boolean;
+ revoke?: boolean;
+}
+
+/** The owner changes a worker. Each change reaches it at its next beat. */
+export function patchWorker(id: string, p: WorkerPatch, now = Date.now()): { view: WorkerView | null; token?: string } {
+ const d = db();
+ const w = d.prepare("SELECT * FROM relay_workers WHERE id = ? AND kind = 'pool' AND revoked_at IS NULL").get(id) as WorkerRow | undefined;
+ if (!w) return { view: null };
+ if (p.revoke) {
+ revokeWorker(id, now);
+ // Its tasks go back in line at once (not the worker's fault).
+ for (const t of d.prepare("SELECT * FROM relay_tasks WHERE worker_id = ? AND state IN ('sending','queued','running','collecting')").all(id) as TaskRow[]) backInLine(t, { blame: false });
+ return { view: null };
+ }
+ const set: Record<string, unknown> = {};
+ if (p.paused !== undefined) {
+ set.paused_server = p.paused ? 1 : 0;
+ if (!p.paused) set.drain = 0;
+ }
+ if (p.pauseNow) Object.assign(set, { paused_server: 1, stop_now: 1 });
+ if (p.drain !== undefined) set.drain = p.drain ? 1 : 0;
+ if (p.hours !== undefined) {
+ if (p.hours !== null && !parseHours(p.hours)) throw new Error("Hours need a time zone and windows like 01:00–09:00");
+ set.hours_json = p.hours === null ? null : JSON.stringify(parseHours(p.hours));
+ }
+ if (p.allow !== undefined) {
+ if (!p.allow || typeof p.allow !== "object") throw new Error("Allowed lanes are a list of lanes, each with a delay");
+ const allow: Record<string, Allow> = {};
+ for (const [lane, v] of Object.entries(p.allow as Record<string, unknown>)) {
+ if (!/^[0-9a-f]{12}$|^small$/.test(lane)) throw new Error(`No such lane: ${lane}`);
+ const delay = Number((v as { delayMs?: unknown })?.delayMs ?? 0);
+ allow[lane] = { delayMs: Number.isFinite(delay) && delay >= 0 ? Math.min(delay, 24 * 3_600_000) : 0 };
+ }
+ set.allow_json = JSON.stringify(allow);
+ }
+ if (p.claimAfterMs !== undefined) set.claim_after_ms = Math.max(0, Math.min(24 * 3_600_000, Math.round(Number(p.claimAfterMs) || 0)));
+ if (p.switchAfterMs !== undefined) set.switch_after_ms = Math.max(0, Math.min(24 * 3_600_000, Math.round(Number(p.switchAfterMs) || 0)));
+ const keys = Object.keys(set);
+ if (keys.length) d.prepare(`UPDATE relay_workers SET ${keys.map((k) => `${k} = @${k}`).join(", ")} WHERE id = @id`).run({ ...set, id });
+ const token = p.rotate ? rotateWorker(id) ?? undefined : undefined;
+ const fresh = d.prepare("SELECT * FROM relay_workers WHERE id = ?").get(id) as WorkerRow;
+ return { view: workerView(fresh, now), ...(token && { token }) };
+}
+
+/** The line for workers by lane: waiting, oldest, the estimate, and which workers have it warm. */
+export function queueView(now = Date.now()) {
+ const index = loadIndex();
+ const rows = db().prepare("SELECT lane, COUNT(*) AS n, MIN(created_at) AS oldest FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' GROUP BY lane").all() as { lane: string | null; n: number; oldest: number }[];
+ const workers = db().prepare("SELECT * FROM relay_workers WHERE kind = 'pool' AND revoked_at IS NULL").all() as WorkerRow[];
+ return {
+ lanes: rows.map((r) => {
+ const last = db().prepare("SELECT * FROM relay_tasks WHERE pools IS NOT NULL AND state = 'waiting' AND lane IS ? ORDER BY rank_at DESC LIMIT 1").get(r.lane) as TaskRow | undefined;
+ return {
+ lane: r.lane ?? "",
+ label: r.lane ? laneLabel(index, r.lane, sha) : "",
+ waiting: r.n,
+ oldestAt: r.oldest,
+ etaS: last ? placeInLine(last, now).etaSeconds : null,
+ warmOn: workers.filter((w) => w.warm_lane === r.lane && eligible(w, now)).map((w) => w.name),
+ };
+ }),
+ };
+}
+
+/** Every lane in this studio's catalog, for the owner to allow per worker. */
+export const lanesCatalog = () => allLanes(loadIndex(), sha).map((l) => ({ lane: l.lane, label: l.label, workflows: l.workflows.length }));
diff --git a/src/server/computer/tasks.ts b/src/server/computer/tasks.ts
index 21aa78ff..be737007 100644
--- a/src/server/computer/tasks.ts
+++ b/src/server/computer/tasks.ts
@@ -34,7 +34,14 @@ import { DATA_DIR, db } from "../db";
* principal's waiting tasks (the runner, renewed by its beats); a task a computer took stays with that computer.
*/
-export type Principal = "owner" | `acct:${string}`;
+/**
+ * Whose tasks: the owner's, an account's, or (for a worker, docs/gpu-workers.md) a pool of the owner's GPUs. A task
+ * always belongs to the owner or an account (its `principal`); a task for workers also names the pools that may take it
+ * (`pools`), and a worker reaches it only through those.
+ */
+export type Principal = "owner" | `acct:${string}` | `pool:${string}`;
+
+export const isPool = (p: Principal): p is `pool:${string}` => p.startsWith("pool:");
/** The relay's own folder: staged inputs and received outputs. Never served as it is. */
export const relayDir = () => path.join(DATA_DIR, "relay");
@@ -87,6 +94,18 @@ export interface TaskRow {
/** Why the computer's ComfyUI can't take it: "setting" (it answers, without Fuobe's setting), else it doesn't answer. */
down_why: string | null;
note: string | null;
+ /** Workers only (all null for a browser computer's task): see pool.ts. */
+ account: string | null;
+ pools: string | null;
+ rank_at: number | null;
+ lane: string | null;
+ needs_json: string | null;
+ est_ms: number | null;
+ tried_json: string | null;
+ requeues: number;
+ not_after: number | null;
+ only_worker: string | null;
+ worker_id: string | null;
created_at: number;
updated_at: number;
claimed_at: number | null;
@@ -116,8 +135,8 @@ export interface Received {
contentType?: string;
}
-const hash = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
-const json = <T,>(s: string | null, fallback: T): T => {
+export const hash = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
+export const json = <T,>(s: string | null, fallback: T): T => {
if (!s) return fallback;
try {
return JSON.parse(s) as T;
@@ -126,7 +145,7 @@ const json = <T,>(s: string | null, fallback: T): T => {
}
};
-function setTask(id: string, fields: Partial<TaskRow>): void {
+export function setTask(id: string, fields: Partial<TaskRow>): void {
const keys = Object.keys(fields);
if (!keys.length) return;
rdb()
@@ -134,12 +153,22 @@ function setTask(id: string, fields: Partial<TaskRow>): void {
.run({ ...fields, updated_at: Date.now(), id });
}
-/** A principal's task, or null (another principal's task is no task at all). */
+/**
+ * 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.
+ */
export function getTask(principal: Principal, id: string): TaskRow | null {
if (typeof id !== "string" || !/^[A-Za-z0-9_-]{16}$/.test(id)) return null;
+ if (isPool(principal)) {
+ 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 = ?").get(id, principal) as TaskRow | undefined) ?? null;
}
+/** The pools that may take a task (none: a browser computer's). */
+export const poolsOf = (t: Pick<TaskRow, "pools">): string[] => (t.pools ? t.pools.split(",").filter(Boolean) : []);
+
// ---------------------------------------------------------------------------
// Inputs: staged by the server when it plans the run (comfyui.ts prepareFile, ctx.upload)
@@ -180,6 +209,8 @@ export interface NewTask {
made?: string;
/** The run's LoRAs (for the words of a refusal). */
loras?: { file: string; url?: string }[];
+ /** 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 };
}
/** A ComfyUI job for a computer: the graph, the inputs it names, and a prompt id minted here. */
@@ -190,9 +221,11 @@ export function createTask(t: NewTask): { id: string; promptId: string } {
const d = rdb();
const named = graphStrings(t.graph);
d.transaction(() => {
+ const pool = t.pool;
d.prepare(
- `INSERT INTO relay_tasks (id, principal, generation_id, state, graph_json, prompt_id, prefix, meta_batch, preview, workflow_id, extra_json, created_at, updated_at)
- VALUES (?, ?, ?, 'waiting', ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ `INSERT INTO relay_tasks (id, principal, generation_id, state, graph_json, prompt_id, prefix, meta_batch, preview, workflow_id, extra_json, created_at, updated_at,
+ account, pools, rank_at, lane, needs_json, est_ms, not_after, only_worker)
+ VALUES (?, ?, ?, 'waiting', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
).run(
id,
t.principal,
@@ -206,6 +239,14 @@ export function createTask(t: NewTask): { id: string; promptId: string } {
JSON.stringify({ made: t.made, loras: t.loras ?? [] }),
now,
now,
+ pool?.account ?? null,
+ pool ? pool.pools.join(",") : null,
+ pool ? pool.rankAt : null,
+ pool?.lane ?? null,
+ pool ? JSON.stringify(pool.needs) : null,
+ pool?.estMs ?? null,
+ pool?.notAfter ?? null,
+ pool?.onlyWorker ?? null,
);
const free = d.prepare("SELECT name FROM relay_inputs WHERE principal = ? AND task_id IS NULL ORDER BY created_at").all(t.principal) as { name: string }[];
let n = 0;
@@ -214,7 +255,7 @@ export function createTask(t: NewTask): { id: string; promptId: string } {
return { id, promptId };
}
-const inputsOf = (taskId: string) => rdb().prepare("SELECT * FROM relay_inputs WHERE task_id = ? ORDER BY n").all(taskId) as InputRow[];
+export const inputsOf = (taskId: string) => rdb().prepare("SELECT * FROM relay_inputs WHERE task_id = ? ORDER BY n").all(taskId) as InputRow[];
// ---------------------------------------------------------------------------
// The runner: one computer at a time runs a principal's waiting tasks
@@ -255,7 +296,7 @@ export function runnerFacts(principal: Principal): (ComputerFacts & { port?: num
*/
export function forgetComputer(principal: Principal, why: "Stopped" | "switched" | "disconnected" = "Stopped"): void {
rdb().prepare("DELETE FROM relay_runners WHERE principal = ?").run(principal);
- for (const t of rdb().prepare(`SELECT id FROM relay_tasks WHERE principal = ? AND state IN (${ACTIVE_STATES.map(() => "?").join(",")})`).all(principal, ...ACTIVE_STATES) as { id: string }[]) {
+ for (const t of rdb().prepare(`SELECT id FROM relay_tasks WHERE principal = ? AND pools IS NULL AND state IN (${ACTIVE_STATES.map(() => "?").join(",")})`).all(principal, ...ACTIVE_STATES) as { id: string }[]) {
endTask(t.id, "canceled", { error: why });
}
}
@@ -333,11 +374,11 @@ export function beat(principal: Principal, b: BeatInput, now = Date.now()): Beat
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 }[]
).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 state = 'waiting'").get(principal) as { n: number }).n;
+ 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 };
}
-function noteProgress(id: string, r: Record<string, unknown>, now: number) {
+export function noteProgress(id: string, r: Record<string, unknown>, now: number) {
const p: Progress = { at: now };
for (const k of ["value", "max", "nodesDone", "position"] as const) {
const v = nonNeg(r[k]);
@@ -357,7 +398,7 @@ export function claim(principal: Principal, device: string, running: string[], n
const d = rdb();
return d.transaction((): ClaimedTask | null => {
const mine = d
- .prepare(`SELECT * FROM relay_tasks WHERE principal = ? AND device = ? AND state IN ('sending','queued','running','collecting') AND stop = 0 ORDER BY created_at LIMIT 40`)
+ .prepare(`SELECT * FROM relay_tasks WHERE principal = ? AND pools IS NULL AND device = ? AND state IN ('sending','queued','running','collecting') AND stop = 0 ORDER BY created_at LIMIT 40`)
.all(principal, device) as TaskRow[];
let t: TaskRow | undefined = mine.find((x) => !running.includes(x.id));
if (!t) {
@@ -366,34 +407,42 @@ export function claim(principal: Principal, device: string, running: string[], n
// The oldest waiting task, or one another computer took but never sent and went quiet on.
t = d
.prepare(
- `SELECT * FROM relay_tasks WHERE principal = ? AND stop = 0 AND (state = 'waiting' OR (state = 'sending' AND sent_at IS NULL AND device != ? AND device_seen_at < ?))
+ `SELECT * FROM relay_tasks WHERE principal = ? AND pools IS NULL AND stop = 0 AND (state = 'waiting' OR (state = 'sending' AND sent_at IS NULL AND device != ? AND device_seen_at < ?))
ORDER BY created_at LIMIT 1`,
)
.get(principal, device, now - RELAY_TIMES.leaseMs) as TaskRow | undefined;
if (!t) return null;
}
- const lease = crypto.randomBytes(32).toString("hex");
- const resume = t.state === "waiting" || t.device !== device ? undefined : (t.state as ClaimedTask["resume"]);
- const fresh = t.state === "waiting" || t.device !== device;
- setTask(t.id, { device, lease_hash: hash(lease), state: t.state === "waiting" ? "sending" : t.state, claimed_at: now, device_seen_at: now });
- if (fresh) d.prepare("UPDATE relay_inputs SET reads = 0 WHERE task_id = ?").run(t.id);
- const inputs: TaskInput[] = inputsOf(t.id).map((i) => ({ n: i.n!, name: i.name, size: i.size, sha256: i.sha256, contentType: i.content_type }));
- return {
- id: t.id,
- generationId: t.generation_id,
- lease,
- graph: json(t.graph_json, {}),
- promptId: t.prompt_id,
- preview: !!t.preview,
- ...(t.prefix && { prefix: t.prefix }),
- ...(t.meta_batch && { metaBatch: true }),
- inputs,
- ...(resume && { resume }),
- ...(t.state === "collecting" && { wanted: json<WantedFile[]>(t.wanted_json, []), received: json<Received[]>(t.received_json, []).map((r) => ({ n: r.n, bytes: r.bytes, done: r.done })) }),
- };
+ return takeTask(t, device, now);
})();
}
+/**
+ * Hand a task to a computer or worker (inside the caller's transaction): a new lease, and the task as it is sent. A task
+ * this device had already resumes where it was; anything else starts by sending its inputs again.
+ */
+export function takeTask(t: TaskRow, device: string, now: number, fields: Partial<TaskRow> = {}): ClaimedTask {
+ const lease = crypto.randomBytes(32).toString("hex");
+ const resume = t.state === "waiting" || t.device !== device ? undefined : (t.state as ClaimedTask["resume"]);
+ const fresh = t.state === "waiting" || t.device !== device;
+ setTask(t.id, { device, lease_hash: hash(lease), state: t.state === "waiting" ? "sending" : t.state, claimed_at: now, device_seen_at: now, ...fields });
+ if (fresh) rdb().prepare("UPDATE relay_inputs SET reads = 0 WHERE task_id = ?").run(t.id);
+ const inputs: TaskInput[] = inputsOf(t.id).map((i) => ({ n: i.n!, name: i.name, size: i.size, sha256: i.sha256, contentType: i.content_type }));
+ return {
+ id: t.id,
+ generationId: t.generation_id,
+ lease,
+ graph: json(t.graph_json, {}),
+ promptId: t.prompt_id,
+ preview: !!t.preview,
+ ...(t.prefix && { prefix: t.prefix }),
+ ...(t.meta_batch && { metaBatch: true }),
+ inputs,
+ ...(resume && { resume }),
+ ...(t.state === "collecting" && { wanted: json<WantedFile[]>(t.wanted_json, []), received: json<Received[]>(t.received_json, []).map((r) => ({ n: r.n, bytes: r.bytes, done: r.done })) }),
+ };
+}
+
export class RelayError extends Error {
constructor(
readonly status: number,
@@ -429,7 +478,7 @@ export function inputFor(t: TaskRow, n: number): { path: string; size: number; c
* Ends a task (its inputs go; its outputs stay until the run has kept them). `takeOff`: a prompt already on the
* computer's ComfyUI is taken off it there (the computer hears it at its next beat): a cancel, or a timeout.
*/
-function endTask(id: string, state: "done" | "failed" | "canceled", fields: Partial<TaskRow> = {}, takeOff = state === "canceled") {
+export function endTask(id: string, state: "done" | "failed" | "canceled", fields: Partial<TaskRow> = {}, takeOff = state === "canceled") {
const t = rdb().prepare("SELECT state, device FROM relay_tasks WHERE id = ?").get(id) as { state: RelayState; device: string | null } | undefined;
const stop = takeOff && t && t.device && (SENT_STATES as readonly string[]).includes(t.state) ? 1 : 0;
setTask(id, { state, finished_at: Date.now(), down_at: null, down_why: null, ...(stop && { stop }), ...fields });
@@ -738,6 +787,7 @@ export function sweepRelay(now = Date.now()): { inputs: number; tasks: number }
* Returns the task as it is now.
*/
export function checkClocks(t: TaskRow, now = Date.now()): TaskRow {
+ if (t.pools) return poolClocks ? poolClocks(t, now) : t;
if (!(SENT_STATES as readonly string[]).includes(t.state)) return t;
if (t.device_seen_at && now - t.device_seen_at > RELAY_TIMES.silentMs) endTask(t.id, "failed", { error: "silent" }, true);
else if (t.down_at && now - t.down_at > RELAY_TIMES.comfyDownMs) endTask(t.id, "failed", { error: "down" }, true);
@@ -745,6 +795,10 @@ export function checkClocks(t: TaskRow, now = Date.now()): TaskRow {
return getTask(t.principal, t.id) ?? t;
}
+/** A task for workers keeps the workers' clocks (pool.ts sets this, so this file needn't import it). */
+let poolClocks: ((t: TaskRow, now: number) => TaskRow) | null = null;
+export const setPoolClocks = (fn: (t: TaskRow, now: number) => TaskRow) => (poolClocks = fn);
+
/** 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);
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index 725aec01..e418929d 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -94,6 +94,7 @@ import {
type Principal,
type TaskRow,
} from "../computer/tasks";
+import { OWNER_BOOST_MS, poolFields, poolWaitMs, poolWaitWords } from "../computer/pool";
export const WORKFLOW_DIR = path.join(process.cwd(), "workflows", "comfyui");
@@ -162,7 +163,27 @@ export function computerScope(): Principal | undefined {
const own = ownGpu();
if (own) return own.kind === "computer" ? own.principal : undefined;
if (serverScope.getStore()) return undefined;
- return getSetting("comfyWhere") === "computer" ? "owner" : 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";
+
+/**
+ * FUOBE_POOL_MEDIA_INPUTS: what a job for workers may send them ("image" unless set; "image,video,audio" for all).
+ * Pictures are always made again from their pixels first (no EXIF, no GPS, nothing a decoder on that PC could trip on).
+ */
+const poolMedia = () => new Set((process.env.FUOBE_POOL_MEDIA_INPUTS ?? "image").split(",").map((s) => s.trim()).filter(Boolean));
+
+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.");
+ if (kind !== "image") return { data, contentType, name };
+ const sharp = (await import("sharp")).default;
+ const png = await sharp(data, { failOn: "error", limitInputPixels: 64 * 2 ** 20 }).rotate().png().toBuffer();
+ return { 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. */
@@ -1749,8 +1770,9 @@ async function uploadTo(worker: ComfyWorker, data: Buffer, contentType: string,
const computer = computerScope();
if (computer) {
if (worker === "isolated") throw new ProviderError(ISOLATED_ON_COMPUTER);
- const staged = stageInput(computer, data, contentType, name);
- rememberSent(staged, data, contentType, name);
+ const sent = onWorkers(computer) ? await forWorkers(data, contentType, name) : { data, contentType, name };
+ const staged = stageInput(computer, sent.data, sent.contentType, sent.name);
+ rememberSent(staged, sent.data, sent.contentType, sent.name);
return staged;
}
const form = new FormData();
@@ -1814,7 +1836,9 @@ async function sweepPasses(prefix: string, worker: ComfyWorker = "main"): Promis
/** Run `fn` as a principal's work on its own computer: an account's (as that account), or the owner's. */
export function onComputer<T>(principal: Principal, fn: () => T): T {
if (principal === "owner") return outsideTenant(() => outsideOwnGpu(fn));
- return runAsTenant({ kind: "account", id: principal.slice(5) }, () => onOwnGpu({ kind: "computer", principal }, fn));
+ // A task always belongs to the owner or an account; a pool only takes it (callers pass the task's own principal).
+ if (!principal.startsWith("acct:")) throw new Error("Not a task's principal");
+ return runAsTenant({ kind: "account", id: principal.slice(5) }, () => onOwnGpu({ kind: "computer", principal: principal as `acct:${string}` }, fn));
}
/** 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. */
@@ -1893,13 +1917,16 @@ async function pollComputer(principal: Principal, meta: Record<string, unknown>,
const found = typeof meta.relay === "string" ? getTask(principal, meta.relay) : null;
if (!found) return { state: "failed", error: "This run was lost. Press Retry." };
const t = checkClocks(found);
+ // 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) };
const p = taskProgress(t.id);
const kind = extraOf(t).made ?? made ?? "image";
const waitMs = tenantAccount() ? ACCOUNT_LIMITS.queueMs : 4 * 3_600_000;
const sentAt = t.sent_at ?? undefined;
// Sent, and the computer's tab stopped answering (closed, asleep): not a run that looks alive for half an hour.
- const r = t.state === "waiting" ? null : runnerFacts(principal);
- const away = t.state !== "waiting" && (!r || Date.now() - r.seenAt >= RELAY_TIMES.onlineMs);
+ const r = t.state === "waiting" || t.pools ? null : runnerFacts(principal);
+ const away = !t.pools && t.state !== "waiting" && (!r || Date.now() - r.seenAt >= RELAY_TIMES.onlineMs);
const down = t.down_at ? (t.down_why === "setting" ? RELAY_WORDS.comfyNoSetting : RELAY_WORDS.comfyDown) : away ? RELAY_WORDS.computerAway : undefined;
switch (t.state) {
case "waiting": {
@@ -1998,6 +2025,8 @@ export const comfyProvider: ProviderAdapter = {
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() }) }),
});
return { externalId: task.promptId, meta: { ...meta, generationId, relay: task.id }, payload: wf };
}
diff --git a/src/server/settings.ts b/src/server/settings.ts
index cf6b195d..a7bb4abd 100644
--- a/src/server/settings.ts
+++ b/src/server/settings.ts
@@ -75,7 +75,7 @@ export const SETTINGS = {
* Where the owner's ComfyUI runs: on this server (its address above), or on the computer the owner uses, reached
* through the owner's own Fuobe tab (a studio on a server, a ComfyUI at home: src/server/computer).
*/
- comfyWhere: { key: "comfyui.where", env: "COMFYUI_WHERE", default: "server", options: ["server", "computer"] },
+ comfyWhere: { key: "comfyui.where", env: "COMFYUI_WHERE", default: "server", options: ["server", "computer", "workers"] },
/**
* ComfyUI's models/loras folder, when it's on this machine: trained LoRAs are copied there, and a recipe's
* LoRAs (looks, motions) are downloaded there before a run needs them (src/server/loras.ts).
diff --git a/tests/workers-pool.test.ts b/tests/workers-pool.test.ts
new file mode 100644
index 00000000..df8e3c1a
--- /dev/null
+++ b/tests/workers-pool.test.ts
@@ -0,0 +1,357 @@
+import crypto from "node:crypto";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import sharp from "sharp";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-workers-pool-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";
+delete process.env.FUOBE_PASSWORD;
+
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const { setSetting } = await import("@/server/settings");
+const tasks = await import("@/server/computer/tasks");
+const pool = await import("@/server/computer/pool");
+const workers = await import("@/server/computer/workers");
+const { principalOf } = await import("@/server/computer/http");
+const beatRoute = await import("@/app/api/gpu/computer/beat/route");
+const claimRoute = await import("@/app/api/gpu/computer/claim/route");
+const reportRoute = await import("@/app/api/gpu/computer/tasks/[id]/report/route");
+const { forWorkers } = await import("@/server/providers/comfyui");
+const { hoursAt, parseHours } = await import("@/lib/worker-hours");
+const { lanesFor, needsOf, laneOf } = await import("@/lib/lanes");
+const { loadIndex } = await import("@/server/gpu/index-file");
+
+const LANE_A = "aaaaaaaaaaaa";
+const LANE_B = "bbbbbbbbbbbb";
+const GB = 2 ** 30;
+const MIN = 60_000;
+let clock = Date.UTC(2026, 10, 2, 3, 0, 0); // a Monday, 03:00 UTC
+
+type W = { id: string; token: string };
+
+/** A worker that is ready in every way (paused nowhere, all day, the given lanes and workflows), unless told otherwise. */
+function worker(name: string, o: { lanes?: string[]; workflows?: string[]; vram?: number; hours?: unknown; claimAfterMs?: number; pausedServer?: boolean } = {}): W {
+ const w = pool.addWorker(name);
+ const lanes = o.lanes ?? [LANE_A];
+ pool.patchWorker(w.id, { paused: !!o.pausedServer, hours: o.hours === undefined ? { always: true } : o.hours, allow: Object.fromEntries(lanes.map((l) => [l, { delayMs: 0 }])), claimAfterMs: o.claimAfterMs ?? 0 });
+ db()
+ .prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ? WHERE id = ?")
+ .run(JSON.stringify({ lanes, workflows: o.workflows ?? ["wf-a", "wf-b"] }), JSON.stringify({ vramBytes: o.vram ?? 24 * GB }), w.id);
+ beat(w);
+ return w;
+}
+
+const row = (w: W) => workers.getWorker(w.id)!;
+
+function beat(w: W, local: { paused?: boolean; why?: string | null } = {}, running: string[] = []) {
+ return pool.workerBeat(
+ row(w),
+ pool.cleanBeat({ device: `wkr-${w.id}`, protocol: 1, version: "1.0.0", local: { paused: local.paused ?? false, why: local.why ?? null, until: null }, gpu: {}, inventoryHash: null, running: running.map((task) => ({ task })), stopped: [] }),
+ clock,
+ );
+}
+
+const claim = (w: W, running: string[] = []) => pool.workerClaim(row(w), running, clock);
+
+let gens = 0;
+function task(o: { lane?: string; workflow?: string; minVram?: number; rankAgoMs?: number; estMs?: number; notAfter?: number } = {}) {
+ const gid = `gen-${++gens}`;
+ 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, clock, clock);
+ const created = clock - (o.rankAgoMs ?? 0);
+ const t = tasks.createTask({
+ principal: "owner",
+ generationId: gid,
+ graph: { "1": { class_type: "SaveImage", inputs: { filename_prefix: "x" } } },
+ pool: { pools: ["pool"], rankAt: created, lane: o.lane ?? LANE_A, needs: { workflowId: o.workflow ?? "wf-a", files: [], packs: [], minVramBytes: o.minVram ?? 0 }, estMs: o.estMs, notAfter: o.notAfter },
+ });
+ db().prepare("UPDATE relay_tasks SET created_at = ? WHERE id = ?").run(created, t.id);
+ return t.id;
+}
+/** "HH:MM" in UTC, some minutes from the test's clock. */
+const at = (minutes: number) => new Date(clock + minutes * MIN).toISOString().slice(11, 16);
+const everyDay = (from: string, to: string) => ({ tz: "UTC", days: Object.fromEntries(["sun", "mon", "tue", "wed", "thu", "fri", "sat"].map((d) => [d, [[from, to]]])) });
+
+const state = (id: string) => db().prepare("SELECT * FROM relay_tasks WHERE id = ?").get(id) as import("@/server/computer/tasks").TaskRow;
+
+beforeAll(() => setSetting("comfyWhere", "workers"));
+afterAll(() => {
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+beforeEach(() => {
+ resetRates();
+ clock += 60 * MIN;
+ db().prepare("DELETE FROM relay_workers").run();
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();
+});
+
+describe("who may claim (check 1)", () => {
+ it("a new worker is paused in both places and claims nothing", () => {
+ const w = pool.addWorker("fresh");
+ task();
+ const a = pool.workerBeat(row({ id: w.id, token: w.token }), pool.cleanBeat({ device: "x", protocol: 1, version: "1", local: { paused: true, why: "here" } }), clock);
+ expect(a.runner).toBe(false);
+ expect(a.worker.paused).toBe(true);
+ expect(pool.workerClaim(row({ id: w.id, token: w.token }), [], clock)).toBeNull();
+ expect(pool.workerState(row({ id: w.id, token: w.token }), clock).words).toBe("Paused here");
+ });
+
+ it("unpaused in both places and inside its hours it claims; outside them it doesn't", () => {
+ const id = task();
+ clock -= clock % (60 * MIN); // on the hour, so the windows below don't cross midnight oddly
+ const w = worker("on", { hours: everyDay(at(-60), at(120)) });
+ expect(claim(w)?.id).toBe(id);
+ const id2 = task();
+ const night = worker("night", { hours: everyDay(at(180), at(240)) });
+ expect(claim(night)).toBeNull();
+ expect(pool.workerState(row(night), clock).words).toBe(`Outside its hours (back at ${at(180)})`);
+ expect(state(id2).state).toBe("waiting");
+ });
+
+ it("paused on the website, or here, or draining: no new task", () => {
+ task();
+ const w = worker("p", { pausedServer: true });
+ expect(claim(w)).toBeNull();
+ pool.patchWorker(w.id, { paused: false });
+ beat(w, { paused: true, why: "here" });
+ expect(claim(w)).toBeNull();
+ beat(w);
+ pool.patchWorker(w.id, { drain: true });
+ expect(claim(w)).toBeNull();
+ pool.patchWorker(w.id, { paused: false });
+ expect(claim(w)).not.toBeNull();
+ });
+});
+
+describe("matching (check 2)", () => {
+ it("a task never goes to a worker that lacks its files or VRAM", () => {
+ const id = task({ workflow: "wf-big", minVram: 16 * GB });
+ const small = worker("small", { workflows: ["wf-big"], vram: 8 * GB });
+ const nofiles = worker("nofiles", { workflows: ["wf-a"], vram: 32 * GB });
+ const otherLane = worker("other", { lanes: [LANE_B], workflows: ["wf-big"], vram: 32 * GB });
+ expect(claim(small)).toBeNull();
+ expect(claim(nofiles)).toBeNull();
+ expect(claim(otherLane)).toBeNull();
+ const fits = worker("fits", { workflows: ["wf-big"], vram: 24 * GB });
+ expect(claim(fits)?.id).toBe(id);
+ });
+
+ it("a lane's delay and claim_after_ms hold a task back that long", () => {
+ const id = task();
+ const late = worker("late", { claimAfterMs: 2 * MIN });
+ expect(claim(late)).toBeNull();
+ clock += 2 * MIN + 1000;
+ beat(late);
+ expect(claim(late)?.id).toBe(id);
+ });
+});
+
+describe("losing a worker (checks 3, 4, 5)", () => {
+ it("a silent worker's task goes to another within 3 minutes, and the old one's late calls get 409", () => {
+ const id = task();
+ const a = worker("a");
+ const got = claim(a)!;
+ expect(got.id).toBe(id);
+ const b = worker("b");
+ clock += 2 * MIN + 30_000;
+ beat(b);
+ const again = claim(b);
+ expect(again?.id).toBe(id);
+ expect(state(id).worker_id).toBe(b.id);
+ expect(JSON.parse(state(id).tried_json!)).toEqual([a.id]);
+ expect(() => tasks.leased("pool:pool", id, got.lease)).toThrow(/Another tab/);
+ });
+
+ it("a task only A can run: A comes back and runs it; with a capable B about, B does", () => {
+ const id = task({ workflow: "wf-only-a" });
+ const a = worker("a", { workflows: ["wf-only-a"] });
+ claim(a);
+ clock += 3 * MIN;
+ beat(a);
+ expect(claim(a)?.id).toBe(id);
+ const id2 = task({ workflow: "wf-only-a" });
+ clock += 3 * MIN;
+ beat(a);
+ const b = worker("b", { workflows: ["wf-only-a"] });
+ // A got id (resume) and id2 is fresh: lose id2 on A first.
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE id = ?").run(id);
+ expect(claim(a)?.id).toBe(id2);
+ clock += 3 * MIN;
+ beat(a);
+ beat(b);
+ expect(claim(a)).toBeNull();
+ expect(claim(b)?.id).toBe(id2);
+ });
+
+ it("the third lost attempt fails the row", () => {
+ const id = task();
+ for (let i = 0; i < 3; i++) {
+ const w = worker(`w${i}`);
+ expect(claim(w)?.id).toBe(id);
+ clock += 3 * MIN;
+ pool.sweepPool(clock);
+ }
+ expect(state(id).state).toBe("failed");
+ expect(state(id).requeues).toBe(3);
+ });
+
+ it("a revoked worker's task goes back in line, and its token gets 401", () => {
+ const id = task();
+ const w = worker("gone");
+ claim(w);
+ pool.patchWorker(w.id, { revoke: true });
+ expect(state(id).state).toBe("waiting");
+ const r = principalOf(new Request("http://localhost:3000/api/gpu/computer/beat", { method: "POST", headers: { host: "localhost:3000", authorization: `Bearer ${w.token}` } }));
+ expect((r as Response).status).toBe(401);
+ });
+
+ it("pause now: the job goes back in line at no cost, and the worker hears the stop", () => {
+ const id = task();
+ const w = worker("now");
+ claim(w);
+ tasks.setTask(id, { state: "running", sent_at: clock });
+ pool.patchWorker(w.id, { pauseNow: true });
+ const a = beat(w, {}, [id]);
+ expect(a.worker.pauseNow).toBe(true);
+ expect(a.stops.map((s) => s.task)).toEqual([id]);
+ expect(state(id).state).toBe("waiting");
+ expect(state(id).requeues).toBe(0);
+ expect(state(id).tried_json).toBeNull();
+ });
+
+ it("a busy GPU on the worker sends its job back the same way", () => {
+ const id = task();
+ const w = worker("busy");
+ claim(w);
+ const a = beat(w, { paused: true, why: "gpu-busy:python.exe" }, [id]);
+ expect(a.stops.map((s) => s.task)).toEqual([id]);
+ expect(state(id).state).toBe("waiting");
+ expect(pool.workerState(row(w), clock).words).toBe("Your GPU is busy (python.exe)");
+ });
+
+ it("a task past its wait limit fails, not charged", () => {
+ const id = task({ notAfter: clock + MIN });
+ clock += 2 * MIN;
+ pool.sweepPool(clock);
+ expect(state(id).state).toBe("failed");
+ expect(state(id).error).toBe("The GPUs were busy. Not charged.");
+ });
+});
+
+describe("order (checks 8, 9)", () => {
+ it("sticky lanes: the warm lane goes first until another lane's best task passes switch_after_ms", () => {
+ const w = worker("sticky", { lanes: [LANE_A, LANE_B] });
+ db().prepare("UPDATE relay_workers SET warm_lane = ?, switch_after_ms = ? WHERE id = ?").run(LANE_A, 30 * MIN, w.id);
+ const b = task({ lane: LANE_B, rankAgoMs: 10 * MIN });
+ const a = task({ lane: LANE_A, rankAgoMs: 1 * MIN });
+ expect(claim(w)?.id).toBe(a);
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE id = ?").run(a);
+ const a2 = task({ lane: LANE_A, rankAgoMs: 0 });
+ db().prepare("UPDATE relay_tasks SET rank_at = ? WHERE id = ?").run(clock - 31 * MIN, b);
+ expect(claim(w)?.id).toBe(b);
+ expect(state(a2).state).toBe("waiting");
+ });
+
+ it("near the end of its hours, a task that would overrun is not claimed", () => {
+ clock -= clock % (60 * MIN);
+ const w = worker("window", { hours: everyDay(at(-120), at(10)) });
+ const long = task({ estMs: 20 * MIN });
+ expect(claim(w)).toBeNull();
+ const short = task({ estMs: 5 * MIN });
+ expect(claim(w)?.id).toBe(short);
+ expect(state(long).state).toBe("waiting");
+ });
+
+ it("the owner's tasks go by rank_at, not by arrival", () => {
+ const w = worker("rank");
+ const later = task({ rankAgoMs: 0 });
+ const boosted = task({ rankAgoMs: pool.OWNER_BOOST_MS });
+ expect(claim(w)?.id).toBe(boosted);
+ expect(state(later).state).toBe("waiting");
+ });
+});
+
+describe("routes", () => {
+ it("three workers that beat every 5 seconds are not rate-limited (check 14)", async () => {
+ clock = Date.now();
+ const ws = [worker("r1"), worker("r2"), worker("r3")];
+ let ok = 0;
+ for (let i = 0; i < 12; i++) {
+ for (const w of ws) {
+ const res = await beatRoute.POST(new Request("http://localhost:3000/api/gpu/computer/beat", { method: "POST", headers: { host: "localhost:3000", authorization: `Bearer ${w.token}`, "content-type": "application/json" }, body: JSON.stringify({ device: "x", protocol: 1, version: "1", local: { paused: false } }) }));
+ if (res.status === 200) ok++;
+ }
+ }
+ expect(ok).toBe(36);
+ });
+
+ it("a worker claims and reports through the same routes as a browser computer", async () => {
+ // The routes keep the real clock.
+ clock = Date.now();
+ const id = task();
+ const w = worker("route");
+ const headers = { host: "localhost:3000", authorization: `Bearer ${w.token}`, "content-type": "application/json" };
+ const c = await claimRoute.POST(new Request("http://localhost:3000/api/gpu/computer/claim", { method: "POST", headers, body: JSON.stringify({ running: [] }) }));
+ const { task: t } = await c.json();
+ expect(t.id).toBe(id);
+ expect(t.lane).toBe(LANE_A);
+ expect(t.runLimitMs).toBe(5 * MIN);
+ const sent = await reportRoute.POST(new Request(`http://localhost:3000/api/gpu/computer/tasks/${id}/report`, { method: "POST", headers: { ...headers, "x-fuobe-lease": t.lease }, body: JSON.stringify({ event: "sent", promptId: t.promptId }) }), {
+ params: Promise.resolve({ id }),
+ });
+ expect(sent.status).toBe(200);
+ expect(state(id).state).toBe("queued");
+ });
+});
+
+describe("pictures for workers (check 15)", () => {
+ it("are made again from their pixels: no EXIF, no GPS", async () => {
+ const jpeg = await sharp({ create: { width: 8, height: 8, channels: 3, background: "#f00" } })
+ .withExif({ IFD0: { Make: "Phone", Model: "X" }, IFD3: { GPSLatitudeRef: "N", GPSLatitude: "12/1 0/1 0/1" } })
+ .jpeg()
+ .toBuffer();
+ expect((await sharp(jpeg).metadata()).exif).toBeDefined();
+ const out = await forWorkers(jpeg, "image/jpeg", "holiday.jpg");
+ expect(out.contentType).toBe("image/png");
+ expect(out.name).toBe("holiday.png");
+ expect((await sharp(out.data).metadata()).exif).toBeUndefined();
+ await expect(forWorkers(Buffer.from("x"), "video/mp4", "a.mp4")).rejects.toThrow(/clips/);
+ });
+});
+
+describe("hours and lanes", () => {
+ it("windows over midnight, the next change, and no hours at all", () => {
+ const h = parseHours({ tz: "UTC", days: { mon: [["22:00", "06:00"]] } })!;
+ expect(hoursAt(h, Date.UTC(2026, 10, 2, 23, 0)).inside).toBe(true);
+ expect(hoursAt(h, Date.UTC(2026, 10, 3, 5, 0)).inside).toBe(true);
+ expect(hoursAt(h, Date.UTC(2026, 10, 3, 6, 30)).inside).toBe(false);
+ expect(hoursAt(h, Date.UTC(2026, 10, 3, 5, 0)).endsAt).toBe(Date.UTC(2026, 10, 3, 6, 0));
+ expect(hoursAt(null, clock).inside).toBe(false);
+ expect(hoursAt({ always: true }, clock)).toEqual({ inside: true, endsAt: null, nextChangeAt: null });
+ expect(parseHours({ tz: "Not/AZone", days: {} })).toBeNull();
+ expect(parseHours({ tz: "UTC", days: { mon: [["25:00", "06:00"]] } })).toBeNull();
+ const ist = parseHours({ tz: "Asia/Kolkata", days: { mon: [["01:00", "09:00"]] } })!;
+ expect(hoursAt(ist, Date.UTC(2026, 10, 1, 20, 0)).inside).toBe(true); // Monday 01:30 in India
+ });
+
+ it("a worker's lanes come from its verified files: a wrong size counts as missing (check 7)", () => {
+ const index = loadIndex();
+ const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
+ const id = Object.keys(index.workflows).find((k) => !index.workflows[k].isolated && index.workflows[k].files.length > 0)!;
+ const needs = needsOf(index, id)!;
+ const good = { files: needs.files.map((f) => ({ ...f })), nodePacks: needs.packs.map((name) => ({ name, commit: null })) };
+ expect(lanesFor(index, good, sha).workflows).toContain(id);
+ const bad = { ...good, files: good.files.map((f, i) => (i === 0 ? { ...f, size: f.size + 1 } : f)) };
+ expect(lanesFor(index, bad, sha).workflows).not.toContain(id);
+ expect(laneOf(index, id, sha)).toMatch(/^([0-9a-f]{12}|small)$/);
+ });
+});