The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
"use client";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Copy, Cpu, Download, KeyRound, Pause, Play, Plus, RotateCw, Search, 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 { laneMatches } from "@/lib/lane-names";
import { PLACE_NAME_DEFAULT, PLACE_NAME_MAX } from "@/lib/place-name";
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][]> };
/**
* A lane a worker may run: how long a job waits before it takes it, the longest clip it takes there (none: no limit),
* and a shorter longest clip for frames larger than `bigFrom` megapixels.
*/
type LaneAllow = { delayMs: number; maxSeconds?: number; bigFrom?: number; bigMaxSeconds?: number };
interface WorkerView {
id: string;
name: string;
pool: string;
state: string;
words: string;
pausedServer: boolean;
pausedLocal: boolean;
drain: boolean;
autoResume: boolean | null;
/** Its RAM guard (a server from before sends none). */
ramGuard?: boolean;
hours: Hours | null;
allow: Record<string, LaneAllow>;
/** Its pick order: above 0, it gets first pick of the jobs it can run while it is free (a server from before sends none). */
pickOrder?: number;
/** The workflows it takes only with every weight on its card, newest first (a server from before sends none). */
noStream?: { workflowId: string; at: number }[];
/** The lanes it can run every workflow of. */
lanes: string[];
/** The lanes it can run only some workflows of (a server from before sends none). */
partLanes?: Record<string, { runnable: number; of: number }>;
/** Node packs it has whose nodes its ComfyUI didn't load (a server or worker from before sends none). */
unloaded?: { pack: string; classes: string[]; workflows: 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;
/** Its program against the site's version (a server from before sends none). */
update?: WorkerUpdate;
}
interface WorkerUpdate {
state: "current" | "updating" | "behind";
words: string;
askedAt: number | null;
peopleHeld: number;
}
interface Lane {
lane: string;
/** Who uses it and its model: "InfiniteTalk · Wan 2.1 I2V 480p fp8". */
label: string;
workflows: number;
/** A server from before sends none of these. */
apps?: string[];
model?: string | null;
/** Its largest model file. */
file?: string | null;
workflowIds?: string[];
}
/** Runs made but waiting to enter the line (hosted runs), by why they wait, and when the oldest was pressed. */
interface HeldCounts {
mine: number;
today: number;
service: number;
hour: number;
list: number;
credits: number;
oldestAt: number | null;
}
/** "Waiting to enter the line: 3 (oldest 12 min)", or null when none waits. */
export function heldLine(h: HeldCounts | undefined, now: number): string | null {
if (!h) return null;
const n = h.mine + h.today + h.service + h.hour + h.list + h.credits;
if (!n) return null;
const min = h.oldestAt === null ? null : Math.max(0, Math.round((now - h.oldestAt) / 60_000));
return `Waiting to enter the line: ${n}${min === null ? "" : ` (oldest ${min} min)`}`;
}
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'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'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>
);
}
/** How much of a lane a worker can run: every workflow, some of them, or none (its files are missing). */
export type LaneFit = { kind: "all" } | { kind: "some"; runnable: number; of: number } | { kind: "none" };
type LaneSource = Pick<WorkerView, "lanes" | "partLanes">;
export function laneFit(w: LaneSource, lane: string): LaneFit {
if (w.lanes.includes(lane)) return { kind: "all" };
const part = w.partLanes?.[lane];
return part && part.runnable > 0 ? { kind: "some", runnable: part.runnable, of: part.of } : { kind: "none" };
}
/** The note after a lane's name: none when it runs every workflow, "(24 of 26 workflows)", or "(files missing)". */
export function laneNote(fit: LaneFit): string | null {
if (fit.kind === "all") return null;
return fit.kind === "some" ? `(${fit.runnable} of ${fit.of} workflows)` : "(files missing)";
}
/** Every lane it can run at least one workflow of. */
export const runnableLanes = (w: LaneSource): string[] => [...new Set([...w.lanes, ...Object.keys(w.partLanes ?? {})])];
/**
* The lanes Allow all it can run allows: each one it can run any workflow of (a task goes only to a worker that can run
* its own workflow, so a lane it runs part of is safe to allow), each keeping a wait it already had.
*/
export function allowAllItCanRun(w: LaneSource, allow: Record<string, LaneAllow>): Record<string, LaneAllow> {
const next: Record<string, LaneAllow> = {};
for (const lane of runnableLanes(w)) next[lane] = allow[lane] ?? { delayMs: 0 };
return next;
}
const FIT_RANK = { all: 0, some: 1, none: 2 } as const;
/** A small number box that keeps what is typed ("0.", "0.5") and reports a number past 0, or undefined. */
function NumberBox({ value, onValue, label, placeholder }: { value?: number; onValue: (n: number | undefined) => void; label: string; placeholder: string }) {
const [text, setText] = useState(value ? String(value) : "");
return (
<Input
aria-label={label}
className="h-7 w-14"
inputMode="decimal"
placeholder={placeholder}
value={text}
onChange={(e) => {
setText(e.target.value);
const n = Number(e.target.value);
onValue(e.target.value.trim() && Number.isFinite(n) && n > 0 ? n : undefined);
}}
/>
);
}
export function LanesEditor({ w, lanes, onSave }: { w: WorkerView; lanes: Lane[]; onSave: (allow: Record<string, LaneAllow>) => void }) {
const [allow, setAllow] = useState(w.allow);
// The large-frame limit: a number past 0 sets each half, anything else clears it (both are needed to take effect).
const setLimit = (lane: string, k: "maxSeconds" | "bigFrom" | "bigMaxSeconds", v: number | undefined) =>
setAllow((was) => {
const next: LaneAllow = { ...(was[lane] ?? { delayMs: 0 }) };
if (v) next[k] = v;
else delete next[k];
return { ...was, [lane]: next };
});
// Every workflow first, then some of them, then none; by name within each.
const sorted = [...lanes].sort((a, b) => FIT_RANK[laneFit(w, a.lane).kind] - FIT_RANK[laneFit(w, b.lane).kind] || a.label.localeCompare(b.label));
const runnable = runnableLanes(w).length;
const [query, setQuery] = useState("");
const shown = sorted.filter((l) => laneMatches(l, query));
return (
<details className="text-[13px]">
<summary className="cursor-pointer text-muted-foreground">
Lanes it may run: {Object.keys(w.allow).length} of {lanes.length} ({runnable} it can run)
</summary>
<label className="mt-2 flex items-center gap-2">
<Search className="size-4 shrink-0 text-muted-foreground" />
<Input aria-label="Search lanes" placeholder="Search by app, model or lane" value={query} onChange={(e) => setQuery(e.target.value)} className="h-8" />
</label>
<ul className="mt-2 max-h-72 space-y-1 overflow-y-auto">
{query && !shown.length && <li className="text-muted-foreground">No lane matches.</li>}
{shown.map((l) => {
const fit = laneFit(w, l.lane);
const note = laneNote(fit);
return (
<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="min-w-0">
<span className={cn("block truncate", fit.kind === "none" && "text-muted-foreground")}>
{l.label}
{note && <span className="ml-2 text-[11px] text-muted-foreground">{note}</span>}
</span>
{l.file && <span className="block truncate text-[11px] text-muted-foreground">{l.file}</span>}
</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]: { ...allow[l.lane], delayMs: Math.max(0, Number(e.target.value) || 0) * 1000 } })}
/>
s first
</label>
)}
{l.lane in allow && (
<span className="flex flex-wrap items-center gap-1 text-[12px] text-muted-foreground">
clips up to
<NumberBox label={`Longest clip for ${l.label}`} placeholder="any" value={allow[l.lane]?.maxSeconds} onValue={(n) => setLimit(l.lane, "maxSeconds", n)} />
s, above
<NumberBox label={`Frame size for shorter clips on ${l.label}`} placeholder="MP" value={allow[l.lane]?.bigFrom} onValue={(n) => setLimit(l.lane, "bigFrom", n)} />
MP up to
<NumberBox label={`Longest clip of larger frames for ${l.label}`} placeholder="any" value={allow[l.lane]?.bigMaxSeconds} onValue={(n) => setLimit(l.lane, "bigMaxSeconds", n)} />
s
</span>
)}
</li>
);
})}
</ul>
<div className="mt-2 flex flex-wrap items-center gap-2">
{/* One click for every lane the PC can run any workflow of (each keeps a wait it already had), saved at once. */}
<Button
size="sm"
className="h-8"
disabled={!runnable}
onClick={() => {
const next = allowAllItCanRun(w, allow);
setAllow(next);
onSave(next);
}}
>
Allow all it can run ({runnable})
</Button>
<Button size="sm" variant="ghost" className="h-8" disabled={!Object.keys(allow).length} onClick={() => setAllow({})}>
Clear
</Button>
<Button size="sm" variant="secondary" className="h-8" onClick={() => onSave(allow)}>
Save lanes
</Button>
</div>
</details>
);
}
/** A pack whose nodes didn't load on the worker's PC, in words: what is missing and which workflows it isn't sent. */
export function unloadedLine(u: { pack: string; classes: string[]; workflows: string[] }): string {
const n = u.workflows.length;
return (
`${u.pack} didn't load in this PC's ComfyUI (missing ${u.classes.join(", ")}; its comfyui.log says why). ` +
(n ? `${n === 1 ? "The workflow that needs it isn't" : `The ${n} workflows that need it aren't`} sent here: ${u.workflows.join(", ")}.` : "No workflow here needs those nodes.")
);
}
/**
* Its program against the site's version: nothing while it is on it; while it updates by itself, the words only; behind
* for longer, a warning and Update now (it looks for new code at once and restarts after the job in hand).
*/
export function UpdateLine({ w, now }: { w: Pick<WorkerView, "id" | "words" | "update">; now: number }) {
const qc = useQueryClient();
const ask = useMutation({
mutationFn: () => call<{ worker: WorkerView }>("POST", `/api/admin/workers/${encodeURIComponent(w.id)}/update`, {}),
onSuccess: () => {
toast.success("Asked: it updates after the job in hand");
void qc.invalidateQueries({ queryKey: ["admin", "workers"] });
},
onError: (e) => toast.error((e as Error).message),
});
const u = w.update;
if (!u || u.state === "current") return null;
if (u.state === "updating") return u.words === w.words ? null : <p className="text-[12px] text-muted-foreground">{u.words}</p>;
const asked = u.askedAt !== null && now - u.askedAt < 15 * 60_000;
return (
<div className="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-amber-500/40 bg-amber-500/5 px-2.5 py-2 text-[13px]">
<span>{asked ? `${u.words}. Update asked ${Math.max(0, Math.round((now - u.askedAt!) / 60_000))} min ago.` : u.words}</span>
<Button size="sm" className="h-8" disabled={ask.isPending} onClick={() => ask.mutate()}>
<Download /> Update now
</Button>
</div>
);
}
/** How long ago, in minutes, hours or days. */
const agoWords = (ms: number) => {
const min = Math.max(0, Math.round(ms / 60_000));
if (min < 60) return `${min} min ago`;
const h = Math.round(min / 60);
return h < 48 ? `${h} h ago` : `${Math.round(h / 24)} days ago`;
};
/**
* The workflows a worker takes only with every weight on its card: a job of each ran out of memory there with its
* weights streamed from RAM, and went to another worker. Clearing one lets the worker stream it again.
*/
function NoStreamList({ list, now, busy, onClear }: { list: { workflowId: string; at: number }[]; now: number; busy: boolean; onClear: (ids: true | string[]) => void }) {
return (
<div className="space-y-1 text-[13px]">
<p>
Runs these only with every weight on its card
<span className="block text-[12px] text-muted-foreground">A job of each ran out of memory here with its weights streamed from RAM, and another worker took it. Clear one to let this worker stream it again.</span>
</p>
<ul className="space-y-0.5">
{list.map((n) => (
<li key={n.workflowId} className="flex items-center justify-between gap-2">
<span className="min-w-0 truncate">
{n.workflowId} <span className="text-[12px] text-muted-foreground">· {agoWords(now - n.at)}</span>
</span>
<Button size="sm" variant="ghost" className="h-7 shrink-0" disabled={busy} onClick={() => onClear([n.workflowId])}>
Clear
</Button>
</li>
))}
</ul>
{list.length > 1 && (
<Button size="sm" variant="ghost" className="h-7" disabled={busy} onClick={() => onClear(true)}>
Clear all
</Button>
)}
</div>
);
}
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>
<UpdateLine w={w} now={now} />
<p className="text-[12px] text-muted-foreground">{hoursWords(w.hours)}</p>
{w.unloaded?.map((u) => (
<p key={u.pack} className="text-[12px] text-destructive">
{unloadedLine(u)}
</p>
))}
<label className="flex items-start gap-2 text-[13px]">
<input
type="checkbox"
className="mt-0.5 size-4 accent-[var(--primary)]"
checked={!!w.autoResume}
disabled={patch.isPending}
onChange={(e) => patch.mutate({ autoResume: e.target.checked })}
/>
<span>
Resume by itself after another program used the GPU
<span className="block text-[12px] text-muted-foreground">
Once the GPU has been free for its cool-down. A pause by hand always waits for a resume by hand.
{w.autoResume === null && " Now: as the PC's own setting says."}
</span>
</span>
</label>
{w.ramGuard !== undefined && (
<label className="flex items-start gap-2 text-[13px]">
<input
type="checkbox"
className="mt-0.5 size-4 accent-[var(--primary)]"
checked={w.ramGuard}
disabled={patch.isPending}
onChange={(e) => patch.mutate({ ramGuard: e.target.checked })}
/>
<span>
RAM guard
<span className="block text-[12px] text-muted-foreground">
For a PC someone also works on. While other programs use a lot of its memory, this worker lets go of its own memory before each job and gives jobs that need extra memory to another worker when one is free. It keeps taking work, so nobody waits.
</span>
</span>
</label>
)}
{w.pickOrder !== undefined && (
<label className="flex items-start gap-2 text-[13px]">
<input
type="checkbox"
className="mt-0.5 size-4 accent-[var(--primary)]"
checked={w.pickOrder > 0}
disabled={patch.isPending}
onChange={(e) => patch.mutate({ pickOrder: e.target.checked ? 1 : 0 })}
/>
<span>
Picks first
<span className="block text-[12px] text-muted-foreground">
This worker gets a job before the others when it's free and can run it. When it's off, paused, busy or outside its hours, another worker takes the job at once.
</span>
</span>
</label>
)}
{!!w.noStream?.length && <NoStreamList list={w.noStream} now={now} busy={patch.isPending} onClear={(clearNoStream) => patch.mutate({ clearNoStream })} />}
<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[]; held?: HeldCounts; hosted?: boolean }>("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 now = useNow(30_000);
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's owner manages workers.</p>;
const workers = q.data?.workers ?? [];
const held = heldLine(q.data?.held, now);
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'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's ComfyUI jobs on the workers
</label>
</div>
{/* The name visitors read for these GPUs: asked for only while hosted runs are on. */}
{q.data?.hosted && <PlaceNameField saved={where.data?.find((s) => s.name === "hostedPlaceName")} />}
{q.data?.hosted && <OnlyWhatCanRunField saved={where.data?.find((s) => s.name === "hostedOnlyWhatCanRun")?.value} />}
{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>}
{held && (
<p data-held-line className="text-[13px] text-muted-foreground tabular-nums">
{held}
</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 name visitors read for this studio's GPUs while hosted runs are on ("Runs on Our GPUs", src/lib/place-name.ts).
* Empty: FUOBE_PLACE_NAME, else "Our GPUs". A billing service's own name for them wins over both.
*/
function PlaceNameField({ saved }: { saved?: { value: string; fromEnv: boolean } }) {
const qc = useQueryClient();
const [typed, setTyped] = useState<string | null>(null);
const value = typed ?? (saved && !saved.fromEnv ? saved.value : "");
const save = useMutation({
mutationFn: () => call("PUT", "/api/settings", { hostedPlaceName: value.trim() }),
onSuccess: () => {
setTyped(null);
toast.success("Saved");
void qc.invalidateQueries({ queryKey: ["settings"] });
void qc.invalidateQueries({ queryKey: ["status"] });
},
onError: (e) => toast.error((e as Error).message),
});
return (
<form
className="max-w-2xl space-y-1.5"
onSubmit={(e) => {
e.preventDefault();
save.mutate();
}}
>
<label htmlFor="place-name" className="text-[14px] font-medium">
Name for your GPUs
</label>
<div className="flex flex-wrap items-center gap-2">
<Input id="place-name" maxLength={PLACE_NAME_MAX} placeholder={saved?.fromEnv ? saved.value : PLACE_NAME_DEFAULT} value={value} onChange={(e) => setTyped(e.target.value)} className="h-9 w-64" />
<Button size="sm" variant="secondary" className="h-9" disabled={typed === null || save.isPending}>
Save
</Button>
</div>
<p className="text-[13px] text-muted-foreground">
Visitors read it where their runs go, as in “Runs on {value.trim() || (saved?.fromEnv ? saved.value : PLACE_NAME_DEFAULT)}”. Shown while runs on your GPUs are open to accounts.
</p>
</form>
);
}
/**
* Whether people's runs on this studio's GPUs are offered only the lengths and sizes a GPU on now makes (on by default):
* src/server/capacity.ts. Off, every length and size is offered, as the models do.
*/
function OnlyWhatCanRunField({ saved }: { saved?: string }) {
const qc = useQueryClient();
const save = useMutation({
mutationFn: (on: boolean) => call("PUT", "/api/settings", { hostedOnlyWhatCanRun: on ? "on" : "off" }),
onSuccess: () => {
toast.success("Saved");
void qc.invalidateQueries({ queryKey: ["settings"] });
void qc.invalidateQueries({ queryKey: ["capacity"] });
},
onError: (e) => toast.error((e as Error).message),
});
return (
<div className="max-w-2xl space-y-1.5">
<label className="flex items-center gap-2 text-[14px]">
<input type="checkbox" checked={saved !== "off"} disabled={save.isPending || saved === undefined} onChange={(e) => save.mutate(e.target.checked)} />
Offer only the lengths and sizes the site's GPUs can make now
</label>
<p className="text-[13px] text-muted-foreground">
People pick from what a GPU that is on can make, and a choice that isn't made now steps down to the nearest one. Off, every length and size is offered.
</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>
);
}