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.

Assist and owner runs: plan only steps the GPUs here can run

Adarsh4ca66ef9878a
diff --git a/src/server/assist/tools.ts b/src/server/assist/tools.ts
index abc9a9b7..fce5fd1e 100644
--- a/src/server/assist/tools.ts
+++ b/src/server/assist/tools.ts
@@ -23,6 +23,7 @@ import { createGenerations, currentRequest, getGeneration, listGenerations, outp
import { provider } from "../providers";
import { llmBackends, llmLabel } from "../providers/llm";
import { engineMode } from "../settings";
+import { NotOnGpusError, ownerGpusRun, sameJobModels } from "../runs-here";
import { readRef } from "../storage";
import { katanaTool } from "../katana";
import { createStoryboard, estimateStoryboard } from "../storyboard";
@@ -89,6 +90,8 @@ function summarize(m: ModelDef) {
? `$${p.usd} per ${p.unit}${p.note ? ` — ${p.note}` : ""}${p.lorasUnknown ? "; with LoRAs the price is unknown (not published yet)" : ""}${p.withLorasPerMegapixel ? `; with LoRAs $${p.withLorasPerMegapixel} per megapixel` : ""}`
: "unknown",
connected: configured,
+ // A ComfyUI model the GPUs here can't run yet (no worker has its files, or none is allowed it): plan another one.
+ ...(!ownerGpusRun(m) && { notOnYourGpus: "Your GPUs can't run it yet: pick another model" }),
...(o.aspectRatios && { aspectRatios: o.aspectRatios }),
...(o.resolutions && { resolutions: o.resolutions }),
...(o.durations && { durations: o.durations }),
@@ -135,8 +138,9 @@ const searchModels = defineTool({
});
if (scored.some((x) => x.s)) list = scored.filter((x) => x.s).sort((a, b) => b.s - a.s).map((x) => x.m);
}
- // The engine the user picked first, then the rest.
- list = [...list].sort((a, b) => Number(runsOn(b, ctx.engine)) - Number(runsOn(a, ctx.engine)));
+ // The engine the user picked first, then the rest; on each, the models the GPUs here can't run yet last.
+ const rank = (m: ModelDef) => (runsOn(m, ctx.engine) ? 0 : 2) + (ownerGpusRun(m) ? 0 : 1);
+ list = [...list].sort((a, b) => rank(a) - rank(b));
const shown = list.slice(0, 20);
return {
content: JSON.stringify({ engineMode: mode, preferredEngine: ctx.engine, total: list.length, models: shown.map(summarize) }),
@@ -455,37 +459,63 @@ interface ChainedJob {
after?: number;
preview?: ReturnType<typeof previewChained>;
error?: string;
+ /** The model it named can't run on the GPUs here: why (the job then runs on another model, or not at all). */
+ notOnGpus?: NotOnGpusError;
+ /** It runs on another model than the one it named, and why ("LTX-2.5 isn't on your GPUs yet, so …"). */
+ instead?: string;
+}
+
+/** How many other models a job that can't run here is planned on before it is said so. */
+const MAX_TRIES = 30;
+
+/**
+ * A job whose model the GPUs here can't run (runs-here.ts: no worker has its files, or none is allowed it) runs on the
+ * best model that does the same job and can run now, as it would be planned and priced: a model on the GPUs here first,
+ * then a cloud model with a key (never a demo). Its prompt and settings stay; a clip asked for in shots keeps them where
+ * a model makes shots. None: the job stays as it was, with the plain reason as its error, before anything runs.
+ */
+function runnableInstead(first: ChainedJob, plan: (job: JobInput) => ChainedJob): ChainedJob {
+ const miss = first.notOnGpus!;
+ const named = getModel(miss.modelId);
+ if (!named) return first;
+ const shots = (first.job.shots ?? 0) > 1;
+ for (const c of sameJobModels(named, miss.op, { multiShot: shots }).slice(0, MAX_TRIES)) {
+ const t = plan({ ...first.job, model_id: c.id, op: miss.op, engine: dualEngine(getModel(c.id)) ? c.engine : undefined });
+ if (!t.preview || t.preview.demo) continue;
+ const oneShot = shots && !t.preview.model.options.multiShot ? ` It makes the clip as one shot.` : "";
+ return { ...t, instead: `${named.name} isn't on your GPUs yet, so this step runs on ${t.preview.model.name}.${oneShot}` };
+ }
+ return first;
}
/** Validate and price the jobs of one generate call, wiring `after` into chain slots. Never throws. */
function chainJobs(jobs: JobInput[], engine?: "cloud" | "open"): ChainedJob[] {
const out: ChainedJob[] = [];
- jobs.forEach((job, i) => {
- const req = toRequest(job, engine);
- const after = job.after;
- if (after === undefined) {
+ jobs.forEach((asked, i) => {
+ const after = asked.after;
+ const dep = after === undefined ? undefined : out[after];
+ if (after !== undefined) {
+ const req = toRequest(asked, engine);
+ if (!Number.isInteger(after) || after < 0 || after >= i || !dep) {
+ out.push({ job: asked, req, after, error: `"after" must point at an earlier job in this call (0–${i - 1})` });
+ return;
+ }
+ if (!dep.preview) {
+ out.push({ job: asked, req, after, error: `Job ${after} can't run, so this one can't either` });
+ return;
+ }
+ }
+ const plan = (job: JobInput): ChainedJob => {
+ const own = toRequest(job, engine);
+ const req: GenerationRequest = dep?.preview ? { ...own, chain: [slotFor(outputKind(dep.preview.op, dep.preview.model), own.op)] } : own;
try {
- out.push({ job, req, preview: previewChained(req, 0) });
+ return { job, req, ...(after !== undefined && { after }), preview: previewChained(req, dep ? 1 : 0) };
} catch (e) {
- out.push({ job, req, error: (e as Error).message });
+ return { job, req, ...(after !== undefined && { after }), error: (e as Error).message, ...(e instanceof NotOnGpusError && { notOnGpus: e }) };
}
- return;
- }
- const dep = out[after];
- if (!Number.isInteger(after) || after < 0 || after >= i || !dep) {
- out.push({ job, req, after, error: `"after" must point at an earlier job in this call (0–${i - 1})` });
- return;
- }
- if (!dep.preview) {
- out.push({ job, req, after, error: `Job ${after} can't run, so this one can't either` });
- return;
- }
- const chained: GenerationRequest = { ...req, chain: [slotFor(outputKind(dep.preview.op, dep.preview.model), req.op)] };
- try {
- out.push({ job, req: chained, after, preview: previewChained(chained, 1) });
- } catch (e) {
- out.push({ job, req: chained, after, error: (e as Error).message });
- }
+ };
+ const first = plan(asked);
+ out.push(first.notOnGpus ? runnableInstead(first, plan) : first);
});
return out;
}
@@ -493,8 +523,10 @@ function chainJobs(jobs: JobInput[], engine?: "cloud" | "open"): ChainedJob[] {
function plannedJob(c: ChainedJob): PlannedJob {
if (c.preview) {
const p = c.preview;
- // A value the model's route makes differently (2K on a model that makes up to 1080p) is said on the card before it runs.
- const changes = fittedSettings(p.model, p.op, { ...p.model.defaults, ...c.req.params }, { provider: p.route.provider, negativePrompt: c.req.negativePrompt }).changes.map((x) => x.note);
+ // A value the model's route makes differently (2K on a model that makes up to 1080p) is said on the card before it runs,
+ // and so is a model the job moved to because the GPUs here can't run the one it named.
+ const fitted = fittedSettings(p.model, p.op, { ...p.model.defaults, ...c.req.params }, { provider: p.route.provider, negativePrompt: c.req.negativePrompt }).changes.map((x) => x.note);
+ const changes = c.instead ? [c.instead, ...fitted] : fitted;
return { tool: "generate", modelId: p.model.id, modelName: p.model.name, kind: outputKind(p.op, p.model), op: p.op, prompt: c.job.prompt, count: p.outputs, costUsd: p.costUsd, demo: p.demo, ...(changes.length && { changes }) };
}
const m = getModel(c.job.model_id);
@@ -545,13 +577,18 @@ const generate = defineTool({
const ids: string[] = [];
const results: unknown[] = [];
const batch = list.length > 1 ? { batchId: nanoid(10) } : {};
- for (const j of list) {
+ // Each job as it was planned and priced on the card (on the model it moved to, when the GPUs here can't run its own).
+ for (const c of chainJobs(list, engineOf(ctx))) {
+ if (!c.preview) {
+ results.push({ model: c.job.model_id, error: c.error });
+ continue;
+ }
try {
- const gens = createGenerations({ ...toRequest(j, engineOf(ctx)), batchTitle }, batch);
+ const gens = createGenerations({ ...c.req, batchTitle }, batch);
ids.push(...gens.map((g) => g.id));
- results.push({ model: j.model_id, started: gens.map((g) => g.id), demo: gens.some((g) => g.provider === "mock") || undefined, costUsd: gens.reduce((s, g) => s + (g.costUsd ?? 0), 0) || undefined });
+ results.push({ model: c.job.model_id, started: gens.map((g) => g.id), demo: gens.some((g) => g.provider === "mock") || undefined, costUsd: gens.reduce((s, g) => s + (g.costUsd ?? 0), 0) || undefined });
} catch (e) {
- results.push({ model: j.model_id, error: (e as Error).message });
+ results.push({ model: c.job.model_id, error: (e as Error).message });
}
}
const failed = results.length && ids.length === 0;
diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.ts
index 02566ed0..570beda4 100644
--- a/src/server/computer/pool.ts
+++ b/src/server/computer/pool.ts
@@ -1016,6 +1016,14 @@ export function workersCanRun(workflowId: string | null, o: { size?: Needs["size
return ableWorkers(workflowId, o).length > 0;
}
+/**
+ * Does a worker hold everything this workflow needs (its files and node packs, as its last list of files said), whether
+ * or not it is allowed the workflow's lane? Tells a model whose files no GPU here has from one whose lane is switched off.
+ */
+export function workersHold(workflowId: string): boolean {
+ return poolWorkers().some((w) => w.pool === "pool" && capableOf(w).workflows.includes(workflowId));
+}
+
/**
* The largest job of a workflow any worker that may and can run it makes (its PC's ceiling), each limit apart: undefined
* where one of them has no limit, and for a workflow none of them runs. Said before Run with a size they don't make.
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 0079e39a..39758272 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -151,6 +151,7 @@ import { heldLine, placeInLine, poolOnWorkers, poolRunsProvider, poolWaitMs, req
import { hostedRunsOn } from "./hosted-switch";
import { catalogVersion } from "./computer/catalog-version";
import { gettingReady, poolLane, queueOfGeneration, type LinePlace } from "./computer/pool";
+import { ownerGpuMiss } from "./runs-here";
import { noteCatalogProcess, processStart } from "./computer/ticket-refresh";
import { hasJobFor, runPreviewAt, stopJobsOf } from "./computer/tasks";
import { runCeilingMs } from "./queue-settings";
@@ -1253,6 +1254,10 @@ function prepare(original: GenerationRequest) {
// A preset can route to another model than the one asked for: its routes that are on (or the switch that's off).
const prefer = isCloudProvider(worded.prefer) ? worded.prefer : undefined;
const { route, demo } = chooseRoute(triedRoutes(plan.model, offeredRoutes(plan.model, routesFor(plan.model, plan.op, plan.params))), req.inputs?.images?.length ?? 0, plan.loras, seconds, !!worded.demo, prefer);
+ // The owner's run on their own GPUs (the workers): one that none of them can take is refused when it is planned and
+ // priced (runs-here.ts), as a visitor's is, never after an earlier step of its chain ran.
+ const notOnGpus = demo ? null : ownerGpuMiss(route, plan.model, plan.op);
+ if (notOnGpus) throw notOnGpus;
// Qwen-Image 2.1's Options → Speed loads its speed's LoRA in the graph: that LoRA switched off holds the speed.
const tier = route.provider === "comfyui" ? speedLora(route.endpoint, plan.params.extra) : undefined;
if (tier && offeredLoras([{ file: tier.file }]).dropped.length) {
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index 349a3885..c7ba2d4b 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -93,7 +93,8 @@ import {
type Principal,
type TaskRow,
} from "../computer/tasks";
-import { attemptDeadline, poolFacts, poolFields, poolLane, poolWaitMs, poolWaitWords, runPlaceOf, workersCanRun } from "../computer/pool";
+import { attemptDeadline, poolFacts, poolFields, poolLane, poolWaitMs, poolWaitWords, runPlaceOf, workersCanRun, workersHold } from "../computer/pool";
+import { notOnGpusText } from "../runs-here";
import { catalogVersion } from "../computer/catalog-version";
import { ticketProblem, type JobTicket } from "@/lib/job-ticket";
import { catalogKnows, ticketFor } from "@/lib/ticket-compose";
@@ -2006,8 +2007,11 @@ export const comfyProvider: ProviderAdapter = {
const metaBatch = !!meta.metaBatch;
const forPool = onWorkers(computer);
// The owner's job that no worker is allowed and able to run would wait with no end (the owner's jobs have no wait
- // limit unless the owner sets one): it is refused now, as an account's run is.
- if (forPool && computer === "owner" && !workersCanRun(manifest.id)) throw new ProviderError(NO_WORKER_FOR_LANE);
+ // limit unless the owner sets one): it is refused now, as an account's run is. Its true cause in plain words: no
+ // worker has its files, or one has them but isn't allowed its lane.
+ if (forPool && computer === "owner" && !workersCanRun(manifest.id)) {
+ throw new ProviderError(workersHold(manifest.id) ? NO_WORKER_FOR_LANE : notOnGpusText(model?.name ?? "this model", "files"));
+ }
// A job larger than every PC that could run it may ever make (its ceiling) would never be taken: refused now, the
// owner's and an account's alike, before it waits in line.
if (forPool && workersCanRun(manifest.id) && !workersCanRun(manifest.id, { size: prepared.size })) throw new ProviderError(computer === "owner" ? NO_WORKER_FOR_SIZE : POOL_TOO_BIG);
diff --git a/src/server/runs-here.ts b/src/server/runs-here.ts
new file mode 100644
index 00000000..08ac49f1
--- /dev/null
+++ b/src/server/runs-here.ts
@@ -0,0 +1,97 @@
+import "server-only";
+import { MODELS } from "@/lib/catalog";
+import { dualEngine } from "@/lib/catalog/engines";
+import type { Engine, ModelDef, Operation } from "@/lib/catalog/types";
+import { AUDIO_STUDIO, EDIT_STUDIO, IMAGE_STUDIO, MUSIC_STUDIO, VIDEO_STUDIO } from "@/lib/studios";
+import { workersHold } from "./computer/pool";
+import { poolOnWorkers, poolTakes, workflowPicks } from "./hosted";
+import { isOffered } from "./model-access";
+import { ownGpu } from "./providers/comfyui";
+import { tenant } from "./tenant";
+
+/**
+ * The owner's runs on their own GPUs (Settings: ComfyUI runs on "workers") meet the same check before Run as a visitor's
+ * run on them (hosted-run.ts poolGate): a worker is allowed the workflow's lane and holds its files (poolTakes). A run
+ * nothing here can take is refused when it is planned and priced, in plain words, so a chain never runs its first step
+ * and then stops at a later one.
+ */
+export class NotOnGpusError extends Error {
+ constructor(
+ readonly modelId: string,
+ readonly modelName: string,
+ readonly op: Operation,
+ /** "files": no GPU here has the model's files; "lane": one has them, but isn't allowed its lane. */
+ readonly why: "files" | "lane",
+ ) {
+ super(notOnGpusText(modelName, why));
+ this.name = "NotOnGpusError";
+ }
+}
+
+/** What the owner reads when their GPUs can't run a model: the true cause, in plain words. */
+export function notOnGpusText(name: string, why: "files" | "lane"): string {
+ return why === "files"
+ ? `Your GPUs don't have ${name}'s files yet. Add them to a worker's ComfyUI, or pick another model.`
+ : `Your GPUs have ${name}'s files, but none of them is allowed to run it. Allow its lane in Settings → Open-source engine · ComfyUI → Workers, or pick another model.`;
+}
+
+/** Whether no worker holds a workflow's files (for one that picks its graph at run time, any graph it may pick). */
+export function filesMissing(endpoint: string): boolean {
+ const picks = endpoint.includes("{") ? workflowPicks(endpoint) : [endpoint];
+ return !picks.length || !picks.every((id) => workersHold(id));
+}
+
+/**
+ * The owner's run of this ComfyUI workflow, when their GPUs can't take it: why, as an error to throw. Null when they
+ * can, when the run is an account's or a visitor's (hosted-run.ts checks those), and when the owner's ComfyUI is not on
+ * the workers (their own computer or server says what it lacks itself).
+ */
+export function ownerGpuMiss(route: { provider: string; endpoint: string }, model: Pick<ModelDef, "id" | "name">, op: Operation): NotOnGpusError | null {
+ if (route.provider !== "comfyui" || tenant() || ownGpu() || !poolOnWorkers()) return null;
+ if (poolTakes(route.endpoint)) return null;
+ return new NotOnGpusError(model.id, model.name, op, filesMissing(route.endpoint) ? "files" : "lane");
+}
+
+/**
+ * Whether the owner's GPUs run a model now: a model with no ComfyUI route, or one of its ComfyUI workflows they take
+ * (ownerGpuMiss). Assist lists the models they don't run last, saying why.
+ */
+export function ownerGpusRun(m: ModelDef): boolean {
+ const comfy = m.routes.filter((r) => r.provider === "comfyui");
+ return !comfy.length || comfy.some((r) => !ownerGpuMiss(r, m, r.op));
+}
+
+/** The studios' default models: a step that can't run moves to one of these first. */
+const DEFAULTS = new Set([IMAGE_STUDIO, EDIT_STUDIO, VIDEO_STUDIO, AUDIO_STUDIO, MUSIC_STUDIO].flatMap((s) => [s.defaultModels?.open, s.defaultModels?.cloud]).filter(Boolean) as string[]);
+
+const rank = (m: ModelDef, op: Operation): number => {
+ if (DEFAULTS.has(m.id)) return 0;
+ // A model ranked by its badges only for some operations isn't ranked for the others (src/lib/composer.ts bestForStudio).
+ if (m.bestOps && !m.bestOps.includes(op)) return 9;
+ // A Fuobe Original keeps its own recipe and words: last of its engine, never first.
+ if (dualEngine(m)) return 8;
+ return m.badges?.includes("top") ? 1 : m.badges?.includes("new") ? 2 : 5;
+};
+
+/**
+ * Other models that do the same job as `model` (its kind and this operation), best first: on its own engine first (the
+ * studios' defaults, then top picks, then what's new, then the rest), then on the other engine. Only models Settings
+ * offers, never hidden ones, and none that runs without a prompt when it takes one. `multiShot`: those that cut a clip
+ * into shots first. The caller plans each one as it would run (its route, a key, the GPUs here) and keeps the first
+ * that runs.
+ */
+export function sameJobModels(model: ModelDef, op: Operation, o: { multiShot?: boolean } = {}): { id: string; engine: Engine }[] {
+ const out: { id: string; engine: Engine; score: number; i: number }[] = [];
+ MODELS.forEach((m, i) => {
+ if (m.id === model.id || m.hidden || m.kind !== model.kind || (m.options.promptless && !model.options.promptless)) return;
+ if (!m.routes.some((r) => r.op === op)) return;
+ const engines: Engine[] = m.engines?.length ? m.engines : [m.engine];
+ for (const engine of engines) {
+ if (!isOffered(m.id, engine)) continue;
+ const other = engine !== model.engine ? 100 : 0;
+ const shots = o.multiShot && !m.options.multiShot ? 10 : 0;
+ out.push({ id: m.id, engine, score: other + shots + rank(m, op), i });
+ }
+ });
+ return out.sort((a, b) => a.score - b.score || a.i - b.i).map(({ id, engine }) => ({ id, engine }));
+}
diff --git a/tests/assist-runnable.test.ts b/tests/assist-runnable.test.ts
new file mode 100644
index 00000000..c051dc9c
--- /dev/null
+++ b/tests/assist-runnable.test.ts
@@ -0,0 +1,218 @@
+import crypto from "node:crypto";
+import { beforeAll, describe, expect, it, vi } from "vitest";
+import { tempDir } from "./helpers/temp-dir";
+import RUNNABLE from "./fixtures/gpu-runnable-workflows.json";
+
+/**
+ * Assist never plans a free step the GPUs here can't run. The pool is one worker built from a real GPU's files (the
+ * workflows it ran, as lanesFor reads them back from its files and packs): no LTX-2.5 files on it. Every starter, chip
+ * and skill on the offline planner, and every open model and operation the generate tool plans, is checked: a step
+ * planned on the GPUs here (free) is one a worker can take, a step whose model can't run moves to the best one that can
+ * (said on the card), and the owner's run of a model nothing here runs is refused before anything starts, in plain words.
+ */
+
+vi.setConfig({ testTimeout: 120_000 });
+const dir = tempDir("fuobe-assist-runnable-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+delete process.env.FUOBE_HOSTED_RUNS;
+
+const { setSetting } = await import("@/server/settings");
+const agent = await import("@/server/assist/agent");
+const tools = await import("@/server/assist/tools");
+const { db } = await import("@/server/db");
+const pool = await import("@/server/computer/pool");
+const { catalogVersion } = await import("@/server/computer/catalog-version");
+const { loadIndex } = await import("@/server/gpu/index-file");
+const { allLanes, lanesFor, needsOf } = await import("@/lib/lanes");
+const { poolTakes } = await import("@/server/hosted");
+const { createGenerations } = await import("@/server/generations");
+const { createPipeline } = await import("@/server/chains");
+const { listSkills } = await import("@/server/skills");
+const { ASSIST_STARTERS } = await import("@/lib/starters/assist");
+const { ASSIST_SUGGESTIONS } = await import("@/lib/assist");
+const { MODELS, getModel } = await import("@/lib/catalog");
+const { notOnGpusText } = await import("@/server/runs-here");
+
+const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
+
+/** The workflows the worker runs: lanesFor over the files and node packs of the workflows the real GPU ran. */
+let runnable: string[] = [];
+
+beforeAll(() => {
+ setSetting("demoMode", "auto");
+ setSetting("engineMode", "both");
+ setSetting("comfyWhere", "workers");
+ const index = loadIndex();
+ const known = (RUNNABLE as string[]).filter((id) => index.workflows[id]);
+ const files = new Map<string, { folder: string; name: string; size: number; sha256: string | null }>();
+ const packs = new Set<string>();
+ for (const id of known) {
+ const n = needsOf(index, id)!;
+ for (const f of n.files) files.set(`${f.folder}/${f.name}`, f);
+ for (const p of n.packs) packs.add(p);
+ }
+ const can = lanesFor(index, { files: [...files.values()], nodePacks: [...packs].map((name) => ({ name, commit: null })), media: ["image", "video", "audio"] }, sha);
+ runnable = can.workflows;
+ // One worker, allowed every lane (as the owner's is), holding exactly those workflows.
+ const w = pool.addWorker("studio-gpu");
+ pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: Object.fromEntries(allLanes(index, sha).map((l) => [l.lane, { delayMs: 0 }])), claimAfterMs: 0 });
+ db()
+ .prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ?, catalog_version = ?, protocol = 3, seen_at = ?, paused_local = 0 WHERE id = ?")
+ .run(JSON.stringify({ lanes: can.lanes, workflows: can.workflows }), JSON.stringify({ vramBytes: 32 * 2 ** 30 }), catalogVersion(), Date.now(), w.id);
+});
+
+type Planned = ReturnType<typeof tools.planFor>["jobs"][number];
+
+/** A step the card calls free: it runs on the GPUs here at no cost. */
+const free = (j: Planned) => !j.error && !j.demo && j.costUsd === 0 && getModel(j.modelId)?.routes.some((r) => r.provider === "comfyui" && r.op === j.op);
+
+/** The worker takes the step's workflow (as the run's own check reads it). */
+const takes = (j: Planned) => {
+ const m = getModel(j.modelId)!;
+ return m.routes.some((r) => r.provider === "comfyui" && r.op === j.op && poolTakes(r.endpoint));
+};
+
+const offline = (text: string, engine: "open" | "cloud", hint?: Parameters<typeof agent.offlinePlan>[2]) => {
+ const p = agent.offlinePlan(text, engine, hint);
+ return p && "input" in p ? { p, plan: tools.planFor(p.tool, p.input, { engine }) } : null;
+};
+
+describe("the fake pool", () => {
+ it("is the real GPU's: Ideogram 4, MiniMax H3 and Wan 2.2 run, LTX-2.5 doesn't", () => {
+ expect(runnable).toEqual(expect.arrayContaining(["ideogram4-t2i", "minimax-h3-i2v", "wan22-i2v-14b-lightx2v"]));
+ expect(runnable).not.toContain("ltx25-i2v");
+ expect(poolTakes("ltx25-i2v")).toBe(false);
+ expect(poolTakes("wan22-i2v-14b")).toBe(true);
+ });
+});
+
+describe("Assist plans only free steps that can run", () => {
+ it("the gold watch ad: the still, then a clip on a model the GPUs run, in shots, said on the card", () => {
+ const r = offline(ASSIST_SUGGESTIONS[0], "open")!;
+ expect(r.plan.jobs.map((j) => [j.kind, j.op])).toEqual([
+ ["image", "t2i"],
+ ["video", "i2v"],
+ ]);
+ const clip = r.plan.jobs[1];
+ expect(clip.error).toBeUndefined();
+ expect(clip.modelId).not.toBe("oss-ltx25");
+ expect(free(clip) && takes(clip)).toBe(true);
+ expect(getModel(clip.modelId)?.options.multiShot).toBeTruthy();
+ expect(clip.changes?.[0]).toMatch(/^LTX-2\.5 isn't on your GPUs yet, so this step runs on /);
+ // The run starts what the card showed: both steps, on the same models, nothing refused.
+ expect(tools.planFor(r.p.tool, r.p.input, { engine: "open" }).jobs.map((j) => j.modelId)).toEqual(r.plan.jobs.map((j) => j.modelId));
+ });
+
+ it.each(["open", "cloud"] as const)("every chip, starter and skill on the offline planner (%s)", (engine) => {
+ const asks: { what: string; text: string; hint?: Parameters<typeof agent.offlinePlan>[2] }[] = [
+ ...ASSIST_SUGGESTIONS.map((text) => ({ what: `chip: ${text}`, text })),
+ ...ASSIST_STARTERS.flatMap(({ id, seed }) => {
+ if (seed.kind !== "assist") return [];
+ const skill = seed.skill;
+ return [{ what: `starter ${id}`, text: seed.prompt, hint: skill ? listSkills().find((k) => k.name === skill)?.offline : undefined }];
+ }),
+ ...listSkills().map((s) => ({ what: `skill ${s.name}`, text: "A model in a red silk gown on a Lake Como terrace at golden hour", hint: s.offline })),
+ ...listSkills().map((s) => ({ what: `skill ${s.name}, animated`, text: "A hero still of a gold watch on a model's wrist, then animate it", hint: s.offline })),
+ ];
+ for (const a of asks) {
+ const r = offline(a.text, engine, a.hint);
+ if (!r) continue;
+ for (const j of r.plan.jobs) {
+ // No step names a model nothing here runs: it moved to one that does.
+ expect(j.error ?? "", a.what).not.toMatch(/isn't on your GPUs|don't have .*files/);
+ if (free(j)) expect(takes(j), `${a.what}: ${j.modelName} (${j.op})`).toBe(true);
+ }
+ }
+ });
+
+ it("every open model and operation the generate tool plans: free only where a worker takes it", () => {
+ const img = "/api/files/x/still.png";
+ const vid = "/api/files/x/clip.mp4";
+ const snd = "/api/files/x/voice.wav";
+ let freeSteps = 0;
+ for (const m of MODELS) {
+ if (m.hidden) continue;
+ for (const r of m.routes) {
+ if (r.provider !== "comfyui") continue;
+ const job = { model_id: m.id, op: r.op, prompt: "A model in a black velvet suit on a palace staircase", images: [img], video: vid, audio: snd, ...(m.engines?.length ? { engine: "open" as const } : {}) };
+ const plan = tools.planFor("generate", { summary: "check", jobs: [job] }, { engine: "open" });
+ for (const j of plan.jobs) {
+ if (!free(j)) continue;
+ freeSteps++;
+ expect(takes(j), `${m.id} ${r.op} → ${j.modelId}`).toBe(true);
+ }
+ }
+ }
+ expect(freeSteps).toBeGreaterThan(20);
+ });
+
+ it("search_models lists what the GPUs can't run last, saying so", async () => {
+ const out = await tools.getTool("search_models")!.run({ kind: "video", task: "i2v" }, { engine: "open" } as never);
+ const models = JSON.parse(String(out.content)).models as { id: string; notOnYourGpus?: string }[];
+ const ltx = models.findIndex((m) => m.id === "oss-ltx25");
+ expect(ltx).toBeGreaterThan(-1);
+ expect(models[ltx].notOnYourGpus).toBeTruthy();
+ expect(models.findIndex((m) => m.id === "oss-wan22-14b")).toBeLessThan(ltx);
+ expect(models.find((m) => m.id === "oss-wan22-14b")?.notOnYourGpus).toBeUndefined();
+ });
+});
+
+describe("the owner's runs meet the same check before anything starts", () => {
+ const still = { feature: "image", modelId: "oss-ideogram-4", prompt: "A gold watch on a model's wrist" };
+ const clip = { feature: "video", modelId: "oss-ltx25", op: "i2v", prompt: "The still comes to life" } as const;
+ const rows = () => (db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n;
+
+ it("a run of a model whose files no GPU has is refused in plain words", () => {
+ const before = rows();
+ expect(() => createGenerations({ ...clip, inputs: { images: ["/api/files/x/still.png"] } } as never)).toThrow("Your GPUs don't have LTX-2.5's files yet.");
+ expect(rows()).toBe(before);
+ });
+
+ it("a chain whose second step can't run starts nothing", () => {
+ const before = rows();
+ expect(() =>
+ createPipeline([
+ { key: "still", request: still as never },
+ { key: "clip", request: clip as never, after: "still" },
+ ]),
+ ).toThrow(/LTX-2\.5's files/);
+ expect(rows()).toBe(before);
+ });
+
+ const jobs = [
+ { model_id: "oss-ideogram-4", prompt: "A gold watch" },
+ { model_id: "oss-ltx25", op: "i2v", prompt: "It comes to life", after: 0 },
+ ];
+
+ it("an Assist plan that names LTX-2.5 (an AI planner's) moves that step before Run", () => {
+ const plan = tools.planFor("generate", { summary: "x", jobs }, { engine: "open" });
+ expect(plan.jobs[1].error).toBeUndefined();
+ expect(plan.jobs[1].modelId).not.toBe("oss-ltx25");
+ expect(free(plan.jobs[1]) && takes(plan.jobs[1])).toBe(true);
+ });
+
+ it("a step nothing here can take, and no key runs in the cloud, is said before Run and blocks the chain", () => {
+ const w = db().prepare("SELECT id, lanes_json FROM relay_workers").get() as { id: string; lanes_json: string };
+ const keep = JSON.parse(w.lanes_json) as { lanes: string[]; workflows: string[] };
+ // The worker loses every video workflow: no image-to-video model runs on the GPUs here, and no cloud key is set.
+ db()
+ .prepare("UPDATE relay_workers SET lanes_json = ? WHERE id = ?")
+ .run(JSON.stringify({ lanes: keep.lanes, workflows: keep.workflows.filter((id) => !/i2v|video|h3|wan|ltx|hunyuan|kandinsky/.test(id)) }), w.id);
+ try {
+ const plan = tools.planFor("generate", { summary: "x", jobs }, { engine: "open" });
+ expect(plan.jobs[1].error).toBe("Your GPUs don't have LTX-2.5's files yet. Add them to a worker's ComfyUI, or pick another model.");
+ expect(plan.jobs[1].costUsd).not.toBeNull();
+ expect(free(plan.jobs[1])).toBe(false);
+ } finally {
+ db().prepare("UPDATE relay_workers SET lanes_json = ? WHERE id = ?").run(w.lanes_json, w.id);
+ }
+ });
+
+ it("the words for a missing model's files name the cause, not a lane setting", () => {
+ expect(notOnGpusText("LTX-2.5", "files")).toMatch(/^Your GPUs don't have LTX-2\.5's files yet\./);
+ expect(notOnGpusText("LTX-2.5", "files")).not.toMatch(/lane/i);
+ expect(notOnGpusText("LTX-2.5", "lane")).toMatch(/Allow its lane/);
+ });
+});
diff --git a/tests/fixtures/gpu-runnable-workflows.json b/tests/fixtures/gpu-runnable-workflows.json
new file mode 100644
index 00000000..02df81fd
--- /dev/null
+++ b/tests/fixtures/gpu-runnable-workflows.json
@@ -0,0 +1,174 @@
+[
+ "any-angle-3d",
+ "any-angle-shot",
+ "audio-join-crossfade",
+ "audio-loop-crossfade",
+ "audio-timeline",
+ "bg-remove-birefnet",
+ "captions-burnin",
+ "character-describe-qwen3vl",
+ "fibo2-dev-edit",
+ "fibo2-dev-t2i",
+ "fibo2-edit-turbo-edit",
+ "flux1-dev-t2i",
+ "flux1-fill-inpaint",
+ "flux1-fill-outpaint",
+ "flux2-dev-edit",
+ "flux2-dev-multiref",
+ "flux2-dev-t2i",
+ "flux2-dev-t2i-turbo",
+ "flux3-klein-edit",
+ "flux3-klein-t2i",
+ "fps-rtx-framegen",
+ "frame-extract",
+ "grid-zimage-contact-sheet",
+ "head-swap-qwen-image-21",
+ "ideogram4-t2i",
+ "image-face-mosaic-sam3",
+ "image-from-picture-prepare",
+ "image-person-mask-sam3",
+ "image-to-3d-hunyuan3d-21",
+ "image-to-3d-idol",
+ "image-to-3d-pixal3d",
+ "image-to-3d-trellis2",
+ "image-to-mesh-idol",
+ "image-to-splat-idol",
+ "image-to-splat-triposplat",
+ "image-vectorize-vtracer",
+ "image-watermark-remove-qwen21",
+ "image-watermark-remove-qwen21-brush",
+ "image-watermark-scan-qwen3vl",
+ "interpolate-rife",
+ "interpolate-rife-fps",
+ "interpolate-rife-vfi",
+ "kenburns-still",
+ "krea2-edit-general",
+ "krea2-edit-identity",
+ "krea2-realism-t2i",
+ "krea2-turbo-i2i",
+ "krea2-turbo-t2i",
+ "minimax-h3-fast-flf2v",
+ "minimax-h3-fast-i2v",
+ "minimax-h3-fast-t2v",
+ "minimax-h3-flex-ref2va",
+ "minimax-h3-flf2v",
+ "minimax-h3-flf2v-hq",
+ "minimax-h3-i2v",
+ "minimax-h3-i2v-hq",
+ "minimax-h3-orbit",
+ "minimax-h3-t2v",
+ "minimax-h3-t2v-hq",
+ "mixed-media-zimage-frames",
+ "moss-image-t2i",
+ "music-ace-step-15",
+ "ocr-lines-qwen35",
+ "outfit-swap-qwen-image-21",
+ "outfit-swap-qwen-image-21-text",
+ "palette-transfer-image",
+ "palette-transfer-video",
+ "palette-zimage-hex",
+ "product-shot-qwen-edit-2509",
+ "qwen-image-21-edit",
+ "qwen-image-21-edit-details",
+ "qwen-image-21-edit-draft",
+ "qwen-image-21-edit-fast",
+ "qwen-image-21-inpaint",
+ "qwen-image-21-inpaint-draft",
+ "qwen-image-21-inpaint-fast",
+ "qwen-image-21-next-scene",
+ "qwen-image-21-outpaint",
+ "qwen-image-21-outpaint-draft",
+ "qwen-image-21-outpaint-fast",
+ "qwen-image-21-recolor",
+ "qwen-image-21-relight",
+ "qwen-image-21-t2i",
+ "qwen-image-21-t2i-details",
+ "qwen-image-21-t2i-draft",
+ "qwen-image-21-t2i-fast",
+ "qwen-image-21-turbo-edit",
+ "qwen-image-2512-t2i",
+ "qwen-image-2512-t2i-lightning",
+ "qwen-image-edit-2509",
+ "qwen-image-edit-2511",
+ "qwen-image-edit-2511-multi",
+ "relight-qwen-edit-2509",
+ "relight-qwen-edit-2509-reference",
+ "relight-scene-read",
+ "restore-qwen-image-21",
+ "scene-mesh-moge",
+ "sdr-to-hdr-rtx",
+ "selftest-image",
+ "selftest-meta-batch",
+ "selftest-video",
+ "separate-soundtrack-dbs",
+ "sfx-hunyuan-foley",
+ "sfx-mmaudio-t2a",
+ "sfx-stable-audio-3-small",
+ "sfx-stable-audio-open",
+ "soul-cast-sheet-zimage",
+ "soundtrack-remix-dbs",
+ "steam-it-qwen-image-21",
+ "still-to-clip",
+ "storyboard-qwen-edit-2509-next-scene",
+ "style-ref-flux2-klein-4b",
+ "style-ref-qwen-edit-2511",
+ "style-ref-uso-flux1",
+ "upscale-image-esrgan",
+ "upscale-image-seedvr2",
+ "upscale-video-esrgan",
+ "upscale-video-esrgan-chunked",
+ "upscale-video-rtx",
+ "v2a-hunyuan-foley",
+ "v2a-mmaudio",
+ "video-append-endcard",
+ "video-bg-remove-birefnet",
+ "video-bg-remove-sam3",
+ "video-character-swap-h3",
+ "video-composite-mask",
+ "video-concat-2",
+ "video-concat-3",
+ "video-concat-4",
+ "video-concat-encoded",
+ "video-concat-sound1-2",
+ "video-concat-sound1-3",
+ "video-concat-sound1-4",
+ "video-concat-sound2-2",
+ "video-concat-sound2-3",
+ "video-concat-sound2-4",
+ "video-depth-da3",
+ "video-export-exr",
+ "video-export-pro",
+ "video-export-pro-chunked",
+ "video-fit-clip",
+ "video-fix-colours",
+ "video-from-picture-h3",
+ "video-from-picture-solar",
+ "video-group-swap-h3",
+ "video-group-swap-h3-one-by-one",
+ "video-inpaint-wan-vace",
+ "video-inpaint-wan-vace-painted",
+ "video-insert-wan-vace",
+ "video-motion-transfer-h3",
+ "video-mux-audio",
+ "video-mux-audio-replace",
+ "video-person-remove-h3-mask",
+ "video-scene-describe",
+ "video-scene-edit-h3",
+ "video-sdr-to-hdr",
+ "video-sdr-to-hdr-exr",
+ "video-segment-resample",
+ "video-swap-wan-vace",
+ "video-trim",
+ "voice-clean-bed-reuse",
+ "voice-clean-reuse",
+ "wan-animate2",
+ "wan21-vace-14b-ref2v",
+ "wan22-flf2v-14b",
+ "wan22-i2v-14b",
+ "wan22-i2v-14b-lightx2v",
+ "wan22-i2v-14b-lora",
+ "wan22-t2v-14b",
+ "wan22-t2v-14b-lightx2v",
+ "z-image-turbo-i2i",
+ "z-image-turbo-t2i"
+]
diff --git a/tests/pool-runtime-files.test.ts b/tests/pool-runtime-files.test.ts
index cf986a0b..04ea256b 100644
--- a/tests/pool-runtime-files.test.ts
+++ b/tests/pool-runtime-files.test.ts
@@ -123,7 +123,8 @@ const taskOf = (generationId: string) => db().prepare("SELECT * FROM relay_tasks
describe("a run that adds files at run time, on this install's GPUs", () => {
it("knows the look's LoRAs as the run's files beyond its workflow's own", () => {
expect(lookFiles).toEqual(expect.arrayContaining(["AWPortrait-Z.safetensors"]));
- const p = previewGeneration(soulRun);
+ // (Planned as a visitor's run on these GPUs: no worker is here yet, and the owner's own run would be refused for that.)
+ const p = hosted.runOnPool(null, () => previewGeneration(soulRun));
expect(p.route.provider).toBe("comfyui");
const r = runtimeNeeds(lookFiles, loadIndex(), p.route.endpoint);
expect(r.unknown).toEqual([]);