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.

Hosted runs: a chain's last step keeps its run's place, and a press says where every step runs

Adarsh23b7a037d16d
diff --git a/src/lib/pool-rules.ts b/src/lib/pool-rules.ts
index 75457f0f..897efdc2 100644
--- a/src/lib/pool-rules.ts
+++ b/src/lib/pool-rules.ts
@@ -14,6 +14,8 @@ import { ownSetupOnly, type OwnSetup } from "./own-setup";
* - `kinds`: a kind set to false runs on the visitor's own GPU only (absent: every kind).
* - `own`: open models this studio's GPUs can't run right now (none of them holds the model, serves its kind of work,
* or has the card it needs), each with what the visitor needs to run it on its own setup.
+ * - `presets`: presets whose press these GPUs can't run in whole right now (a step of it none of them runs, such as the
+ * start-and-end-frame clip after its end frame), each with what the visitor needs: kept off with that label.
*/
export interface PoolRules {
allow?: string[];
@@ -21,24 +23,31 @@ export interface PoolRules {
apps?: { allow?: string[]; deny?: string[] };
kinds?: Partial<Record<MediaKind, boolean>>;
own?: Record<string, OwnSetup>;
+ presets?: Record<string, OwnSetup>;
}
-/** A preset as the rules see it: its id, and the open model it runs on with the kind it makes (none: no open route). */
+/**
+ * A preset as the rules see it: its id, and the open model it runs on with the kind it makes (none: no open route).
+ * `steps`: the open models of its run's other steps (the edit that makes its end frame first), each with the kind it makes.
+ */
export interface PresetModel {
id: string;
model?: { id: string; kind: MediaKind };
+ steps?: { id: string; kind: MediaKind }[];
}
/**
* The rules a policy's pool lists and kinds make, or undefined when they keep nothing off. `presets`: the catalog's
* presets with their open models, so a preset is kept off with its model (by id, in the app lists: the shorter of the
* two lists when the policy has no app allow list of its own), and with a model that runs on a visitor's own setup only.
- * `own`: the open models this studio's GPUs can't run right now (src/server/pool-own-setup.ts poolOwnSetups).
+ * `own`: the open models this studio's GPUs can't run right now (src/server/pool-own-setup.ts poolOwnSetups);
+ * `ownPresets`: the presets whose press they can't run in whole right now (poolOwnPresets).
*/
export function poolRulesOf(
p: { pool?: { allow?: string[]; deny?: string[]; apps?: { allow?: string[]; deny?: string[] } }; kinds?: Partial<Record<MediaKind, boolean>> },
presets: readonly PresetModel[] = [],
own: Record<string, OwnSetup> = {},
+ ownPresets: Record<string, OwnSetup> = {},
): PoolRules | undefined {
const list = (xs: unknown) => (Array.isArray(xs) ? xs.filter((x): x is string => typeof x === "string") : undefined);
const lists = p.pool ?? {};
@@ -50,9 +59,13 @@ export function poolRulesOf(
const off = Object.entries(p.kinds ?? {}).filter(([, v]) => v === false);
if (off.length) out.kinds = Object.fromEntries(off) as PoolRules["kinds"];
if (Object.keys(own).length) out.own = own;
+ if (Object.keys(ownPresets).length) out.presets = ownPresets;
let appsAllow = list(lists.apps?.allow);
let appsDeny = list(lists.apps?.deny);
- const modelOff = new Set(presets.filter((x) => x.model && (!poolRunsModel(out, { ...x.model, engine: "open" }) || ownSetupOnly(x.model.id, "open"))).map((x) => x.id));
+ // A preset whose own model, or the model of any other step of its run, these GPUs can't run is kept off with it: its
+ // card says so before the press, never a run whose later step can't go on.
+ const keptOff = (m: { id: string; kind: MediaKind }) => !poolRunsModel(out, { ...m, engine: "open" }) || !!ownSetupOnly(m.id, "open");
+ const modelOff = new Set(presets.filter((x) => !!ownPresets[x.id] || (x.model && [x.model, ...(x.steps ?? [])].some(keptOff))).map((x) => x.id));
if (modelOff.size) {
if (appsAllow) appsAllow = appsAllow.filter((id) => !modelOff.has(id));
// Most presets kept off: the presets still on make the shorter list.
@@ -94,6 +107,7 @@ export function modelOwnSetup(rules: PoolRules | undefined, m: { id: string; kin
/** Does this studio's GPUs run this app, camera motion or effect under the rules (no rules: yes)? */
export function poolRunsPreset(rules: PoolRules | undefined, presetId: string): boolean {
+ if (rules?.presets?.[presetId]) return false;
const apps = rules?.apps;
if (!apps) return true;
if (apps.deny?.includes(presetId)) return false;
@@ -120,7 +134,8 @@ export function presetOwnSetup(rules: PoolRules | undefined, p: { id: string; op
// A catalog preset names its open model; a gallery card only says it has an open route.
const open = p.open && typeof p.open === "object" ? (p.open as { modelId?: unknown }) : null;
const model = typeof open?.modelId === "string" ? open.modelId : undefined;
- return (model && (rules?.own?.[model] ?? ownSetupOnly(model, "open"))) || ANY_GPU;
+ // Its open model's needs first, then those of its press as a whole (a step of it these GPUs can't run).
+ return (model && (rules?.own?.[model] ?? ownSetupOnly(model, "open"))) || rules?.presets?.[p.id] || ANY_GPU;
}
/**
diff --git a/src/server/account-gpu.ts b/src/server/account-gpu.ts
index 0ed4b29f..0b595328 100644
--- a/src/server/account-gpu.ts
+++ b/src/server/account-gpu.ts
@@ -8,6 +8,7 @@ import type { OwnerGpuView } from "@/lib/connections";
import { runnerFacts, type Principal } from "./computer/tasks";
import { offeredSummary } from "./model-access";
import { getModel, PRESETS } from "@/lib/catalog";
+import { presetRoutes } from "@/lib/catalog/preset-recipe-routes";
import { operationOutput } from "@/lib/catalog/types";
import { PROVIDERS } from "./providers";
import { blockedForAccounts, fetchPublic, isLoopbackGpu, peekText } from "./remote-fetch";
@@ -15,9 +16,9 @@ import { redactKey } from "./provider-keys";
import { networkCode, recordRunEvent } from "./run-events";
import { isInstallHost, REFUSED_ADDRESS } from "./gpu/hosts";
import { balance as billingBalance, policy as billingPolicy, type Action, type Balance } from "./billing";
-import { poolReady } from "./hosted";
+import { poolReady, poolTakes } from "./hosted";
import { placeName } from "./place-name";
-import { poolOwnModels } from "./pool-own-setup";
+import { poolOwnModels, poolOwnPresets, type PresetPress } from "./pool-own-setup";
import { ranOwnFirst, runOnOf, type RunOn } from "./run-on";
import { poolRulesOf, type PoolRules, type PresetModel } from "@/lib/pool-rules";
import { diagnoseAddress, diagnoseGpu, gpuHostOf, type Diagnosis, type GpuFailure, type GpuPlace, type GpuStage } from "@/lib/diagnose";
@@ -375,13 +376,32 @@ export interface VisitorView {
declare global {
var __fuobePresetModels: PresetModel[] | undefined;
+ var __fuobePresetPresses: PresetPress[] | undefined;
}
-/** Every preset with the open model it runs on and the kind it makes (for the pickers' rules): made once. */
+/** A preset's open route as its run plans it: its recipe's (with the end frame it edits first), else its own. */
+const openRoute = (p: (typeof PRESETS)[number]) => presetRoutes(p, "open", (id) => !!getModel(id))[0] ?? p.open ?? undefined;
+
+/**
+ * Every preset with the open model it runs on and the kind it makes, and the open models of its run's other steps (the
+ * edit that makes its end frame first), for the pickers' rules: made once.
+ */
const presetModels = (): PresetModel[] =>
(globalThis.__fuobePresetModels ??= PRESETS.map((p) => {
const m = p.open ? getModel(p.open.modelId) : undefined;
- return m && p.open ? { id: p.id, model: { id: m.id, kind: operationOutput(p.open.op, m.kind) } } : { id: p.id };
+ if (!m || !p.open) return { id: p.id };
+ const step = openRoute(p)?.end;
+ const end = step && getModel(step.modelId);
+ return { id: p.id, model: { id: m.id, kind: operationOutput(p.open.op, m.kind) }, ...(step && end && { steps: [{ id: end.id, kind: operationOutput(step.op, end.kind) }] }) };
+ }));
+
+/** Every preset's press on its open route, step by step (its end frame's edit first, then its clip to that frame): made once. */
+const presetPresses = (): PresetPress[] =>
+ (globalThis.__fuobePresetPresses ??= PRESETS.flatMap((p) => {
+ const route = openRoute(p);
+ if (!route) return [];
+ const end = route.end;
+ return [{ id: p.id, steps: [...(end ? [{ modelId: end.modelId, op: end.op }] : []), { modelId: route.modelId, op: end ? "flf2v" : route.op }] }];
}));
/** Keys whose balance ran out on a run, as the status says them. */
@@ -445,7 +465,7 @@ export async function visitorStatus(account: Account | null) {
// What this studio's GPUs keep off, the open models they can't run right now among it: shown in the pickers with
// what the visitor needs to run them on its own setup. For every viewer, a GPU of its own or not: its runs go
// there first too, and the label says what runs on its own GPU instead.
- const rules = p?.hosted ? poolRulesOf(p, presetModels(), poolOwnModels()) : undefined;
+ const rules = p?.hosted ? poolRulesOf(p, presetModels(), poolOwnModels(), poolOwnPresets(presetPresses(), poolTakes)) : undefined;
if (rules) viewer.pool = rules;
if (account && p?.links?.length) viewer.links = p.links;
if (account && p?.notice) viewer.notice = p.notice;
diff --git a/src/server/chains.ts b/src/server/chains.ts
index df5792ca..a9c337f8 100644
--- a/src/server/chains.ts
+++ b/src/server/chains.ts
@@ -16,6 +16,7 @@ import { provider } from "./providers";
import { llmLabel } from "./providers/llm";
import { loadManifest } from "./providers/comfyui";
import { offeredRoutes, requireOffered } from "./model-access";
+import { withoutStamp } from "./run-stamp";
/**
* Multi-step jobs built from chained generations: each step waits for the ones it needs and
@@ -65,12 +66,17 @@ export function assertOneMode(steps: ModeStep[]): void {
function withAsked(made: Generation[], asked: GenerationRequest, engine: Engine): Generation[] {
const [first, ...rest] = made;
if (!first) return made;
- // A Fuobe Original keeps the engine it ran on, as a plain row's request does (createGenerations).
- const request = { ...asked, ...(dualEngine(getModel(asked.modelId)) && { engine }) };
+ // A Fuobe Original keeps the engine it ran on, as a plain row's request does (createGenerations). What was asked is
+ // what a retry sends again: the run's stamp (its place, its hold) is the server's, never part of it.
+ const request: GenerationRequest = withoutStamp({ ...asked, ...(dualEngine(getModel(asked.modelId)) && { engine }) });
for (const k of ["asked", "chainFilled", "chainSkipped", "notice"] as const) delete request[k];
- const stored: GenerationRequest = { ...first.request, asked: request };
- db().prepare("UPDATE generations SET request_json = ? WHERE id = ?").run(JSON.stringify(stored), first.id);
- return [{ ...first, request: stored }, ...rest];
+ // The row as it was made, with its stamp: a Generation's request has none (toGeneration), and a last step written back
+ // from it would lose its run's place (a chain on this install's GPUs would end on the account's own GPU), its hold
+ // and its output check.
+ const row = db().prepare("SELECT request_json FROM generations WHERE id = ?").get(first.id) as { request_json: string } | undefined;
+ const kept = row ? (JSON.parse(row.request_json) as GenerationRequest) : first.request;
+ db().prepare("UPDATE generations SET request_json = ? WHERE id = ?").run(JSON.stringify({ ...kept, asked: request }), first.id);
+ return [{ ...first, request: { ...first.request, asked: request } }, ...rest];
}
/** Steps still waiting for their inputs (nothing spent yet) are canceled when the chain they feed can't be made. */
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 744c23b8..49f2fcc4 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -2011,6 +2011,15 @@ const comfyWaits = (): Map<string, number> => (globalThis.__fuobeComfyWaits ??=
/** How long such a step waits for ComfyUI to answer again before chainMode fails it. */
export const COMFY_WAIT = { ms: 60_000 };
+/**
+ * A chain's last step made before it kept its run's stamp (chains.ts withAsked wrote it back without one): the stamp it
+ * was asked with, so a step of a run on this install's GPUs runs there too, never on the account's own GPU.
+ */
+function withAskedStamp(req: GenerationRequest): GenerationRequest {
+ if (!req.account || req.place || req.asked?.place !== "pool") return req;
+ return { ...req, ...stampOf(req.asked), asked: withoutStamp(req.asked) };
+}
+
/** Launch dependent jobs whose inputs finished; fail the ones whose inputs failed. Never waits for an upload. */
async function advanceDependents(): Promise<void> {
// A server that is stopping launches no step (the app process that goes on does), and leaves the steps it looked at.
@@ -2025,7 +2034,7 @@ async function advanceDependents(): Promise<void> {
if (submitting().has(r.id) || isParked(r.id)) continue;
// A step queued before its model was retired runs on what replaced it (and its row says so).
const moved = currentRequest(JSON.parse(r.request_json) as GenerationRequest);
- const stored = moved.request;
+ const stored = withAskedStamp(moved.request);
const allIds = depIds(r.depends_on);
const allSlots = slotsFor(stored, allIds.length);
const allDeps = allIds.map(
diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.ts
index 6852311c..18da0b6e 100644
--- a/src/server/hosted-run.ts
+++ b/src/server/hosted-run.ts
@@ -440,6 +440,10 @@ export function poolGate(
for (const s of steps ?? []) {
const later = s.provider === "comfyui" ? ownSetupHere(s.modelId, "open") : null;
if (later) return { ok: false, reason: "ownSetup", setup: later };
+ // A later step nothing here runs right now (no worker holds its files or serves its lane): the whole press runs on the
+ // visitor's own GPU, labelled with what that step needs, as the run's own step is. Never a first step run here
+ // and a later one that can't go on.
+ if (s.provider === "comfyui" && !poolTakes(stepEndpoint(s))) return { ok: false, reason: "ownSetup", setup: needsGpu(stepEndpoint(s)) };
}
const problem = steps && p ? stepsProblem(p, steps) : null;
if (problem) return { ok: false, reason: problem === hostedWords(placeFor(p)).rtxCard ? "rtxCard" : "notOffered", setup: gpu };
diff --git a/src/server/pool-own-setup.ts b/src/server/pool-own-setup.ts
index 4ec0c875..da41ef53 100644
--- a/src/server/pool-own-setup.ts
+++ b/src/server/pool-own-setup.ts
@@ -154,3 +154,37 @@ export function poolCardRefuses(modelId: string): boolean {
/** The open models this install's GPUs can't run right now (poolOwnSetups), for GET /api/status's pool rules. */
export const poolOwnModels = (): Record<string, OwnSetup> => poolOwnSetups(poolTakes, poolCardRefuses);
+
+/** A preset's press as the cards see it: each step's open model and operation (its end frame's edit first, then its clip). */
+export interface PresetPress {
+ id: string;
+ steps: { modelId: string; op: string }[];
+}
+
+/**
+ * The presets whose press this install's GPUs can't run in whole right now, with what a visitor needs to run them on its
+ * own setup: a step none of whose workflows for its operation `takes` (a start-and-end-frame clip while only the plain
+ * clip's workflow is held, or an end frame's edit no worker holds). Their cards say so before the press, as the price
+ * check does (hosted-run.ts poolGate): never "Try free" for a run whose later step can't go on there. A step with no
+ * workflow for its operation is left to the price check.
+ */
+export function poolOwnPresets(presets: readonly PresetPress[], takes: (endpoint: string) => boolean): Record<string, OwnSetup> {
+ const out: Record<string, OwnSetup> = {};
+ const known = new Map<string, boolean>();
+ const taken = (e: string) => {
+ let v = known.get(e);
+ if (v === undefined) known.set(e, (v = takes(e)));
+ return v;
+ };
+ const byId = new Map(MODELS.map((m) => [m.id, m]));
+ for (const p of presets) {
+ for (const s of p.steps) {
+ const m = byId.get(s.modelId);
+ const endpoints = m ? [...new Set(m.routes.filter((r) => r.provider === "comfyui" && r.op === s.op).map((r) => r.endpoint))] : [];
+ if (!endpoints.length || endpoints.some(taken)) continue;
+ out[p.id] = needsGpu(endpoints[0]);
+ break;
+ }
+ }
+ return out;
+}
diff --git a/tests/hosted-pickers.test.ts b/tests/hosted-pickers.test.ts
index 6eeccb79..0c0458ff 100644
--- a/tests/hosted-pickers.test.ts
+++ b/tests/hosted-pickers.test.ts
@@ -112,6 +112,25 @@ describe("presets kept off with their model or the kind they make", () => {
expect(presets.filter((p) => poolRunsPreset(rules, p.id)).map((p) => p.id)).toEqual(["app-portrait", "app-cloud-only"]);
});
+ it("a preset whose end frame is made first on a model these GPUs can't run is kept off with it, labelled with what its press needs", async () => {
+ const { presetOwnSetup } = await import("@/lib/pool-rules");
+ const chained = [...presets, { id: "effect-bloom", model: { id: "oss-clip", kind: "video" as const }, steps: [{ id: "oss-edit", kind: "image" as const }] }];
+ const free = tryFreeFor({ hosted: true, cardText: "Try free", gpu: { connected: false }, pool: poolRulesOf({ pool: { deny: ["oss-edit"] } }, chained) }, "both")!.runs;
+ expect(free({ id: "effect-bloom", open: true })).toBe(false);
+ expect(free({ id: "effect-melt", open: true })).toBe(true);
+ // No GPU here holds the edit model: its card says what the visitor's own setup needs for it.
+ const own = { "oss-edit": { need: "gpu" as const, vramGb: 48 } };
+ const rules = poolRulesOf({}, chained, own);
+ expect(poolRunsPreset(rules, "effect-bloom")).toBe(false);
+ expect(presetOwnSetup(rules, { id: "effect-bloom", open: { modelId: "oss-clip" }, cloud: null }, "open")).toEqual({ need: "gpu" });
+ expect(poolRunsPreset(rules, "effect-melt")).toBe(true);
+ // A press these GPUs can't run in whole (a step none of them runs, its model otherwise run): kept off with that label.
+ const whole = poolRulesOf({}, presets, {}, { "effect-melt": { need: "gpu", vramGb: 32 } });
+ expect(poolRunsPreset(whole, "effect-melt")).toBe(false);
+ expect(presetOwnSetup(whole, { id: "effect-melt", open: { modelId: "oss-clip" }, cloud: null }, "open")).toEqual({ need: "gpu", vramGb: 32 });
+ expect(poolRunsPreset(whole, "motion-orbit")).toBe(true);
+ });
+
it("keeps the shorter list, and the policy's own app lists", () => {
// Most presets kept off: the ones still on are listed instead.
expect(poolRulesOf({ pool: { allow: ["oss-portrait"] } }, presets)?.apps).toEqual({ allow: ["app-portrait", "app-cloud-only"] });
diff --git a/tests/pool-chain-steps.test.ts b/tests/pool-chain-steps.test.ts
new file mode 100644
index 00000000..7a29ce94
--- /dev/null
+++ b/tests/pool-chain-steps.test.ts
@@ -0,0 +1,319 @@
+import crypto from "node:crypto";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { startLocalComfy, type LocalComfy } from "./helpers/fake-local-comfy";
+import { apiAs, loadRoutes, sha256, type ComputerRoutes } from "./helpers/computer-tab";
+import { tempDir } from "./helpers/temp-dir";
+import { composeOnWorker } from "./helpers/ticket-worker";
+
+/**
+ * A chain's later steps of a run on this install's GPUs go there too: an account with no GPU and no key of its own presses
+ * a preset that makes its end frame first (MiniMax H3's start-and-end-frame clip), and both steps go in line for the
+ * workers and are run by one. A chain whose later step the workers can't run is said before anything is queued, in
+ * the label of that step, never as a dead "Connect your GPU" after the first step ran.
+ */
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+vi.setConfig({ testTimeout: 60_000 });
+
+const dir = tempDir("fuobe-pool-chain-steps-");
+process.env.FUOBE_DATA_DIR = dir;
+// Nothing answers here: no test may reach a real ComfyUI on this machine.
+const DEAD = "http://127.0.0.1:7";
+process.env.COMFYUI_URL = DEAD;
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_HOSTED_RUNS;
+delete process.env.FUOBE_HOSTED_FREE;
+delete process.env.FUOBE_BILLING_URL;
+delete process.env.FUOBE_MODERATION_URL;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const realFetch = globalThis.fetch;
+let allowed: string[] = [];
+globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input instanceof Request ? input.url : input);
+ if (allowed.some((a) => url.startsWith(a))) return realFetch(input, init);
+ return new Response("not reachable in this test", { status: 599 });
+}) as typeof fetch;
+
+const auth = await import("@/server/auth");
+const generationsRoute = await import("@/app/api/generations/route");
+const uploadsRoute = await import("@/app/api/uploads/route");
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const { setSetting } = await import("@/server/settings");
+const pool = await import("@/server/computer/pool");
+const billing = await import("@/server/billing");
+const { loadManifest } = await import("@/server/providers/comfyui");
+const { loadIndex } = await import("@/server/gpu/index-file");
+const { allLanes } = await import("@/lib/lanes");
+const { getModel } = await import("@/lib/catalog");
+const { ComputerRunner } = await import("@/lib/computer-runner");
+const { CONNECT_GPU_MESSAGE } = await import("@/lib/guest-access");
+const { catalogVersion } = await import("@/server/computer/catalog-version");
+const { TINY_PNG } = await import("./helpers/fake-comfy-runner");
+const hosted = await import("@/server/hosted");
+const { captureRun, createGenerations, getGeneration } = await import("@/server/generations");
+const { withRunStamp } = await import("@/server/run-stamp");
+const { visitorStatus } = await import("@/server/account-gpu");
+const { needsGpu } = await import("@/server/pool-own-setup");
+const { getPreset, PRESETS } = await import("@/lib/catalog");
+const { presetRoutes } = await import("@/lib/catalog/preset-recipe-routes");
+const { ownSetupLabel } = await import("@/lib/own-setup");
+const { pickerRules, presetOwnSetup, tryFreeFor } = await import("@/lib/pool-rules");
+const { checkedPool, placeRows, runPlace } = await import("@/lib/run-place");
+
+const HOST = "localhost:3000";
+const SITE_HEADERS = { host: HOST, "sec-fetch-site": "same-origin", origin: `http://${HOST}` };
+const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
+const PRESET = "effect-nature-bloom";
+const CLIP_MODEL = "oss-minimax-h3";
+
+let comfy: LocalComfy;
+let routes: ComputerRoutes;
+let accountId = "";
+let cookie = "";
+
+beforeAll(async () => {
+ comfy = await startLocalComfy({ cors: "*", steps: 2, stepMs: 10, latencyMs: 10 });
+ allowed = [comfy.url];
+ routes = await loadRoutes();
+ auth.setPassword("install password");
+ // No GPU and no key of its own: its runs go to this install's GPUs.
+ accountId = auth.createAccount("[email protected]", "long enough").id;
+ cookie = `${auth.SESSION_COOKIE}=${auth.createSession(accountId).value}`;
+});
+afterAll(async () => {
+ globalThis.fetch = realFetch;
+ globalThis.__fuobeTestDiskFree = undefined;
+ for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_HOSTED_FREE"]) delete process.env[k];
+ await comfy.close();
+});
+beforeEach(() => {
+ resetRates();
+ billing.resetBillingCache();
+ process.env.FUOBE_HOSTED_RUNS = "1";
+ process.env.FUOBE_HOSTED_FREE = "1";
+ process.env.COMFYUI_URL = DEAD;
+ setSetting("comfyWhere", "workers");
+ setSetting("comfyUrl", "");
+ setSetting("engineMode", "open");
+ setSetting("demoMode", "off");
+ db().prepare("DELETE FROM relay_workers").run();
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();
+});
+
+/** A worker the owner added and resumed, allowed every lane, able to run the given workflows (all of them by default). */
+function standInWorker(workflows = loadManifest().workflows.map((x) => x.id)) {
+ const w = pool.addWorker("stand-in");
+ const lanes = allLanes(loadIndex(), sha);
+ pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: Object.fromEntries(lanes.map((l) => [l.lane, { delayMs: 0 }])), claimAfterMs: 0 });
+ db()
+ .prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ?, catalog_version = ?, protocol = 3, seen_at = ?, paused_local = 0 WHERE id = ?")
+ .run(JSON.stringify({ lanes: lanes.map((l) => l.lane), workflows }), JSON.stringify({ vramBytes: 96 * 2 ** 30 }), catalogVersion(), Date.now(), w.id);
+ return w;
+}
+
+function workerRunner(token: string) {
+ return new ComputerRunner(
+ {
+ api: apiAs(routes, null, { authorization: `Bearer ${token}` }),
+ local: (url, init) => realFetch(url, init),
+ socket: (url) => new WebSocket(url) as never,
+ sha256,
+ origin: "http://localhost:3000",
+ sleep: (ms) => new Promise((r) => setTimeout(r, Math.min(ms, 50))),
+ compose: (t) => composeOnWorker(t),
+ beatExtra: () => ({ protocol: 3, version: "test", local: { paused: false, why: null, until: null }, gpu: { otherApps: [], tempC: null }, inventoryHash: null, warmLane: null, catalogVersion: catalogVersion() }),
+ },
+ { device: "worker", port: comfy.port, clientId: "worker-test" },
+ );
+}
+
+const request = (url: string, body: unknown) => {
+ const text = JSON.stringify(body);
+ return new Request(`http://${HOST}${url}`, { method: "POST", headers: { ...SITE_HEADERS, cookie, "content-type": "application/json", "content-length": String(Buffer.byteLength(text)) }, body: text });
+};
+const run = async (body: Record<string, unknown>, url = "/api/generations") => {
+ const r = await generationsRoute.POST(request(url, body));
+ return { status: r.status, body: (await r.json()) as Record<string, unknown> & { items?: { id: string }[]; code?: string; error?: string } };
+};
+const tick = () => globalThis.__fuobeRunner?.tick();
+const taskOf = (generationId: string) => db().prepare("SELECT * FROM relay_tasks WHERE generation_id = ? ORDER BY created_at DESC").get(generationId) as import("@/server/computer/tasks").TaskRow | undefined;
+const stored = (id: string) => JSON.parse((db().prepare("SELECT request_json FROM generations WHERE id = ?").get(id) as { request_json: string }).request_json) as Record<string, unknown>;
+async function until<T>(fn: () => T | Promise<T>, tries = 300, everyMs = 25): Promise<T> {
+ let v = await fn();
+ for (let i = 0; i < tries && !v; i++) {
+ await tick();
+ await new Promise((r) => setTimeout(r, everyMs));
+ v = await fn();
+ }
+ return v;
+}
+async function photo(): Promise<string> {
+ const up = await uploadsRoute.POST(
+ new Request(`http://${HOST}/api/uploads`, { method: "POST", headers: { ...SITE_HEADERS, cookie, "content-type": "image/png", "x-file-name": "me.png", "content-length": String(TINY_PNG.length) }, body: new Uint8Array(TINY_PNG) }),
+ );
+ expect(up.status).toBe(201);
+ return ((await up.json()) as { url: string }).url;
+}
+const press = async () => ({ feature: "video", presetId: PRESET, modelId: CLIP_MODEL, op: "i2v", prompt: "", inputs: { images: [await photo()] }, params: { aspectRatio: "auto", resolution: "768p", duration: 5 } });
+const ended = async (id: string) =>
+ (await until(() => {
+ const g = getGeneration(id);
+ return g && g.status !== "queued" && g.status !== "running" ? g : null;
+ }, 600))!;
+
+describe("a preset's end-frame chain on this install's GPUs", () => {
+ it("both steps keep the run's place: the end frame and the clip go in line for the workers and a worker runs them", async () => {
+ const w = standInWorker();
+ const r = await run(await press());
+ expect(r.status, JSON.stringify(r.body)).toBe(201);
+ const items = r.body.items!;
+ expect(items).toHaveLength(2);
+ const clipId = items[0].id;
+ const endId = items[1].id;
+ // Every row of the run carries its place (and its stamp) on the server; the clip's asked request carries none.
+ expect(stored(endId).place).toBe("pool");
+ expect(stored(clipId)).toMatchObject({ place: "pool", op: "flf2v", chain: [{ slot: "endImage" }] });
+ expect(stored(clipId).hold).toEqual(stored(endId).hold);
+ expect(stored(clipId).standalone).toBe(true);
+ expect((stored(clipId).asked as Record<string, unknown>).place).toBeUndefined();
+ expect((stored(clipId).asked as Record<string, unknown>).hold).toBeUndefined();
+ expect(getGeneration(clipId)?.place).toBe("pool");
+
+ // The end frame: a task for the workers, run by the stand-in worker.
+ const worker = workerRunner(w.token);
+ const first = await until(() => taskOf(endId));
+ expect(first?.account).toBe(accountId);
+ await worker.beat();
+ await worker.claimAndRun();
+ expect((await ended(endId)).status).toBe("succeeded");
+
+ // The clip: never "Connect your GPU", a task for the workers in its run's place, run by the same worker.
+ const second = await until(() => taskOf(clipId) ?? (getGeneration(clipId)?.status === "failed" ? getGeneration(clipId) : undefined));
+ expect(getGeneration(clipId)?.error ?? null).not.toBe(CONNECT_GPU_MESSAGE);
+ expect(second && "pools" in second ? second.pools : null).toBe("pool");
+ const clipTask = taskOf(clipId)!;
+ expect(clipTask.account).toBe(accountId);
+ expect(clipTask.workflow_id ?? JSON.parse(clipTask.needs_json ?? "{}").workflowId).toBe(getModel(CLIP_MODEL)!.routes.find((x) => x.provider === "comfyui" && x.op === "flf2v")!.endpoint);
+ await worker.beat();
+ await worker.claimAndRun();
+ const clip = await ended(clipId);
+ expect(clip.status, clip.error ?? "").toBe("succeeded");
+ expect(stored(clipId).place).toBe("pool");
+ });
+
+ it("a clip step stored without its run's stamp (made before it was kept) still runs on the workers, with the stamp it was asked with", async () => {
+ const w = standInWorker();
+ const r = await run(await press());
+ expect(r.status, JSON.stringify(r.body)).toBe(201);
+ const [clipId, endId] = r.body.items!.map((x) => x.id);
+ // As such a step was stored: no place or hold of its own, the run's stamp only in what was asked.
+ const was = stored(clipId);
+ const { place, hold, charge, waitMs, standalone, ...rest } = was;
+ db()
+ .prepare("UPDATE generations SET request_json = ? WHERE id = ?")
+ .run(JSON.stringify({ ...rest, asked: { ...(was.asked as object), place, hold, charge, waitMs, standalone } }), clipId);
+ expect(stored(clipId).place).toBeUndefined();
+ const worker = workerRunner(w.token);
+ await until(() => taskOf(endId));
+ await worker.beat();
+ await worker.claimAndRun();
+ expect((await ended(endId)).status).toBe("succeeded");
+ await until(() => taskOf(clipId) ?? (getGeneration(clipId)?.status === "failed" ? getGeneration(clipId) : undefined));
+ expect(getGeneration(clipId)?.error ?? null).toBeNull();
+ expect(taskOf(clipId)?.account).toBe(accountId);
+ expect(stored(clipId)).toMatchObject({ place: "pool", standalone: true });
+ expect(stored(clipId).hold).toEqual(hold);
+ expect((stored(clipId).asked as Record<string, unknown>).place).toBeUndefined();
+ await worker.beat();
+ await worker.claimAndRun();
+ expect((await ended(clipId)).status).toBe("succeeded");
+ });
+
+ /**
+ * A press whose step `endpoint` no worker runs: the card, the price check (the place chip and the price) and the press
+ * all say where it really runs, before anything is made. Never "Free" on this install's GPUs, never a Run on them.
+ */
+ async function saidBeforeThePress(endpoint: string) {
+ standInWorker(loadManifest().workflows.map((x) => x.id).filter((x) => x !== endpoint));
+ const setup = needsGpu(endpoint);
+ // The card: kept off these GPUs, labelled with what that step needs, and no "Try free".
+ const viewer = (await visitorStatus(auth.accountById(accountId)!)).viewer;
+ const preset = getPreset(PRESET)!;
+ expect(viewer.pool?.presets?.[PRESET]).toEqual(setup);
+ expect(presetOwnSetup(pickerRules(viewer), preset, "open")).toEqual(setup);
+ const tryFree = tryFreeFor({ ...viewer, cardText: "Try free" }, "open");
+ expect(tryFree?.runs({ id: PRESET, open: true })).toBe(false);
+ // A preset these GPUs run in whole still says "Try free".
+ const plain = PRESETS.find((x) => {
+ const r = presetRoutes(x, "open", (id) => !!getModel(id))[0];
+ return r && !r.end && r.modelId === CLIP_MODEL && r.op === "i2v" && !r.params?.extra;
+ })!;
+ expect(plain).toBeDefined();
+ expect(tryFree?.runs({ id: plain.id, open: true })).toBe(true);
+ expect(viewer.pool?.presets?.[plain.id]).toBeUndefined();
+
+ // The price check: refused here with that setup, so the chip says the visitor's own GPU, with no price and no Run on list.
+ const body = await press();
+ const check = (await run({ ...body, place: "pool" }, "/api/generations?preview=1")).body as { place?: "pool"; quote?: { allowed: boolean; text: string; ownSetup?: import("@/lib/own-setup").OwnSetup } };
+ expect(check.quote?.allowed).toBe(false);
+ expect(check.quote?.ownSetup).toEqual(setup);
+ expect(check.quote?.text).toBe(ownSetupLabel(setup));
+ const pool = checkedPool(check);
+ const chip = runPlace({ audience: "account", engine: "open", models: ["MiniMax H3"], hosted: true, gpu: false, pool, format: String });
+ expect(chip).toMatchObject({ where: "gpu", label: "Your GPU", price: "", needs: "gpu", setup });
+ expect(`${chip.label} ${chip.price} ${chip.send}`).not.toMatch(/Free|Fuobe Cloud|Our GPUs/);
+ expect(placeRows({ ...viewer, kind: "account" } as never, { siteRuns: !chip.setup })).toBeNull();
+
+ // The press: refused with the same words and the setup that runs it, before any step is made.
+ const before = (db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n;
+ const r = await run(body);
+ expect(r.status, JSON.stringify(r.body)).toBe(403);
+ expect(r.body).toMatchObject({ error: check.quote!.text, code: "connect-gpu", ownSetup: setup });
+ expect((db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n).toBe(before);
+ }
+
+ it("a clip step no worker can run: the card, the place chip and the press say the visitor's own GPU, and nothing is queued", async () => {
+ await saidBeforeThePress(getModel(CLIP_MODEL)!.routes.find((x) => x.provider === "comfyui" && x.op === "flf2v")!.endpoint);
+ });
+
+ it("an end frame no worker can make is said before the press the same way", async () => {
+ // The edit that makes the end frame, as the preset's recipe plans it.
+ const end = presetRoutes(getPreset(PRESET)!, "open", (id) => !!getModel(id))[0]?.end;
+ expect(end).toBeDefined();
+ const edits = [...new Set(getModel(end!.modelId)!.routes.filter((x) => x.provider === "comfyui" && x.op === end!.op).map((x) => x.endpoint))];
+ expect(edits).toHaveLength(1);
+ await saidBeforeThePress(edits[0]);
+ });
+});
+
+describe("every chain keeps its run's stamp on every step", () => {
+ const STAMP = { place: "pool" as const, hold: "h-chain-test", charge: "Free", checkOutputs: true, standalone: true };
+ /** The rows a run makes on this install's GPUs, made and not sent. */
+ const made = (req: Record<string, unknown>) => {
+ const run = hosted.runOnPool(accountId, () => withRunStamp(STAMP, () => captureRun(() => createGenerations(req as never))));
+ db()
+ .prepare(`UPDATE generations SET status = 'canceled' WHERE id IN (${run.ids.map(() => "?").join(", ")})`)
+ .run(...run.ids);
+ return run;
+ };
+ // Pictures are taken for runs on this install's GPUs while a worker is there to run them.
+ beforeEach(() => void standInWorker());
+
+ it.each([
+ ["a preset's end frame, then its clip", async () => press()],
+ ["a film shot by shot, then joined", async () => ({ feature: "video", modelId: "oss-wan22-14b-fast", prompt: "A fox in the snow", inputs: { images: [await photo()] }, params: { aspectRatio: "16:9", shots: [{ prompt: "wide shot", duration: 3 }, { prompt: "close-up", duration: 5 }] } })],
+ ["a film made from its frames, then joined", async () => ({ feature: "video", modelId: "oss-wan22-14b-fast", op: "keyframes", prompt: "A paper boat drifts", inputs: { images: [await photo(), await photo(), await photo()] }, params: { aspectRatio: "16:9", resolution: "480p", duration: 6, keyframeTimes: [0, 2.5, 4] } })],
+ ])("%s", async (_, body) => {
+ const run = made(await body());
+ expect(run.ids.length).toBeGreaterThan(1);
+ for (const id of run.ids) expect(stored(id), id).toMatchObject(STAMP);
+ // What was asked (a retry sends it again) carries no stamp: it is the server's.
+ const head = run.value[0];
+ expect(stored(head.id).asked).toBeDefined();
+ for (const k of Object.keys(STAMP)) expect((stored(head.id).asked as Record<string, unknown>)[k], k).toBeUndefined();
+ });
+});