The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Runs on your own GPU or key: a wait survives a restart or a deploy, and heals without sending twice
Adarsh51ac65829ce0
diff --git a/src/app/api/generations/[id]/smaller/route.ts b/src/app/api/generations/[id]/smaller/route.tsnew file mode 100644index 00000000..35d867c1--- /dev/null+++ b/src/app/api/generations/[id]/smaller/route.ts@@ -0,0 +1,29 @@+import { requestAccount } from "@/server/auth";+import { generationAccount } from "@/server/account-library";+import { getGeneration } from "@/server/generations";+import { hit } from "@/server/rate";+import { SmallerCopyError, withSmallerCopy } from "@/server/smaller-copy";++/**+ * "Send a smaller copy" (an account's own failed run whose file was too big, or too slow, to send to its GPU): a smaller+ * copy of that file is made and kept as a new file of the account's, and the run's request comes back with it. The+ * studio then starts it as any run (POST /api/generations: every limit applies there).+ */+export async function POST(request: Request, ctx: RouteContext<"/api/generations/[id]/smaller">) {+ const account = requestAccount(request);+ if (!account) return Response.json({ error: "Log in to send a smaller copy." }, { status: 400 });+ const { id } = await ctx.params;+ const g = generationAccount(id) === account.id ? getGeneration(id) : null;+ if (!g) return Response.json({ error: "We can't find that run." }, { status: 404 });+ const cause = g.status === "failed" ? g.trouble?.cause : undefined;+ if (cause !== "gpu-too-big" && cause !== "gpu-slow-upload") return Response.json({ error: "This run's files weren't too big. Press Retry." }, { status: 409 });+ const rate = hit(`smaller:${account.id}`, 6, 60_000);+ if (!rate.ok) return Response.json({ error: "Making smaller copies takes a moment. Try again in a minute." }, { status: 429, headers: { "Retry-After": String(rate.retryAfterS) } });+ try {+ const { request: again, bytes } = await withSmallerCopy(account.id, g.request);+ return Response.json({ request: again, note: `Sent a smaller copy (${Math.max(1, Math.round(bytes / 2 ** 20))} MB).` });+ } catch (e) {+ if (e instanceof SmallerCopyError) return Response.json({ error: e.message }, { status: 422 });+ throw e;+ }+}diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.tsindex 76e49d67..3fa9d1ab 100644--- a/src/app/api/generations/route.ts+++ b/src/app/api/generations/route.ts@@ -19,7 +19,7 @@ import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskimport { accountInputProblem } from "@/server/account-inputs";import { db } from "@/server/db";import { findView, requestViewKey } from "@/server/any-angle";-import { accountLoraFix, accountRun, AccountRunError, asAccount, asVisitor, createGenerations, getGeneration, listGenerations, outputKind, previewGeneration, type AccountRunRefusal } from "@/server/generations";+import { accountLoraFix, accountRun, AccountRunError, asAccount, asVisitor, cancelGeneration, createGenerations, getGeneration, listGenerations, outputKind, previewGeneration, type AccountRunRefusal } from "@/server/generations";import { ensureTrashPurge, listOptionsFrom } from "@/server/library";import { hit, unhit } from "@/server/rate";import { GenerationRequestSchema } from "@/server/request-schema";@@ -47,16 +47,41 @@ export async function GET(request: Request) {return Response.json({ items: listGenerations({ ...listOptionsFrom(new URL(request.url).searchParams), account: viewer.kind === "account" ? viewer.account.id : undefined }) });}-/** An account's runs going now (queued or running), counted as runs: a run's jobs and chain steps share a batch. */-function activeRuns(accountId: string): number {+/** A run waiting for the account's own GPU or key to come back: no job yet, its wait kept with it (generations.ts `heal`). */+const WAITING = "(external_id IS NULL AND json_valid(external_meta_json) AND json_extract(external_meta_json, '$.heal') IS NOT NULL)";++/**+ * An account's runs going now (queued or running), counted as runs: a run's jobs and chain steps share a batch. Runs+ * waiting for its own GPU or key are counted apart (`waiting`): they use neither while they wait. `except`: a run the new+ * one takes the place of ("Run with your key" on a waiting run).+ */+function activeRuns(accountId: string, except?: string): number {const r = db().prepare(- "SELECT COUNT(DISTINCT COALESCE(batch_id, id)) AS n FROM generations WHERE status IN ('queued', 'running') AND json_extract(request_json, '$.account') = ?",+ `SELECT COUNT(DISTINCT COALESCE(batch_id, id)) AS n FROM generations WHERE status IN ('queued', 'running') AND json_extract(request_json, '$.account') = ? AND NOT ${WAITING} AND id IS NOT ?`,)- .get(accountId) as { n: number };+ .get(accountId, except ?? null) as { n: number };return r.n;}+function waitingRuns(accountId: string, except?: string): number {+ const r = db()+ .prepare(`SELECT COUNT(DISTINCT COALESCE(batch_id, id)) AS n FROM generations WHERE status = 'queued' AND json_extract(request_json, '$.account') = ? AND ${WAITING} AND id IS NOT ?`)+ .get(accountId, except ?? null) as { n: number };+ return r.n;+}++/**+ * Beside the request: the account's own run (waiting for its GPU or key, or failed) this one takes the place of ("Run+ * with your fal.ai key" on it): it stops once this one is made.+ */+function replacedRun(body: unknown, accountId: string): string | undefined {+ const id = (body as { replaces?: unknown } | null)?.replaces;+ if (typeof id !== "string" || !/^[A-Za-z0-9_-]{1,40}$/.test(id)) return undefined;+ const row = db().prepare("SELECT status, external_id FROM generations WHERE id = ? AND json_extract(request_json, '$.account') = ?").get(id, accountId) as { status: string; external_id: string | null } | undefined;+ return row && (row.status === "failed" || (row.status === "queued" && !row.external_id)) ? id : undefined;+}+/** What the sign-in proxy passes on of a request body (next.config.ts proxyClientMaxBodySize). */const PROXY_BODY_BYTES = 4 * 1024 * 1024;const BODY_TOO_BIG = "That request is over 4 MB. Upload pictures and clips first (POST /api/uploads), then send their /api/files/ paths.";@@ -127,11 +152,12 @@ export async function POST(request: Request) {return refuse(r.status, r.body.error, r.body, r.headers);};const notes: string[] = [];+ const replaces = account && !preview ? replacedRun(body, account.id) : undefined;if (account && !preview) {// Room on the server, room in the account's files, and a fair share of runs.if (!diskHasRoom()) return refuse(503, ACCOUNT_MESSAGES.diskLow);if (accountUsage(account.id).total >= accountTotalBytes(account.id)) return refuse(413, filesFullMessage(account.id));- if (activeRuns(account.id) >= ACCOUNT_LIMITS.activeRuns) return refuse(429, ACCOUNT_MESSAGES.activeRuns, { code: ACTIVE_RUNS_CODE }, { "Retry-After": "30" });+ if (activeRuns(account.id, replaces) >= ACCOUNT_LIMITS.activeRuns) return refuse(429, ACCOUNT_MESSAGES.activeRuns, { code: ACTIVE_RUNS_CODE }, { "Retry-After": "30" });const rate = hit(`run:${account.id}`, ACCOUNT_LIMITS.runsPerHour, 60 * 60_000);if (!rate.ok) return refuse(429, ACCOUNT_MESSAGES.runRate, {}, { "Retry-After": String(rate.retryAfterS) });if ((req.params?.numOutputs ?? 1) > ACCOUNT_LIMITS.outputsPerRun) {@@ -183,7 +209,7 @@ export async function POST(request: Request) {if (account && onPool && billingConfigured()) {// The billing service's limits for runs on this install's GPUs (never above the studio's own).const lim = onPool.policy.limits;- if (lim.activeRuns > 0 && activeRuns(account.id) >= lim.activeRuns) {+ if (lim.activeRuns > 0 && activeRuns(account.id, replaces) >= lim.activeRuns) {unhit(`run:${account.id}`);return refuse(429, ACCOUNT_MESSAGES.activeRuns, { code: ACTIVE_RUNS_CODE }, { "Retry-After": "30" });}@@ -198,6 +224,8 @@ export async function POST(request: Request) {// 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").let gpuWarning: string | undefined;+ // Where the run goes (its GPU, or a key): runs waiting for the GPU are counted apart, and only a run for the GPU waits too.+ let goesTo: string | undefined;// (A run on this install's GPUs: its plan was checked by decidePlace; the pre-flight is about the account's own GPU.)if (viewer.kind !== "guest" && !onPool) {let planned: ReturnType<typeof previewGeneration> | null = null;@@ -208,6 +236,7 @@ export async function POST(request: Request) {if (e instanceof AccountRunError) return refused(e.refusal);// Otherwise createGenerations says what's wrong with the request.}+ goesTo = planned?.route.provider;if (account && planned) {// Where the run goes decides what the account needs: its GPU for ComfyUI, its own key for fal.ai or Replicate.const own = accountRun(account.id, planned.route.provider, "submit");@@ -260,10 +289,11 @@ export async function POST(request: Request) {}// Counted again just before the run is stored, with nothing awaited in between: requests that arrived together all// passed the first count while the checks above waited.- if (account && activeRuns(account.id) >= ACCOUNT_LIMITS.activeRuns) {+ const waitingFull = !onPool && goesTo === "comfyui" && waitingRuns(account?.id ?? "", replaces) >= ACCOUNT_LIMITS.waitingRuns;+ if (account && (activeRuns(account.id, replaces) >= ACCOUNT_LIMITS.activeRuns || waitingFull)) {unhit(`run:${account.id}`);if (stamp?.hold) queueRelease(stamp.hold);- return refuse(429, ACCOUNT_MESSAGES.activeRuns, { code: ACTIVE_RUNS_CODE }, { "Retry-After": "30" });+ return refuse(429, waitingFull ? ACCOUNT_MESSAGES.waitingRuns : ACCOUNT_MESSAGES.activeRuns, { code: ACTIVE_RUNS_CODE }, { "Retry-After": "30" });}const make = () => createGenerations(req);let items: ReturnType<typeof createGenerations>;@@ -274,6 +304,8 @@ export async function POST(request: Request) {if (stamp?.hold) queueRelease(stamp.hold);throw e;}+ // The run this one takes the place of stops now (it was waiting, or it failed): never two of the same.+ if (replaces) await cancelGeneration(replaces);// A script's open-source run while ComfyUI is on the owner's computer: it waits for the owner's Fuobe tab there.if (viewer.kind === "owner" && token && getSetting("comfyWhere") === "computer" && items.some((g) => g.provider === "comfyui")) notes.push(RUNS_ON_COMPUTER_NOTE);// What the run leaves out or changes (a model that replaced a retired one, a LoRA that runs only on a GPU, a length the API rounds).diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.tsindex e0aace87..817a1277 100644--- a/src/lib/catalog/types.ts+++ b/src/lib/catalog/types.ts@@ -1226,6 +1226,11 @@ export interface GenerationRequest {* Unset: the install's engine mode, else the first one connected (your GPU before the cloud).*/engine?: Engine;+ /**+ * An account's cloud run on this provider's key when the model is on several ("Run with your Replicate key"): its+ * routes there go first. Without a key for it the run asks for one.+ */+ prefer?: "fal" | "replicate";/** Chained jobs: where the previous job's image goes among `inputs.images` (one dependency). */chainFrom?: "first" | "last";/** Chained jobs with several dependencies: where each one's first output goes, in dependsOn order. */@@ -1464,6 +1469,11 @@ export interface Generation {* help (Start your pod, Check my GPU, Replace key…; src/lib/diagnose.ts). The plain sentence is `error`.*/trouble?: RunTrouble;+ /**+ * An account's run waiting for its own GPU or key to come back (it goes on by itself): why, the buttons that help+ * (Start your pod, Run with your key…), and when it stops waiting.+ */+ waiting?: RunTrouble & { until?: number };/** Failed or stopped before its paid provider took the job (no external id): the card says "Not billed", not its price. */notBilled?: true;/** Ran on this install's GPUs (hosted runs), not the account's own. */diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.tsindex 20a3e7eb..a0c78afc 100644--- a/src/lib/guest-access.ts+++ b/src/lib/guest-access.ts@@ -170,8 +170,8 @@ const GENERATION = /^\/api\/generations\/(?!(?:facets|trash|stream|zip|bulk|loca/** The generation an account's request is about (its own runs: the proxy checks it made it), or undefined. */export function accountGeneration(method: string, pathname: string): string | undefined {- // Cancel, and Fuobe Soul's finished picture for its own result.- const step = /^\/api\/generations\/([^/]+)\/(cancel|finish)$/.exec(pathname);+ // Cancel, Fuobe Soul's finished picture for its own result, and a smaller copy of its failed run's file.+ const step = /^\/api\/generations\/([^/]+)\/(cancel|finish|smaller)$/.exec(pathname);if (method === "POST" && step) return step[1];const one = GENERATION.exec(pathname);// PATCH: a like, a pin or a review status (all the route changes).diff --git a/src/server/account-files.ts b/src/server/account-files.tsindex c0909dcd..4c536c1d 100644--- a/src/server/account-files.ts+++ b/src/server/account-files.ts@@ -46,6 +46,8 @@ export const ACCOUNT_LIMITS = {diskFreeBytes: 20 * GB,/** Runs: at once (queued or running), per hour, and outputs per run. */activeRuns: 4,+ /** Runs waiting for the account's own GPU or key to come back (they use neither meanwhile): counted apart. */+ waitingRuns: 4,runsPerHour: 60,outputsPerRun: 4,/** What one run request may weigh (inputs are uploaded first, so a request is only words and file paths). */@@ -83,6 +85,7 @@ export const ACCOUNT_MESSAGES = {uploadStalled: "The upload stopped arriving. Check your connection, then try again.",diskLow: "Uploads are paused for a moment. Please try again shortly.",activeRuns: "You have 4 runs going. Start the next one when one finishes.",+ waitingRuns: "You have 4 runs waiting for your GPU. Cancel one, or run one with your key, to start another.",runRate: "That's a lot of runs this hour. Try again later.",finishRate: "That's a lot of finished pictures this hour. Try again later.",finishBusy: "Your last pictures are still being saved. Try again in a moment.",diff --git a/src/server/account-gpu.ts b/src/server/account-gpu.tsindex ec3d9c74..2f4a10c8 100644--- a/src/server/account-gpu.ts+++ b/src/server/account-gpu.ts@@ -2,7 +2,7 @@ import "server-only";import dns from "node:dns/promises";import net from "node:net";import { isCloudProvider, type CloudProvider } from "@/lib/your-keys";-import { accountEngineMode, accountProviders, paidAllowed } from "./account-keys";+import { accountEngineMode, accountKeyInfo, accountProviders, paidAllowed, usableProviders } from "./account-keys";import { accountGpu, type Account, type AccountGpu } from "./auth";import type { OwnerGpuView } from "@/lib/connections";import { runnerFacts, type Principal } from "./computer/tasks";@@ -11,6 +11,8 @@ import { MODELS } from "@/lib/catalog";import { hostedUntestedSummary } from "@/lib/catalog/hosted-untested";import { PROVIDERS } from "./providers";import { blockedForAccounts, fetchPublic, isLoopbackGpu, peekText } from "./remote-fetch";+import { redactKey } from "./provider-keys";+import { networkCode, recordRunEvent } from "./run-events";import { isInstallHost, REFUSED_ADDRESS } from "./gpu/hosts";import { balance as billingBalance, OPEN_POLICY, policy as billingPolicy, type Action, type Balance } from "./billing";import { poolReady } from "./hosted";@@ -39,8 +41,12 @@ export class GpuError extends Error {}}-/** A check's failure, read for the person. */-const failed = (f: GpuFailure, place: GpuPlace) => new GpuError(diagnoseGpu(f, place), f);+/** A check's failure, read for the person. A token the answer echoed (a page that repeats the request's headers) never in it. */+const failed = (f: GpuFailure, place: GpuPlace, token?: string) => {+ const out = (t: string | undefined) => (t === undefined || !token ? t : redactKey(t, token));+ const clean = { ...f, body: out(f.body), error: out(f.error), location: out(f.location) };+ return new GpuError(diagnoseGpu(clean, place), clean);+};const allowPrivate = () => process.env.FUOBE_ALLOW_PRIVATE_URLS === "1";@@ -97,9 +103,9 @@ export async function checkGpuAddress(raw: string, o: { resolve?: (host: string)try {addrs = net.isIP(host) ? [host] : await resolve(host);} catch {- throw new GpuError(diagnoseAddress("not-found", host));+ throw new GpuError(diagnoseAddress("not-found", u.href));}- if (!addrs.length) throw new GpuError(diagnoseAddress("not-found", host));+ if (!addrs.length) throw new GpuError(diagnoseAddress("not-found", u.href));// Private networks, this machine's own addresses (loopback too, even with FUOBE_ALLOW_PRIVATE_URLS), wrapped IPv4.if (addrs.some(blockedForAccounts)) throw new GpuError(diagnoseAddress("local"));}@@ -162,12 +168,15 @@ export async function testGpu(const from = safeUrl(url);if (next && from && from.protocol === "http:" && next.protocol === "https:" && next.hostname === from.hostname) {res.body?.cancel().catch(() => {});- url = normal(new URL(`https://${from.hostname}${from.pathname}`));+ // To the port the redirect named (none: 443), never one it didn't.+ url = normal(new URL(`https://${next.host}${from.pathname}`));res = await ask(url);}} catch (e) {- console.warn(`[your-gpu] ${gpu.url}: ${(e as Error).message}`);- throw failed({ stage, error: (e as Error).message }, place);+ // The kind of address and what went wrong, never the address (nor the IP and port a socket error names).+ // (Not for the status strip's check, every 30 s while a page is open: a run that can't reach it logs its own line.)+ if (stage !== "status") recordRunEvent("your-gpu-check", { stage, hostKind: gpuHostOf(gpu.url).kind, code: networkCode((e as Error).message) }, "warn");+ throw failed({ stage, error: (e as Error).message }, place, gpu.token);}const contentType = res.headers.get("content-type") ?? undefined;if (!res.ok) {@@ -176,14 +185,14 @@ export async function testGpu(const body = redirect ? "" : await peekText(res);res.body?.cancel().catch(() => {});const retryAfterS = Number(res.headers.get("retry-after")) || undefined;- throw failed({ stage, status: res.status, body, contentType, location: res.headers.get("location") ?? undefined, retryAfterS }, place);+ throw failed({ stage, status: res.status, body, contentType, location: res.headers.get("location") ?? undefined, retryAfterS }, place, gpu.token);}const text = await headText(res, o.maxBytes ?? 1 * 2 ** 20);let s: { system?: { comfyui_version?: string }; devices?: { name?: string; vram_total?: number }[] } | null = null;try {s = JSON.parse(text);} catch {}- if (!s?.system) throw failed({ stage, status: res.status, body: text.slice(0, 4096), contentType }, place);+ if (!s?.system) throw failed({ stage, status: res.status, body: text.slice(0, 4096), contentType }, place, gpu.token);const dev = s.devices?.[0];return { device: dev?.name, vramBytes: typeof dev?.vram_total === "number" ? dev.vram_total : undefined, version: s.system.comfyui_version, ...(url !== gpu.url && { url }) };}@@ -313,6 +322,10 @@ export interface VisitorView {};/** The providers it has its own key for that this server can open ("Your keys"): never a key. */keys: CloudProvider[];+ /** Of those, the ones a run would be taken on now (not refused by the provider, balance not known to be empty). */+ usableKeys?: CloudProvider[];+ /** Keys whose provider account's balance ran out on a run (Add credit before the next one). */+ emptyKeys?: CloudProvider[];/** The studio lets accounts run paid models on their own keys (it isn't open-source only). */paidAllowed: boolean;/**@@ -328,6 +341,13 @@ export interface VisitorView {notice?: { id: string; text: string; url?: string };}+/** Keys whose balance ran out on a run, as the status says them. */+function emptyKeysOf(id: string): { emptyKeys: CloudProvider[] } | Record<string, never> {+ const info = accountKeyInfo(id);+ const empty = (Object.keys(info) as CloudProvider[]).filter((p) => info[p]?.balanceEmptyAt);+ return empty.length ? { emptyKeys: empty } : {};+}+/** What the status strip and the composer show of a GPU that didn't answer: never more than the person's own GPU said. */export type VisitorTrouble = Pick<Diagnosis, "cause" | "words" | "actions" | "retryable" | "details">;@@ -356,6 +376,8 @@ export async function visitorStatus(account: Account | null) {}: { connected: false },keys,+ ...(account && keys.length && { usableKeys: usableProviders(account.id) }),+ ...(account && keys.length && emptyKeysOf(account.id)),paidAllowed: paidAllowed(),};// Hosted runs and the billing hook: nothing of either with them off.diff --git a/src/server/generations.ts b/src/server/generations.tsindex 14c75710..03dfdce1 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -74,26 +74,34 @@ import { setResolver, watchGenerations, type LiveEvent } from "./live";import { provider, PROVIDERS, RETIRED_PROVIDER_ERROR } from "./providers";import { comfyLoraFiles, comfyPlace, computerScope, onOwnGpu, outputFetch, outsideOwnGpu, OWN_OUTPUT_LIMITS, ownGpu, ownLink, probeComfy, relayFile, troubleError, type OwnGpu } from "./providers/comfyui";import { accountById, accountGpu, gpuLink, type AccountGpu } from "./auth";-import { accountEngineMode, accountKey, accountProviders, paidAllowed } from "./account-keys";-import { addKeyMessage, CLOUD_PROVIDERS, isCloudProvider, keyRemovedMessage, type CloudProvider } from "@/lib/your-keys";+import { accountEngineMode, accountKey, markKeyGood, paidAllowed, usableProviders } from "./account-keys";+import { addKeyMessage, CLOUD_KEY, CLOUD_PROVIDERS, isCloudProvider, keyRemovedMessage, type CloudProvider } from "@/lib/your-keys";import { cachedGpuState, GpuError, noteGpuState, testGpu } from "./account-gpu";import { presetRoutes } from "@/lib/catalog/preset-recipe-routes";import {backoffMs,+ cleanDetails,diagnoseGpu,diagnoseGpuJob,diagnoseKey,+ diagnoseKeyJob,+ gpuHostOf,+ HEAL_CAP_MS,resultExpired,retryPlan,troubleOf,waitingWords,withKeyAction,+ withOfferAfterFirst,type Diagnosis,type GpuFailure,type KeyStage,type RunTrouble,type TroubleAction,+ type TroubleCause,} from "@/lib/diagnose";+import { draining } from "./shutdown";+import { keptText, networkCode, recordOwnRun, type HostKind } from "./run-events";import { CONNECT_GPU_MESSAGE, GUEST_RUN_MESSAGE, OWN_GPU_TOOL_MESSAGE } from "@/lib/guest-access";import { outsideTenant, runAsTenant, tenant, tenantAccount } from "./tenant";import { generationAccount } from "./account-library";@@ -221,6 +229,8 @@ export function toGeneration(r: Row): Generation {review: isReviewStatus(r.review) ? r.review : null,...(r.status === "failed" && r.fix_json && { fix: parseFix(r.fix_json) }),...(r.status === "failed" && r.fix_json && parseTrouble(r.fix_json)),+ // Waiting for its own GPU or key to come back: why, the buttons that help, and until when (never the owner's note).+ ...(r.status === "queued" && !r.external_id && r.external_meta_json && waitingOf(r.external_meta_json)),// Failed or stopped before a paid provider took the job (a refused key, an empty balance): nothing was billed....((r.status === "failed" || r.status === "canceled") && !r.external_id && (r.provider === "fal" || r.provider === "replicate") && { notBilled: true as const }),// On this install's GPUs (hosted runs): what it cost, or that it cost nothing.@@ -259,6 +269,118 @@ function parseTrouble(json: string): { trouble: RunTrouble } | Record<string, ne}}+/** A waiting run's diagnosis (external_meta_json `heal`), as the Generation field. */+function waitingOf(json: string): { waiting: RunTrouble & { until?: number } } | Record<string, never> {+ const h = readMeta(json).heal;+ return h?.trouble && typeof h.trouble.cause === "string" && Array.isArray(h.trouble.actions) ? { waiting: { ...h.trouble, ...(h.deadline && { until: h.deadline }) } } : {};+}++/**+ * What a run keeps in external_meta_json before its provider has it (external_id NULL): which instance is handing it+ * over or waiting on it (`lease`, renewed while it does), and, while it waits for its own GPU or key, how the wait goes+ * (`heal`), so another instance (a restart, a deploy) goes on with it instead of failing it. Once handed over the column+ * holds the provider's meta.+ */+interface PendingMeta {+ lease?: { by: string; until: number };+ heal?: HealState;+ /** Sent again after its GPU lost it (once). */+ resent?: boolean;+ /** Which of its batch's jobs it is (its seed is the batch's + this). */+ jobIndex?: number;+}++/** A run's wait for its own GPU or key, kept with it (survives a restart). */+interface HealState {+ since: number;+ /** When it stops waiting (per cause, never past HEAL_CAP_MS from `since`). */+ deadline: number;+ /** When each cause was first seen: a change of cause (off, then starting up) gets that cause's whole budget. */+ firstSeen: Partial<Record<TroubleCause, number>>;+ tries: number;+ /** When it tries again. */+ next: number;+ index: number;+ rechecked?: boolean;+ /** The words of the last try (the run fails in them when the wait is over), and what helps meanwhile. */+ words?: string;+ trouble?: RunTrouble;+}++const readMeta = (json: string | null | undefined): PendingMeta & Record<string, unknown> => {+ if (!json) return {};+ try {+ const m = JSON.parse(json) as unknown;+ return m && typeof m === "object" && !Array.isArray(m) ? (m as PendingMeta & Record<string, unknown>) : {};+ } catch {+ return {};+ }+};++declare global {+ /** This process among the instances that share the database (a deploy runs two at once for a moment). */+ var __fuobeInstance: string | undefined;+ var __fuobeLeaseTimer: NodeJS.Timeout | undefined;+}+const instance = () => (globalThis.__fuobeInstance ??= nanoid(10));++/**+ * How long an instance holds a run it is handing over (or waiting on) without renewing it, and how often it renews:+ * past `ms`, another instance may take it (a restart, or a deploy's old instance gone). Tests make it shorter.+ */+export const LEASE = { ms: 60_000, renewMs: 15_000 };++/**+ * Take a run that isn't handed over yet for this instance: only when no other instance holds it (its lease ran out, or+ * it never had one). True when this instance holds it now.+ */+function claim(id: string): boolean {+ const now = Date.now();+ return (+ db()+ .prepare(+ `UPDATE generations SET external_meta_json = json_set(CASE WHEN json_valid(external_meta_json) THEN external_meta_json ELSE '{}' END, '$.lease', json(@lease))+ WHERE id = @id AND external_id IS NULL AND status IN ('queued', 'running')+ AND (NOT json_valid(external_meta_json) OR json_extract(external_meta_json, '$.lease.until') IS NULL+ OR json_extract(external_meta_json, '$.lease.until') < @now OR json_extract(external_meta_json, '$.lease.by') = @me)`,+ )+ .run({ id, now, me: instance(), lease: JSON.stringify({ by: instance(), until: now + LEASE.ms }) }).changes > 0+ );+}++/** Renew this instance's hold on every run it is handing over or waiting on (a timer; it keeps going while the server drains). */+function renewLeases(): void {+ const ids = [...submitting()];+ if (!ids.length) return;+ const lease = JSON.stringify({ by: instance(), until: Date.now() + LEASE.ms });+ const stmt = db().prepare(+ `UPDATE generations SET external_meta_json = json_set(CASE WHEN json_valid(external_meta_json) THEN external_meta_json ELSE '{}' END, '$.lease', json(@lease))+ WHERE id = @id AND external_id IS NULL AND status IN ('queued', 'running')`,+ );+ db().transaction(() => {+ for (const id of ids) stmt.run({ id, lease });+ })();+}++/** Another instance holds this run now (its lease hasn't run out). */+function heldElsewhere(json: string | null | undefined): boolean {+ const lease = readMeta(json).lease;+ return !!lease && lease.by !== instance() && typeof lease.until === "number" && lease.until > Date.now();+}++/** A row still waiting for its hand-over (queued or running, no job yet): only then is it changed. */+const PENDING = "status IN ('queued', 'running') AND external_id IS NULL";++/** Change a run only while it is still going (queued or running): a cancel or a failure written meanwhile stays. */+function updateIfGoing(id: string, fields: Partial<Row>, extra = ""): boolean {+ const keys = Object.keys(fields);+ return (+ db()+ .prepare(`UPDATE generations SET ${keys.map((k) => `${k} = @${k}`).join(", ")}${keys.length ? ", " : ""}updated_at = @__now WHERE id = @__id AND status IN ('queued', 'running')${extra}`)+ .run({ ...fields, __now: Date.now(), __id: id }).changes > 0+ );+}+function update(id: string, fields: Partial<Row>): void {const keys = Object.keys(fields);if (!keys.length) return;@@ -604,10 +726,16 @@ export function deleteGeneration(id: string): void {* `loras` and `seconds` (the clip length asked for) prefer a route that carries every LoRA and makes that* length (Replicate's Wan 2.2 fast renders only 81–121 frames, fal's 17–161).*/-export function chooseRoute(candidates: ModelRoute[], images = 0, loras: LoraRef[] = [], seconds?: number, forceDemo = false): { route: ModelRoute; demo: boolean } {+export function chooseRoute(candidates: ModelRoute[], images = 0, loras: LoraRef[] = [], seconds?: number, forceDemo = false, prefer?: CloudProvider): { route: ModelRoute; demo: boolean } {// Honour the preferred cloud aggregator (Settings → API configuration) when a model is on several.const preferred = getSetting("cloudProvider");- const routes = preferred === "auto" ? candidates : [...candidates].sort((a, b) => Number(b.provider === preferred) - Number(a.provider === preferred));+ let routes = preferred === "auto" ? candidates : [...candidates].sort((a, b) => Number(b.provider === preferred) - Number(a.provider === preferred));+ // An account's "Run with your Replicate key": that provider's routes first, on its own key (none: it asks for one).+ const account = tenantAccount();+ if (prefer && account && routes.some((r) => r.provider === prefer)) {+ if (accountKey(account, prefer) === null) throw new AccountRunError(paidAllowed() ? { error: addKeyMessage(prefer), code: "add-key", provider: prefer } : { error: OPEN_ONLY_RUN, code: "open-only" });+ routes = [...routes].sort((a, b) => Number(b.provider === prefer) - Number(a.provider === prefer));+ }const demo = getSetting("demoMode");// A request marked demo (a skill recipe's free dry run) runs on the demo provider whatever Settings says, as does// anything a studio starts inside runAsDemo (a skill's dry run of a studio step, src/server/demo-scope.ts).@@ -839,7 +967,8 @@ function prepare(original: GenerationRequest) {if (access.dropped.length) plan = { ...plan, loras: access.loras, prompt: withoutTriggers(plan.prompt, plan.loras.filter((l) => !access.loras.some((k) => k.file === l.file)), access.loras) };else if (access.loras.some((l, i) => l !== plan.loras[i])) plan = { ...plan, loras: access.loras };// A preset can route to another model than the one asked for: its routes that are on (or the switch that's off).- 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);+ const prefer = tenantAccount() && 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);// 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) {@@ -1458,7 +1587,7 @@ async function advanceDependents(): Promise<void> {// A forced look at ComfyUI, at most one a sweep, for the steps that found it not answering.let lookedAgain: Promise<boolean> | undefined;for (const r of rows) {- if (submitting().has(r.id)) continue;+ if (submitting().has(r.id) || heldElsewhere(r.external_meta_json)) 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;@@ -1494,6 +1623,8 @@ async function advanceDependents(): Promise<void> {fail(`${earlier} ${short}`);continue;}+ // Another instance (a deploy's other one) launching this step already: left to it.+ if (!claim(r.id)) continue;submitting().add(r.id);let handedOff = false;// An account's step reads its inputs, and is planned, as its run was: as that account, on its own ComfyUI and its own@@ -1797,12 +1928,12 @@ const poolOf = (r: Pick<Row, "request_json">): boolean => {}};-function submit(id: string, route: ModelRoute, providerId: ProviderId, plan: ReturnType<typeof planGeneration>, req: GenerationRequest, index: number): Promise<void> {+function submit(id: string, route: ModelRoute, providerId: ProviderId, plan: ReturnType<typeof planGeneration>, req: GenerationRequest, index: number, resume?: HealState): Promise<void> {if (!req.account) return submitNow(id, route, providerId, plan, req, index);// On this install's GPUs (hosted runs): as the account, on this install's ComfyUI server only.if (req.place === "pool") {if (providerId !== "comfyui") {- update(id, { status: "failed", error: OWN_GPU_ONLY, completed_at: Date.now(), message: null });+ updateIfGoing(id, { status: "failed", error: OWN_GPU_ONLY, completed_at: Date.now(), message: null });submitting().delete(id);return Promise.resolve();}@@ -1810,17 +1941,32 @@ function submit(id: string, route: ModelRoute, providerId: ProviderId, plan: Ret}const own = accountRun(req.account, providerId, "submit");if ("error" in own) {- update(id, { status: "failed", error: own.error, completed_at: Date.now(), message: null });+ updateIfGoing(id, { status: "failed", error: own.error, completed_at: Date.now(), message: null });// A chained step advanceDependents marked as being handed over isn't any more.submitting().delete(id);return Promise.resolve();}- return own.run(() => submitNow(id, route, providerId, plan, req, index));+ return own.run(() => submitNow(id, route, providerId, plan, req, index, resume));}/** A song's cloud tools (Mureka): the song's length and format are read before it's sent. */const SONG_TOOL_OPS = new Set<Operation>(["song-extend", "song-remix", "song-stems"]);+/** What an earlier try of a hand-over already sent (an input's name or link at the provider, a voice it cloned): reused. */+type HandOverCache = Map<string, string>;++/** What a run's log line and its owner's note say of it (src/server/run-events.ts). */+interface RunFacts {+ provider: string;+ model: string;+ op?: string;+ stage?: string;+ attempt?: number;+ waitedMs?: number;+}++const factsOf = (r: Pick<Row, "provider" | "model_id" | "op">, more: Omit<RunFacts, "provider" | "model" | "op"> = {}): RunFacts => ({ provider: r.provider, model: r.model_id, op: r.op, ...more });+async function submitNow(id: string,route: ModelRoute,@@ -1828,66 +1974,106 @@ async function submitNow(plan: ReturnType<typeof planGeneration>,req: GenerationRequest,index: number,+ resume?: HealState,): Promise<void> {submitting().add(id);+ // Another instance (a deploy's other one) holds this run: it is left to that one.+ if (!claim(id)) {+ submitting().delete(id);+ return;+ }// MiniMax H3's 2K hand-off, decided here, on the ComfyUI this run goes to.if (providerId === "comfyui") {const extra = latentHandOff(plan.params.extra, req.account);if (extra !== plan.params.extra) plan = { ...plan, params: { ...plan.params, extra } };}// An account's run on its own GPU or key (not on this install's GPUs): a passing problem (a GPU that is off or starting- // up, a busy or down provider) is waited out within a budget, the tile saying what it waits for; anything else fails- // in plain words, with what helps (src/lib/diagnose.ts). The owner's runs and runs on this install's GPUs fail at once,- // in their own words, as before.+ // up, a busy or down provider) is waited out within a budget, the tile saying what it waits for and what helps; the+ // wait is kept with the run, so a restart or a deploy goes on with it. Anything else fails in plain words, with what+ // helps (src/lib/diagnose.ts). The owner's runs and runs on this install's GPUs fail at once, in their own words.const account = req.account && req.place !== "pool" ? req.account : undefined;- const link = account && providerId === "comfyui" ? gpuLink(accountGpu(account)) : null;+ // The GPU this run was planned for (its scope read it when it began).+ const gpu = account && providerId === "comfyui" ? accountGpu(account) : null;+ const link = gpuLink(gpu);+ const pod = !!link && gpuHostOf(link.url).kind === "runpod";const started = Date.now();- let tries = 0;- let rechecked = false;+ const heal: HealState = resume ? { ...resume, firstSeen: { ...resume.firstSeen } } : { since: started, deadline: started, firstSeen: {}, tries: 0, next: 0, index };+ const facts = (more: Omit<RunFacts, "provider" | "model" | "op"> = {}): RunFacts => ({ provider: providerId, model: plan.model.id, op: plan.op, stage: "submit", ...more });+ const sent: HandOverCache = new Map();try {+ // Taken over (a restart, another instance): what is left of its wait first, then a look at its GPU.+ if (resume && resume.next > Date.now() && !(await pause(id, resume.next - Date.now()))) return;+ let lookFirst = !!resume && !!link;+ // The first try reads the GPU's last status check (never asked again here): one that is off waits at once,+ // instead of sending files to an address that answers nothing.+ const known = link && !resume ? cachedGpuState(account!, link.url) : undefined;for (;;) {let error: unknown;- // The first try reads the GPU's last status check (never asked again here): one that is off waits at once,- // instead of sending files to an address that answers nothing.- const known = link && tries === 0 ? cachedGpuState(account!, link.url) : undefined;- if (known && !known.online && known.trouble?.retryable) error = troubleError(known.trouble);- else {+ if (heal.tries === 0 && !resume && known && !known.online && known.trouble?.retryable) error = troubleError(known.trouble);+ else if (link && (heal.tries > 0 || lookFirst)) {+ lookFirst = false;+ // Tried again: first a look at the GPU (its /system_stats, no files, outside the send line). Files go once it answers.+ const look = await probeGpu(account!, link);+ if (look !== "online") error = look;+ }+ if (!error) {try {- await handOver(id, route, providerId, plan, req, index);+ await handOver(id, route, providerId, plan, req, index, sent);if (link && statusOf(id) !== "failed") noteHandedOver(account!, link.url);+ if (account && heal.tries > 0) recordOwnRun({ run: id, account, ...facts({ attempt: heal.tries, waitedMs: Date.now() - heal.since }), hostKind: hostKindOf(gpu), outcome: "healed" });return;} catch (e) {error = e;+ // A voice the provider cloned for this run (a billed step) is kept for the next try.+ const voice = (e as { voiceEmbedding?: unknown } | null)?.voiceEmbedding;+ if (typeof voice === "string") sent.set("voiceEmbedding", voice);}}+ // Cancelled, failed or taken by another instance, deleted, or handed over meanwhile: nothing more to do here.const status = statusOf(id);- // A cancel during the hand-over stays a cancel.- if (!status || status === "canceled") return;+ if (status !== "queued" && status !== "running") return;let trouble = account ? accountTrouble(error, account, providerId, "submit", req) : undefined;- const heal = trouble?.retryable ? retryPlan(trouble.cause) : null;- if (heal && trouble) {- tries++;- const wait = backoffMs(tries, heal, trouble.retryAfterMs) * SELF_HEAL.scale;- if (Date.now() - started + wait <= heal.budgetMs * SELF_HEAL.scale) {+ const budget = trouble?.retryable ? retryPlan(trouble.cause) : null;+ if (budget && trouble) {+ heal.tries++;+ const now = Date.now();+ // Each cause has its own budget from when it was first seen (a GPU that was off and is starting up now gets the+ // whole of starting up's), never past the cap from the first try.+ const first = (heal.firstSeen[trouble.cause] ??= now);+ heal.deadline = Math.min(heal.since + HEAL_CAP_MS * SELF_HEAL.scale, Math.max(heal.deadline, first + budget.budgetMs * SELF_HEAL.scale));+ const wait = backoffMs(heal.tries, budget, trouble.retryAfterMs) * SELF_HEAL.scale;+ if (now + wait <= heal.deadline) {if (link) noteGpuState(account!, link.url, false, { trouble: asStatus(error, trouble, link) });- update(id, { status: "queued", message: waitingWords(trouble, isCloudProvider(providerId) ? providerId : undefined) });+ // Kept with the run (another instance goes on with it after a restart or a deploy), the tile saying what it+ // waits for and showing what helps.+ if (!markWaiting(id, heal, trouble, now + wait, waitingWords(trouble, isCloudProvider(providerId) ? providerId : undefined, pod))) return;+ if (heal.tries === 1 || heal.firstSeen[trouble.cause] === now) ownEvent(id, account!, error, trouble, facts({ attempt: heal.tries, waitedMs: now - heal.since }), "waiting");if (!(await pause(id, wait))) return;- // The account moved its GPU meanwhile (another address, or this computer): this run was planned for the old one.- if (link && gpuLink(accountGpu(account!))?.url !== link.url) {- failRun(id, error, diagnoseGpuJob({ kind: "moved" }, { kind: "link", url: link.url }), req.account);- return;+ // The account changed its GPU meanwhile (a new address or password, this computer, or none): this run goes there.+ if (providerId === "comfyui" && account && gpuChanged(account, gpu)) {+ if (!accountGpu(account)) {+ failRun(id, error, diagnoseGpuJob({ kind: "disconnected" }, { kind: "link", url: link?.url ?? "" }), account, facts({ attempt: heal.tries }));+ return;+ }+ const p = replan(id, account);+ if (!p || p.providerId !== providerId) {+ failRun(id, error, diagnoseGpuJob({ kind: "moved" }, { kind: "link", url: link?.url ?? "" }), account, facts({ attempt: heal.tries }));+ return;+ }+ if (!updateIfGoing(id, { message: "Your GPU has a new address, so this run goes there" }, " AND external_id IS NULL")) return;+ return await submit(id, p.route, p.providerId, p.plan, p.req, index, { ...heal, tries: 0, rechecked: false, next: 0 });}continue;}// Out of time: a GPU that seemed off is asked once more before the run fails (it may be back by now).- if (link && !rechecked) {- rechecked = true;+ if (link && !heal.rechecked) {+ heal.rechecked = true;const again = await recheckGpu(account!, link);if (again === "online") continue;trouble = { ...again, actions: withKeyOffer(again.actions, account!, req) };}}- failRun(id, error, trouble, req.account);+ failRun(id, error, trouble, req.account, account ? facts({ attempt: heal.tries, waitedMs: Date.now() - heal.since }) : undefined, !!account);return;}} finally {@@ -1898,53 +2084,114 @@ async function submitNow(/** Self-healing's clock: tests make it faster (0.001: a 30-minute wait takes 1.8 s). */export const SELF_HEAL = { scale: 1 };-/** Wait `ms`, looking every second whether the run was cancelled (false: it was, or it was deleted). */+/** An account's job waiting in its own GPU's (or provider's) queue: how long without moving. Tests make it shorter. */+export const OWN_QUEUE = { scale: 1 };+/** The longest an account's job waits in its own GPU's (or provider's) queue, however it moves. */+const OWN_QUEUE_CAP_MS = 2 * 60 * 60_000;++/** The words a waiting run's tile shows, its wait kept with it (external_meta_json `heal`). False: it isn't waiting any more. */+function markWaiting(id: string, heal: HealState, trouble: Diagnosis, next: number, message: string): boolean {+ heal.next = next;+ heal.words = trouble.words;+ heal.trouble = troubleOf(trouble);+ return (+ db()+ .prepare(+ `UPDATE generations SET status = 'queued', message = @message, updated_at = @now,+ external_meta_json = json_set(CASE WHEN json_valid(external_meta_json) THEN external_meta_json ELSE '{}' END, '$.heal', json(@heal))+ WHERE id = @id AND ${PENDING}`,+ )+ .run({ id, message, now: Date.now(), heal: JSON.stringify(heal) }).changes > 0+ );+}++/**+ * Wait `ms`, looking every second whether the run still waits here. False: it was cancelled, failed, deleted or handed+ * over meanwhile, another instance holds it, or this server is stopping (the next one goes on with it).+ */async function pause(id: string, ms: number): Promise<boolean> {const end = Date.now() + ms;for (;;) {+ if (draining()) return false;const left = end - Date.now();if (left <= 0) return true;await new Promise((r) => setTimeout(r, Math.min(1000, left)));- const s = statusOf(id);- if (!s || s === "canceled") return false;+ const r = db().prepare("SELECT status, external_id, external_meta_json FROM generations WHERE id = ?").get(id) as Pick<Row, "status" | "external_id" | "external_meta_json"> | undefined;+ if (!r || (r.status !== "queued" && r.status !== "running") || r.external_id || heldElsewhere(r.external_meta_json)) return false;}}-/** A failed run in its words: an account's plain sentence (the owner's own detail as before), with what helps and "Fix it". */-function failRun(id: string, e: unknown, trouble: Diagnosis | undefined, account: string | undefined): void {- const fix = (e as { fix?: GenerationFix }).fix;+/**+ * A failed run in its words: an account's plain sentence (the owner's own detail as before), with what helps and "Fix it".+ * Only while the run is still going: a Cancel (or another instance's failure) written meanwhile stays. `facts`: an+ * account's own run, logged and noted for the owner (run-events.ts).+ */+function failRun(id: string, e: unknown, trouble: Diagnosis | undefined, account: string | undefined, facts?: RunFacts, own = !!facts): boolean {+ const fix = (e as { fix?: GenerationFix } | null)?.fix;const kept = keptFix(fix, trouble);// What the GPU was missing (a model, a node class) is kept, so the tile offers "Fix it", and its GPU check counts as stale.- update(id, { status: "failed", error: trouble?.words ?? (e as Error).message, completed_at: Date.now(), message: null, ...(kept && { fix_json: kept }) });+ const done = updateIfGoing(id, { status: "failed", error: trouble?.words ?? String((e as Error | null)?.message ?? e), completed_at: Date.now(), message: null, ...(kept && { fix_json: kept }) });+ if (!done) return false;if (fix) markStale(account ? `acct:${account}` : "install");+ if (own && account && facts) ownEvent(id, account, e, trouble, facts, "failed");+ return true;}/** generations.fix_json: what the GPU was missing (GenerationFix) and, for an account, what its GPU or key ran into. */const keptFix = (fix: GenerationFix | undefined, trouble: Diagnosis | undefined): string | undefined =>fix || trouble ? JSON.stringify({ ...(fix ?? {}), ...(trouble && { trouble: troubleOf(trouble) }) }) : undefined;+/** Where an account's GPU is, as the log says it: a RunPod pod, a tunnel, a web address, or the person's own computer. */+function hostKindOf(gpu: AccountGpu | null | undefined): HostKind | undefined {+ if (!gpu) return undefined;+ if (gpu.mode === "computer") return "computer";+ return gpuHostOf(gpu.url).kind;+}++/**+ * An account's run on its own GPU or key that waits, healed or failed: one log line, and (failed) the note the owner+ * reads. Its stage and code from what came back, the provider's own words without the GPU's address, a token or a key.+ */+function ownEvent(id: string, account: string, e: unknown, trouble: Diagnosis | undefined, f: RunFacts, outcome: "failed" | "waiting"): void {+ try {+ const failure = (e as { failure?: GpuFailure } | null)?.failure;+ const status = failure?.status ?? (e as { status?: unknown } | null)?.status;+ const net = failure?.error ?? networkReason(e);+ const code = typeof status === "number" && status > 0 ? String(status) : net ? networkCode(net) : undefined;+ const own = f.provider === "comfyui" ? ownGpu() : undefined;+ const link = own && own.kind !== "computer" ? own : undefined;+ const hostKind: HostKind | undefined = f.provider !== "comfyui" ? undefined : own?.kind === "computer" ? "computer" : link?.url ? gpuHostOf(link.url).kind : undefined;+ const said = keptText(failure?.body || failure?.error || failure?.location || ((e as { said?: unknown } | null)?.said as string | undefined) || (e as Error | null)?.message, { url: link?.url, secret: link?.token });+ recordOwnRun({ run: id, account, ...f, stage: failure?.stage ?? f.stage, code, hostKind, cause: trouble?.cause, outcome }, said);+ } catch {+ // A log line never stops a run.+ }+}+/** A network failure (no answer at all) as its words, or undefined for any other error. */function networkReason(e: unknown): string | undefined {- const err = e as { message?: unknown; cause?: { code?: unknown } } | null;+ const err = e as { message?: unknown; name?: unknown; cause?: { code?: unknown } } | null;const code = typeof err?.cause?.code === "string" ? err.cause.code : undefined;const msg = String(err?.message ?? "");- if (!code && !/fetch failed|ECONNREFUSED|ENOTFOUND|ECONNRESET|ETIMEDOUT|EAI_AGAIN|socket hang up|UND_ERR/i.test(msg)) return undefined;- return [msg, code && !msg.includes(code) ? code : undefined].filter(Boolean).join(" ");+ const aborted = err?.name === "TimeoutError" || err?.name === "AbortError";+ if (!code && !aborted && !/fetch failed|ECONNREFUSED|ENOTFOUND|ECONNRESET|ETIMEDOUT|EAI_AGAIN|socket hang up|UND_ERR|aborted due to timeout|operation was aborted/i.test(msg)) return undefined;+ return [msg || String(err?.name ?? ""), code && !msg.includes(code) ? code : undefined].filter(Boolean).join(" ");}-/** Another key of the account that runs the same model (Replicate for fal.ai, or the other way round). */+/** Another key of the account that runs the same model (Replicate for fal.ai, or the other way round), and would take it now. */function otherKeyFor(account: string, p: CloudProvider, modelId: string | undefined): CloudProvider | undefined {const m = modelId ? getModel(modelId) : undefined;- return m ? accountProviders(account).find((k) => k !== p && m.routes.some((r) => r.provider === k)) : undefined;+ return m ? usableProviders(account).find((k) => k !== p && m.routes.some((r) => r.provider === k)) : undefined;}/*** The cloud version of a run on the account's GPU that one of its keys runs: a preset's first cloud route, or the same- * Fuobe Original on the cloud engine. Null without a key that serves it, or when the studio is open-source only.+ * Fuobe Original on the cloud engine. Null without a key that would take it (one the provider refused, or whose balance+ * ran out, isn't offered), or when the studio is open-source only.*/export function cloudTwin(req: Pick<GenerationRequest, "presetId" | "modelId">, account: string): { modelId: string; provider: CloudProvider; op?: string } | null {if (!paidAllowed()) return null;- const keys = accountProviders(account);+ const keys = usableProviders(account);if (!keys.length) return null;const has = (id: string) => !!getModel(id);const preset = req.presetId ? getPreset(req.presetId) : undefined;@@ -1962,11 +2209,14 @@ export function cloudTwin(req: Pick<GenerationRequest, "presetId" | "modelId">,return null;}-/** A GPU trouble's buttons, with "Run with your … key" when one of the account's keys runs this tool's cloud version. */+/**+ * A GPU trouble's buttons, with "Run with your … key" when one of the account's keys runs this tool's cloud version: right+ * after the first (the one that fixes the GPU), so a tile that shows only a few keeps it.+ */function withKeyOffer(actions: TroubleAction[], account: string, req: Pick<GenerationRequest, "presetId" | "modelId">): TroubleAction[] {if (actions.some((a) => a.kind === "run-with-key")) return actions;const twin = cloudTwin(req, account);- return twin ? [...actions, withKeyAction(twin.provider, twin.modelId, twin.op)] : actions;+ return withOfferAfterFirst(actions, twin && withKeyAction(twin.provider, twin.modelId, twin.op));}/**@@ -1989,7 +2239,10 @@ function accountTrouble(e: unknown, account: string, providerId: string, stage:const said = (e as { said?: unknown } | null)?.said;if (typeof status === "number" && status > 0) return diagnoseKey({ stage, status, text: typeof said === "string" ? said : message }, ctx);const net = networkReason(e);- return net ? diagnoseKey({ stage, error: net }, ctx) : undefined;+ if (net) return diagnoseKey({ stage, error: net }, ctx);+ // A step at the provider that failed in words of its own (a voice it couldn't clone): plain words already, its own in details.+ if (typeof said === "string" && said) return { cause: "provider-failed", words: message, details: cleanDetails(said, 200) || undefined, actions: [{ kind: "retry", label: "Retry" }], retryable: false };+ return undefined;}/** A short, stable name for the address a run was sent to (kept with the run, never the address itself). */@@ -2001,20 +2254,45 @@ function noteHandedOver(account: string, url: string): void {if (known && !known.online) noteGpuState(account, url, true);}+declare global {+ /** A look at an account's GPU on its way (one per account and address: runs that wait share it). */+ var __fuobeGpuLooks: Map<string, Promise<"online" | (Error & { trouble: Diagnosis })>> | undefined;+}++/**+ * A look at the account's GPU before a waiting run tries again: its /system_stats only (no files, outside the send line),+ * shared by the account's runs that wait. "online", or the run's error, in a run's words (what came back kept for the+ * details). The status strip learns the answer too.+ */+function probeGpu(account: string, link: { url: string; token?: string }): Promise<"online" | (Error & { trouble: Diagnosis })> {+ const probes = (globalThis.__fuobeGpuLooks ??= new Map());+ const key = `${account} ${link.url}`;+ const going = probes.get(key);+ if (going) return going;+ const place = { kind: "link" as const, url: link.url, hasToken: !!link.token };+ const p = testGpu(link, { timeoutMs: 8000, stage: "status" })+ .then(+ ({ url: _moved, ...info }) => {+ void _moved;+ noteGpuState(account, link.url, true, { info });+ return "online" as const;+ },+ (e: unknown) => {+ const f: GpuFailure = (e instanceof GpuError && e.failure) || { stage: "status", error: (e as Error).message };+ // The status strip keeps the check's words; the run says the same in a run's words.+ noteGpuState(account, link.url, false, { trouble: e instanceof GpuError && !e.failure ? e.trouble : diagnoseGpu(f, place) });+ return troubleError(e instanceof GpuError && !e.failure ? e.trouble : diagnoseGpu({ ...f, stage: "poll" }, place), f.status, f);+ },+ )+ .finally(() => probes.delete(key));+ probes.set(key, p);+ return p;+}+/** The account's GPU asked once more, before a run that couldn't reach it fails: "online", or why not (the run's words). */async function recheckGpu(account: string, link: { url: string; token?: string }): Promise<"online" | Diagnosis> {- const place = { kind: "link" as const, url: link.url, hasToken: !!link.token };- try {- const { url: _moved, ...info } = await testGpu(link, { timeoutMs: 8000, stage: "status" });- void _moved;- noteGpuState(account, link.url, true, { info });- return "online";- } catch (e) {- // The status strip keeps the check's words; the run says the same in a run's words.- const f: GpuFailure = (e instanceof GpuError && e.failure) || { stage: "status", error: (e as Error).message };- noteGpuState(account, link.url, false, { trouble: e instanceof GpuError && !e.failure ? e.trouble : diagnoseGpu(f, place) });- return e instanceof GpuError && !e.failure ? e.trouble : diagnoseGpu({ ...f, stage: "poll" }, place);- }+ const r = await probeGpu(account, link);+ return r === "online" ? "online" : r.trouble;}/** A run's GPU trouble as the status strip says it (in a check's words) when what came back is known; else as it is. */@@ -2023,6 +2301,25 @@ function asStatus(error: unknown, trouble: Diagnosis, link: { url: string; tokenreturn f ? diagnoseGpu({ ...f, stage: "status" }, { kind: "link", url: link.url, hasToken: !!link.token }) : trouble;}+/** The account's GPU isn't the one a run was planned for any more: another address or password, this computer, or none. */+function gpuChanged(account: string, was: AccountGpu | null): boolean {+ const now = accountGpu(account);+ if (!now || !was) return now !== was;+ if (now.mode === "computer" || was.mode === "computer") return now.mode !== was.mode;+ return now.url !== was.url || (now.token ?? "") !== (was.token ?? "");+}++/** A run planned again, as its account runs now (its GPU, its keys): when the GPU changed, or another instance takes it. */+function replan(id: string, account: string): ReturnType<typeof prepare> | null {+ const r = db().prepare("SELECT request_json FROM generations WHERE id = ?").get(id) as Pick<Row, "request_json"> | undefined;+ if (!r) return null;+ try {+ return asAccount(account, () => prepare(JSON.parse(r.request_json) as GenerationRequest));+ } catch {+ return null;+ }+}+declare global {/** Account runs whose polls keep failing: since when, how many in a row, and when to ask again (self-healing). */var __fuobePollHeals: Map<string, { first: number; n: number; next: number }> | undefined;@@ -2037,29 +2334,50 @@ const resentRuns = () => (globalThis.__fuobeResent ??= new Set());/** What a poll can't wait out: a key refused, credit gone, no access; a GPU that wants a password or a sign-in. */const FINAL_AT_POLL: ReadonlySet<string> = new Set(["key-rejected", "key-balance", "key-permission", "gpu-password", "gpu-password-wrong", "gpu-sign-in", "address-local"]);-/** How long an account's run's polls may keep failing before it stops: its own GPU, or its key's provider. */-const POLL_HEAL_MS = { comfyui: 15 * 60_000, cloud: 10 * 60_000 };+/** How long an account's run's polls on its own GPU may keep failing before it stops (its key's provider: the run's own clock). */+const POLL_HEAL_MS = { comfyui: 15 * 60_000 };/** Polls that fail in a row before the tile says it is waiting. */const POLL_MISSES_SAID = 3;+/** How long a made result's copy is tried again (a GPU or provider that dropped the connection for a while). */+const SAVE_HEAL_MS = 15 * 60_000;++/** Which of its batch's jobs a run is (its seed is the batch's + this): kept at hand-over, else read from its batch. */+function jobIndexOf(r: Pick<Row, "batch_id" | "created_at">, meta: PendingMeta): number {+ if (typeof meta.jobIndex === "number" && meta.jobIndex >= 0) return meta.jobIndex;+ if (!r.batch_id) return 0;+ // createGenerations stamps a batch's jobs created_at = now + i.+ const first = db().prepare("SELECT MIN(created_at) FROM generations WHERE batch_id = ?").pluck().get(r.batch_id) as number | null;+ const i = first === null ? 0 : r.created_at - first;+ return i >= 0 && i < 64 ? i : 0;+}/**- * A run its GPU lost (ComfyUI restarted): sent again once, planned as it was (inputs uploaded again). False when it- * can't be (sent again before, or its plan doesn't go to the same place any more).+ * A run its GPU lost (ComfyUI restarted): sent again once, planned as it was (inputs uploaded again), as the same job of+ * its batch (its own seed). False when it can't be (sent again before, or its plan doesn't go to the same place any more).*/function resend(r: Row, account: string, words: string): boolean {- if (resentRuns().has(r.id)) return false;+ const was = readMeta(r.external_meta_json);+ if (resentRuns().has(r.id) || was.resent) return false;try {const stored = JSON.parse(r.request_json) as GenerationRequest;const p = asAccount(account, () => prepare(stored));if (p.providerId !== r.provider) return false;+ const index = jobIndexOf(r, was);resentRuns().add(r.id);if (resentRuns().size > 5000) resentRuns().delete(resentRuns().values().next().value!);- db().transaction(() => {- update(r.id, { external_id: null, external_meta_json: null, status: "queued", progress: null, message: words });- db().prepare("DELETE FROM generation_runs WHERE id = ?").run(r.id);+ const again = db().transaction(() => {+ const changed = db()+ .prepare(+ `UPDATE generations SET external_id = NULL, external_meta_json = @meta, status = 'queued', progress = NULL, message = @words, updated_at = @now+ WHERE id = @id AND external_id = @ext AND status IN ('queued', 'running')`,+ )+ .run({ id: r.id, ext: r.external_id, meta: JSON.stringify({ resent: true, jobIndex: index }), words, now: Date.now() }).changes;+ if (changed) db().prepare("DELETE FROM generation_runs WHERE id = ?").run(r.id);+ return changed > 0;})();+ if (!again) return false;submitting().add(r.id);- void submit(r.id, p.route, p.providerId, p.plan, p.req, 0);+ void submit(r.id, p.route, p.providerId, p.plan, p.req, index);return true;} catch {return false;@@ -2068,8 +2386,9 @@ function resend(r: Row, account: string, words: string): boolean {/*** An account's poll that failed: a key that won't work (refused, no credit, no access) fails the run at once; a passing- * problem (its GPU off, its provider busy) is asked again with a growing wait, the tile saying so, until the budget is- * spent: then its GPU is asked once more, and the run fails in plain words. True when the poll was handled here.+ * problem (its GPU off, its provider busy) is asked again with a growing wait, the tile saying so. A run on its own GPU+ * stops when that has lasted its budget (its GPU asked once more first); one on its key is never cut short here (the+ * job is accepted, and paid): the run's own clock in pollOne ends it. True when the poll was handled here.*/async function healPoll(r: Row, ctx: PollContext, account: string, pollError: unknown): Promise<boolean> {const stored = JSON.parse(r.request_json) as GenerationRequest;@@ -2079,9 +2398,8 @@ async function healPoll(r: Row, ctx: PollContext, account: string, pollError: un.cancel?.(ctx).catch(() => {});if (d && !d.retryable && FINAL_AT_POLL.has(d.cause)) {- await cancel();pollHeals().delete(r.id);- failRun(r.id, pollError, d, account);+ if (failRun(r.id, pollError, d, account, factsOf(r, { stage: "poll" }))) await cancel();return true;}if (!d) return false;@@ -2090,39 +2408,48 @@ async function healPoll(r: Row, ctx: PollContext, account: string, pollError: unh.n++;h.next = now + backoffMs(h.n, { budgetMs: 0, firstMs: 5_000, maxMs: 60_000 }, d.retryAfterMs) * SELF_HEAL.scale;pollHeals().set(r.id, h);- const budget = (r.provider === "comfyui" ? POLL_HEAL_MS.comfyui : POLL_HEAL_MS.cloud) * SELF_HEAL.scale;- if (now - h.first >= budget) {- const link = r.provider === "comfyui" ? gpuLink(accountGpu(account)) : null;+ if (h.n === 1) ownEvent(r.id, account, pollError, d, factsOf(r, { stage: "poll", attempt: 1 }), "waiting");+ if (r.provider === "comfyui" && now - h.first >= POLL_HEAL_MS.comfyui * SELF_HEAL.scale) {+ const link = gpuLink(accountGpu(account));// Its GPU asked once more: back, it is polled again at once (and collected, or found lost and sent again).if (link && (await recheckGpu(account, link)) === "online") {pollHeals().delete(r.id);return true;}- await cancel();pollHeals().delete(r.id);const minutes = Math.max(1, Math.round((now - h.first) / 60_000));const end = link ? diagnoseGpuJob({ kind: "gone", minutes }, { kind: "link", url: link.url }) : d;- failRun(r.id, pollError, { ...end, actions: link ? withKeyOffer(end.actions, account, stored) : end.actions }, account);+ if (failRun(r.id, pollError, { ...end, actions: link ? withKeyOffer(end.actions, account, stored) : end.actions }, account, factsOf(r, { stage: "poll", attempt: h.n, waitedMs: now - h.first }))) await cancel();return true;}if (h.n >= POLL_MISSES_SAID) {const words = r.provider === "comfyui" ? "Your GPU stopped answering. Waiting for it to come back" : waitingWords(d, isCloudProvider(r.provider) ? r.provider : undefined);- if (r.message !== words) update(r.id, { message: words });+ if (r.message !== words) updateIfGoing(r.id, { message: words });}return true;}-/** Copy one result of an account's run, trying again a few times when the copy breaks off (a passing network problem). */-async function persistWithRetry(o: RichOutput, id: string): Promise<OutputFile> {+/**+ * A copy of a made result that broke off for a passing reason: the connection refused, reset or idle, or a 5xx, 429 or+ * 408 answer. Never the whole copy's time limit, nor a file over its size: trying again can't change those.+ */+function passingSave(e: unknown): boolean {+ if (e instanceof AccountFilesFull) return false;+ const msg = (e as Error | null)?.message ?? "";+ if (msg === ACCOUNT_MESSAGES.diskLow || /^The answer was over/.test(msg) || /took over \d+ s to answer/.test(msg)) return false;+ if (/^download (5\d\d|429|408)$/.test(msg)) return true;+ if (e instanceof RemoteFetchError) return /stopped answering|Timed out reaching|Couldn't reach/.test(msg);+ return !!networkReason(e);+}++/** Copy one result of an account's run, trying again once at once when the copy breaks off for a passing reason. */+async function persistWithRetry(o: RichOutput, id: string, linked: Record<string, unknown> | undefined): Promise<OutputFile> {for (let n = 1; ; n++) {try {- return await persistOutput(o, id);+ return await persistOutput(o, id, { linked });} catch (e) {- const msg = (e as Error).message ?? "";- const passing =- !(e instanceof AccountFilesFull) && !/^The answer was over/.test(msg) && msg !== ACCOUNT_MESSAGES.diskLow && (/^download (5\d\d|429|408)$/.test(msg) || e instanceof RemoteFetchError || !!networkReason(e));- if (!passing || n >= 3) throw e;- await new Promise((r) => setTimeout(r, [2_000, 5_000][n - 1] * SELF_HEAL.scale));+ if (!passingSave(e) || n >= 2) throw e;+ await new Promise((r) => setTimeout(r, 2_000 * SELF_HEAL.scale));}}}@@ -2143,9 +2470,14 @@ function saveTrouble(e: unknown, provider: string): Diagnosis | undefined {* Hand a run over to its provider once: its files, then the job. Throws what went wrong (submitNow decides whether to wait* and try again, or to fail the run).*/-async function handOver(id: string, route: ModelRoute, providerId: ProviderId, plan: ReturnType<typeof planGeneration>, req: GenerationRequest, index: number): Promise<void> {+async function handOver(id: string, route: ModelRoute, providerId: ProviderId, plan: ReturnType<typeof planGeneration>, req: GenerationRequest, index: number, sent?: HandOverCache): Promise<void> {/** Why the run failed, once it has: its files still waiting to be sent are not sent. */let failed: { error: unknown } | undefined;+ /** Still this run's to hand over: queued or running, no job yet (a cancel, a failure or another instance stops it). */+ const going = () => {+ const s = statusOf(id);+ return s === "queued" || s === "running";+ };try {// An account's run on its own ComfyUI and keys only (asAccount): outside it, nothing is sent.const adapter = adapterFor(providerId, req.account);@@ -2160,7 +2492,7 @@ async function handOver(id: string, route: ModelRoute, providerId: ProviderId, pif (!req.account) return fn();return accountSend(req.account, async () => {if (failed) throw failed.error;- if (statusOf(id) === "canceled") throw new Error("Stopped");+ if (!going()) throw new Error("Stopped");try {return await fn();} catch (e) {@@ -2169,21 +2501,34 @@ async function handOver(id: string, route: ModelRoute, providerId: ProviderId, p}});};+ // An input an earlier try of this hand-over already sent is used as it was sent (its name or link at the provider):+ // a run that waits and tries again never sends a file twice.+ const upload = async (key: string, data: Buffer, contentType: string, name: string) => {+ const was = sent?.get(key);+ if (was) return was;+ const at = await adapter.prepareFile(data, contentType, name, route);+ sent?.set(key, at);+ return at;+ };const prep = async (ref?: string) => {if (!ref) return undefined;+ const was = sent?.get(`file:${ref}`);+ if (was) return was;return gate(async () => {const f = await readRef(ref);- return adapter.prepareFile(f.data, f.contentType, f.name, route);+ return upload(`file:${ref}`, f.data, f.contentType, f.name);});};// An end-frame step crops the start frame before the edit (the recipe's crop of the subject).const cropWindow = isCropWindow(plan.params.extra?.crop) ? plan.params.extra.crop : undefined;const prepCropped = async (ref?: string) => {if (!ref || !cropWindow) return prep(ref);+ const was = sent?.get(`crop:${ref}`);+ if (was) return was;return gate(async () => {const f = await readRef(ref);const data = cropPicture(f.data, cropWindow);- return adapter.prepareFile(data, "image/png", f.name.replace(/\.[^.]+$/, ".png"), route);+ return upload(`crop:${ref}`, data, "image/png", f.name.replace(/\.[^.]+$/, ".png"));});};// The input clip's header (size, frame rate, length): upscalers that take a factor and frame-count routes read it.@@ -2198,7 +2543,7 @@ async function handOver(id: string, route: ModelRoute, providerId: ProviderId, p...(facts.fps ? { sourceFps: facts.fps } : {}),...(facts.duration ? { sourceDuration: facts.duration } : {}),};- return adapter.prepareFile(f.data, f.contentType, f.name, route);+ return upload(`file:${ref}`, f.data, f.contentType, f.name);});};// A talking avatar is as long as its voice (fal's InfiniteTalk and Wan 2.2 S2V take a frame count): the voice's header.@@ -2208,7 +2553,7 @@ async function handOver(id: string, route: ModelRoute, providerId: ProviderId, pconst f = await readRef(ref);const facts = mediaFacts(f.data);if (facts.duration && !source.sourceDuration) source = { ...source, sourceDuration: facts.duration };- return adapter.prepareFile(f.data, f.contentType, f.name, route);+ return upload(`file:${ref}`, f.data, f.contentType, f.name);});};// A song tool's song (Mureka): its length read as a voice's is, and one Mureka refuses (Stems: MP3 or M4A, 10 MB; Remix:@@ -2221,7 +2566,7 @@ async function handOver(id: string, route: ModelRoute, providerId: ProviderId, pif (facts.duration && !source.sourceDuration) source = { ...source, sourceDuration: facts.duration };const problem = providerId === "mock" ? null : songToolProblem(plan.op, { format: songFormat(f.contentType, f.name), bytes: f.data.length, seconds: facts.duration });if (problem) throw new Error(problem);- return adapter.prepareFile(f.data, f.contentType, f.name, route);+ return upload(`file:${ref}`, f.data, f.contentType, f.name);});};// Reference clips and clip elements a model bills with the output (Kling 4.0, Pricing.clipInput): their headers' lengths.@@ -2234,16 +2579,18 @@ async function handOver(id: string, route: ModelRoute, providerId: ProviderId, pconst f = await readRef(ref);const facts = mediaFacts(f.data);if (facts.duration) clipLengths[i] = facts.duration;- return adapter.prepareFile(f.data, f.contentType, f.name, route);+ return upload(`file:${ref}`, f.data, f.contentType, f.name);});};const prepMask = async (ref?: string) => {if (!ref) return undefined;+ const was = sent?.get(`mask:${ref}`);+ if (was) return was;return gate(async () => {const f = await readRef(ref);const fmt = route.map?.maskFormat;const data = fmt && fmt !== "white" && f.contentType === "image/png" ? convertMask(f.data, fmt) : f.data;- return adapter.prepareFile(data, f.contentType, f.name, route);+ return upload(`mask:${ref}`, data, f.contentType, f.name);});};let prompt = plan.prompt;@@ -2430,30 +2777,49 @@ async function handOver(id: string, route: ModelRoute, providerId: ProviderId, p// gated Restore or Detail Refine IC-LoRA) gets them downloaded too.await ensureLorasOnComfy([...(input.loras ?? []), ...graphLoras(route.endpoint, input.extra)], await comfyLoraFiles(route), (message) => update(id, { message }));}+ // A voice an earlier try had the provider clone (a billed step) is used again, not cloned twice.+ const cloned = sent?.get("voiceEmbedding");+ if (cloned && route.map?.cloneFirst && !input.voiceEmbedding) input.voiceEmbedding = cloned;+ // Nothing is sent once the run stopped being this one's to send (cancelled, failed, or taken by another instance).+ if (!going()) throw new Error("Stopped");const res = await adapter.submit({ generationId: id, model: plan.model, route, input });// A saved voice the cloud just cloned keeps the embedding (the owner's runs only), so its next line skips the clone.if (typeof res.meta?.voiceEmbedding === "string" && !req.account) void keepVoiceEmbedding(req.inputs?.voiceAudio, res.meta.voiceEmbedding).catch(() => {});const now = Date.now();- const status = statusOf(id);- if (!status || status === "canceled") {- // Canceled (or deleted) while it was being handed over: stop the provider's job too.- await adapter.cancel?.({ externalId: res.externalId, meta: res.meta ?? {}, route, model: plan.model, createdAt: now }).catch(() => {});- if (status) update(id, { external_id: res.externalId, external_meta_json: JSON.stringify(res.meta ?? {}), message: null });- return;- }// An account's link: which address the job went to (its name, never the address), so a run whose account moved to// another address meanwhile says so instead of asking the new one about it.const sentTo = req.account && req.place !== "pool" && providerId === "comfyui" ? ownLink()?.url : undefined;- db().transaction(() => {- update(id, {- external_id: res.externalId,- external_meta_json: JSON.stringify({ ...(res.meta ?? {}), ...(sentTo && { sentTo: addressKey(sentTo) }) }),- provider_input_json: res.payload ? JSON.stringify(res.payload).slice(0, 200_000) : null,- // A run sent again after its GPU lost it says so until its GPU reports on it.- message: resentRuns().has(id) ? RESENT_WORDS : "Queued",- });- recordSubmission(id, now);+ const before = readMeta((db().prepare("SELECT external_meta_json FROM generations WHERE id = ?").get(id) as Pick<Row, "external_meta_json"> | undefined)?.external_meta_json);+ // Only onto a run still waiting for its job (never one cancelled, failed or handed over by another instance meanwhile).+ const handed = db().transaction(() => {+ const changed = db()+ .prepare(+ `UPDATE generations SET external_id = @external_id, external_meta_json = @meta, provider_input_json = @payload, message = @message, updated_at = @now+ WHERE id = @id AND ${PENDING}`,+ )+ .run({+ id,+ now,+ external_id: res.externalId,+ meta: JSON.stringify({ ...(res.meta ?? {}), ...(sentTo && { sentTo: addressKey(sentTo) }), jobIndex: index, ...(before.resent && { resent: true }) }),+ payload: res.payload ? JSON.stringify(res.payload).slice(0, 200_000) : null,+ // A run sent again after its GPU lost it says so until its GPU reports on it.+ message: before.resent || resentRuns().has(id) ? RESENT_WORDS : "Queued",+ }).changes;+ if (changed) recordSubmission(id, now);+ return changed > 0;})();+ if (!handed) {+ // Cancelled, failed or deleted while it was being handed over (or another instance sent it): its job stops too.+ await adapter.cancel?.({ externalId: res.externalId, meta: res.meta ?? {}, route, model: plan.model, createdAt: now }).catch(() => {});+ // A cancelled row keeps the job's id (as before), so what was stopped can be found.+ db()+ .prepare("UPDATE generations SET external_id = ?, external_meta_json = ?, message = NULL, updated_at = ? WHERE id = ? AND status = 'canceled' AND external_id IS NULL")+ .run(res.externalId, JSON.stringify(res.meta ?? {}), now, id);+ return;+ }+ // The provider took a run on the account's key: a refusal or an empty balance noted before is over.+ if (req.account && req.place !== "pool" && isCloudProvider(providerId)) markKeyGood(req.account, providerId);} catch (e) {failed ??= { error: e };throw e;@@ -2472,8 +2838,8 @@ const TIMEOUT_MS = 45 * 60 * 1000;const WORLDCAST_TIMEOUT_MS = 3 * 60 * 60 * 1000;/** …and how long it may wait in the provider's queue first (a busy local GPU works through jobs one by one). */const QUEUE_TIMEOUT_MS = 4 * 60 * 60 * 1000;-/** A row this old with no external id, that no submit in this process is working on, was cut off by a restart. */-const STALE_SUBMIT_MS = 2 * 60 * 1000;+/** A row this old with no external id that no instance holds (LEASE) was cut off by a restart: a wait goes on, a hand-over fails. */+export const STALE_SUBMIT = { ms: 2 * 60 * 1000 };interface RunnerState {timer: NodeJS.Timeout;@@ -2509,6 +2875,7 @@ export function ensureRunner(): void {function startRunner(): void {watchGenerations(db());+ keepLeases();const cur = globalThis.__fuobeRunner;if (cur) {// After a dev hot-reload, point the existing timers at this module's (fresh) code.@@ -2538,16 +2905,80 @@ function startRunner(): void {resumeTurntables();}-/** Jobs that never got an external id (the server died mid-submit) can't be recovered. Runs every tick. */+/**+ * Runs with no job yet that no instance holds any more (none renewed its hold: a restart, or a deploy's old instance gone).+ * One waiting for its own GPU or key goes on here, with what is left of its wait (one instance takes it); one cut off in+ * the middle of its hand-over can't be recovered, and fails. Runs at start and every tick.+ */function sweepInterrupted(): void {+ const now = Date.now();const rows = db()- .prepare("SELECT id FROM generations WHERE status IN ('queued','running') AND external_id IS NULL AND depends_on IS NULL AND created_at < ?")- .all(Date.now() - STALE_SUBMIT_MS) as Pick<Row, "id">[];+ .prepare("SELECT id, request_json, external_meta_json FROM generations WHERE status IN ('queued','running') AND external_id IS NULL AND depends_on IS NULL AND created_at < ?")+ .all(now - STALE_SUBMIT.ms) as Pick<Row, "id" | "request_json" | "external_meta_json">[];const busy = submitting();for (const r of rows) {if (busy.has(r.id)) continue;- update(r.id, { status: "failed", error: "This run stopped before it started. Press Retry.", completed_at: Date.now(), message: null });+ const meta = readMeta(r.external_meta_json);+ // An instance that is alive holds it (this one's renewals included).+ if (meta.lease && typeof meta.lease.until === "number" && meta.lease.until > now) continue;+ if (meta.heal && takeOver(r, meta.heal)) continue;+ updateIfGoing(r.id, { status: "failed", error: "This run stopped before it started. Press Retry.", completed_at: Date.now(), message: null }, " AND external_id IS NULL");+ }+}++/**+ * A waiting run no instance holds any more: taken by this one, planned again as its account runs now (its GPU, its keys),+ * and its wait goes on where it was (its budget and its tries kept). False: it isn't one this can take.+ */+function takeOver(r: Pick<Row, "id" | "request_json">, h: HealState): boolean {+ let stored: GenerationRequest;+ try {+ stored = JSON.parse(r.request_json) as GenerationRequest;+ } catch {+ return false;}+ const account = stored.account;+ if (!account || stored.place === "pool") return false;+ // Another instance took it first.+ if (!claim(r.id)) return true;+ let p: ReturnType<typeof prepare>;+ try {+ p = asAccount(account, () => prepare(stored));+ } catch (e) {+ // It can't run as the account runs now (its key removed, its model switched off): said in its own words.+ const refusal = e instanceof AccountRunError ? e.refusal.error : (e as Error).message;+ updateIfGoing(r.id, { status: "failed", error: refusal, completed_at: Date.now(), message: null }, " AND external_id IS NULL");+ return true;+ }+ submitting().add(r.id);+ void submit(r.id, p.route, p.providerId, p.plan, p.req, typeof h.index === "number" ? h.index : 0, h);+ return true;+}++declare global {+ /** The renewal of this instance's holds (pointed at the newest code after a hot reload). */+ var __fuobeLeaseRenew: (() => void) | undefined;+}++/**+ * Renew this instance's holds every LEASE.renewMs. Not one of the runners a stopping server stops (shutdown.ts): a+ * hand-over under way keeps its hold until it lands; a wait hands itself over (pause stops it).+ */+function keepLeases(): void {+ globalThis.__fuobeLeaseRenew = renewLeases;+ if (globalThis.__fuobeLeaseTimer) return;+ const next = () => {+ globalThis.__fuobeLeaseTimer = setTimeout(() => {+ try {+ globalThis.__fuobeLeaseRenew?.();+ } catch {+ // A busy database: the next renewal comes well before a hold runs out.+ }+ next();+ }, LEASE.renewMs);+ globalThis.__fuobeLeaseTimer.unref?.();+ };+ next();}async function pollGuarded(r: Row): Promise<void> {@@ -2677,12 +3108,15 @@ async function pollOne(r: Row): Promise<void> {const now = gpuLink(accountGpu(own));if (now && addressKey(now.url) !== ctx.meta.sentTo) {pollHeals().delete(r.id);- return failRun(r.id, new Error("moved"), diagnoseGpuJob({ kind: "moved" }, { kind: "link", url: now.url }), own);+ failRun(r.id, new Error("moved"), diagnoseGpuJob({ kind: "moved" }, { kind: "link", url: now.url }), own, factsOf(r, { stage: "poll" }));+ return;}}- // A poll that failed a moment ago waits its turn (a growing wait), instead of asking every 1.5 s.+ // A poll that failed a moment ago waits its turn (a growing wait), instead of asking every 1.5 s; so does a made result+ // whose copy broke off (it is copied again at the next poll).const healing = own ? pollHeals().get(r.id) : undefined;if (healing && Date.now() < healing.next) return;+ if (own && typeof ctx.meta.saveNext === "number" && Date.now() < ctx.meta.saveNext) return;try {res = await adapterFor(r.provider, account).poll(ctx);} catch (e) {@@ -2690,7 +3124,14 @@ async function pollOne(r: Row): Promise<void> {}if (own && pollError && (await healPoll(r, ctx, own, pollError))) {if (statusOf(r.id) !== "queued" && statusOf(r.id) !== "running") return;- } else if (own && !pollError) pollHeals().delete(r.id);+ } else if (own && !pollError) {+ const was = pollHeals().get(r.id);+ pollHeals().delete(r.id);+ if (was) recordOwnRun({ run: r.id, account: own, ...factsOf(r, { stage: "poll", attempt: was.n, waitedMs: Date.now() - was.first }), outcome: "healed" });+ // Its GPU answered: the status strip and the next run take it as online (one slow status check doesn't say otherwise).+ const link = r.provider === "comfyui" ? ownLink() : null;+ if (link) noteHandedOver(own, link.url);+ }// An account's job waits at most 30 minutes in its own ComfyUI's queue (or its provider's).const stored = JSON.parse(r.request_json) as GenerationRequest;const onPool = !!account && stored.place === "pool";@@ -2706,26 +3147,54 @@ async function pollOne(r: Row): Promise<void> {// A job that has just left the queue gets its full running time from now.const startsNow = res?.state === "running" && !run.started_at;const runMs = r.provider === "worldcast" ? WORLDCAST_TIMEOUT_MS : TIMEOUT_MS;- const overdue = run.started_at ? now - run.started_at > runMs : !startsNow && now - run.submitted_at > queueMs;+ // An account's own GPU (or its provider) whose queue keeps moving: the job waits on. Only a queue that hasn't moved+ // for the limit, or one waited in for 2 hours, ends it.+ const ownQueue = !!own && !onPool;+ let movedAt = typeof ctx.meta.queueMovedAt === "number" ? ctx.meta.queueMovedAt : run.submitted_at;+ const pos = res?.state === "queued" && typeof res.position === "number" ? res.position : undefined;+ if (ownQueue && pos !== undefined && (typeof ctx.meta.queuePos !== "number" || pos < ctx.meta.queuePos)) {+ movedAt = now;+ db()+ .prepare("UPDATE generations SET external_meta_json = json_set(CASE WHEN json_valid(external_meta_json) THEN external_meta_json ELSE '{}' END, '$.queuePos', @pos, '$.queueMovedAt', @now) WHERE id = @id AND external_id IS NOT NULL")+ .run({ id: r.id, pos, now });+ }+ const queueOver = ownQueue+ ? now - Math.max(run.submitted_at, movedAt) > queueMs * OWN_QUEUE.scale || now - run.submitted_at > OWN_QUEUE_CAP_MS * OWN_QUEUE.scale+ : now - run.submitted_at > queueMs;+ const overdue = run.started_at ? now - run.started_at > runMs : !startsNow && queueOver;if (overdue) {// Stop the provider's job too, so it doesn't keep rendering (or billing) for nothing.- await adapterFor(r.provider, account)- .cancel?.(ctx)- .catch(() => {});- update(r.id, {- status: "failed",- error: run.started_at- ? `Timed out after ${runMs / 60_000} minutes`- : res?.state === "queued" && res.timeoutError- ? res.timeoutError- : onPool- ? POOL_WAITED- : account- ? `This waited over ${queueMs / 60_000} minutes to start. Press Retry.`- : "This took too long to start. Press Retry.",- completed_at: now,- message: null,- });+ const cancel = () =>+ adapterFor(r.provider, account)+ .cancel?.(ctx)+ .catch(() => {});+ const words = run.started_at+ ? `Timed out after ${runMs / 60_000} minutes`+ : res?.state === "queued" && res.timeoutError+ ? res.timeoutError+ : onPool+ ? POOL_WAITED+ : account+ ? `This waited over ${queueMs / 60_000} minutes to start. Press Retry.`+ : "This took too long to start. Press Retry.";+ if (ownQueue) {+ // An account's own GPU or key: why, in plain words, with what helps.+ const waited = Math.max(1, Math.round((now - run.submitted_at) / 60_000));+ const link = r.provider === "comfyui" ? ownLink() : null;+ const ctxKey = isCloudProvider(r.provider) ? { provider: r.provider, other: otherKeyFor(own!, r.provider, r.model_id) } : null;+ const d: Diagnosis | undefined =+ res?.state === "queued" && res.timeoutError+ ? { cause: "gpu-offline", words: res.timeoutError, actions: [{ kind: "retry", label: "Retry" }, ...(/paired/i.test(res.timeoutError) ? [{ kind: "pair" as const, label: "Pair with a code", target: "/connect" }] : [])], retryable: false }+ : ctxKey+ ? diagnoseKeyJob(run.started_at ? { kind: "too-long", minutes: runMs / 60_000 } : { kind: "busy", minutes: waited }, ctxKey)+ : r.provider === "comfyui"+ ? diagnoseGpuJob(run.started_at ? { kind: "too-long", minutes: runMs / 60_000 } : { kind: "busy", minutes: waited }, link ?? { kind: "computer" })+ : undefined;+ if (failRun(r.id, new Error(words), d, own, factsOf(r, { stage: "poll", waitedMs: now - run.submitted_at }))) await cancel();+ return;+ }+ await cancel();+ updateIfGoing(r.id, { status: "failed", error: words, completed_at: now, message: null });return;}if (!res) {@@ -2751,8 +3220,12 @@ async function pollOne(r: Row): Promise<void> {): undefined);// What the GPU was missing (a model, a node class): the tile offers "Fix it", and the GPU's check counts as stale.- const kept = keptFix(res.fix, own ? trouble : undefined);- update(r.id, { status: "failed", error: (own && trouble?.words) || res.error, completed_at: Date.now(), message: null, ...(kept && { fix_json: kept }) });+ if (own) {+ failRun(r.id, Object.assign(new Error(res.error), { said: res.error, ...(res.fix && { fix: res.fix }) }), trouble, own, factsOf(r, { stage: "poll" }));+ return;+ }+ const kept = keptFix(res.fix, undefined);+ updateIfGoing(r.id, { status: "failed", error: res.error, completed_at: Date.now(), message: null, ...(kept && { fix_json: kept }) });if (res.fix) markStale(account ? `acct:${account}` : "install");return;}@@ -2799,8 +3272,10 @@ async function pollOne(r: Row): Promise<void> {} else {for (const o of keepMatte(res.outputs as RichOutput[], matte)) {try {- // An account's own GPU or key: a copy that breaks off is tried again a few times (the result is made, and paid).- outputs.push(await (own ? persistWithRetry(o, r.id) : persistOutput(o, r.id)));+ // An account's own GPU or key: a copy that breaks off is tried again (the result is made, and paid). The files a+ // result links to are kept once, before (never fetched again with each try of the main file).+ const linked = own ? await persistArtifacts(o.meta, r.id, o.url) : undefined;+ outputs.push(await (own ? persistWithRetry(o, r.id, linked) : persistOutput(o, r.id)));} catch (e) {if (account) {for (const kept of outputs) if (kept.assetId) deleteAsset(kept.assetId);@@ -2809,11 +3284,34 @@ async function pollOne(r: Row): Promise<void> {const left = rest.url ? scratchOutputFile(rest.url) : null;if (left) fs.rmSync(left, { force: true });}+ // Its own GPU or key, a copy that broke off for a passing reason (the GPU or the provider dropped it for a+ // while): copied again at a later poll, with a growing wait, for some minutes. The tile says so.+ if (own && passingSave(e)) {+ const at = Date.now();+ const since = typeof ctx.meta.saveSince === "number" ? ctx.meta.saveSince : at;+ const tries = (typeof ctx.meta.saveTries === "number" ? ctx.meta.saveTries : 0) + 1;+ if (at - since < SAVE_HEAL_MS * SELF_HEAL.scale) {+ const next = at + backoffMs(tries, { budgetMs: 0, firstMs: 5_000, maxMs: 60_000 }) * SELF_HEAL.scale;+ const words = r.provider === "comfyui" ? "Your result is made. Copying it from your GPU" : `Your result is made. Copying it from ${isCloudProvider(r.provider) ? CLOUD_KEY[r.provider].label : "the provider"}`;+ db()+ .prepare(+ `UPDATE generations SET message = @words, updated_at = @at,+ external_meta_json = json_set(CASE WHEN json_valid(external_meta_json) THEN external_meta_json ELSE '{}' END, '$.saveSince', @since, '$.saveTries', @tries, '$.saveNext', @next)+ WHERE id = @id AND status = 'running'`,+ )+ .run({ id: r.id, words, at, since, tries, next });+ if (tries === 1) ownEvent(r.id, own, e, saveTrouble(e, r.provider), factsOf(r, { stage: "result", attempt: 1 }), "waiting");+ return;+ }+ }// Its own GPU or key: why, and what helps (a file over the cap, an expired link, a GPU that went away).const trouble = own && !(e instanceof AccountFilesFull) ? saveTrouble(e, r.provider) : undefined;const why = e instanceof AccountFilesFull ? e.message : (trouble?.words ?? "We couldn't save this result. Press Retry.");- const kept = keptFix(undefined, trouble);- update(r.id, { status: "failed", error: why, completed_at: Date.now(), message: null, ...(kept && { fix_json: kept }) });+ if (own) failRun(r.id, Object.assign(new Error(why), { said: (e as Error).message }), trouble, own, factsOf(r, { stage: "result" }));+ else {+ const kept = keptFix(undefined, trouble);+ updateIfGoing(r.id, { status: "failed", error: why, completed_at: Date.now(), message: null, ...(kept && { fix_json: kept }) });+ }return;}outputs.push({ url: o.url, kind: o.kind ?? r.kind, ...inlineText(o.text, o.meta), ...(o.draftId ? { draftId: o.draftId } : {}) });@@ -3157,8 +3655,9 @@ async function persistRelayOutput(o: RichOutput, generationId: string, account:};}-async function persistOutput(o: RichOutput, generationId: string): Promise<OutputFile> {- const linked = await persistArtifacts(o.meta, generationId, o.url);+/** Save one result. `pre`: the files it links to, kept already (persistArtifacts runs once for a copy tried again). */+async function persistOutput(o: RichOutput, generationId: string, pre?: { linked: Record<string, unknown> | undefined }): Promise<OutputFile> {+ const linked = pre ? pre.linked : await persistArtifacts(o.meta, generationId, o.url);const account = tenantAccount();if (o.url?.startsWith("relay:") || o.url?.startsWith("scratch:")) return persistRelayOutput(o, generationId, account, linked);if (account && o.url && /^https?:\/\//.test(o.url)) return persistAccountOutput(o, generationId, account, linked);diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex 5d04c8f9..98cb3ba3 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -108,6 +108,7 @@ import { discardBody, fetchPublic, peekText, RemoteFetchError } from "../remote-import { zipToFile } from "../zip";import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "../account-files";import { accountSend } from "../account-send";+import { redactKey } from "../provider-keys";import { outsideTenant, runAsTenant, tenantAccount } from "../tenant";import { ask, checkReach, reachSync, sharedCheck, type Reach } from "./reach";import { ProviderError, type PollResult, type ProviderAdapter, type RemoteOutput } from "./types";@@ -303,17 +304,23 @@ export const OWN_FRAME_MAX_BYTES = 100 * 2 ** 20;/*** What an account's ComfyUI may answer, by path: a file (/view) up to 1 GB in 15 minutes; an upload's answer 1 MB, in- * 5 minutes (the time covers sending the file); the node list (/object_info) 64 MB in 2 minutes; anything else 8 MB in- * 60 seconds. A slow or endless answer can't hold the server.+ * the time sending its file takes at a slow 128 KB/s plus a minute (5 to 30 minutes: the time covers sending the file);+ * the node list (/object_info) 64 MB in 2 minutes; anything else 8 MB in 60 seconds. A slow or endless answer can't+ * hold the server.*/-export function ownGpuLimits(p: string): { maxBytes: number; deadlineMs: number } {+export function ownGpuLimits(p: string, bytes = 0): { maxBytes: number; deadlineMs: number } {const at = p.split("?")[0];if (at.startsWith("/view")) return OWN_OUTPUT_LIMITS;- if (at.startsWith("/upload/")) return { maxBytes: 2 ** 20, deadlineMs: 5 * 60_000 };+ if (at.startsWith("/upload/")) return { maxBytes: 2 ** 20, deadlineMs: uploadDeadlineMs(bytes) };if (at.startsWith("/object_info")) return { maxBytes: 64 * 2 ** 20, deadlineMs: 2 * 60_000 };return { maxBytes: 8 * 2 ** 20, deadlineMs: 60_000 };}+/** How long sending a file of `bytes` to an account's ComfyUI may take: 128 KB/s plus a minute, between 5 and 30 minutes. */+export function uploadDeadlineMs(bytes: number): number {+ return Math.min(30 * 60_000, Math.max(5 * 60_000, Math.ceil((Math.max(0, bytes) / (128 * 1024)) * 1000) + 60_000));+}+/** A job id as ComfyUI gives it (a UUID): anything else from an account's ComfyUI is refused, never put in a path. */export const PROMPT_ID = /^[\w-]{1,64}$/;@@ -365,8 +372,19 @@ export function troubleError(d: Diagnosis, status?: number, failure?: GpuFailurereturn Object.assign(new ProviderError(d.words, status), { trouble: d, ...(failure && { failure }) });}-/** What came back from an account's link, read for the person (diagnose.ts), as the run's error. */-const gpuTrouble = (f: GpuFailure, place: Parameters<typeof diagnoseGpu>[1]) => troubleError(diagnoseGpu(f, place), f.status, f);+/** What came back from an account's link, read for the person (diagnose.ts), as the run's error. Its token never in it. */+const gpuTrouble = (f: GpuFailure, place: Parameters<typeof diagnoseGpu>[1]) => {+ const own = ownGpu();+ const token = own && own.kind !== "computer" ? own.token : undefined;+ const clean = token ? withoutToken(f, token) : f;+ return troubleError(diagnoseGpu(clean, place), clean.status, clean);+};++/** What came back, with a token it echoed taken out (a page that repeats the request's headers). */+export function withoutToken(f: GpuFailure, token: string): GpuFailure {+ const out = (t: string | undefined) => (t === undefined ? t : redactKey(t, token));+ return { ...f, body: out(f.body), error: out(f.error), location: out(f.location) };+}/** An answer from an account's link that isn't what was asked: read for the person (its body's first KB, for details). */async function linkAnswer(res: Response, f: Omit<GpuFailure, "status" | "body" | "contentType" | "location" | "retryAfterS">, link: NonNullable<ReturnType<typeof ownLink>>): Promise<ProviderError> {@@ -395,7 +413,8 @@ async function comfyFetch(p: string, init: RequestInit = {}, worker: ComfyWorker// A visitor without a GPU of its own (a price check): nothing to reach, and never the install's.if (!base) throw new ProviderError(CONNECT_GPU_MESSAGE);try {- return await fetchPublic(`${base}${p}`, { ...init, headers: { "ngrok-skip-browser-warning": "1", ...authHeaders(worker), ...(init.headers ?? {}) } }, { timeoutMs: 120_000, ...ownGpuLimits(p) });+ // A connection that doesn't open in 15 s is a GPU that doesn't answer (the idle time, 2 minutes, is for a slow one).+ return await fetchPublic(`${base}${p}`, { ...init, headers: { "ngrok-skip-browser-warning": "1", ...authHeaders(worker), ...(init.headers ?? {}) } }, { timeoutMs: 120_000, connectTimeoutMs: 15_000, ...ownGpuLimits(p, o.bytes) });} catch (e) {// The account's words (a stopped pod, a GPU that doesn't answer…); the reason itself goes in the details line.throw gpuTrouble({ stage: stageOf(p), error: (e as Error).message, bytes: o.bytes }, ownLink() ?? { kind: "link", url: base });@@ -2664,17 +2683,20 @@ export function planRelayOutputs(t: Pick<TaskRow, "id" | "workflow_id" | "meta_breturn { wanted, outputs, budget: Number.isFinite(budget) ? budget : Number.MAX_SAFE_INTEGER };}+/** An account's ComfyUI that refused a job without saying why: plain words (the owner's keep the status). */+const REFUSED_PLAIN = "Your ComfyUI couldn't start this run. Update your add-ons, then press Retry.";+/** A task's error as the run's words (and what was missing, for "Fix it"). */function relayFailure(t: TaskRow, manifest: ManifestWorkflow | undefined): { error: string; fix?: GenerationFix } {const refusal = refusalOf(t);if (refusal && manifest) {const r = promptRefusal((refusal.body ?? {}) as PromptRefusalBody, refusal.status, manifest, extraOf(t).loras ?? []);- return { error: r.message ?? `Your ComfyUI refused the job (HTTP ${refusal.status})`, ...(r.fix && { fix: r.fix }) };+ return { error: r.message ?? (tenantAccount() ? REFUSED_PLAIN : `Your ComfyUI refused the job (HTTP ${refusal.status})`), ...(r.fix && { fix: r.fix }) };}- if (refusal) return { error: `Your ComfyUI refused the job (HTTP ${refusal.status})` };+ if (refusal) return { error: tenantAccount() ? REFUSED_PLAIN : `Your ComfyUI refused the job (HTTP ${refusal.status})` };const e = t.error ?? "";const tab = /^tab:([a-z-]+)(?::(\d+))?$/.exec(e);- if (tab) return { error: tabFailureWords(tab[1] as TabFailure, tab[2] ? Number(tab[2]) : undefined) };+ if (tab) return { error: tabFailureWords(tab[1] as TabFailure, tab[2] ? Number(tab[2]) : undefined, !!tenantAccount()) };const words: Record<string, string> = { lost: RELAY_WORDS.lost, silent: RELAY_WORDS.computerSilent, down: RELAY_WORDS.comfyDownTooLong, tooBig: RELAY_WORDS.tooBig };if (e === "full") {const account = tenantAccount();@@ -2958,7 +2980,7 @@ export const comfyProvider: ProviderAdapter = {return { state: "failed", error: "ComfyUI restarted and lost this run. Press Retry." };}globalThis.__fuobeComfyMisses?.delete(externalId);- if (pendingIdx >= 0) return { state: "queued", message: pendingIdx === 0 ? "Next in ComfyUI's queue" : `In ComfyUI's queue · ${pendingIdx} ahead` };+ if (pendingIdx >= 0) return { state: "queued", position: pendingIdx, message: pendingIdx === 0 ? "Next in ComfyUI's queue" : `In ComfyUI's queue · ${pendingIdx} ahead` };const total = Number(meta.nodeCount ?? 0);const stepFrac = p && p.max ? p.value / p.max : 0;const progressValue = total ? Math.min(0.99, ((p?.nodesDone ?? 0) - 1 + stepFrac) / total) : stepFrac || undefined;diff --git a/src/server/providers/fal.ts b/src/server/providers/fal.tsindex 828771f7..039806c1 100644--- a/src/server/providers/fal.ts+++ b/src/server/providers/fal.ts@@ -47,7 +47,7 @@ const falRun = () => standIn("fal") ?? RUN;*/async function uploadSong(upload: { endpoint: string; purpose: string }, fileUrl: string): Promise<string> {const res = (await falFetch(`${falRun()}/${upload.endpoint}`, { method: "POST", body: JSON.stringify({ file_url: fileUrl, purpose: upload.purpose }) })) as { id?: unknown };- if (typeof res?.id !== "string" || !res.id) throw new ProviderError("The song couldn't be sent to Mureka: try again");+ if (typeof res?.id !== "string" || !res.id) throw Object.assign(new ProviderError("We couldn't send the song. Press Retry."), { said: "Mureka gave no file id" });return res.id;}@@ -158,13 +158,21 @@ function key(): string {return cloudKey("fal");}+/**+ * How long a call to fal.ai may take: a submit or a result 60 s, a status or a cancel 20 s. A hung call fails (a status is+ * asked again later; a submit isn't sent twice by itself, as its job may exist) instead of holding the run for minutes.+ */+export const FAL_CALL_MS = { long: 60_000, short: 20_000 };+export async function falFetch(url: string, init: RequestInit = {}): Promise<unknown> {const k = key();if (!k && tenant()) throw missingKeyError("fal");// A status, result or cancel address is the one fal.ai gave at submit: the key goes to fal.ai's own hosts only.if (!keyOrigin(url)) throw new ProviderError("fal.ai gave an address outside fal.ai, so Fuobe didn't send the key there");+ const short = /\/(status|cancel)(\?|$)/.test(url) || init.method === "PUT";const res = await fetch(url, {...init,+ signal: init.signal ?? AbortSignal.timeout(short ? FAL_CALL_MS.short : FAL_CALL_MS.long),headers: { Authorization: `Key ${k}`, "Content-Type": "application/json", ...(init.headers ?? {}) },});const text = await res.text();@@ -225,7 +233,8 @@ export async function cloneVoice(cf: NonNullable<FieldMap["cloneFirst"]>, audio:for (let wait = 500; ; wait = Math.min(wait * 1.5, 3000)) {const st = (await falFetch(job.status_url)) as { status?: string; error?: string };if (st.status === "COMPLETED") {- if (st.error) throw new ProviderError(`Couldn't clone the voice: ${st.error}`);+ // fal.ai's own words go to the run's details line; the sentence is plain.+ if (st.error) throw Object.assign(new ProviderError("We couldn't copy this voice. Try a longer, clearer sample, or press Retry."), { said: st.error });break;}if (Date.now() + wait > until) throw new ProviderError("Cloning the voice took too long. Try again.");@@ -278,7 +287,11 @@ export const falProvider: ProviderAdapter = {const song = map.songSource;if (song && payload[song.songId] === undefined) {if (!input.audio) throw new ProviderError("Add the song");- payload[song.uploadId] = await uploadSong(song.upload, input.audio);+ try {+ payload[song.uploadId] = await uploadSong(song.upload, input.audio);+ } catch (e) {+ throw embedding && e && typeof e === "object" ? Object.assign(e, { voiceEmbedding: embedding }) : e;+ }}let endpoint: string;try {@@ -286,10 +299,13 @@ export const falProvider: ProviderAdapter = {} catch (e) {throw new ProviderError((e as Error).message);}- const res = (await falFetch(`${falQueue()}/${endpoint}`, {- method: "POST",- body: JSON.stringify(payload),- })) as { request_id: string; status_url: string; response_url: string; cancel_url: string };+ let res: { request_id: string; status_url: string; response_url: string; cancel_url: string };+ try {+ res = (await falFetch(`${falQueue()}/${endpoint}`, { method: "POST", body: JSON.stringify(payload) })) as typeof res;+ } catch (e) {+ // The voice it cloned (a billed step) goes with the error: a try again of this run uses it, never clones twice.+ throw embedding && e && typeof e === "object" ? Object.assign(e, { voiceEmbedding: embedding }) : e;+ }return {externalId: res.request_id,meta: { statusUrl: res.status_url, responseUrl: res.response_url, cancelUrl: res.cancel_url, ...(embedding && { voiceEmbedding: embedding }) },@@ -305,7 +321,7 @@ export const falProvider: ProviderAdapter = {error?: string;};if (status.status === "IN_QUEUE") {- return { state: "queued", message: status.queue_position != null ? `In queue · position ${status.queue_position + 1}` : "In queue" };+ return { state: "queued", ...(status.queue_position != null && { position: status.queue_position }), message: status.queue_position != null ? `In queue · position ${status.queue_position + 1}` : "In queue" };}if (status.status === "IN_PROGRESS") {const last = status.logs?.at(-1)?.message;@@ -331,6 +347,8 @@ export const falProvider: ProviderAdapter = {const s = (e as { status?: number }).status;if (tenantAccount() && e instanceof ProviderError && (s === 429 || (s !== undefined && s >= 500) || (s === undefined && /fetch failed|ECONN|ETIMEDOUT|ENOTFOUND/i.test(e.message)))) throw e;if (tenantAccount() && e instanceof TypeError && /fetch failed/i.test(e.message)) throw e;+ // A result call that hung past its time: asked again too.+ if (tenantAccount() && (e as Error | null)?.name === "TimeoutError") throw e;return { state: "failed", error: (e as Error).message };}}diff --git a/src/server/providers/replicate.ts b/src/server/providers/replicate.tsindex 80e1f20f..b72979bd 100644--- a/src/server/providers/replicate.ts+++ b/src/server/providers/replicate.ts@@ -31,8 +31,11 @@ async function rFetch(url: string, init: RequestInit = {}): Promise<unknown> {if (!t && tenant()) throw missingKeyError("replicate");const origin = originOf(url);if (origin !== HOST && origin !== standIn("replicate")) throw new ProviderError("That address is outside Replicate, so Fuobe didn't send the token there");+ // A hung call fails in time (a submit or a file 60 s; a status or a cancel 20 s), never holding a run for minutes.+ const short = !init.method || init.method === "GET" || /\/cancel$/.test(url);const res = await fetch(url, {...init,+ signal: init.signal ?? AbortSignal.timeout(short ? 20_000 : 60_000),headers: { Authorization: `Bearer ${t}`, ...(init.body instanceof FormData ? {} : { "Content-Type": "application/json" }), ...(init.headers ?? {}) },});const text = await res.text();diff --git a/src/server/providers/types.ts b/src/server/providers/types.tsindex 0568e529..c57009a7 100644--- a/src/server/providers/types.ts+++ b/src/server/providers/types.ts@@ -35,7 +35,7 @@ export interface RemoteOutput {* what was missing when it failed (`fix`: the tile's "Fix it").*/export type PollResult =- | { state: "queued"; progress?: number; message?: string; sentAt?: number; timeoutError?: string }+ | { state: "queued"; progress?: number; message?: string; sentAt?: number; timeoutError?: string; /** Jobs ahead of it in the queue (0: next). */ position?: number }| { state: "running"; progress?: number; message?: string; sentAt?: number }| { state: "succeeded"; outputs: RemoteOutput[]; message?: string }/**diff --git a/src/server/remote-fetch.ts b/src/server/remote-fetch.tsindex 75d78126..0c81afce 100644--- a/src/server/remote-fetch.ts+++ b/src/server/remote-fetch.ts@@ -96,6 +96,11 @@ declare global {var __fuobeSelfAddresses: { at: number; set: Set<string> } | undefined;/** Tests only: the port of a stand-in ComfyUI an account may use on this machine (see loopbackGpuPort). */var __fuobeTestGpuPort: number | undefined;+ /**+ * Tests only: web addresses (a RunPod pod's, a tunnel's) that reach the stand-in ComfyUI at this port on this machine,+ * over plain http (see testGpuHost), so a test runs the real address's words without calling it.+ */+ var __fuobeTestGpuHosts: Record<string, number> | undefined;}/** An address as compared: IPv4 as it is, IPv6 as 8 hextets (no zone). */@@ -189,8 +194,19 @@ export function loopbackGpuPort(): number | null {return typeof v === "number" && Number.isInteger(v) && v >= 1024 && v <= 65535 && !RESERVED_PORTS.includes(v) ? v : null;}+/**+ * Tests only (vitest, never a live server): the port of the stand-in that a named address (a RunPod pod's, a tunnel's)+ * stands for, from globalThis.__fuobeTestGpuHosts; null anywhere else.+ */+export function testGpuHost(u: URL): number | null {+ if (process.env.NODE_ENV === "production" || process.env.VITEST !== "true") return null;+ const port = globalThis.__fuobeTestGpuHosts?.[u.hostname.toLowerCase()];+ return typeof port === "number" && Number.isInteger(port) && port >= 1024 && port <= 65535 && !RESERVED_PORTS.includes(port) ? port : null;+}+/** An address that is the stand-in ComfyUI of loopbackGpuPort: http://localhost or http://127.0.0.1 at exactly that port. */export function isLoopbackGpu(u: URL): boolean {+ if (testGpuHost(u) !== null) return true;const port = loopbackGpuPort();const host = u.hostname.replace(/^\[|\]$/g, "").toLowerCase();return port !== null && u.protocol === "http:" && (host === "localhost" || host === "127.0.0.1") && Number(u.port) === port;@@ -360,6 +376,8 @@ export interface PublicFetchOptions extends Pick<RemoteFetchOptions, "resolve" |deadlineMs?: number;/** The most the answer's body may hold (default 8 MiB): past it, reading the body fails. */maxBytes?: number;+ /** How long the connection may take to open (none: only the idle time): past it, the address doesn't answer. */+ connectTimeoutMs?: number;}export const PUBLIC_FETCH_MAX_BYTES = 8 * 2 ** 20;@@ -402,10 +420,13 @@ export async function peekText(res: Response, maxBytes = 4096, ms = 2000): Promiconst mbOf = (n: number) => (n >= 2 ** 30 ? `${Math.round(n / 2 ** 30)} GB` : `${Math.max(1, Math.round(n / 2 ** 20))} MB`);export async function fetchPublic(url: string, init: RequestInit = {}, o: PublicFetchOptions = {}): Promise<Response> {- const target = new URL(url);+ const named = new URL(url);+ // Tests only: a named address that stands for the stand-in ComfyUI on this machine (its own name in the messages).+ const standIn = testGpuHost(named);+ const target = standIn === null ? named : new URL(`http://127.0.0.1:${standIn}${named.pathname}${named.search}`);if (target.protocol !== "http:" && target.protocol !== "https:") throw new RemoteFetchError(`Only http(s) addresses, not ${target.protocol}`);// A stand-in ComfyUI on this machine (tests and `next dev` only): loopback, and nothing else, for this request.- const blocked = o.blocked ?? (isLoopbackGpu(target) ? (ip: string) => !LOOPBACK.has(ip) : blockedForAccounts);+ const blocked = o.blocked ?? (standIn !== null || isLoopbackGpu(target) ? (ip: string) => !LOOPBACK.has(ip) : blockedForAccounts);const maxBytes = o.maxBytes ?? PUBLIC_FETCH_MAX_BYTES;const deadlineMs = o.deadlineMs ?? 60_000;const resolve = o.resolve ?? (async (host: string) => (await dns.lookup(host, { all: true, verbatim: true })).map((a) => a.address));@@ -446,7 +467,7 @@ export async function fetchPublic(url: string, init: RequestInit = {}, o: Publicsettle(e);};// The whole exchange, not only the idle time: a ComfyUI that drips a byte at a time can't hold a request open.- const deadline = setTimeout(() => fail(new RemoteFetchError(`${target.host} took over ${Math.round(deadlineMs / 1000)} s to answer`)), deadlineMs);+ const deadline = setTimeout(() => fail(new RemoteFetchError(`${named.host} took over ${Math.round(deadlineMs / 1000)} s to answer`)), deadlineMs);deadline.unref?.();const req = (target.protocol === "https:" ? https : http).request(target, { method: asked.method, headers, lookup, timeout: o.timeoutMs ?? 60_000 }, (res) => {const status = res.statusCode ?? 0;@@ -483,7 +504,7 @@ export async function fetchPublic(url: string, init: RequestInit = {}, o: Public});const stream = counted;res.on("error", (e) => stream.destroy(e));- res.on("aborted", () => stream.destroy(new RemoteFetchError(`${target.host} stopped answering`)));+ res.on("aborted", () => stream.destroy(new RemoteFetchError(`${named.host} stopped answering`)));// Read to its end, failed, or let go by the caller (discardBody): the connection closes at once, never held// open until the deadline.stream.on("close", () => {@@ -493,9 +514,20 @@ export async function fetchPublic(url: string, init: RequestInit = {}, o: Publicres.pipe(stream);settle(undefined, new Response(Readable.toWeb(stream) as ReadableStream<Uint8Array>, { status, statusText: res.statusMessage, headers: out }));});- req.on("timeout", () => req.destroy(new RemoteFetchError(`Timed out reaching ${target.host}`)));+ req.on("timeout", () => req.destroy(new RemoteFetchError(`Timed out reaching ${named.host}`)));+ // A connection that doesn't open in time: the address doesn't answer (the idle time is for a slow answer).+ if (o.connectTimeoutMs) {+ req.on("socket", (socket) => {+ if (!socket.connecting) return;+ const t = setTimeout(() => req.destroy(new RemoteFetchError(`Couldn't reach ${named.host}: connect ETIMEDOUT (no answer in ${Math.round(o.connectTimeoutMs! / 1000)} s)`)), o.connectTimeoutMs);+ t.unref?.();+ const clear = () => clearTimeout(t);+ socket.once("connect", clear);+ socket.once("close", clear);+ });+ }req.on("error", (e) => {- const err = e instanceof RemoteFetchError ? e : new RemoteFetchError(`Couldn't reach ${target.host}: ${e.message}`);+ const err = e instanceof RemoteFetchError ? e : new RemoteFetchError(`Couldn't reach ${named.host}: ${e.message}`);counted?.destroy(err);clearTimeout(deadline);settle(err);diff --git a/src/server/request-schema.ts b/src/server/request-schema.tsindex a427ccda..e141751f 100644--- a/src/server/request-schema.ts+++ b/src/server/request-schema.ts@@ -127,6 +127,8 @@ export const GenerationRequestSchema = z.object({// A Fuobe Original runs on both engines: the one to run on (the composer's switch). Unset: the engine mode, else// the first connected.engine: z.enum(["open", "cloud"]).optional(),+ // The provider whose key a cloud run goes on when the model is on several ("Run with your Replicate key").+ prefer: z.enum(["fal", "replicate"]).optional(),// A recipe's LoRAs (the evaluation harness, scripts/eval): added after the preset's own. On ComfyUI `file` must// already be in models/loras (ComfyUI checks the name against its list); a cloud LoRA endpoint takes `url`.loras: zdiff --git a/src/server/run-events.ts b/src/server/run-events.tsnew file mode 100644index 00000000..a9f367e6--- /dev/null+++ b/src/server/run-events.ts@@ -0,0 +1,102 @@+import "server-only";+import { db } from "./db";+import { withoutAddress, withoutSecrets } from "@/lib/diagnose";++/**+ * What happened to a run on an account's own GPU or own key, for the owner: one structured log line per wait, heal and+ * failure, and on a failed run a short note kept beside it (generations.external_meta_json `ownRun`) that only+ * owner-side code reads (ownRunNote). Never a prompt, a key, a token, a GPU's address or a file's name: an address is+ * its kind ("runpod", "tunnel", "web", "connect", "computer"), and the provider's own text is kept without the address+ * or any credential it echoed, 2 KB at most. Accounts and visitors never get any of it (toGeneration leaves the column+ * out). Other kinds of runs can log through the same line later (recordRunEvent).+ */++export type RunPlace = "own-gpu" | "own-key";+export type RunOutcome = "failed" | "waiting" | "healed";+export type HostKind = "runpod" | "tunnel" | "web" | "connect" | "computer";++export interface OwnRunEvent {+ run: string;+ account: string;+ provider: string;+ model: string;+ op?: string;+ stage?: string;+ /** An answer's status ("404"), or what kind of network failure it was ("refused", "dns", "tls", "timeout", "reset", "network"). */+ code?: string;+ hostKind?: HostKind;+ cause?: string;+ attempt?: number;+ waitedMs?: number;+ outcome: RunOutcome;+}++/** What is kept with a failed run for the owner (never sent to the account or a visitor). */+export interface OwnRunNote {+ at: number;+ cause?: string;+ stage?: string;+ code?: string;+ hostKind?: HostKind;+ /** The provider's or GPU's own words, without an address or a credential. */+ said?: string;+}++const MAX_SAID = 2048;++/** A network failure's message as a short code. */+export function networkCode(text: string): string {+ if (/ECONNREFUSED|connection refused/i.test(text)) return "refused";+ if (/ENOTFOUND|EAI_AGAIN|EAI_NONAME|getaddrinfo|Couldn't resolve/i.test(text)) return "dns";+ if (/certificate|CERT_|self[- ]signed|SSL|TLS|wrong version number/i.test(text)) return "tls";+ if (/ECONNRESET|socket hang up|stopped answering|EPIPE/i.test(text)) return "reset";+ if (/timed? ?out|ETIMEDOUT|took over \d+ s|aborted|TimeoutError/i.test(text)) return "timeout";+ if (/won't fetch/i.test(text)) return "private";+ return "network";+}++/** Text from a GPU or a provider, as it may be kept: no address, no credential, no key, 2 KB at most. */+export function keptText(text: string | undefined, o: { url?: string; secret?: string } = {}): string | undefined {+ if (!text) return undefined;+ let t = withoutSecrets(withoutAddress(String(text), o.url));+ if (o.secret && o.secret.length >= 4) t = t.split(o.secret).join("••••");+ t = t.replace(/\s+/g, " ").trim();+ return t ? t.slice(0, MAX_SAID) : undefined;+}++/** One line for the server's log (JSON). Any kind of run event goes through here. */+export function recordRunEvent(evt: string, fields: Record<string, unknown>, level: "warn" | "info" = "info"): void {+ const line = JSON.stringify({ evt, ...Object.fromEntries(Object.entries(fields).filter(([, v]) => v !== undefined && v !== "")) });+ if (level === "warn") console.warn(line);+ else console.info(line);+}++/**+ * A wait, a heal or a failure of an account's run on its own GPU or key: logged (a failure as a warning), and a failure's+ * note kept beside the run for the owner.+ */+export function recordOwnRun(e: OwnRunEvent, said?: string): void {+ const place: RunPlace = e.provider === "comfyui" ? "own-gpu" : "own-key";+ recordRunEvent("own-run", { run: e.run, account: e.account, place, provider: e.provider, model: e.model, op: e.op, stage: e.stage, code: e.code, hostKind: e.hostKind, cause: e.cause, attempt: e.attempt, waitedMs: e.waitedMs, outcome: e.outcome }, e.outcome === "failed" ? "warn" : "info");+ if (e.outcome !== "failed") return;+ const note: OwnRunNote = { at: Date.now(), cause: e.cause, stage: e.stage, code: e.code, hostKind: e.hostKind, ...(said && { said: said.slice(0, MAX_SAID) }) };+ try {+ db()+ .prepare("UPDATE generations SET external_meta_json = json_set(CASE WHEN json_valid(external_meta_json) THEN external_meta_json ELSE '{}' END, '$.ownRun', json(?)) WHERE id = ?")+ .run(JSON.stringify(note), e.run);+ } catch {+ // The note is for the owner's convenience: a run is never held up for it.+ }+}++/** The owner's note on an account's failed run (owner-side code only: never an account's or a visitor's answer). */+export function ownRunNote(runId: string): OwnRunNote | null {+ const row = db().prepare("SELECT external_meta_json FROM generations WHERE id = ?").get(runId) as { external_meta_json: string | null } | undefined;+ if (!row?.external_meta_json) return null;+ try {+ const note = (JSON.parse(row.external_meta_json) as { ownRun?: OwnRunNote }).ownRun;+ return note && typeof note.at === "number" ? note : null;+ } catch {+ return null;+ }+}diff --git a/src/server/smaller-copy.ts b/src/server/smaller-copy.tsnew file mode 100644index 00000000..bb18cdca--- /dev/null+++ b/src/server/smaller-copy.ts@@ -0,0 +1,105 @@+import "server-only";+import { spawn } from "node:child_process";+import fs from "node:fs";+import path from "node:path";+import { nanoid } from "nanoid";+import sharp from "sharp";+import type { GenerationRequest } from "@/lib/catalog/types";+import { accountTotalBytes, accountUsage } from "./account-files";+import { adoptFile, readRef, scratchDir } from "./storage";++/**+ * "Send a smaller copy": a run whose file was too big for the account's GPU address (its tunnel's or its pod's size+ * limit, or ComfyUI's), or too slow to send over it, made again with a smaller copy of that file. A clip becomes 720p at+ * most (H.264, a lighter quality), a picture 2048 px on its longest side. The copy is a new file of the account's (its+ * original stays), and only made when the person presses the button.+ */++/** The run's inputs that a copy can stand in for, by where they are in the request. */+type Slot = { key: "video" | "audio" | "endImage"; ref: string } | { key: "images" | "videos"; at: number; ref: string };++function slots(req: GenerationRequest): Slot[] {+ const i = req.inputs ?? {};+ return [+ ...(i.video ? [{ key: "video" as const, ref: i.video }] : []),+ ...(i.endImage ? [{ key: "endImage" as const, ref: i.endImage }] : []),+ ...(i.images ?? []).map((ref, at) => ({ key: "images" as const, at, ref })),+ ...(i.videos ?? []).map((ref, at) => ({ key: "videos" as const, at, ref })),+ ];+}++export class SmallerCopyError extends Error {}++const CANT = "We couldn't make a smaller copy of this file. Trim the clip, or pick a smaller file.";++/** A clip re-encoded at 720p at most (ffmpeg), into `out`. */+function shrinkClip(input: string, out: string): Promise<void> {+ return new Promise((resolve, reject) => {+ const args = ["-hide_banner", "-loglevel", "error", "-y", "-i", input, "-vf", "scale=-2:'min(720,ih)'", "-c:v", "libx264", "-preset", "veryfast", "-crf", "28", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart", out];+ let child;+ try {+ child = spawn(process.env.FFMPEG_PATH || "ffmpeg", args, { stdio: ["ignore", "ignore", "ignore"] });+ } catch {+ return reject(new SmallerCopyError(CANT));+ }+ const timer = setTimeout(() => child.kill("SIGKILL"), 10 * 60_000);+ child.on("error", () => {+ clearTimeout(timer);+ reject(new SmallerCopyError(CANT));+ });+ child.on("close", (code) => {+ clearTimeout(timer);+ if (code === 0) resolve();+ else reject(new SmallerCopyError(CANT));+ });+ });+}++/**+ * The run's request again with a smaller copy of its biggest file (saved as a new file of the account's), and that copy's+ * size. Throws SmallerCopyError in plain words when no copy can be made (or it isn't smaller).+ */+export async function withSmallerCopy(accountId: string, req: GenerationRequest): Promise<{ request: GenerationRequest; bytes: number }> {+ const files: { slot: Slot; data: Buffer; contentType: string; name: string }[] = [];+ for (const slot of slots(req)) {+ try {+ const f = await readRef(slot.ref);+ files.push({ slot, data: f.data, contentType: f.contentType, name: f.name });+ } catch {+ // A file that is gone: the run can't be made again with it, whatever its size.+ }+ }+ const biggest = files.filter((f) => /^(image|video)\//.test(f.contentType)).sort((a, b) => b.data.length - a.data.length)[0];+ if (!biggest) throw new SmallerCopyError(CANT);+ const work = path.join(scratchDir(), `smaller-${nanoid(8)}`);+ const video = biggest.contentType.startsWith("video/");+ const out = `${work}-out.${video ? "mp4" : "jpg"}`;+ try {+ if (video) {+ fs.writeFileSync(work, biggest.data);+ await shrinkClip(work, out);+ } else {+ const small = await sharp(biggest.data).rotate().resize({ width: 2048, height: 2048, fit: "inside", withoutEnlargement: true }).jpeg({ quality: 82 }).toBuffer();+ fs.writeFileSync(out, small);+ }+ const bytes = fs.statSync(out).size;+ // Only a copy that is clearly smaller helps.+ if (!bytes || bytes > biggest.data.length * 0.8) throw new SmallerCopyError("This file is as small as we can make it here. Trim the clip, or pick a smaller file.");+ if (accountUsage(accountId).total + bytes > accountTotalBytes(accountId)) throw new SmallerCopyError("Your files are full, so a smaller copy can't be kept. Delete a few results, then try again.");+ const name = `${biggest.name.replace(/\.[^.]+$/, "") || "file"}-smaller.${video ? "mp4" : "jpg"}`;+ const asset = adoptFile({ from: out, contentType: video ? "video/mp4" : "image/jpeg", name, source: "upload", accountId });+ const inputs = { ...req.inputs };+ const s = biggest.slot;+ if (s.key === "images" || s.key === "videos") {+ const list = [...(inputs[s.key] ?? [])];+ list[s.at] = asset.url;+ inputs[s.key] = list;+ } else inputs[s.key] = asset.url;+ return { request: { ...req, inputs }, bytes };+ } catch (e) {+ fs.rmSync(out, { force: true });+ throw e instanceof SmallerCopyError ? e : new SmallerCopyError(CANT);+ } finally {+ fs.rmSync(work, { force: true });+ }+}diff --git a/tests/helpers/fake-cloud.ts b/tests/helpers/fake-cloud.tsindex 5eb88273..4cb92a7b 100644--- a/tests/helpers/fake-cloud.ts+++ b/tests/helpers/fake-cloud.ts@@ -36,6 +36,8 @@ export interface FakeCloud {* refuses): its status, body and headers. Null or undefined: the request goes on as usual.*/script: ((r: CloudRequest) => { status: number; body?: unknown; headers?: Record<string, string> } | null | undefined) | null;+ /** A request it never answers while this says so (a provider that hangs). */+ hang: ((r: CloudRequest) => boolean) | null;close(): Promise<void>;}@@ -49,13 +51,14 @@ const json = (res: http.ServerResponse, status: number, body: unknown) => {};async function start(handle: (fake: FakeCloud, req: CloudRequest, res: http.ServerResponse, key: string | null) => Promise<void> | void, scheme: "Key" | "Bearer", port = 0): Promise<FakeCloud> {- const fake = { log: [], keys: {}, pollsToFinish: 2, holdSubmits: null, canceled: [], script: null } as unknown as FakeCloud;+ const fake = { log: [], keys: {}, pollsToFinish: 2, holdSubmits: null, canceled: [], script: null, hang: null } as unknown as FakeCloud;const server = http.createServer((req, res) => {const chunks: Buffer[] = [];req.on("data", (c: Buffer) => chunks.push(c));req.on("end", () => {const r: CloudRequest = { method: req.method ?? "GET", path: req.url ?? "/", authorization: req.headers.authorization, body: Buffer.concat(chunks).toString("latin1") };fake.log.push(r);+ if (fake.hang?.(r)) return;const said = fake.script?.(r);if (said) {res.writeHead(said.status, { "Content-Type": "application/json", ...said.headers });@@ -94,6 +97,8 @@ const ZERO = "00000000-0000-0000-0000-000000000000";export function startFakeFal(port = 0): Promise<FakeCloud> {let n = 0;const polls = new Map<string, number>();+ /** Jobs of a voice clone endpoint (Qwen3-TTS clone-voice): their result is a speaker embedding file. */+ const clones = new Set<string>();return start(async (fake, r, res, key) => {const path = r.path.split("?")[0];@@ -122,11 +127,13 @@ export function startFakeFal(port = 0): Promise<FakeCloud> {if (seen > fake.pollsToFinish) return json(res, 200, { status: "COMPLETED", logs: [] });return json(res, 200, seen === 1 ? { status: "IN_QUEUE", queue_position: 0 } : { status: "IN_PROGRESS", logs: [{ message: "50%" }] });}+ if (clones.has(id)) return json(res, 200, { speaker_embedding: { url: `${fake.url}/files/voice-${id}.safetensors` } });return json(res, 200, { images: [{ url: PNG_DATA_URI, content_type: "image/png" }] });}if (r.method === "POST") {if (fake.holdSubmits) await fake.holdSubmits;const id = `fal-${++n}`;+ if (/\/clone-voice\//.test(path)) clones.add(id);// fal's status paths drop an endpoint's sub-path: the app's first two parts.const app = path.split("/").slice(1, 3).join("/");const base = `${fake.url}/${app}/requests/${id}`;diff --git a/tests/helpers/fake-comfy-runner.ts b/tests/helpers/fake-comfy-runner.tsindex 68850a25..f0ce0070 100644--- a/tests/helpers/fake-comfy-runner.ts+++ b/tests/helpers/fake-comfy-runner.ts@@ -51,9 +51,9 @@ export interface FakeComfyOptions {mixed?: boolean;/*** Answers a request before anything else when it returns one (a GPU that is off, starting up, behind a password or a- * web page): its status, body and content type. Undefined: the request goes on as usual.+ * web page): its status, body, content type and any headers (a redirect's location). Undefined: the request goes on as usual.*/- answer?: (method: string, path: string) => { status: number; body?: string; contentType?: string } | undefined;+ answer?: (method: string, path: string) => { status: number; body?: string; contentType?: string; headers?: Record<string, string> } | undefined;}/** A tiny but real WAV (mono, 16-bit, 8 kHz, 0.1 s of silence). */@@ -206,7 +206,7 @@ export function startFakeComfy(opts: FakeComfyOptions = {}, port = 0): Promise<Fconst p = url.pathname;const said = opts.answer?.(entry.method, p);if (said) {- res.writeHead(said.status, { "content-type": said.contentType ?? "text/html" });+ res.writeHead(said.status, { "content-type": said.contentType ?? "text/html", ...said.headers });return res.end(said.body ?? "");}if (p === "/system_stats") return json(200, { system: { comfyui_version: "0.3.fake", ram_total: 64 * 2 ** 30 }, devices: [{ name: "Fake GPU", vram_total: 24 * 2 ** 30 }] });diff --git a/tests/own-gpu-graceful.test.ts b/tests/own-gpu-graceful.test.tsindex f6a9f6f5..b3f98234 100644--- a/tests/own-gpu-graceful.test.ts+++ b/tests/own-gpu-graceful.test.ts@@ -1,4 +1,5 @@-import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import crypto from "node:crypto";import http from "node:http";import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";import { tempDir } from "./helpers/temp-dir";@@ -10,6 +11,8 @@ import { tempDir } from "./helpers/temp-dir";* says so; the status strip (the composer's check before Run) knows why the GPU is offline. All against a stand-in* ComfyUI on this machine: no real ComfyUI, RunPod or fuobe.com is called.*/+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));+const dir = tempDir("fuobe-own-gpu-graceful-");process.env.FUOBE_DATA_DIR = dir;process.env.COMFYUI_URL = "http://owner-comfy.test:8188";@@ -30,7 +33,10 @@ const auth = await import("@/server/auth");const generationsRoute = await import("@/app/api/generations/route");const uploadsRoute = await import("@/app/api/uploads/route");const gpuRoute = await import("@/app/api/account/gpu/route");-const { getGeneration, SELF_HEAL } = await import("@/server/generations");+const generationRoute = await import("@/app/api/generations/[id]/route");+const smallerRoute = await import("@/app/api/generations/[id]/smaller/route");+const { cancelGeneration, getGeneration, LEASE, OWN_QUEUE, SELF_HEAL, STALE_SUBMIT } = await import("@/server/generations");+const { ownRunNote } = await import("@/server/run-events");const { cleanGpuAddress, checkGpuAddress, visitorStatus } = await import("@/server/account-gpu");const { comfyProvider, onOwnGpu } = await import("@/server/providers/comfyui");const { db } = await import("@/server/db");@@ -61,6 +67,7 @@ beforeEach(() => {Object.assign(fake.opts, { loras: [], delayMs: 0, answer: undefined });fake.log.length = 0;auth.setAccountGpu(a, { url: fake.url });+ globalThis.__fuobeTestGpuHosts = undefined;globalThis.__fuobeAccountGpus?.clear();globalThis.__fuobePollHeals?.clear();db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();@@ -114,7 +121,8 @@ describe("Settings → Your GPU: Test says what is wrong, in plain words, with wexpect(starting.body.trouble).toMatchObject({ cause: "gpu-starting", retryable: true });expect(starting.body.error).toBe(starting.body.trouble!.words);expect(starting.body.error).toMatch(/starting up/);- expect(starting.body.trouble!.details).toBe(`127.0.0.1:${fake.port} · HTTP 502 · Bad gateway`);+ // The kind of address, never the address itself.+ expect(starting.body.trouble!.details).toBe("your web address · HTTP 502 · Bad gateway");plainWords(starting.body.error);// Today's wrong advice is gone.expect(starting.body.error).not.toMatch(/isn't a ComfyUI/);@@ -164,6 +172,30 @@ describe("Settings → Your GPU: Test says what is wrong, in plain words, with wexpect(pw.body.trouble).toMatchObject({ cause: "address-credentials", words: "A password goes in the Access token box, not in the address." });});+ it("an http address that sends to https is followed to the port it named (none: 443), never another", async () => {+ globalThis.__fuobeTestGpuHosts = { "gpu-redirect.example.com": fake.port };+ for (const [to, kept] of [+ ["https://gpu-redirect.example.com:8443/system_stats", "https://gpu-redirect.example.com:8443"],+ ["https://gpu-redirect.example.com/system_stats", "https://gpu-redirect.example.com"],+ ]) {+ let asked = 0;+ fake.opts.answer = (_m, p) => (p === "/system_stats" && asked++ === 0 ? { status: 301, body: "", contentType: "text/plain", headers: { location: to } } : undefined);+ const r = await put({ url: "http://gpu-redirect.example.com:8188" });+ expect(r.status, JSON.stringify(r.body)).toBe(200);+ expect(r.body.url).toBe(kept);+ }+ });++ it("a token the address echoes back is never in what the person reads", async () => {+ const token = "sekret-token-4815162342";+ fake.opts.answer = (_m, p) => (p === "/system_stats" ? { status: 200, body: `{"headers": {"Authorization": "Bearer ${token}"}}`, contentType: "application/json" } : undefined);+ const r = await put({ url: fake.url, token });+ expect(r.status).toBe(422);+ expect(r.body.trouble?.cause).toBe("gpu-not-comfy");+ expect(JSON.stringify(r.body)).not.toContain(token);+ expect(JSON.stringify(r.body)).not.toContain("4815162342");+ });+it("too many checks: says when it checks again, by itself", async () => {let last: Awaited<ReturnType<typeof put>> | undefined;for (let i = 0; i < 12; i++) last = await put({ url: fake.url });@@ -225,29 +257,64 @@ describe("a run on an account's own GPU heals itself, or fails in plain words wiexpect(g?.status).toBe("failed");expect(g?.error).toBe("Your GPU is starting up, so ComfyUI wasn't ready for this run. Press Retry in a minute.");plainWords(g?.error);- expect(g?.trouble).toMatchObject({ cause: "gpu-starting", details: `127.0.0.1:${fake.port} · HTTP 502 · Bad gateway` });+ expect(g?.trouble).toMatchObject({ cause: "gpu-starting", details: "your web address · HTTP 502 · Bad gateway" });expect(kinds(g?.trouble)).toEqual(expect.arrayContaining(["retry", "check-gpu", "gpu-settings"]));- // Tried several times, then asked once more (/system_stats) before failing.+ // The file went once: each try after it only looked at the GPU (/system_stats), and it was asked once more at the end.const paths = fake.log.map((e) => e.path);- expect(paths.filter((p) => p === "/upload/image").length).toBeGreaterThan(1);+ expect(paths.filter((p) => p === "/upload/image")).toHaveLength(1);+ expect(paths.filter((p) => p === "/system_stats").length).toBeGreaterThan(2);expect(paths.lastIndexOf("/system_stats")).toBeGreaterThan(paths.indexOf("/upload/image"));// What it learnt shows in the status strip too.expect((await visitorStatus(auth.accountById(a)!)).viewer.gpu).toMatchObject({ online: false, trouble: { cause: "gpu-starting" } });});- it("while a run waits, the status strip says so in a check's words; a GPU moved meanwhile stops the run in plain words", async () => {+ it("while a run waits, the status strip says so in a check's words; a new address saved meanwhile is where the run goes", async () => {SELF_HEAL.scale = 0.01;- fake.opts.answer = (_m, p) => (p === "/upload/image" ? html(502) : undefined);+ fake.opts.answer = (_m, p) => (p === "/upload/image" || p === "/system_stats" ? html(502) : undefined);const id = await startRun();for (let i = 0; i < 500 && getGeneration(id)?.message !== "Waiting for your GPU to start up"; i++) await new Promise((r) => setTimeout(r, 10));expect(getGeneration(id)?.message).toBe("Waiting for your GPU to start up");+ // The tile shows what helps while it waits, and until when.+ expect(getGeneration(id)?.waiting).toMatchObject({ cause: "gpu-starting", until: expect.any(Number) });+ expect(kinds(getGeneration(id)?.waiting)).toContain("check-gpu");// The composer's check before Run reads this (Settings' words, not a run's "press Retry").const s = await visitorStatus(auth.accountById(a)!);expect(s.viewer.gpu).toMatchObject({ online: false, trouble: { cause: "gpu-starting", words: expect.stringMatching(/we connect as soon as ComfyUI is ready/) } });- auth.setAccountGpu(a, { url: `${fake.url}/elsewhere` });+ // The person pastes a new address (a tunnel that restarted): the run goes there, and runs.+ globalThis.__fuobeTestGpuHosts = { "new-river.trycloudflare.com": fake.port };+ fake.opts.answer = undefined;+ auth.setAccountGpu(a, { url: "https://new-river.trycloudflare.com" });+ const g = await settle(id, 20_000);+ expect(g?.status, g?.error ?? "").toBe("succeeded");+ // Sent to the new address (the run keeps which, by a name made from it, never the address).+ const sentTo = (JSON.parse(String(db().prepare("SELECT external_meta_json FROM generations WHERE id = ?").pluck().get(id))) as { sentTo?: string }).sentTo;+ expect(sentTo).toBe(crypto.createHash("sha256").update("https://new-river.trycloudflare.com").digest("hex").slice(0, 16));+ });++ it("a GPU disconnected while a run waits stops the run, saying so, with Connect your GPU", async () => {+ SELF_HEAL.scale = 0.01;+ fake.opts.answer = (_m, p) => (p === "/upload/image" || p === "/system_stats" ? html(502) : undefined);+ const id = await startRun();+ for (let i = 0; i < 500 && getGeneration(id)?.message !== "Waiting for your GPU to start up"; i++) await new Promise((r) => setTimeout(r, 10));+ auth.setAccountGpu(a, null);const g = await settle(id);expect(g?.status).toBe("failed");- expect(g?.error).toBe("This run stopped because your GPU moved to a new address. Press Retry.");+ expect(g?.error).toBe("You disconnected your GPU, so this run stopped. Connect it again, then press Retry.");+ expect(g?.trouble?.actions[0]).toMatchObject({ kind: "gpu-settings", label: "Connect your GPU" });+ });++ it("Cancel while a run waits stays a cancel, and nothing more is sent", async () => {+ SELF_HEAL.scale = 0.01;+ fake.opts.answer = (_m, p) => (p === "/upload/image" || p === "/system_stats" ? html(502) : undefined);+ const id = await startRun();+ for (let i = 0; i < 500 && getGeneration(id)?.message !== "Waiting for your GPU to start up"; i++) await new Promise((r) => setTimeout(r, 10));+ await cancelGeneration(id);+ const at = Date.now();+ fake.opts.answer = undefined;+ await new Promise((r) => setTimeout(r, 1500));+ await settle(id, 500);+ expect(getGeneration(id, { includeDeleted: true })?.status).toBe("canceled");+ expect(fake.log.filter((e) => e.at > at && (e.path === "/upload/image" || e.path === "/prompt"))).toEqual([]);});it("never waits out what waiting can't fix: a password, a web page instead of ComfyUI", async () => {@@ -293,6 +360,56 @@ describe("a run on an account's own GPU heals itself, or fails in plain words wiexpect(kinds(g?.trouble)).toEqual(expect.arrayContaining(["retry", "check-gpu"]));});+ it("a made result whose copy breaks off is copied again at a later look, the tile saying so, and never made twice", async () => {+ let refused = 0;+ fake.opts.answer = (_m, p) => (p === "/view" && refused++ < 4 ? html(502) : undefined);+ const seen: string[] = [];+ const g = await settle(await startRun(), 20_000, seen);+ expect(g?.status, g?.error ?? "").toBe("succeeded");+ expect(seen).toContain("Your result is made. Copying it from your GPU");+ expect(refused).toBeGreaterThan(4);+ expect(fake.log.filter((e) => e.path === "/prompt")).toHaveLength(1);+ });++ it("the time a file may take to reach the GPU grows with its size", async () => {+ const { ownGpuLimits, uploadDeadlineMs } = await import("@/server/providers/comfyui");+ // Sending a file may take as long as it needs at a slow 128 KB/s, plus a minute: 5 to 30 minutes.+ expect(uploadDeadlineMs(1024)).toBe(5 * 60_000);+ expect(uploadDeadlineMs(80 * 2 ** 20)).toBe(Math.ceil(((80 * 2 ** 20) / (128 * 1024)) * 1000) + 60_000);+ expect(uploadDeadlineMs(10 * 2 ** 30)).toBe(30 * 60_000);+ expect(ownGpuLimits("/upload/image", 80 * 2 ** 20).deadlineMs).toBeGreaterThan(10 * 60_000);+ expect(ownGpuLimits("/system_stats", 80 * 2 ** 20).deadlineMs).toBe(60_000);+ });++ it("a run its GPU lost twice is sent again only once, then says so with Retry", async () => {+ let prompts = 0;+ fake.opts.answer = (m, p) => {+ if (p === "/prompt" && m === "POST") {+ prompts++;+ return undefined;+ }+ // A ComfyUI that forgets every run.+ if (p === "/queue" && m === "GET") return { status: 200, body: JSON.stringify({ queue_running: [], queue_pending: [] }), contentType: "application/json" };+ if (p.startsWith("/history/")) return { status: 200, body: "{}", contentType: "application/json" };+ return undefined;+ };+ const g = await settle(await startRun(), 20_000);+ expect(g?.status).toBe("failed");+ expect(prompts).toBe(2);+ expect(g?.trouble?.cause).toBe("gpu-restarted");+ expect(kinds(g?.trouble)).toContain("retry");+ });++ it("each job of a batch keeps its place (its seed) when it is handed over", async () => {+ const pic = await uploadPng();+ const r = await generationsRoute.POST(json("/api/generations", "POST", { feature: "video", modelId: "fuobe-dop", presetId: "motion-zoom-in", prompt: "", inputs: { images: [pic] }, params: { numOutputs: 2, seed: 1234 } }));+ expect(r.status).toBe(201);+ const ids = ((await r.json()) as { items: { id: string }[] }).items.map((x) => x.id);+ for (const id of ids) await settle(id);+ const index = (id: string) => (JSON.parse(String(db().prepare("SELECT external_meta_json FROM generations WHERE id = ?").pluck().get(id) ?? "{}")) as { jobIndex?: number }).jobIndex;+ expect(ids.map(index)).toEqual(ids.length === 2 ? [0, 1] : [0]);+ });+it("a run its GPU lost (ComfyUI restarted) is sent again once, and finishes", async () => {let prompts = 0;fake.opts.answer = (m, p) => {@@ -345,7 +462,239 @@ describe("a run on an account's own GPU heals itself, or fails in plain words wifake.opts.answer = (_m, p) => (p === "/upload/image" ? { status: 404, body: "404 page not found", contentType: "text/plain" } : undefined);const e = (await onOwnGpu({ url: fake.url }, () => comfyProvider.prepareFile(Buffer.from("png"), "image/png", "a.png")).catch((x: unknown) => x)) as Error & { trouble?: { cause: string; details?: string } };expect(e.message).not.toMatch(/upload failed|404/);- expect(e.trouble).toMatchObject({ cause: "gpu-not-comfy", details: `127.0.0.1:${fake.port} · HTTP 404 · 404 page not found` });+ expect(e.trouble).toMatchObject({ cause: "gpu-not-comfy", details: "your web address · HTTP 404 · 404 page not found" });expect(fetched.filter((u) => u.includes("owner-comfy.test") && !u.endsWith("/system_stats"))).toEqual([]);});});++describe("the reported case, end to end: a RunPod pod that is stopped (its address stands for the stand-in)", () => {+ const POD = "https://abc123xyz-8188.proxy.runpod.net";+ /** A stopped pod: RunPod's proxy answers 404 to everything. */+ const stopped = () => ({ status: 404, body: "404 page not found", contentType: "text/plain" });++ it("Save anyway, Generate: the run waits for the pod, says so with Start your pod, and runs once it is started", async () => {+ globalThis.__fuobeTestGpuHosts = { "abc123xyz-8188.proxy.runpod.net": fake.port };+ SELF_HEAL.scale = 0.01;+ auth.setAccountGpu(a, null);+ fake.opts.answer = stopped;+ const kept = await put({ url: "abc123xyz-8188.proxy.runpod.net", anyway: true }, false);+ expect(kept.status).toBe(200);+ expect(kept.body).toMatchObject({ offline: true, gpu: { url: POD }, trouble: { cause: "gpu-stopped", details: "RunPod pod, port 8188 · HTTP 404 · 404 page not found" } });+ const id = await startRun();+ for (let i = 0; i < 500 && !getGeneration(id)?.waiting; i++) await new Promise((r) => setTimeout(r, 10));+ expect(getGeneration(id)?.message).toBe("Your RunPod pod is off. Start it, and this run goes on by itself");+ expect(getGeneration(id)?.waiting?.actions[0]).toMatchObject({ kind: "start-gpu" });+ // The pod is started.+ fake.opts.answer = undefined;+ const g = await settle(id, 20_000);+ expect(g?.status, g?.error ?? "").toBe("succeeded");+ });++ it("a pod that stays off: the run stops in plain words with Start your pod first, never the raw 404 or the address", async () => {+ globalThis.__fuobeTestGpuHosts = { "abc123xyz-8188.proxy.runpod.net": fake.port };+ auth.setAccountGpu(a, { url: POD });+ fake.opts.answer = stopped;+ const g = await settle(await startRun());+ expect(g?.status).toBe("failed");+ expect(g?.error).toBe("Your RunPod pod isn't running, or ComfyUI isn't on port 8188. Start your pod, then press Retry.");+ plainWords(g?.error);+ expect(g?.trouble?.details).toBe("RunPod pod, port 8188 · HTTP 404 · 404 page not found");+ expect(kinds(g?.trouble)[0]).toBe("start-gpu");+ expect(JSON.stringify(g)).not.toMatch(/abc123xyz|proxy\.runpod|ComfyUI upload failed/);+ });+});++describe("what the owner learns of an account's failed run on its own GPU", () => {+ it("one log line and a note kept with the run (no address, no token), never in the account's own answers", async () => {+ const warn = vi.spyOn(console, "warn");+ try {+ fake.opts.answer = (_m, p) => (p === "/upload/image" ? { status: 401, body: "Unauthorized: token abc123secret from 127.0.0.1", contentType: "text/plain" } : undefined);+ const id = await startRun();+ const g = await settle(id);+ expect(g?.status).toBe("failed");+ const note = ownRunNote(id)!;+ expect(note).toMatchObject({ cause: "gpu-password", stage: "upload", code: "401", hostKind: "web" });+ expect(note.said).toMatch(/^Unauthorized/);+ expect(note.said).not.toMatch(/127\.0\.0\.1|abc123secret/);+ const line = warn.mock.calls.map((c) => String(c[0])).find((l) => l.includes('"evt":"own-run"') && l.includes(id));+ expect(JSON.parse(line!)).toMatchObject({ evt: "own-run", run: id, account: a, place: "own-gpu", provider: "comfyui", stage: "upload", code: "401", hostKind: "web", cause: "gpu-password", outcome: "failed" });+ expect(line).not.toMatch(/127\.0\.0\.1|localhost|abc123secret|me\.png|Unauthorized/);+ // The account's own answers never carry it.+ const list = await generationsRoute.GET(new Request("http://localhost:3000/api/generations", { headers: headers() }));+ const one = await generationRoute.GET(new Request(`http://localhost:3000/api/generations/${id}`, { headers: headers() }), { params: Promise.resolve({ id }) });+ for (const r of [list, one]) {+ const text = await r.text();+ expect(text).toContain(id);+ expect(text).not.toMatch(/ownRun|Unauthorized|abc123secret|"lease"|"heal"/);+ }+ } finally {+ warn.mockRestore();+ }+ });+});++describe("a busy GPU: a queue that keeps moving is waited out", () => {+ const queue = (pos: number) => ({ status: 200, body: JSON.stringify({ queue_running: [[0, "someone-else"]], queue_pending: [...Array.from({ length: pos }, (_, i) => [i + 1, `other-${i}`]), [pos + 1, "job-moving"]] }), contentType: "application/json" });+ const empty = { status: 200, body: "{}", contentType: "application/json" };++ it("waits on while its place moves up, past the queue limit, and finishes", async () => {+ OWN_QUEUE.scale = 0.0003; // 30 minutes: about half a second+ fake.opts.promptId = "job-moving";+ const started = Date.now();+ // Five ahead, one fewer every 200 ms: about a second in the queue, twice the limit, while it moves.+ fake.opts.answer = (m, p) => {+ const ahead = 5 - Math.floor((Date.now() - started) / 200);+ if (ahead < 0) return undefined;+ if (p === "/queue" && m === "GET") return queue(ahead);+ if (p.startsWith("/history/")) return empty;+ return undefined;+ };+ try {+ const g = await settle(await startRun(), 20_000);+ expect(g?.status, g?.error ?? "").toBe("succeeded");+ } finally {+ OWN_QUEUE.scale = 1;+ fake.opts.promptId = undefined;+ }+ });++ it("stops when its place hasn't moved for the limit, saying the GPU was busy", async () => {+ OWN_QUEUE.scale = 0.0003;+ fake.opts.promptId = "job-moving";+ fake.opts.answer = (m, p) => (p === "/queue" && m === "GET" ? queue(3) : p.startsWith("/history/") ? empty : undefined);+ try {+ const g = await settle(await startRun(), 20_000);+ expect(g?.status).toBe("failed");+ expect(g?.error).toMatch(/^Your GPU was busy for 1 minute, so this run stopped\./);+ expect(kinds(g?.trouble)).toEqual(expect.arrayContaining(["retry", "check-gpu"]));+ } finally {+ OWN_QUEUE.scale = 1;+ fake.opts.promptId = undefined;+ }+ });+});++describe("runs that wait, and a file too big for the address", () => {+ it("runs waiting for the GPU don't fill the account's runs at once; a run that takes a waiting one's place stops it", async () => {+ SELF_HEAL.scale = 0.01;+ fake.opts.answer = (_m, p) => (p === "/upload/image" || p === "/system_stats" ? html(502) : undefined);+ const ids: string[] = [];+ for (let i = 0; i < 4; i++) ids.push(await startRun());+ for (let i = 0; i < 500 && ids.some((id) => !getGeneration(id)?.waiting); i++) await new Promise((r) => setTimeout(r, 10));+ const pic = await uploadPng();+ const body = { feature: "video", modelId: "fuobe-dop", presetId: "motion-zoom-in", prompt: "", inputs: { images: [pic] } };+ // A fifth for the GPU: four already wait for it.+ const fifth = await generationsRoute.POST(json("/api/generations", "POST", body));+ expect(fifth.status).toBe(429);+ expect(((await fifth.json()) as { error: string }).error).toBe("You have 4 runs waiting for your GPU. Cancel one, or run one with your key, to start another.");+ // One that takes a waiting run's place (Run with your key on its tile): accepted, and that run stops.+ const instead = await generationsRoute.POST(json("/api/generations", "POST", { ...body, replaces: ids[0] }));+ expect(instead.status, await instead.clone().text()).toBe(201);+ expect(getGeneration(ids[0])?.status).toBe("canceled");+ for (const id of ids) await cancelGeneration(id);+ for (const g of ((await instead.json()) as { items: { id: string }[] }).items) await cancelGeneration(g.id);+ });++ it("a file the address refuses as too big: Send a smaller copy makes one, and the run made again with it runs", async () => {+ // A big picture (noise: it doesn't shrink as a PNG).+ const sharp = (await import("sharp")).default;+ const noise = (await import("node:crypto")).randomBytes(2400 * 2400 * 3);+ const big = await sharp(noise, { raw: { width: 2400, height: 2400, channels: 3 } }).png({ compressionLevel: 1 }).toBuffer();+ const up = await uploadsRoute.POST(new Request("http://localhost:3000/api/uploads", { method: "POST", headers: headers({ "content-type": "image/png", "x-file-name": "big.png", "content-length": String(big.length) }), body: big }));+ expect(up.status, await up.clone().text()).toBe(201);+ const pic = ((await up.json()) as { url: string }).url;+ // The tunnel's own size limit: its web page, 413.+ fake.opts.answer = (_m, p) => (p === "/upload/image" ? { status: 413, body: "<html><title>413 Request Entity Too Large</title></html>", contentType: "text/html" } : undefined);+ const r = await generationsRoute.POST(json("/api/generations", "POST", { feature: "video", modelId: "fuobe-dop", presetId: "motion-zoom-in", prompt: "", inputs: { images: [pic] } }));+ const id = ((await r.json()) as { items: { id: string }[] }).items[0].id;+ const g = await settle(id);+ expect(g?.trouble?.cause).toBe("gpu-too-big");+ expect(g?.trouble?.actions[0]).toMatchObject({ kind: "send-smaller", label: "Send a smaller copy" });+ // The proxy lets the account ask for its own run's copy, and nobody else's.+ const { proxy } = await import("@/proxy");+ const { NextRequest } = await import("next/server");+ const via = (who: string) => proxy(new NextRequest(`http://localhost:3000/api/generations/${id}/smaller`, { method: "POST", headers: { cookie: who, host: "localhost:3000" } }));+ expect(via(cookie).headers.get("x-middleware-next")).toBe("1");+ const other = auth.createAccount("[email protected]", "long enough").id;+ expect(via(`${auth.SESSION_COOKIE}=${auth.createSession(other).value}`).status).toBe(403);+ const smaller = await smallerRoute.POST(new Request(`http://localhost:3000/api/generations/${id}/smaller`, { method: "POST", headers: headers() }), { params: Promise.resolve({ id }) });+ expect(smaller.status, await smaller.clone().text()).toBe(200);+ const made = (await smaller.json()) as { request: { inputs: { images: string[] } }; note: string };+ expect(made.note).toMatch(/^Sent a smaller copy \(\d+ MB\)\.$/);+ expect(made.request.inputs.images[0]).not.toBe(pic);+ fake.opts.answer = undefined;+ const again = await generationsRoute.POST(json("/api/generations", "POST", made.request));+ expect(again.status, await again.clone().text()).toBe(201);+ expect((await settle(((await again.json()) as { items: { id: string }[] }).items[0].id))?.status).toBe("succeeded");+ const sentBytes = fake.log.filter((e) => e.path === "/upload/image").at(-1)?.upload?.length ?? 0;+ expect(sentBytes).toBeGreaterThan(0);+ expect(sentBytes).toBeLessThan(big.length * 0.8);+ });+});++// Last: the server's own state is replaced here (a new instance of the runner's module on the same database).+describe("a wait survives a restart or a deploy", () => {+ it("another instance's look while this one holds a waiting run leaves it alone", async () => {+ SELF_HEAL.scale = 0.01;+ STALE_SUBMIT.ms = 0;+ fake.opts.answer = (_m, p) => (p === "/upload/image" || p === "/system_stats" ? html(502) : undefined);+ try {+ const id = await startRun();+ for (let i = 0; i < 500 && !getGeneration(id)?.waiting; i++) await new Promise((r) => setTimeout(r, 10));+ // Another instance's sweep: its own (empty) list of runs in hand, the same database.+ const mine = globalThis.__fuobeSubmitting;+ globalThis.__fuobeSubmitting = new Set();+ await globalThis.__fuobeRunner?.tick();+ globalThis.__fuobeSubmitting = mine;+ expect(getGeneration(id)?.status).toBe("queued");+ fake.opts.answer = undefined;+ const g = await settle(id, 20_000);+ expect(g?.status, g?.error ?? "").toBe("succeeded");+ } finally {+ STALE_SUBMIT.ms = 2 * 60_000;+ }+ });++ it("a deploy's old instance hands its waiting run to the new one, which goes on with it and runs it once", async () => {+ SELF_HEAL.scale = 0.01;+ LEASE.ms = 400;+ LEASE.renewMs = 100;+ fake.opts.answer = (_m, p) => (p === "/upload/image" || p === "/system_stats" ? html(502) : undefined);+ const id = await startRun();+ for (let i = 0; i < 500 && !getGeneration(id)?.waiting; i++) await new Promise((r) => setTimeout(r, 10));+ expect(getGeneration(id)?.message).toBe("Waiting for your GPU to start up");+ // The old instance starts stopping: its wait lets go of the run, without failing it.+ const shut = (globalThis.__fuobeShutdown ??= { stops: new Set(), draining: false, hooked: false });+ shut.draining = true;+ for (let i = 0; i < 500 && globalThis.__fuobeSubmitting?.has(id); i++) await new Promise((r) => setTimeout(r, 10));+ expect(globalThis.__fuobeSubmitting?.has(id)).toBe(false);+ expect(getGeneration(id)?.status).toBe("queued");+ // It is gone: its timers, its runs in hand, its name. A new instance starts on the same database.+ const old = globalThis.__fuobeRunner;+ if (old) {+ clearInterval(old.timer);+ if (old.fastTimer) clearInterval(old.fastTimer);+ }+ globalThis.__fuobeRunner = undefined;+ if (globalThis.__fuobeLeaseTimer) clearTimeout(globalThis.__fuobeLeaseTimer);+ globalThis.__fuobeLeaseTimer = undefined;+ globalThis.__fuobeSubmitting = new Set();+ globalThis.__fuobeInstance = undefined;+ globalThis.__fuobeResent = undefined;+ shut.draining = false;+ vi.resetModules();+ const fresh = await import("@/server/generations");+ fresh.SELF_HEAL.scale = 0.01;+ fresh.STALE_SUBMIT.ms = 0;+ fresh.LEASE.ms = 400;+ // The old hold runs out; the GPU is back.+ await new Promise((r) => setTimeout(r, 500));+ fake.opts.answer = undefined;+ fake.log.length = 0;+ fresh.ensureRunner();+ const g = await settle(id, 20_000);+ expect(g?.status, g?.error ?? "").toBe("succeeded");+ expect(g?.error ?? "").not.toMatch(/stopped before it started/);+ expect(fake.log.filter((e) => e.path === "/prompt")).toHaveLength(1);+ });+});diff --git a/tests/own-keys-graceful.test.ts b/tests/own-keys-graceful.test.tsindex 402b02c2..defd6595 100644--- a/tests/own-keys-graceful.test.ts+++ b/tests/own-keys-graceful.test.ts@@ -29,6 +29,14 @@ const { getModel, getPreset } = await import("@/lib/catalog");const { cloudVersionKey } = await import("@/lib/your-keys");const { BILLING_URL } = await import("@/lib/diagnose");const { onCloudKey } = await import("@/lib/before-run");+const keysRoute = await import("@/app/api/account/keys/[provider]/route");+const { KEY_CHECK } = await import("@/server/your-keys");+const { visitorStatus } = await import("@/server/account-gpu");++const keyRequest = (cookie: string, provider: string, body: unknown) => {+ const text = JSON.stringify(body);+ return new Request(`http://localhost:3000/api/account/keys/${provider}`, { method: "PUT", headers: { cookie, host: "localhost:3000", "content-type": "application/json", "content-length": String(text.length) }, body: text });+};let fal: FakeCloud;let rep: FakeCloud;@@ -74,6 +82,7 @@ beforeEach(async () => {f.log.length = 0;f.pollsToFinish = 2;f.script = null;+ f.hang = null;f.canceled.length = 0;}keys.saveAccountKey(A, "fal", "acct-fal-A");@@ -100,6 +109,24 @@ async function settle(id: string, ms = 15_000, seen: string[] = []) {const isSubmit = (r: CloudRequest) => r.method === "POST" && !r.path.startsWith("/storage/") && !r.path.startsWith("/upload/");const isStatus = (r: CloudRequest) => r.method === "GET" && /\/requests\/[^/]+\/status/.test(r.path);const kinds = (g: { trouble?: { actions: { kind: string }[] } }) => (g.trouble?.actions ?? []).map((a) => a.kind);+/** A tenth of a second of silence as a WAV (a voice sample). */+function tinyWav(): Buffer {+ const data = Buffer.alloc(1600 * 2);+ const h = Buffer.alloc(44);+ h.write("RIFF", 0);+ h.writeUInt32LE(36 + data.length, 4);+ h.write("WAVEfmt ", 8);+ h.writeUInt32LE(16, 16);+ h.writeUInt16LE(1, 20);+ h.writeUInt16LE(1, 22);+ h.writeUInt32LE(16_000, 24);+ h.writeUInt32LE(32_000, 28);+ h.writeUInt16LE(2, 32);+ h.writeUInt16LE(16, 34);+ h.write("data", 36);+ h.writeUInt32LE(data.length, 40);+ return Buffer.concat([h, data]);+}describe("an account's run on its own key waits out a busy or down provider", () => {it("fal.ai busy at submit (429): the tile says so, it tries again by itself, and runs", async () => {@@ -113,6 +140,17 @@ describe("an account's run on its own key waits out a busy or down provider", ()expect(fal.log.filter(isSubmit)).toHaveLength(3);});+ it("an outage while polling that lasts past the old 10-minute end is still waited out (the job is paid), and collected", async () => {+ gens.SELF_HEAL.scale = 0.001; // the old end, 10 minutes: 0.6 s+ let until = Infinity;+ fal.script = (r) => (isStatus(r) && Date.now() < until ? { status: 503, body: { detail: "Service unavailable" } } : null);+ const g = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" });+ until = Date.now() + 1500;+ const done = await settle(g.id, 15_000);+ expect(done.status, done.error ?? "").toBe("succeeded");+ expect(fal.canceled).toEqual([]);+ });+it("fal.ai down while polling: the tile says it waits, and the run is collected once it answers", async () => {let down = 0;fal.script = (r) => (isStatus(r) && down++ < 4 ? { status: 503, body: { detail: "Service unavailable" } } : null);@@ -123,6 +161,41 @@ describe("an account's run on its own key waits out a busy or down provider", ()expect(seen).toContain("Waiting for fal.ai to answer");});+ it("a status call that hangs is given up in time and asked again, and the run is collected", async () => {+ const { FAL_CALL_MS } = await import("@/server/providers/fal");+ FAL_CALL_MS.short = 200;+ try {+ let hung = 0;+ fal.hang = (r) => isStatus(r) && hung++ < 2;+ const started = Date.now();+ const g = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" });+ const done = await settle(g.id);+ expect(done.status, done.error ?? "").toBe("succeeded");+ expect(hung).toBeGreaterThan(2);+ expect(Date.now() - started).toBeLessThan(10_000);+ } finally {+ FAL_CALL_MS.short = 20_000;+ }+ });++ it("a voice it cloned for the run (a billed step) is used again when the run tries again, never cloned twice", async () => {+ const wav = tinyWav();+ const up = await uploadsRoute.POST(+ new Request("http://localhost:3000/api/uploads", { method: "POST", headers: { cookie: cookies.A, host: "localhost:3000", "content-type": "audio/wav", "x-file-name": "sample.wav", "content-length": String(wav.length) }, body: wav }),+ );+ expect(up.status, await up.clone().text()).toBe(201);+ const voice = ((await up.json()) as { url: string }).url;+ const isTts = (r: CloudRequest) => isSubmit(r) && /\/text-to-speech\//.test(r.path);+ let busy = 0;+ fal.script = (r) => (isTts(r) && busy++ < 1 ? { status: 429, body: { detail: "Too many requests" } } : null);+ const g = await run(cookies.A, { feature: "audio", modelId: "qwen-3-tts", engine: "cloud", op: "tts", prompt: "Welcome aboard.", inputs: { voiceAudio: voice } });+ await settle(g.id);+ expect(fal.log.filter((r) => isSubmit(r) && /\/clone-voice\//.test(r.path))).toHaveLength(1);+ const tts = fal.log.filter(isTts);+ expect(tts).toHaveLength(2);+ expect(JSON.parse(tts[1].body)).toMatchObject({ speaker_voice_embedding_file_url: expect.stringMatching(/voice-fal-\d+\.safetensors$/) });+ });+it("a 502 at submit may have started a job already: never sent twice", async () => {fal.script = (r) => (isSubmit(r) ? { status: 502, body: "<!DOCTYPE html><html><head><title>502 Bad gateway</title></head></html>" } : null);const g = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" });@@ -162,6 +235,17 @@ describe("what waiting can't fix fails at once, in plain words, with what helps"expect(done.error).toBe("Your fal.ai balance has run out. Top it up on fal.ai, then run again.");expect(done.trouble?.actions[0]).toEqual({ kind: "add-credit", label: "Add credit on fal.ai", target: BILLING_URL.fal });expect(fal.log.filter(isSubmit)).toHaveLength(1);+ // Settings → Your keys says Add credit (not Ready), and the status tells the composer before the next run.+ expect(keys.accountKeyInfo(A).fal?.balanceEmptyAt).toBeGreaterThan(0);+ expect((await visitorStatus(auth.accountById(A)!)).viewer).toMatchObject({ emptyKeys: ["fal"] });+ // Topped up: a run the provider takes clears it.+ fal.keys["acct-fal-broke"] = "good";+ try {+ expect((await settle((await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" })).id)).status).toBe("succeeded");+ expect(keys.accountKeyInfo(A).fal?.balanceEmptyAt).toBeUndefined();+ } finally {+ fal.keys["acct-fal-broke"] = "broke";+ }});it("a key refused while polling fails the run at once (not after half an hour), and stops the job", async () => {@@ -234,6 +318,44 @@ describe("Run with your key: the cloud version of a tool on the account's GPU",expect(cloudVersionKey(undefined, getModel("fuobe-soul"), ["replicate"], has, getModel)).toBe("replicate");});+ it("Run with your Replicate key runs on Replicate, never back on fal.ai; without that key it asks for one", async () => {+ const asked = { feature: "image" as const, prompt: "a quiet harbour at dawn", modelId: "nano-banana-pro", engine: "cloud" as const };+ const before = fal.log.filter(isSubmit).length;+ const g = await run(cookies.A, onCloudKey(asked, { target: "replicate" }) as unknown as Record<string, unknown>);+ expect(g.provider).toBe("replicate");+ expect((await settle(g.id)).status).toBe("succeeded");+ expect(fal.log.filter(isSubmit)).toHaveLength(before);+ // An account with only a Replicate token asked to run on fal.ai: Add your key, never a silent other route.+ await expect(run(cookies.D, onCloudKey(asked, { target: "fal" }) as unknown as Record<string, unknown>)).rejects.toThrow(/^403: .*add-key/);+ });++ it("a key the provider refused isn't offered for Run with your key; Check again clears it once the provider takes it", async () => {+ const fpv = { presetId: "motion-fpv-drone", modelId: "oss-minimax-h3" };+ keys.markKeyRejected(A, "fal", "acct-fal-A");+ expect(gens.cloudTwin(fpv, A)).toBeNull();+ const again = await keysRoute.PUT(keyRequest(cookies.A, "fal", { recheck: true }), { params: Promise.resolve({ provider: "fal" }) });+ expect(again.status).toBe(200);+ expect(keys.accountKeyInfo(A).fal?.rejectedAt).toBeUndefined();+ expect(gens.cloudTwin(fpv, A)).toEqual({ modelId: "minimax-h3", provider: "fal", op: "i2v" });+ });++ it("the key check asks again by itself while the provider is busy, and says so plainly when it stays busy", async () => {+ KEY_CHECK.waitsMs = [10, 10];+ try {+ let busy = 0;+ fal.script = (r) => (/requests\/0{8}-/.test(r.path) && busy++ < 2 ? { status: 503, body: { detail: "Service unavailable" } } : null);+ const ok = await keysRoute.PUT(keyRequest(cookies.A, "fal", { key: "acct-fal-A" }), { params: Promise.resolve({ provider: "fal" }) });+ expect(ok.status).toBe(200);+ expect(busy).toBe(3);+ fal.script = (r) => (/requests\/0{8}-/.test(r.path) ? { status: 503, body: { detail: "Service unavailable" } } : null);+ const down = await keysRoute.PUT(keyRequest(cookies.A, "fal", { key: "acct-fal-A" }), { params: Promise.resolve({ provider: "fal" }) });+ expect(down.status).toBe(503);+ expect(await down.json()).toEqual({ error: "fal.ai is busy right now, so we couldn't check your key. Try again in a minute.", details: "fal.ai answered 503" });+ } finally {+ KEY_CHECK.waitsMs = [1_000, 3_000];+ }+ });+it("the failed tile's Run with your fal.ai key asks for a run the studio takes, on that key", async () => {const up = await uploadsRoute.POST(new Request("http://localhost:3000/api/uploads", { method: "POST", headers: { cookie: cookies.A, host: "localhost:3000", "content-type": "image/png", "x-file-name": "me.png", "content-length": String(TINY_PNG.length) }, body: TINY_PNG }),