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.

Composer: offer the lengths and sizes the site can make now

Adarsh854da37b7766
diff --git a/src/app/api/capacity/route.ts b/src/app/api/capacity/route.ts
new file mode 100644
index 00000000..50afc96d
--- /dev/null
+++ b/src/app/api/capacity/route.ts
@@ -0,0 +1,12 @@
+import { connection } from "next/server";
+import { capacityView } from "@/server/capacity";
+import { hostedRunsOn } from "@/server/hosted-switch";
+
+/**
+ * The lengths and sizes runs on this install's GPUs are made at now (src/server/capacity.ts): by model, only the ones
+ * limited now. Read by the composer for a visitor's runs there; the same answer for everyone, kept a few seconds.
+ */
+export async function GET() {
+ await connection();
+ return Response.json(hostedRunsOn() ? capacityView() : { m: {} }, { headers: { "Cache-Control": "private, max-age=5" } });
+}
diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.ts
index a2af77f6..9963db22 100644
--- a/src/app/api/generations/route.ts
+++ b/src/app/api/generations/route.ts
@@ -324,10 +324,8 @@ export async function POST(request: Request) {
return refuse(over.status, over.error, { code: over.code, ...(over.limit && { limit: over.limit, refreshAt: over.refreshAt }) }, { "Retry-After": String(over.retryAfterS) });
}
// The request as it runs there (no more outputs than the policy's cap per run): planned and priced as it is.
- if (onPool.capped) {
- req = { ...req, params: onPool.req.params };
- notes.push(ACCOUNT_MESSAGES.outputsCapped);
- }
+ if (onPool.capped || onPool.stepped) req = { ...req, params: onPool.req.params };
+ if (onPool.capped) notes.push(ACCOUNT_MESSAGES.outputsCapped);
}
// GPU pre-flight: a ComfyUI run that is sure to fail for something missing stops here with the plan that fixes it
// (src/server/gpu/gate.ts; never when the check is unknown, for graphics memory, or with gpuCheck "skip").
diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsx
index d32f3369..f93c301f 100644
--- a/src/components/studio/composer.tsx
+++ b/src/components/studio/composer.tsx
@@ -40,6 +40,8 @@ import { EndFrameNote } from "./end-frame-note";
import { modelOwnSetup, pickerRules } from "@/lib/pool-rules";
import { carryParams, closestHere, HERE_SET_UP, hereDefault, hereReason, hereRunLabel, hereSetup, runsHere } from "@/lib/runnable-here";
import { useHere } from "@/hooks/use-pool-rules";
+import { useCapacity } from "@/hooks/use-capacity";
+import { lengthsUnder, limitAt, resolutionOffered, stepDown, type OfferFacts } from "@/lib/capacity";
import { controlSetup, keyOnlySetup } from "@/lib/own-setup-controls";
import { ownSetupDetail, ownSetupLabel, ownSetupShort } from "@/lib/own-setup";
import { OwnSetupChip, useOwnSetupPress, useOwnSetupViewer } from "@/components/own-setup";
@@ -773,6 +775,8 @@ export function Composer({ docked }: { docked: boolean }) {
// The price check is asked with the place the run itself names: none while the studio puts its GPUs first and the
// account's own GPU is online, so it answers for where the server would really send the run.
const askPool = hostedHere && runOn === "pool";
+ // The lengths and sizes made on this studio's GPUs now (read for any viewer whose runs may go there).
+ const capacity = useCapacity(!!viewerInfo?.hosted);
const wantPrice = askPool ? quoteBody(signed.request, runPlace) : null;
const priceBody = useSettled(wantPrice);
const priceQuery = useHostedQuote(priceBody);
@@ -1320,7 +1324,35 @@ export function Composer({ docked }: { docked: boolean }) {
};
// Enhance writes a scene; a tool's optional words (FLUX.3 Upscale's details) stay as typed.
const baseShape = settingsShape(model, effectiveOp, config.kind, showPrompt && !config.hidePrompt, p, config.ops, studioFormats);
- const shape = framesCtx ? framesShape(baseShape, framesCtx.chained) : layoutOn ? layoutShape(baseShape) : baseShape;
+ const fullShape = framesCtx ? framesShape(baseShape, framesCtx.chained) : layoutOn ? layoutShape(baseShape) : baseShape;
+ // A run on this studio's GPUs: only the lengths and sizes some GPU there makes now (src/lib/capacity.ts), the choice
+ // stepped down to them. Studios and models stay as they are, and the owner sees every option.
+ const capLengths = framesCtx ? (framesCtx.chained || !model ? null : framesDurations(model)) : fullShape.duration;
+ const capFacts: OfferFacts | null =
+ askPool && model && capacity?.m[model.id]
+ ? {
+ lengths: capLengths,
+ resolutions: fullShape.resolution,
+ still: model.kind !== "video",
+ limit: (res) => limitAt(capacity, model.id, effectiveOp, res ?? model.defaults?.resolution, fullShape.aspect ? (p.aspectRatio ?? model.defaults?.aspectRatio) : undefined),
+ }
+ : null;
+ const capResolution = p.resolution ?? model?.defaults?.resolution;
+ const capDuration = framesCtx?.duration ?? p.duration ?? model?.defaults?.duration;
+ const shape = capFacts
+ ? {
+ ...fullShape,
+ duration: fullShape.duration && lengthsUnder(fullShape.duration, capFacts.limit(capResolution)),
+ resolution: fullShape.resolution && fullShape.resolution.filter((r) => resolutionOffered(capFacts, r, capDuration)),
+ }
+ : fullShape;
+ const framesLengths = !model ? [5] : capFacts && capLengths ? lengthsUnder(capLengths, capFacts.limit(capResolution)) : framesDurations(model);
+ // A choice no longer offered steps down (a shorter length first, then a smaller size), as other settings are clamped.
+ const capStepKey = JSON.stringify(capFacts ? stepDown(capFacts, { duration: capDuration, resolution: capResolution }) : null);
+ useEffect(() => {
+ const patch = JSON.parse(capStepKey) as { duration?: number; resolution?: string } | null;
+ if (patch) setDraft((d) => ({ params: { ...d.params, ...patch } }));
+ }, [capStepKey, setDraft]);
// An image of a wide scene with a person in it, asked as a small square: one tap makes it 16:9 at a larger size.
const framing =
config.kind === "image" && !framingKept && !layoutOn && !framesOn && model
@@ -1824,7 +1856,7 @@ export function Composer({ docked }: { docked: boolean }) {
<FramesStrip
frames={draft.frames}
duration={framesCtx?.duration ?? p.duration ?? 5}
- durations={model ? framesDurations(model) : [5]}
+ durations={framesLengths}
onDuration={(duration) => setP({ duration })}
onMove={(i, seconds) =>
setDraft((d) => {
diff --git a/src/components/workers-admin.tsx b/src/components/workers-admin.tsx
index be737cfa..0926e49e 100644
--- a/src/components/workers-admin.tsx
+++ b/src/components/workers-admin.tsx
@@ -575,6 +575,7 @@ export function WorkersAdmin() {
</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"
@@ -649,6 +650,34 @@ function PlaceNameField({ saved }: { saved?: { value: string; fromEnv: boolean }
);
}
+/**
+ * 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&apos;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&apos;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;
diff --git a/src/hooks/use-capacity.ts b/src/hooks/use-capacity.ts
new file mode 100644
index 00000000..50c90599
--- /dev/null
+++ b/src/hooks/use-capacity.ts
@@ -0,0 +1,24 @@
+"use client";
+
+import { useQuery } from "@tanstack/react-query";
+import type { CapacityView } from "@/lib/capacity";
+import { fetchWithin, READ_LIMIT_MS } from "@/lib/fetch-within";
+
+/**
+ * The lengths and sizes runs on this install's GPUs are made at now (GET /api/capacity), for a viewer whose runs go
+ * there (`on`). Undefined until read, when off, or when the read fails: then every option stays offered.
+ */
+export function useCapacity(on: boolean): CapacityView | undefined {
+ return useQuery({
+ queryKey: ["capacity"],
+ queryFn: async () => {
+ const res = await fetchWithin("/api/capacity", READ_LIMIT_MS.status);
+ if (!res.ok) throw new Error(String(res.status));
+ return (await res.json()) as CapacityView;
+ },
+ enabled: on,
+ staleTime: 10_000,
+ refetchInterval: on ? 30_000 : false,
+ retry: 1,
+ }).data;
+}
diff --git a/src/lib/capacity.ts b/src/lib/capacity.ts
new file mode 100644
index 00000000..6b20e9ee
--- /dev/null
+++ b/src/lib/capacity.ts
@@ -0,0 +1,172 @@
+/**
+ * What the site can make now, in clip lengths and frame sizes: the workers that are on (online, paused in neither place)
+ * and those back within CAPACITY_GRACE_MS, each lane's longest clip at each frame-size class. The composer offers only
+ * the lengths and sizes some such worker makes, and a new run is stepped down to them.
+ *
+ * Pure: the server (src/server/capacity.ts), the composer and the tests share it.
+ */
+
+/** A worker that stops being on keeps counting for this long (a short drop doesn't change what is offered). */
+export const CAPACITY_GRACE_MS = 5 * 60_000;
+
+/** One worker's limits in a lane: its lane's own clip limits and its PC's ceiling. */
+export interface LaneLimit {
+ maxSeconds?: number;
+ bigFrom?: number;
+ bigMaxSeconds?: number;
+ ceilingSeconds?: number;
+ ceilingMegapixels?: number;
+}
+
+/**
+ * A frame-size class: frames up to `upTo` megapixels (null: any larger) are made up to `seconds` long (null: no limit;
+ * 0: not made at this size). Classes go from the smallest frames up.
+ */
+export type SizeClass = { upTo: number | null; seconds: number | null };
+
+const EPS = 1e-9;
+
+/** The longest clip one worker makes in a lane at this frame size (undefined: no limit; 0: it doesn't make this size). */
+export function workerMostSeconds(l: LaneLimit, megapixels: number): number | undefined {
+ if (l.ceilingMegapixels && megapixels > l.ceilingMegapixels + EPS) return 0;
+ const big = l.bigFrom && l.bigMaxSeconds && megapixels > l.bigFrom + EPS ? l.bigMaxSeconds : undefined;
+ const limits = [l.maxSeconds, big, l.ceilingSeconds].filter((x): x is number => !!x && x > 0);
+ return limits.length ? Math.min(...limits) : undefined;
+}
+
+/**
+ * A lane's classes from the limits of the workers counted in it (none: null, so the lane keeps today's behaviour). The
+ * longest clip of each class is the best any of them makes there.
+ */
+export function laneClasses(limits: readonly LaneLimit[]): SizeClass[] | null {
+ if (!limits.length) return null;
+ const marks = [...new Set(limits.flatMap((l) => [l.bigFrom && l.bigMaxSeconds ? l.bigFrom : 0, l.ceilingMegapixels ?? 0]).filter((x) => x > 0))].sort((a, b) => a - b);
+ const at = (mp: number): number | null => {
+ let best: number | null = 0;
+ for (const l of limits) {
+ const s = workerMostSeconds(l, mp);
+ if (s === undefined) return null;
+ if (best !== null && s > best) best = s;
+ }
+ return best;
+ };
+ const out: SizeClass[] = [];
+ for (const [i, upTo] of [...marks, null].entries()) {
+ // Upper bounds are inclusive (a frame of exactly `bigFrom` megapixels is still small); past the last mark, just over it.
+ const seconds = at(i < marks.length ? marks[i] : (marks.at(-1) ?? 0) + 1e-6);
+ const last = out.at(-1);
+ if (last && last.seconds === seconds) last.upTo = upTo;
+ else out.push({ upTo, seconds });
+ }
+ return out;
+}
+
+/** The longest clip of a frame size in a lane's classes (null: no limit; 0: not made). */
+export function secondsAt(classes: readonly SizeClass[] | null | undefined, megapixels: number): number | null {
+ if (!classes?.length) return null;
+ for (const c of classes) if (c.upTo === null || megapixels <= c.upTo + EPS) return c.seconds;
+ return classes[classes.length - 1].seconds;
+}
+
+/** Does a job of this size fit (`seconds`: 0 for a picture)? */
+export const fitsLimit = (limit: number | null, seconds: number): boolean => limit === null || (limit > 0 && seconds <= limit + EPS);
+
+// ---------------------------------------------------------------------------
+// The view the composer reads (GET /api/capacity)
+
+/** A resolution's limit: one for every aspect, or by aspect ratio. A resolution left out has no limit. */
+export type SizeLimit = number | Record<string, number>;
+
+/** By model id, then operation, then resolution ("" for a model with none): only the models whose lane is limited now. */
+export interface CapacityView {
+ m: Record<string, Record<string, Record<string, SizeLimit>>>;
+}
+
+/**
+ * The longest clip of a model at a resolution and aspect (null: no limit; 0: not made). `op` unknown: the most any of its
+ * operations makes. An aspect it doesn't name (the frame follows a picture): the most of its aspects.
+ */
+export function limitAt(view: CapacityView | null | undefined, modelId: string | undefined, op: string | undefined, resolution: string | undefined, aspect: string | undefined): number | null {
+ const byOp = modelId ? view?.m[modelId] : undefined;
+ if (!byOp) return null;
+ // An operation left out runs in a lane with no limit now.
+ const tables = op ? (byOp[op] ? [byOp[op]] : []) : Object.values(byOp);
+ if (!tables.length) return null;
+ let most = 0;
+ for (const t of tables) {
+ const v = t[resolution ?? ""];
+ if (v === undefined) return null;
+ const n = typeof v === "number" ? v : aspect && v[aspect] !== undefined ? v[aspect] : Math.max(0, ...Object.values(v));
+ most = Math.max(most, n);
+ }
+ return most;
+}
+
+/** The lengths offered under a limit (seconds; a length past it isn't offered). */
+export const lengthsUnder = (lengths: readonly number[], limit: number | null): number[] => (limit === null ? [...lengths] : lengths.filter((s) => fitsLimit(limit, s)));
+
+/** A resolution's size, for "smaller": "768p" → 768, "2K" → 2000, "1MP" → 1000 (unknown: its place in the list). */
+function resolutionRank(r: string, i: number): number {
+ const p = /^(\d+(?:\.\d+)?)p$/i.exec(r);
+ if (p) return Number(p[1]);
+ const k = /^(\d+(?:\.\d+)?)K$/i.exec(r);
+ if (k) return Number(k[1]) * 1000;
+ const mp = /^(\d+(?:\.\d+)?)MP$/i.exec(r);
+ if (mp) return Math.sqrt(Number(mp[1])) * 1000;
+ return i;
+}
+
+/** Resolutions from the largest down. */
+export const largestFirst = (resolutions: readonly string[]): string[] =>
+ resolutions
+ .map((r, i) => ({ r, n: resolutionRank(r, i) }))
+ .sort((a, b) => b.n - a.n)
+ .map((x) => x.r);
+
+export interface OfferFacts {
+ /** The model's lengths to pick from (null: none to pick; the run's length is `duration`). */
+ lengths: readonly number[] | null;
+ /** The model's resolutions to pick from (null: none to pick). */
+ resolutions: readonly string[] | null;
+ /** The longest clip at a resolution (null: no limit; 0: not made). */
+ limit: (resolution: string | undefined) => number | null;
+ /** A picture: only whether its size is made counts. */
+ still?: boolean;
+}
+
+/** Is a resolution offered: made at some length offered (a picture: made at all)? */
+export function resolutionOffered(f: OfferFacts, resolution: string | undefined, duration: number | undefined): boolean {
+ const limit = f.limit(resolution);
+ if (limit === null) return true;
+ if (limit <= 0) return false;
+ if (f.still) return true;
+ if (f.lengths?.length) return lengthsUnder(f.lengths, limit).length > 0;
+ return fitsLimit(limit, duration ?? 0);
+}
+
+/**
+ * A choice stepped down to what is offered: a shorter length first, then a smaller size (the length then the longest
+ * offered there up to the one picked). Null: the choice is offered as it is, or nothing smaller is.
+ */
+export function stepDown(f: OfferFacts, now: { duration?: number; resolution?: string }): { duration?: number; resolution?: string } | null {
+ const fits = (res: string | undefined, d: number | undefined) => {
+ const limit = f.limit(res);
+ return limit === null || (limit > 0 && (f.still || fitsLimit(limit, d ?? 0)));
+ };
+ if (fits(now.resolution, now.duration)) return null;
+ const sizes = f.resolutions?.length ? largestFirst(f.resolutions) : [now.resolution];
+ const from = now.resolution !== undefined && sizes.includes(now.resolution) ? sizes.indexOf(now.resolution) : 0;
+ for (const res of sizes.slice(from)) {
+ const limit = f.limit(res);
+ if (limit !== null && limit <= 0) continue;
+ if (f.still) return res === now.resolution ? null : { resolution: res };
+ const lengths = f.lengths?.length ? [...lengthsUnder(f.lengths, limit)].sort((a, b) => b - a) : null;
+ if (lengths) {
+ if (!lengths.length) continue;
+ const d = lengths.find((s) => s <= (now.duration ?? Infinity) + EPS) ?? lengths[lengths.length - 1];
+ return { ...(d !== now.duration && { duration: d }), ...(res !== now.resolution && { resolution: res }) };
+ }
+ if (fits(res, now.duration)) return res === now.resolution ? null : { resolution: res };
+ }
+ return null;
+}
diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.ts
index b5febde9..2d441caf 100644
--- a/src/lib/guest-access.ts
+++ b/src/lib/guest-access.ts
@@ -25,7 +25,7 @@ export const GUEST_RUN_MESSAGE = "Create a free account to run this.";
export const SIGN_IN_CODE = "sign-in";
/** Catalog and status reads that hold nothing of the owner's library: a guest gets the real answer. */
-const GUEST_READS = new Set(["/api/status", "/api/site/uploads", "/api/examples", "/api/models", "/api/search-index", "/api/comfyui", "/api/settings/models", "/api/gpu/requirements", "/api/live/nodes"]);
+const GUEST_READS = new Set(["/api/status", "/api/capacity", "/api/site/uploads", "/api/examples", "/api/models", "/api/search-index", "/api/comfyui", "/api/settings/models", "/api/gpu/requirements", "/api/live/nodes"]);
/** Catalogs mixed with the owner's own items: the route leaves the owner's part out for a guest (GUEST_HEADER). */
const GUEST_FILTERED = new Set(["/api/moodboards", "/api/palettes", "/api/assist", "/api/assist/skills"]);
diff --git a/src/server/capacity.ts b/src/server/capacity.ts
new file mode 100644
index 00000000..9484a39e
--- /dev/null
+++ b/src/server/capacity.ts
@@ -0,0 +1,132 @@
+import "server-only";
+import { MODELS } from "@/lib/catalog";
+import { operationOutput, type GenerationRequest, type ModelDef } from "@/lib/catalog/types";
+import { fitsLimit, laneClasses, largestFirst, secondsAt, stepDown, type CapacityView, type SizeClass, type SizeLimit } from "@/lib/capacity";
+import { capacityLimits, poolLane } from "./computer/pool";
+import { genjutsuSize, poolOnWorkers, requestMegapixels } from "./hosted";
+import { getSetting } from "./settings";
+
+/**
+ * What the site can make now (src/lib/capacity.ts), for runs on this install's GPUs: by lane, then by model for the
+ * composer (GET /api/capacity), kept for a few seconds. Only while those GPUs are the workers; otherwise nothing is
+ * limited here, and with Settings → Workers' switch off (hostedOnlyWhatCanRun) every option is offered as before.
+ */
+
+const KEEP_MS = 5_000;
+
+/** Is what is offered limited to what the site can make now: on the workers, with Settings → Workers' switch on? */
+export const capacityOn = (): boolean => poolOnWorkers() && getSetting("hostedOnlyWhatCanRun") !== "off";
+let kept: { at: number; lanes: Map<string, SizeClass[]>; view: CapacityView | null } | null = null;
+
+/** Each lane's classes now (a lane no counted worker runs is left out). */
+function lanesNow(now: number): Map<string, SizeClass[]> {
+ if (kept && now - kept.at < KEEP_MS && now >= kept.at) return kept.lanes;
+ const lanes = new Map<string, SizeClass[]>();
+ for (const [lane, limits] of capacityLimits(now)) {
+ const c = laneClasses(limits);
+ if (c) lanes.set(lane, c);
+ }
+ kept = { at: now, lanes, view: null };
+ return lanes;
+}
+
+/** Does a lane have a limit now (some size not made, or a longest clip)? */
+const limited = (c: SizeClass[] | undefined): c is SizeClass[] => !!c && c.some((x) => x.seconds !== null);
+
+/** The megapixels of a frame a route makes at this resolution and aspect, as the run's own check reads it. */
+function framePixels(model: ModelDef, op: string, endpoint: string, resolution: string | undefined, aspect: string | undefined): number {
+ const req = { modelId: model.id, op, feature: model.kind, params: { ...(resolution && { resolution }), ...(aspect && { aspectRatio: aspect }) } } as unknown as GenerationRequest;
+ try {
+ return requestMegapixels(req, operationOutput(op as never, model.kind), model.id, endpoint) ?? 0;
+ } catch {
+ return 0;
+ }
+}
+
+/** One model's limits by operation and resolution (null: none of its routes is limited now). */
+function modelLimits(model: ModelDef, lanes: Map<string, SizeClass[]>): Record<string, Record<string, SizeLimit>> | null {
+ if (model.engine !== "open") return null;
+ const out: Record<string, Record<string, SizeLimit>> = {};
+ for (const r of model.routes) {
+ if (r.provider !== "comfyui" || !r.endpoint || r.endpoint.includes("{") || out[r.op]) continue;
+ const classes = lanes.get(poolLane(r.endpoint));
+ if (!limited(classes)) continue;
+ const still = operationOutput(r.op, model.kind) !== "video";
+ const resolutions = model.options.resolutions?.length ? model.options.resolutions : [model.defaults?.resolution ?? ""];
+ const aspects = model.options.aspectRatios?.length ? model.options.aspectRatios : [model.defaults?.aspectRatio ?? ""];
+ const table: Record<string, SizeLimit> = {};
+ for (const res of resolutions) {
+ const byAspect: Record<string, number> = {};
+ for (const ar of aspects) {
+ const s = secondsAt(classes, framePixels(model, r.op, r.endpoint, res || undefined, ar || undefined));
+ // A picture: only a size that isn't made at all.
+ if (s !== null && (!still || s === 0)) byAspect[ar] = still ? 0 : s;
+ }
+ const values = Object.values(byAspect);
+ if (!values.length) continue;
+ table[res] = values.length === aspects.length && values.every((v) => v === values[0]) ? values[0] : byAspect;
+ }
+ if (Object.keys(table).length) out[r.op] = table;
+ }
+ return Object.keys(out).length ? out : null;
+}
+
+/** What the site can make now, by model (only the models limited now), for the composer. Empty off the workers. */
+export function capacityView(now = Date.now()): CapacityView {
+ if (!capacityOn()) return { m: {} };
+ const lanes = lanesNow(now);
+ if (kept?.view) return kept.view;
+ const m: CapacityView["m"] = {};
+ if ([...lanes.values()].some(limited)) {
+ for (const model of MODELS) {
+ const t = modelLimits(model, lanes);
+ if (t) m[model.id] = t;
+ }
+ }
+ const view = { m };
+ if (kept) kept.view = view;
+ return view;
+}
+
+/** The longest clip a lane makes now at a frame size (null: no limit, or no worker runs the lane now; 0: not made). */
+export function laneLimitNow(lane: string, megapixels: number, now = Date.now()): number | null {
+ if (!capacityOn()) return null;
+ return secondsAt(lanesNow(now).get(lane), megapixels);
+}
+
+/** Forget the classes kept (the tests change workers between checks). */
+export function forgetCapacity(): void {
+ kept = null;
+}
+
+/**
+ * A new run on this install's GPUs against what the site can make now: "fits" as asked, a request stepped down to the
+ * nearest length and size made now (a shorter length first, then a smaller size), or "none" when nothing it could be
+ * stepped down to is made. A run whose own size its request states (a Genjutsu part), or a model whose lane has no
+ * limit now, fits.
+ */
+export function fitRequest(req: GenerationRequest, route: { endpoint?: string; op: string }, model: ModelDef, now = Date.now()): { kind: "fits" } | { kind: "stepped"; req: GenerationRequest } | { kind: "none" } {
+ const endpoint = route.endpoint;
+ if (!endpoint || endpoint.includes("{") || !capacityOn() || genjutsuSize(req)) return { kind: "fits" };
+ const classes = lanesNow(now).get(poolLane(endpoint));
+ if (!limited(classes)) return { kind: "fits" };
+ const kind = operationOutput(route.op as never, model.kind);
+ if (kind !== "video" && kind !== "image") return { kind: "fits" };
+ const still = kind === "image";
+ const limit = (resolution: string | undefined) => {
+ const r = { ...req, params: { ...req.params, ...(resolution && { resolution }) } };
+ try {
+ return secondsAt(classes, requestMegapixels(r, kind, model.id, endpoint) ?? 0);
+ } catch {
+ return null;
+ }
+ };
+ const duration = req.params?.duration ?? (still ? undefined : model.defaults?.duration);
+ const resolution = req.params?.resolution ?? model.defaults?.resolution;
+ if (fitsLimit(limit(resolution), still ? 0 : (duration ?? 0))) return { kind: "fits" };
+ const lengths = !still && model.options.durations?.length ? model.options.durations : null;
+ const resolutions = model.options.resolutions?.length ? largestFirst(model.options.resolutions) : null;
+ const next = stepDown({ lengths, resolutions, limit, still }, { duration, resolution });
+ if (!next) return { kind: "none" };
+ return { kind: "stepped", req: { ...req, params: { ...req.params, ...next } } };
+}
diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.ts
index 150d906c..e2cc4b9e 100644
--- a/src/server/computer/pool.ts
+++ b/src/server/computer/pool.ts
@@ -11,6 +11,7 @@ import { runtimeFileKeys } from "@/lib/runtime-files";
import { APPS, MODELS } from "@/lib/catalog";
import { laneName, type LaneName } from "@/lib/lane-names";
import { clock, hoursAt, parseHours, type Hours } from "@/lib/worker-hours";
+import { CAPACITY_GRACE_MS, type LaneLimit } from "@/lib/capacity";
import { db } from "../db";
import { indexKey, loadIndex } from "../gpu/index-file";
import { hostedRunsOn } from "../hosted-switch";
@@ -526,6 +527,8 @@ export function workerBeat(w: WorkerRow, b: WorkerBeat, now = Date.now()): BeatA
...(s.prefix && { prefix: s.prefix }),
}));
const fresh = d.prepare("SELECT * FROM relay_workers WHERE id = ?").get(w.id) as WorkerRow;
+ // On at this beat: what the site can make now counts it until CAPACITY_GRACE_MS after its last such beat.
+ if (onNow(fresh, now)) d.prepare("UPDATE relay_workers SET available_at = ? WHERE id = ?").run(now, w.id);
// Its lanes from another requirements index (the catalog changed since its list came): worked out again now.
const lanesRefreshed = refreshLanes(fresh);
// Stop now (the website, or the worker paused itself with --now / a busy GPU): its jobs go back in line at no cost,
@@ -1929,6 +1932,40 @@ function onSoon(w: WorkerRow, now: number): boolean {
);
}
+/**
+ * Is a worker on now for what the site can make: one of the site's workers, heard from within the silence limit, paused
+ * neither on the website nor on its PC, not draining, new enough and inside its hours.
+ */
+function onNow(w: WorkerRow, now: number): boolean {
+ return w.kind === "pool" && w.pool === "pool" && onSoon(w, now);
+}
+
+/**
+ * Each lane's limits, one per worker counted for what the site can make now (src/lib/capacity.ts): on now, or on at a
+ * beat within CAPACITY_GRACE_MS, so a short drop (a restart, a power cut) changes nothing. A worker counts in the lanes
+ * it is allowed, inside its PC's ceiling. A lane no such worker runs is left out.
+ */
+export function capacityLimits(now = Date.now()): Map<string, LaneLimit[]> {
+ const out = new Map<string, LaneLimit[]>();
+ for (const w of poolWorkers()) {
+ if (w.pool !== "pool" || (w.expires_at && w.expires_at <= now) || (w.protocol ?? 0) < MIN_PROTOCOL) continue;
+ if (!onNow(w, now) && !(w.available_at && now - w.available_at < CAPACITY_GRACE_MS)) continue;
+ const allow = allowOf(w);
+ const ceiling = ceilingOf(w);
+ for (const lane of lanesInside(Object.keys(allow), ceiling)) {
+ const a = allow[lane];
+ const limit: LaneLimit = {
+ ...(a?.maxSeconds && { maxSeconds: a.maxSeconds }),
+ ...(a?.bigFrom && a.bigMaxSeconds && { bigFrom: a.bigFrom, bigMaxSeconds: a.bigMaxSeconds }),
+ ...(ceiling?.maxSeconds && { ceilingSeconds: ceiling.maxSeconds }),
+ ...(ceiling?.maxMegapixels && { ceilingMegapixels: ceiling.maxMegapixels }),
+ };
+ out.set(lane, [...(out.get(lane) ?? []), limit]);
+ }
+ }
+ return out;
+}
+
/**
* Is every worker that could run an account's job of this workflow (any workflow: null) away now: paused, draining,
* outside its hours, silent, or never connected? Only workers that take job tickets now count (ticketReady), as an
diff --git a/src/server/computer/workers.ts b/src/server/computer/workers.ts
index 9a3c14df..90c599e4 100644
--- a/src/server/computer/workers.ts
+++ b/src/server/computer/workers.ts
@@ -103,6 +103,8 @@ export interface WorkerRow {
update_asked_commit?: string | null;
/** Its PC's live hardware stats (src/lib/relay.ts WorkerStats) and when the studio heard them, as its last beat said. */
stats_json?: string | null;
+ /** The last beat at which it was on (online, paused in neither place): what the site can make now counts it a while after. */
+ available_at?: number | null;
}
const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
diff --git a/src/server/db.ts b/src/server/db.ts
index 9847fe01..fc68e731 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -1158,6 +1158,8 @@ const RELAY_COLUMNS: [string, string, string][] = [
// streaming from RAM (its RAM guard: pool.ts streamTakers).
["relay_workers", "ram_guard", "INTEGER NOT NULL DEFAULT 0"],
["relay_workers", "asked_no_stream", "INTEGER NOT NULL DEFAULT 0"],
+ // The last beat at which a worker was on (pool.ts capacityLimits).
+ ["relay_workers", "available_at", "INTEGER"],
];
declare global {
diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.ts
index b08d5822..20d53022 100644
--- a/src/server/hosted-run.ts
+++ b/src/server/hosted-run.ts
@@ -41,6 +41,8 @@ import {
import { getModel } from "@/lib/catalog";
import { PLACE_ASK_HEADER, RUN_PLACE_HEADER, RUN_SHOWN_HEADER } from "@/lib/guest-access";
import { db } from "./db";
+import { fitRequest } from "./capacity";
+import { POOL_TOO_BIG } from "./providers/comfyui";
import { AccountRunError, createGenerations, outputKind, plannedSteps, previewChained, previewGeneration, runLoraFiles, stepsOf, type PlannedStep } from "./generations";
import { loadIndex } from "./gpu/index-file";
import { attemptLimitMs, MAX_ATTEMPTS, poolLane } from "./computer/pool";
@@ -136,7 +138,7 @@ function refusedForOwnSetup(e: unknown, req: GenerationRequest): OwnSetup | null
*/
export type PlaceDecision =
| { kind: "own" }
- | { kind: "pool"; planned: Planned; policy: Policy; steps: RunFacts["steps"]; req: GenerationRequest; capped: boolean; light: boolean }
+ | { kind: "pool"; planned: Planned; policy: Policy; steps: RunFacts["steps"]; req: GenerationRequest; capped: boolean; stepped?: boolean; light: boolean }
| { kind: "refuse"; refusal: Refusal };
const OWN = { kind: "own" } as const;
@@ -592,7 +594,9 @@ export async function decidePlace(account: Account, asked: GenerationRequest, wi
// Closed to this account: its own GPU (or today's "Connect your GPU"); asked for by name, said so.
if (!p.hosted) return wish === "pool" ? notOffered(hostedWords(placeFor(p)).notHosted) : OWN;
// Planned, checked and priced for the outputs it would make there (the policy's cap per run).
- const { req, capped } = poolRequest(asked, p);
+ const outputs = poolRequest(asked, p);
+ let req = outputs.req;
+ const capped = outputs.capped;
if (capped) {
try {
planned = runOnPool(account.id, () => previewGeneration(req));
@@ -600,6 +604,20 @@ export async function decidePlace(account: Account, asked: GenerationRequest, wi
return OWN;
}
}
+ // A length or size that no GPU on now makes (src/server/capacity.ts): stepped down to the nearest one made (a shorter
+ // length first, then a smaller size), planned and priced as it is; with none, refused in the words for a size not
+ // offered (or its own GPU, as for any run these GPUs don't take). Only a new run: one already in line is never changed.
+ const fit = fitRequest(req, { endpoint: planned.route.endpoint, op: planned.op }, planned.model);
+ if (fit.kind === "none") return ownFallback ? OWN : { kind: "refuse", refusal: { status: 400, body: { error: POOL_TOO_BIG }, headers: {} } };
+ const stepped = fit.kind === "stepped";
+ if (fit.kind === "stepped") {
+ try {
+ planned = runOnPool(account.id, () => previewGeneration(fit.req));
+ req = fit.req;
+ } catch {
+ return OWN;
+ }
+ }
// The same check as the price check before Run (poolGate): what this install's GPUs can't take (a label the person
// reads before Run) goes to the account's own GPU when it has one and didn't ask for this install's; otherwise it is
// refused in the same words. A run they take is taken even while every GPU that could run it is away or being updated:
@@ -612,7 +630,7 @@ export async function decidePlace(account: Account, asked: GenerationRequest, wi
// Its own GPU didn't answer the check: asked, never moved to this install's GPUs (and charged) without a word, unless
// the account said yes to running there automatically when its GPU can't (site-fallback.ts).
if (ownOffline && !siteFallbackOn(account.id)) return { kind: "refuse", refusal: askPlace(placeFor(p)) };
- return { kind: "pool", planned, policy: p, steps: gate.steps ? pricedSteps(gate.steps) : undefined, req, capped, light: lightRun(gate.steps) };
+ return { kind: "pool", planned, policy: p, steps: gate.steps ? pricedSteps(gate.steps) : undefined, req, capped, stepped, light: lightRun(gate.steps) };
}
/** The input files of a request, for the moderation service: their kind and sha256 (pictures' previews: not sent yet). */
diff --git a/src/server/settings.ts b/src/server/settings.ts
index 353278ff..ae5903cb 100644
--- a/src/server/settings.ts
+++ b/src/server/settings.ts
@@ -88,6 +88,11 @@ export const SETTINGS = {
* Workers. A billing service's own name for them wins (src/server/place-name.ts); empty: "Our GPUs".
*/
hostedPlaceName: { key: "hosted.placeName", env: "FUOBE_PLACE_NAME" },
+ /**
+ * Settings → Workers: "on" offers people's runs on this install's GPUs only the lengths and sizes a GPU on now makes,
+ * and steps a new run down to them (src/server/capacity.ts); "off" offers every one, as the models do.
+ */
+ hostedOnlyWhatCanRun: { key: "hosted.onlyWhatCanRun", default: "on", options: ["on", "off"] },
/**
* 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/capacity.test.ts b/tests/capacity.test.ts
new file mode 100644
index 00000000..0065a827
--- /dev/null
+++ b/tests/capacity.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from "vitest";
+import { laneClasses, largestFirst, lengthsUnder, limitAt, resolutionOffered, secondsAt, stepDown, workerMostSeconds, type CapacityView, type OfferFacts } from "@/lib/capacity";
+
+describe("a lane's classes from the workers counted now", () => {
+ const small = { bigFrom: 0.5, bigMaxSeconds: 5.2 };
+ it("no worker: no classes (the lane keeps today's behaviour)", () => {
+ expect(laneClasses([])).toBeNull();
+ });
+ it("one worker with no limit: none at any size", () => {
+ expect(laneClasses([{}])).toEqual([{ upTo: null, seconds: null }]);
+ });
+ it("a small worker alone: any length up to its frame mark, 5.2 s past it", () => {
+ const c = laneClasses([small])!;
+ expect(c).toEqual([
+ { upTo: 0.5, seconds: null },
+ { upTo: null, seconds: 5.2 },
+ ]);
+ expect(secondsAt(c, 0.4)).toBeNull();
+ // Exactly at the mark is still small, as the line reads it.
+ expect(secondsAt(c, 0.5)).toBeNull();
+ expect(secondsAt(c, 1.03)).toBe(5.2);
+ });
+ it("the best of the workers in each class", () => {
+ const c = laneClasses([small, { maxSeconds: 8 }])!;
+ expect(secondsAt(c, 0.3)).toBeNull();
+ expect(secondsAt(c, 1)).toBe(8);
+ expect(secondsAt(laneClasses([small, {}]), 1)).toBeNull();
+ });
+ it("a PC's ceiling: no frame past its megapixels, no clip past its seconds", () => {
+ expect(workerMostSeconds({ ceilingMegapixels: 0.3 }, 0.6)).toBe(0);
+ expect(workerMostSeconds({ ceilingSeconds: 6, maxSeconds: 10 }, 0.2)).toBe(6);
+ const c = laneClasses([{ ceilingMegapixels: 0.3 }])!;
+ expect(secondsAt(c, 0.25)).toBeNull();
+ expect(secondsAt(c, 0.6)).toBe(0);
+ });
+});
+
+describe("what the composer offers and where a choice steps down to", () => {
+ const view: CapacityView = { m: { h3: { t2v: { "768p": 5.2 }, i2v: { "768p": { "16:9": 5.2, "1:1": 10 } } }, wan: { t2v: { "720p": 0 } } } };
+ it("the limit by model, operation, resolution and aspect", () => {
+ expect(limitAt(view, "h3", "t2v", "768p", "16:9")).toBe(5.2);
+ expect(limitAt(view, "h3", "i2v", "768p", "1:1")).toBe(10);
+ // No aspect to pick (the frame follows a picture): the most of its aspects.
+ expect(limitAt(view, "h3", "i2v", "768p", undefined)).toBe(10);
+ // An operation, resolution or model left out: no limit.
+ expect(limitAt(view, "h3", "ref2v", "768p", "16:9")).toBeNull();
+ expect(limitAt(view, "wan", "t2v", "480p", "16:9")).toBeNull();
+ expect(limitAt(view, "other", "t2v", "720p", "16:9")).toBeNull();
+ expect(limitAt(undefined, "h3", "t2v", "768p", "16:9")).toBeNull();
+ });
+ it("lengths past the limit aren't offered", () => {
+ expect(lengthsUnder([3, 5, 10, 15], 5.2)).toEqual([3, 5]);
+ expect(lengthsUnder([3, 5], null)).toEqual([3, 5]);
+ expect(lengthsUnder([3, 5], 0)).toEqual([]);
+ });
+ const wan: OfferFacts = { lengths: [5, 8, 10], resolutions: ["480p", "720p", "1080p"], limit: (r) => (r === "1080p" ? 0 : r === "720p" ? 5 : null) };
+ it("a size is offered when some offered length is made at it", () => {
+ expect(resolutionOffered(wan, "480p", 10)).toBe(true);
+ expect(resolutionOffered(wan, "720p", 10)).toBe(true);
+ expect(resolutionOffered(wan, "1080p", 5)).toBe(false);
+ expect(resolutionOffered({ ...wan, still: true }, "720p", undefined)).toBe(true);
+ });
+ it("steps down a shorter length first, then a smaller size", () => {
+ expect(stepDown(wan, { duration: 10, resolution: "720p" })).toEqual({ duration: 5 });
+ expect(stepDown(wan, { duration: 5, resolution: "720p" })).toBeNull();
+ expect(stepDown(wan, { duration: 10, resolution: "1080p" })).toEqual({ duration: 5, resolution: "720p" });
+ expect(stepDown(wan, { duration: 10, resolution: "480p" })).toBeNull();
+ // Nothing smaller is made: no step (the server refuses such a run).
+ expect(stepDown({ ...wan, limit: () => 0 }, { duration: 5, resolution: "480p" })).toBeNull();
+ // A picture: a smaller size only.
+ expect(stepDown({ lengths: null, resolutions: ["1K", "2K", "4K"], still: true, limit: (r) => (r === "1K" ? null : 0) }, { resolution: "4K" })).toEqual({ resolution: "1K" });
+ });
+ it("orders sizes largest first", () => {
+ expect(largestFirst(["480p", "1080p", "720p"])).toEqual(["1080p", "720p", "480p"]);
+ expect(largestFirst(["1K", "0.5K", "2K"])).toEqual(["2K", "1K", "0.5K"]);
+ });
+});
diff --git a/tests/pool-account-runs.test.ts b/tests/pool-account-runs.test.ts
index d2cac0d1..b85546f6 100644
--- a/tests/pool-account-runs.test.ts
+++ b/tests/pool-account-runs.test.ts
@@ -46,7 +46,7 @@ const auth = await import("@/server/auth");
const generationsRoute = await import("@/app/api/generations/route");
const { db } = await import("@/server/db");
const { resetRates } = await import("@/server/rate");
-const { setSetting } = await import("@/server/settings");
+const { getSetting, setSetting } = await import("@/server/settings");
const { getGeneration, shownError, toGeneration } = await import("@/server/generations");
const tasks = await import("@/server/computer/tasks");
const pool = await import("@/server/computer/pool");
@@ -113,6 +113,7 @@ beforeEach(() => {
setSetting("demoMode", "off");
// People read the plain sentence only, unless a test says otherwise (Settings → Failed runs).
setSetting("runFailureDetail", "friendly");
+ setSetting("hostedOnlyWhatCanRun", "on");
db().prepare("DELETE FROM relay_workers").run();
db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();
db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();
@@ -834,6 +835,7 @@ describe("an account's run that a worker can't finish", () => {
expect(guest.headers.get("x-middleware-next")).not.toBe("1");
// Friendly only: the same run reads the plain sentence alone.
setSetting("runFailureDetail", "friendly");
+ setSetting("hostedOnlyWhatCanRun", "on");
expect(getGeneration(id)!.errorDetail).toBeUndefined();
expect(await visitorList()).not.toMatch(/InstantHMR|errorDetail/);
});
@@ -1079,3 +1081,132 @@ describe("files for runs on the workers", () => {
}
});
});
+
+describe("what the site can make now", () => {
+ const H3 = "oss-minimax-h3";
+ const MINUTE = 60_000;
+ /** Two workers: a large one with no limit of its own, and a small one that makes frames over 0.5 MP up to 5.2 s. */
+ async function twoWorkers() {
+ const big = standInWorker("big");
+ const small = standInWorker("small");
+ const lanes = allLanes(loadIndex(), sha).map((l) => l.lane);
+ db()
+ .prepare("UPDATE relay_workers SET allow_json = ? WHERE id = ?")
+ .run(JSON.stringify(Object.fromEntries(lanes.map((l) => [l, { delayMs: 0, bigFrom: 0.5, bigMaxSeconds: 5.2 }]))), small.id);
+ const capacity = await import("@/server/capacity");
+ const lib = await import("@/lib/capacity");
+ const view = () => {
+ capacity.forgetCapacity();
+ return capacity.capacityView();
+ };
+ const limit = () => lib.limitAt(view(), H3, "t2v", "768p", "16:9");
+ /** The large worker paused on the website, its last beat while on `agoMs` ago (the few seconds kept are skipped). */
+ const bigAway = (agoMs: number) => {
+ db().prepare("UPDATE relay_workers SET paused_server = 1, available_at = ? WHERE id = ?").run(Date.now() - agoMs, big.id);
+ capacity.forgetCapacity();
+ };
+ const bigBack = () => {
+ db().prepare("UPDATE relay_workers SET paused_server = 0, seen_at = ? WHERE id = ?").run(Date.now(), big.id);
+ capacity.forgetCapacity();
+ };
+ return { big, small, view, limit, bigAway, bigBack, capacity };
+ }
+ const h3Run = (duration: number) => run({ feature: "video", modelId: H3, op: "t2v", prompt: "a lighthouse at dusk", params: { duration, resolution: "768p", aspectRatio: "16:9" } });
+ const askedOf = (id: string) => (JSON.parse((db().prepare("SELECT request_json FROM generations WHERE id = ?").get(id) as { request_json: string }).request_json) as { params?: { duration?: number; resolution?: string } }).params;
+
+ it("keeps what a worker makes through a short drop, takes it away after 5 minutes gone, and gives it back as soon as the worker is on", async () => {
+ const { limit, bigAway, bigBack, view } = await twoWorkers();
+ // Both on: the large one makes any length.
+ expect(view().m[H3]).toBeUndefined();
+ expect(limit()).toBeNull();
+ // Gone 2 minutes (a restart, a power cut): nothing changes.
+ bigAway(2 * MINUTE);
+ expect(limit()).toBeNull();
+ // Gone 6 minutes: only what the small one makes.
+ bigAway(6 * MINUTE);
+ expect(limit()).toBe(5.2);
+ expect(view().m[H3]?.t2v).toBeDefined();
+ // Back: at once.
+ bigBack();
+ expect(limit()).toBeNull();
+ });
+
+ it("a beat while on marks the worker; a beat while paused on its PC doesn't", async () => {
+ const { big } = await twoWorkers();
+ const at = () => (db().prepare("SELECT available_at FROM relay_workers WHERE id = ?").get(big.id) as { available_at: number | null }).available_at;
+ const beat = (paused: boolean, now: number) =>
+ pool.workerBeat(
+ db().prepare("SELECT * FROM relay_workers WHERE id = ?").get(big.id) as never,
+ pool.cleanBeat({ device: `wkr-${big.id}`, protocol: 3, version: "1", local: { paused, why: paused ? "here" : null, until: null }, gpu: {}, running: [], stopped: [], catalogVersion: catalogVersion() }),
+ now,
+ );
+ const t0 = Date.now();
+ beat(false, t0);
+ expect(at()).toBe(t0);
+ beat(true, t0 + 5_000);
+ expect(at()).toBe(t0);
+ });
+
+ it("a new run steps down to the nearest length made now (shorter first); one already in line is never changed", async () => {
+ const { bigAway, bigBack } = await twoWorkers();
+ // In line while the large worker is on: 10 s as asked.
+ const before = await h3Run(10);
+ expect(before.status, JSON.stringify(before.body)).toBe(201);
+ const queuedId = before.body.items![0].id;
+ expect(askedOf(queuedId)?.duration).toBe(10);
+ // The large worker gone for 6 minutes: a new 10 s or 15 s run is made at 5 s, a 3 s one as asked.
+ bigAway(6 * MINUTE);
+ for (const [asked, made] of [
+ [10, 5],
+ [15, 5],
+ [3, 3],
+ ] as const) {
+ const r = await h3Run(asked);
+ expect(r.status, JSON.stringify(r.body)).toBe(201);
+ expect(askedOf(r.body.items![0].id)).toMatchObject({ duration: made, resolution: "768p" });
+ // (Stopped once checked: an account has a few runs going at most.)
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE id = ?").run(r.body.items![0].id);
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE generation_id = ?").run(r.body.items![0].id);
+ }
+ // The run already in line keeps its length and its place.
+ await tick();
+ expect(askedOf(queuedId)?.duration).toBe(10);
+ expect(getGeneration(queuedId)?.status).toBe("queued");
+ expect(taskOf(queuedId)?.state).toBe("waiting");
+ bigBack();
+ const after = await h3Run(10);
+ expect(after.status, JSON.stringify(after.body)).toBe(201);
+ expect(askedOf(after.body.items![0].id)?.duration).toBe(10);
+ });
+
+ it("a size no worker on now makes is refused in the plain words for a size not offered", async () => {
+ const { small, bigAway, view } = await twoWorkers();
+ db().prepare("UPDATE relay_workers SET ceiling_json = ? WHERE id = ?").run(JSON.stringify({ maxMegapixels: 0.3 }), small.id);
+ bigAway(6 * MINUTE);
+ expect(view().m[H3]?.t2v?.["768p"]).toBe(0);
+ const { POOL_TOO_BIG } = await import("@/server/providers/comfyui");
+ const r = await h3Run(5);
+ expect(r.status).toBe(400);
+ expect(r.body.error).toBe(POOL_TOO_BIG);
+ expect(r.body.error).not.toMatch(/GPU|worker/i);
+ });
+
+ it("Settings → Workers' switch: on, only what is made now; off, every length and size as the models offer them", async () => {
+ const { limit, bigAway, view } = await twoWorkers();
+ const settingsRoute = await import("@/app/api/settings/route");
+ const put = (v: string) => settingsRoute.PUT(new Request(`http://${HOST}/api/settings`, { method: "PUT", body: JSON.stringify({ hostedOnlyWhatCanRun: v }) }));
+ bigAway(6 * MINUTE);
+ expect((await put("off")).status).toBe(200);
+ expect(getSetting("hostedOnlyWhatCanRun")).toBe("off");
+ expect(view()).toEqual({ m: {} });
+ expect(limit()).toBeNull();
+ const off = await h3Run(10);
+ expect(off.status, JSON.stringify(off.body)).toBe(201);
+ expect(askedOf(off.body.items![0].id)?.duration).toBe(10);
+ expect((await put("on")).status).toBe(200);
+ expect(limit()).toBe(5.2);
+ const on = await h3Run(10);
+ expect(askedOf(on.body.items![0].id)?.duration).toBe(5);
+ expect((await put("maybe")).status).toBe(400);
+ });
+});