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 wait out a passing problem, then say why in plain words
Adarsh8ad80e2ecd0e
diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.tsindex 7c0e3c56..76e49d67 100644--- a/src/app/api/generations/route.ts+++ b/src/app/api/generations/route.ts@@ -5,6 +5,7 @@ import { ADD_KEY_HEADER } from "@/lib/your-keys";import { requestViewer, validToken } from "@/server/auth";import { accountEngineMode } from "@/server/account-keys";import { computerScope, ISOLATED_ON_COMPUTER, workerFor } from "@/server/providers/comfyui";+import { ISOLATED_ON_GPU } from "@/lib/diagnose";import { getSetting } from "@/server/settings";import { RUNS_ON_COMPUTER_NOTE } from "@/lib/relay";import { OPERATION_LABELS } from "@/lib/catalog/types";@@ -219,6 +220,11 @@ export async function POST(request: Request) {if (account) unhit(`run:${account.id}`);return refuse(422, ISOLATED_ON_COMPUTER, { code: "isolated-on-computer" });}+ // The same on an account's own GPU at a web address: one ComfyUI, where the second one these graphs need isn't.+ if (account && planned.route.provider === "comfyui" && workerFor(planned.route.endpoint) === "isolated") {+ unhit(`run:${account.id}`);+ return refuse(422, ISOLATED_ON_GPU, { code: "isolated-on-gpu" });+ }// An account's 3D model (Image to 3D, Photo to 3D, Make it 3D) runs on its own GPU or key, and is finished on// this server under the account's limits (model3d-finish.ts). This install's GPUs don't take 3D: decidePlace// refuses it there, and createGenerations refuses a run stamped for them.diff --git a/src/lib/before-run.ts b/src/lib/before-run.tsnew file mode 100644index 00000000..6cd27e7f--- /dev/null+++ b/src/lib/before-run.ts@@ -0,0 +1,74 @@+/**+ * The check before Run (public sign-up): an account whose own GPU at a web address didn't answer its last status check+ * (the status strip's, every 30 s; nothing here asks the GPU) sees what is wrong and its fixes above Generate, instead+ * of starting a run that can only wait. When one of its keys runs the tool's cloud version, "Run with your fal.ai key"+ * is offered too: an explicit click, because it spends the person's own credit. Pure, for the composer and its tests.+ */+import { dualEngine } from "./catalog/engines";+import type { Engine, GenerationRequest } from "./catalog/types";+import { withKeyAction, type Diagnosis, type TroubleAction } from "./diagnose";+import { cloudVersionKey, type CloudProvider } from "./your-keys";++type Routed = { id: string; engine: string; engines?: Engine[]; routes: { provider: string }[] };++export interface BeforeRunViewer {+ kind: "guest" | "account";+ gpu: { connected: boolean; mode?: "computer" | "link"; online?: boolean; trouble?: Pick<Diagnosis, "cause" | "words" | "actions" | "retryable" | "details"> };+ keys?: CloudProvider[];+ paidAllowed?: boolean;+}++/** What the composer shows before Run: the plain sentence, a details line, and the buttons (Retry never: no run yet). */+export interface BeforeRun {+ words: string;+ details?: string;+ actions: TroubleAction[];+}++/** The words when the status check gave no reason (an older answer). */+export const GPU_OFF_WORDS = "Your GPU isn't answering right now.";++/**+ * The check before Run, or null when there is nothing to say: not an account, the tool doesn't run on its own GPU (a+ * cloud model, the Cloud engine, this studio's GPUs), its GPU isn't a web address (this computer and a paired ComfyUI+ * have their own notes), or the GPU answered.+ */+export function gpuBeforeRun(o: {+ viewer: BeforeRunViewer | undefined;+ model: Routed | undefined;+ engine: Engine;+ /** The run goes to this studio's GPUs (hosted runs), not the account's own. */+ onPool?: boolean;+ preset?: Parameters<typeof cloudVersionKey>[0];+ has: (id: string) => boolean;+ getModel: (id: string) => Routed | undefined;+}): BeforeRun | null {+ const { viewer, model } = o;+ if (viewer?.kind !== "account" || !model || o.onPool) return null;+ // A Fuobe Original runs where the engine switch says; any other model on its own engine.+ const toOwnGpu = dualEngine(model) ? o.engine === "open" : model.engine === "open";+ const gpu = viewer.gpu;+ if (!toOwnGpu || !gpu.connected || gpu.mode !== "link" || gpu.online !== false) return null;+ const key = viewer.paidAllowed !== false ? cloudVersionKey(o.preset, model, viewer.keys ?? [], o.has, o.getModel) : null;+ const base: TroubleAction[] = gpu.trouble?.actions ?? [+ { kind: "check-gpu", label: "Check my GPU" },+ { kind: "gpu-settings", label: "Open Settings → Your GPU", target: "/settings#your-gpu" },+ ];+ return {+ words: gpu.trouble?.words ?? GPU_OFF_WORDS,+ ...(gpu.trouble?.details && { details: gpu.trouble.details }),+ actions: [...base.filter((a) => a.kind !== "retry" && a.kind !== "run-with-key"), ...(key ? [withKeyAction(key)] : [])],+ };+}++/**+ * A failed run's request again, on the cloud version its trouble names ("Run with your fal.ai key"): the same words and+ * inputs on the cloud engine. A preset's open-graph settings (`extra`) stay behind when the model changes.+ */+export function onCloudKey(request: GenerationRequest, a: Pick<TroubleAction, "modelId" | "op">): GenerationRequest {+ const modelId = a.modelId ?? request.modelId;+ if (modelId === request.modelId) return { ...request, engine: "cloud" };+ const { extra: _extra, ...params } = request.params ?? {};+ void _extra;+ return { ...request, engine: "cloud", modelId, params, ...(a.op && { op: a.op as GenerationRequest["op"] }) };+}diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.tsindex c849f283..e0aace87 100644--- a/src/lib/catalog/types.ts+++ b/src/lib/catalog/types.ts@@ -9,6 +9,7 @@*/import type { CameraKey } from "@/lib/camera-path";import type { SignatureRecord } from "./palettes";+import type { RunTrouble } from "@/lib/diagnose";export type Engine = "cloud" | "open";@@ -1458,6 +1459,11 @@ export interface Generation {* "Fix it", which opens the GPU pre-flight's guided fix.*/fix?: GenerationFix | null;+ /**+ * An account's failed run on its own GPU or key: why (the cause), a details line for the curious, and the buttons that+ * help (Start your pod, Check my GPU, Replace key…; src/lib/diagnose.ts). The plain sentence is `error`.+ */+ trouble?: RunTrouble;/** 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/relay.ts b/src/lib/relay.tsindex faee95e4..63b95217 100644--- a/src/lib/relay.ts+++ b/src/lib/relay.ts@@ -337,6 +337,9 @@ export const RELAY_WORDS = {disconnected: "You disconnected your computer, so this run stopped. Press Retry.",/** A run sent to the computer whose Fuobe tab stopped answering (closed, asleep): it goes on once that tab is back. */computerAway: "Waiting for your computer. Open Fuobe there to finish this run.",+ /** A run waiting for a ComfyUI paired with a code (Fuobe Connect runs inside it, no tab needed) that is off. */+ pairedAway: "Waiting for your paired ComfyUI. Start ComfyUI there (or start your pod), and this run goes on by itself.",+ pairedWaitedTooLong: (ms: number) => `Your paired ComfyUI didn't come online for ${duration(ms)}. Start it, then press Retry.`,} as const;/** A script's open-source run (an API token) while the owner's ComfyUI is on the owner's computer. */diff --git a/src/lib/your-keys.ts b/src/lib/your-keys.tsindex a28329a1..e7935c87 100644--- a/src/lib/your-keys.ts+++ b/src/lib/your-keys.ts@@ -1,4 +1,6 @@import { FAL_KEYS_URL } from "./connections";+import { dualEngine } from "./catalog/engines";+import { presetRoutes } from "./catalog/preset-recipe-routes";/*** Your keys (public sign-up): an account's own fal.ai key or Replicate token, so it can run paid models billed to its own@@ -86,6 +88,27 @@ export function paidThrough(m: Routed | undefined, s: KeyStatus | undefined): Clreturn CLOUD_PROVIDERS.find((p) => keys.includes(p) && m.routes.some((r) => r.provider === p)) ?? null;}+/**+ * The account's key that runs a tool's cloud version, for "Run with your fal.ai key" when its own GPU is off: a preset's+ * cloud routes in order, or a Fuobe Original (both engines) on the cloud engine. Null when no key of its runs one.+ */+export function cloudVersionKey(+ preset: Parameters<typeof presetRoutes>[0] | undefined,+ model: (Routed & { id: string }) | undefined,+ keys: readonly CloudProvider[],+ has: (id: string) => boolean,+ getModel: (id: string) => Routed | undefined,+): CloudProvider | null {+ if (!keys.length) return null;+ const ids = preset ? presetRoutes(preset, "cloud", has).map((r) => r.modelId) : model && dualEngine(model as Parameters<typeof dualEngine>[0]) ? [model.id] : [];+ for (const id of ids) {+ const m = getModel(id);+ const p = m && CLOUD_PROVIDERS.find((k) => keys.includes(k) && m.routes.some((r) => r.provider === k));+ if (p) return p;+ }+ return null;+}+/** "Add your fal.ai key": the words on a paid model an account can't run yet. */export const addKeyLabel = (p: CloudProvider) => `Add your ${CLOUD_KEY[p].label} key`;diff --git a/src/server/computer/tasks.ts b/src/server/computer/tasks.tsindex 6f256a77..07bc28f6 100644--- a/src/server/computer/tasks.ts+++ b/src/server/computer/tasks.ts@@ -273,6 +273,14 @@ interface RunnerRow {const runnerOf = (principal: Principal) => rdb().prepare("SELECT * FROM relay_runners WHERE principal = ?").get(principal) as RunnerRow | undefined;+/**+ * The principal's runner is a ComfyUI paired with a code (Fuobe Connect runs inside ComfyUI, device "connect-…"), not+ * a Fuobe tab: a run waiting for it needs that ComfyUI started, not a tab opened.+ */+export function pairedRunner(principal: Principal): boolean {+ return !!runnerOf(principal)?.device.startsWith("connect-");+}+/** Is a computer of this principal's online: it beat in the last 30 s, and its ComfyUI answered? */export function runnerOnline(principal: Principal, now = Date.now()): boolean {const r = runnerOf(principal);diff --git a/src/server/generations.ts b/src/server/generations.tsindex cb541e98..14c75710 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -1,4 +1,5 @@import "server-only";+import crypto from "node:crypto";import fs from "node:fs";import path from "node:path";import { nanoid } from "nanoid";@@ -71,10 +72,28 @@ import { kandinskyPrompt } from "@/lib/kandinsky-prompt";import { carriesLayout } from "@/lib/layout-prompt";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, probeComfy, relayFile, type OwnGpu } from "./providers/comfyui";+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, paidAllowed } from "./account-keys";-import { addKeyMessage, isCloudProvider, keyRemovedMessage, type CloudProvider } from "@/lib/your-keys";+import { accountEngineMode, accountKey, accountProviders, paidAllowed } from "./account-keys";+import { addKeyMessage, 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,+ diagnoseGpu,+ diagnoseGpuJob,+ diagnoseKey,+ resultExpired,+ retryPlan,+ troubleOf,+ waitingWords,+ withKeyAction,+ type Diagnosis,+ type GpuFailure,+ type KeyStage,+ type RunTrouble,+ type TroubleAction,+} from "@/lib/diagnose";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";@@ -201,6 +220,7 @@ export function toGeneration(r: Row): Generation {pinnedAt: r.pinned_at ?? null,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)),// 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.@@ -221,13 +241,24 @@ function poolQueue(id: string): { queue: { place: number; etaSeconds: number | nfunction parseFix(json: string): GenerationFix | null {try {- const f = JSON.parse(json) as GenerationFix;+ const { trouble: _trouble, ...f } = JSON.parse(json) as GenerationFix & { trouble?: unknown };+ void _trouble;return f && typeof f.code === "string" && Array.isArray(f.items) ? f : null;} catch {return null;}}+/** What an account's GPU or key ran into (fix_json `trouble`), as the Generation field. */+function parseTrouble(json: string): { trouble: RunTrouble } | Record<string, never> {+ try {+ const t = (JSON.parse(json) as { trouble?: RunTrouble }).trouble;+ return t && typeof t.cause === "string" && Array.isArray(t.actions) ? { trouble: t } : {};+ } catch {+ return {};+ }+}+function update(id: string, fields: Partial<Row>): void {const keys = Object.keys(fields);if (!keys.length) return;@@ -451,7 +482,8 @@ export const ASSET_REFS: AssetRef[] = [*/export const ASSET_FREE: Record<string, string> = {"generations.provider_input_json": "what a provider was sent: its own upload URLs or file names, never ours",- "generations.fix_json": "what a failed ComfyUI run was missing: model file names, node classes and packs",+ "generations.fix_json":+ "what a failed ComfyUI run was missing (model file names, node classes and packs), and what an account's GPU or key ran into: a cause, a details line and its buttons' links","gpu_snapshots.inventory_json": "what a GPU's ComfyUI has (class names, model file names and sizes), never a Fuobe file","gpu_snapshots.report_json": "readiness built from that inventory","generations.external_meta_json": "the provider's job handles",@@ -1798,13 +1830,322 @@ async function submitNow(index: number,): Promise<void> {submitting().add(id);- /** Why the run failed, once it has: its files still waiting to be sent are not sent. */- let failed: { error: unknown } | undefined;// 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.+ const account = req.account && req.place !== "pool" ? req.account : undefined;+ const link = account && providerId === "comfyui" ? gpuLink(accountGpu(account)) : null;+ const started = Date.now();+ let tries = 0;+ let rechecked = false;+ try {+ 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 {+ try {+ await handOver(id, route, providerId, plan, req, index);+ if (link && statusOf(id) !== "failed") noteHandedOver(account!, link.url);+ return;+ } catch (e) {+ error = e;+ }+ }+ const status = statusOf(id);+ // A cancel during the hand-over stays a cancel.+ if (!status || status === "canceled") 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) {+ if (link) noteGpuState(account!, link.url, false, { trouble: asStatus(error, trouble, link) });+ update(id, { status: "queued", message: waitingWords(trouble, isCloudProvider(providerId) ? providerId : undefined) });+ 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;+ }+ 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;+ const again = await recheckGpu(account!, link);+ if (again === "online") continue;+ trouble = { ...again, actions: withKeyOffer(again.actions, account!, req) };+ }+ }+ failRun(id, error, trouble, req.account);+ return;+ }+ } finally {+ submitting().delete(id);+ }+}++/** 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). */+async function pause(id: string, ms: number): Promise<boolean> {+ const end = Date.now() + ms;+ for (;;) {+ 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;+ }+}++/** 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;+ 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 }) });+ if (fix) markStale(account ? `acct:${account}` : "install");+}++/** 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;++/** 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 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(" ");+}++/** Another key of the account that runs the same model (Replicate for fal.ai, or the other way round). */+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;+}++/**+ * 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.+ */+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);+ if (!keys.length) return null;+ const has = (id: string) => !!getModel(id);+ const preset = req.presetId ? getPreset(req.presetId) : undefined;+ const asked = getModel(req.modelId);+ const routes: { modelId: string; op?: string }[] = preset ? presetRoutes(preset as Parameters<typeof presetRoutes>[0], "cloud", has) : asked && dualEngine(asked) ? [{ modelId: asked.id }] : [];+ for (const { modelId: id, op } of routes) {+ const m = getModel(id);+ if (!m) continue;+ const cloud = dualEngine(m) ? onEngine(m, "cloud") : m;+ if (cloud.engine === "open") continue;+ const p = CLOUD_PROVIDERS.find((k) => keys.includes(k) && cloud.routes.some((r) => r.provider === k));+ // Another model: its operation there goes with it (the same model keeps the run's own).+ if (p) return { modelId: id, provider: p, ...(op && id !== req.modelId && { op }) };+ }+ 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. */+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;+}++/**+ * What an account's run ran into, as diagnose.ts reads it: its own GPU's words (comfyui.ts troubleError), or its key's+ * provider's status and words. Undefined for anything else (a request's own problem, already in plain words).+ */+function accountTrouble(e: unknown, account: string, providerId: string, stage: KeyStage, req?: Pick<GenerationRequest, "presetId" | "modelId">): Diagnosis | undefined {+ const own = (e as { trouble?: Diagnosis } | null)?.trouble;+ if (own) return providerId === "comfyui" && req && own.cause.startsWith("gpu-") ? { ...own, actions: withKeyOffer(own.actions, account, req) } : own;+ if (!isCloudProvider(providerId)) return undefined;+ const ctx = { provider: providerId, other: otherKeyFor(account, providerId, req?.modelId) };+ const message = String((e as Error | null)?.message ?? "");+ // No key to send (removed, or one this server can't open any more): its own words, and where to add one.+ if (message === addKeyMessage(providerId) || message === keyRemovedMessage(providerId)) {+ return { cause: "key-rejected", words: message, actions: [{ kind: "key-settings", label: "Add your key", target: "/settings#your-keys" }], retryable: false };+ }+ const status = (e as { status?: unknown } | null)?.status;+ // The provider's own words (provider-keys.ts accountKeyError keeps them, without the key) tell a refused key from a+ // model the key may not run.+ 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;+}++/** A short, stable name for the address a run was sent to (kept with the run, never the address itself). */+const addressKey = (url: string) => crypto.createHash("sha256").update(url.replace(/\/+$/, "")).digest("hex").slice(0, 16);++/** A run reached the account's GPU: the status strip and the next run take it as online (without asking it). */+function noteHandedOver(account: string, url: string): void {+ const known = cachedGpuState(account, url);+ if (known && !known.online) noteGpuState(account, url, true);+}++/** 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);+ }+}++/** 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. */+function asStatus(error: unknown, trouble: Diagnosis, link: { url: string; token?: string }): Diagnosis {+ const f = (error as { failure?: GpuFailure } | null)?.failure;+ return f ? diagnoseGpu({ ...f, stage: "status" }, { kind: "link", url: link.url, hasToken: !!link.token }) : trouble;+}++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;+ /** Account runs already sent again once after their GPU restarted and lost them. */+ var __fuobeResent: Set<string> | undefined;+}+const pollHeals = () => (globalThis.__fuobePollHeals ??= new Map());+/** A run its GPU lost, sent again (diagnose.ts diagnoseGpuJob "lost"). */+const RESENT_WORDS = "Your GPU restarted, so we sent this run again";+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 };+/** Polls that fail in a row before the tile says it is waiting. */+const POLL_MISSES_SAID = 3;++/**+ * 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).+ */+function resend(r: Row, account: string, words: string): boolean {+ if (resentRuns().has(r.id)) 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;+ 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);+ })();+ submitting().add(r.id);+ void submit(r.id, p.route, p.providerId, p.plan, p.req, 0);+ return true;+ } catch {+ return false;+ }+}++/**+ * 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.+ */+async function healPoll(r: Row, ctx: PollContext, account: string, pollError: unknown): Promise<boolean> {+ const stored = JSON.parse(r.request_json) as GenerationRequest;+ const d = accountTrouble(pollError, account, r.provider, "poll", stored);+ const cancel = () =>+ adapterFor(r.provider, account)+ .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);+ return true;+ }+ if (!d) return false;+ const now = Date.now();+ const h = pollHeals().get(r.id) ?? { first: now, n: 0, next: 0 };+ h.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;+ // 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);+ 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 });+ }+ 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> {+ for (let n = 1; ; n++) {+ try {+ return await persistOutput(o, id);+ } 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));+ }+ }+}++/** Why an account's result couldn't be saved, in its words: too big, an expired link, or a GPU that stopped answering. */+function saveTrouble(e: unknown, provider: string): Diagnosis | undefined {+ const msg = (e as Error).message ?? "";+ if (msg === ACCOUNT_MESSAGES.diskLow) return undefined;+ // (An account's saved address is in scope for its runs on its keys too: only a run on its GPU was copied from there.)+ const link = provider === "comfyui" ? ownLink() : null;+ const over = /^The answer was over (.+)$/.exec(msg)?.[1];+ if (link) return diagnoseGpuJob({ kind: "save", ...(over && { over }) }, link);+ if (isCloudProvider(provider) && /^download (403|404|410)$/.test(msg)) return resultExpired();+ return 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> {+ /** Why the run failed, once it has: its files still waiting to be sent are not sent. */+ let failed: { error: unknown } | undefined;try {// An account's run on its own ComfyUI and keys only (asAccount): outside it, nothing is sent.const adapter = adapterFor(providerId, req.account);@@ -2100,24 +2441,22 @@ async function submitNow(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 ?? {}),+ 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,- message: "Queued",+ // 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);})();} catch (e) {failed ??= { error: e };- // A cancel during the hand-over stays a cancel. What the GPU was missing (a model, a node class) is kept, so the- // tile offers "Fix it", and the account's GPU check counts as stale.- const fix = (e as { fix?: GenerationFix }).fix;- if (statusOf(id) !== "canceled") update(id, { status: "failed", error: (e as Error).message, completed_at: Date.now(), message: null, ...(fix && { fix_json: JSON.stringify(fix) }) });- if (fix) markStale(req.account ? `acct:${req.account}` : "install");- } finally {- submitting().delete(id);+ throw e;}}@@ -2331,11 +2670,27 @@ async function pollOne(r: Row): Promise<void> {let res: PollResult | undefined;let pollError: unknown;const account = accountOf(r);+ // An account's own GPU or key (not this install's GPUs): its polls heal (healPoll), and its failures say what helps.+ const own = account && !poolOf(r) ? account : undefined;+ if (own && r.provider === "comfyui" && typeof ctx.meta.sentTo === "string") {+ // Sent to a link the account has since replaced with another: the new one knows nothing of it.+ 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);+ }+ }+ // A poll that failed a moment ago waits its turn (a growing wait), instead of asking every 1.5 s.+ const healing = own ? pollHeals().get(r.id) : undefined;+ if (healing && Date.now() < healing.next) return;try {res = await adapterFor(r.provider, account).poll(ctx);} catch (e) {pollError = e;}+ 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);// 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";@@ -2373,14 +2728,31 @@ async function pollOne(r: Row): Promise<void> {});return;}- if (!res) throw pollError;+ if (!res) {+ // An account's poll that healPoll took (waiting with a growing wait): nothing more to do this turn.+ if (own && pollHeals().has(r.id)) return;+ throw pollError;+ }if (startsNow) db().prepare("UPDATE generation_runs SET started_at = ? WHERE id = ?").run(Date.now(), r.id);update(r.id, { status: res.state, progress: res.progress ?? r.progress, message: res.message ?? null });return;}if (res.state === "failed") {+ // Its GPU restarted and lost the job: an account's run is sent again once, as a computer's tab does.+ if (own && res.lost && resend(r, own, RESENT_WORDS)) return;+ // An account's run: its own GPU's words (comfyui.ts), or its key's provider's read plainly; the provider's own words+ // go in the details line. The owner's runs keep the provider's words.+ const trouble =+ res.trouble ??+ (own && isCloudProvider(r.provider)+ ? diagnoseKey(+ { stage: "poll", failed: true, text: res.error, canceled: r.provider === "replicate" && /^(canceled|aborted)$/i.test(res.error.trim()) },+ { provider: r.provider, other: otherKeyFor(own, r.provider, r.model_id) },+ )+ : undefined);// What the GPU was missing (a model, a node class): the tile offers "Fix it", and the GPU's check counts as stale.- update(r.id, { status: "failed", error: res.error, completed_at: Date.now(), message: null, ...(res.fix && { fix_json: JSON.stringify(res.fix) }) });+ 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 (res.fix) markStale(account ? `acct:${account}` : "install");return;}@@ -2427,7 +2799,8 @@ async function pollOne(r: Row): Promise<void> {} else {for (const o of keepMatte(res.outputs as RichOutput[], matte)) {try {- outputs.push(await persistOutput(o, r.id));+ // 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)));} catch (e) {if (account) {for (const kept of outputs) if (kept.assetId) deleteAsset(kept.assetId);@@ -2436,8 +2809,11 @@ async function pollOne(r: Row): Promise<void> {const left = rest.url ? scratchOutputFile(rest.url) : null;if (left) fs.rmSync(left, { force: true });}- const why = e instanceof AccountFilesFull ? e.message : "We couldn't save this result. Press Retry.";- update(r.id, { status: "failed", error: why, completed_at: Date.now(), message: null });+ // 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 }) });return;}outputs.push({ url: o.url, kind: o.kind ?? r.kind, ...inlineText(o.text, o.meta), ...(o.draftId ? { draftId: o.draftId } : {}) });diff --git a/src/server/provider-keys.ts b/src/server/provider-keys.tsindex 7ee0a5e6..bcda584e 100644--- a/src/server/provider-keys.ts+++ b/src/server/provider-keys.ts@@ -53,10 +53,13 @@ export const balanceRefusal = (status: number, text: string): boolean => statusexport function accountKeyError(p: CloudProvider, status: number, text: string, used: string): ProviderError | undefined {const account = tenantAccount();if (!account) return undefined;- if (balanceRefusal(status, text)) return new ProviderError(balanceMessage(p), status);+ // `said`: the provider's own words (the key already taken out), for the run's details line and to tell a key refused+ // from a model the key may not run (src/lib/diagnose.ts).+ const said = (e: ProviderError) => Object.assign(e, { said: text });+ if (balanceRefusal(status, text)) return said(new ProviderError(balanceMessage(p), status));if (status === 401 || status === 403) {if (status === 401) markKeyRejected(account, p, used);- return new ProviderError(keyRejectedMessage(p), status);+ return said(new ProviderError(keyRejectedMessage(p), status));}return undefined;}diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex affbadae..5d04c8f9 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -104,7 +104,7 @@ import { probeAvi } from "../avi-probe";import { probeWebm } from "../webm-probe";import { adoptFile, contentTypeFor, readRef, saveFile, scratchDir } from "../storage";import { CONNECT_GPU_MESSAGE } from "@/lib/guest-access";-import { discardBody, fetchPublic, RemoteFetchError } from "../remote-fetch";+import { discardBody, fetchPublic, peekText, RemoteFetchError } from "../remote-fetch";import { zipToFile } from "../zip";import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "../account-files";import { accountSend } from "../account-send";@@ -112,6 +112,7 @@ 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";import { isOutOfMemory } from "@/lib/gpu/fix-codes";+import { diagnoseGpu, diagnoseGpuJob, diagnoseRefusal, type Diagnosis, type GpuFailure, type GpuStage } from "@/lib/diagnose";import { makingWords, META_BATCH_HISTORY, queueWords, RELAY_TIMES, RELAY_WORDS, savingWords, sendingWords, tabFailureWords, type HistoryEntryLike, type TabFailure, type WantedFile } from "@/lib/relay";import type { GenerationFix } from "@/lib/catalog/types";import {@@ -123,6 +124,7 @@ import {receivedFile,receivedOf,refusalOf,+ pairedRunner,requestStop,resultOf,runnerFacts,@@ -342,7 +344,49 @@ function authHeaders(worker: ComfyWorker = "main"): Record<string, string> {return t ? { Authorization: `Bearer ${t}` } : {};}-async function comfyFetch(p: string, init: RequestInit = {}, worker: ComfyWorker = "main"): Promise<Response> {+/** An account's saved address in scope (its own GPU at a web address), as diagnose.ts reads it; null anywhere else. */+export function ownLink(): { kind: "link"; url: string; hasToken: boolean } | null {+ const own = ownGpu();+ return own && own.kind !== "computer" && own.url ? { kind: "link", url: own.url, hasToken: !!own.token } : null;+}++/** Which step of a run asked the account's GPU, by path. */+const stageOf = (p: string): GpuStage => {+ const at = p.split("?")[0];+ return at.startsWith("/upload/") ? "upload" : at === "/prompt" ? "prompt" : at.startsWith("/view") ? "result" : at === "/system_stats" ? "status" : "poll";+};++/**+ * An account's GPU that didn't answer as ComfyUI: the run's error in plain words, with what helps (`trouble`), which the+ * runner keeps with the run (generations.ts) and uses to wait out a GPU that is off or starting up. `failure`: what came+ * back, so the status strip can say the same in its own words.+ */+export function troubleError(d: Diagnosis, status?: number, failure?: GpuFailure): ProviderError & { trouble: Diagnosis; failure?: GpuFailure } {+ return 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);++/** 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> {+ // The start of an error page only, briefly: a body that never ends can't hold the run (its connection is let go).+ const body = res.status >= 300 && res.status < 400 ? "" : await peekText(res);+ discardBody(res);+ return gpuTrouble(+ {+ ...f,+ status: res.status,+ body,+ contentType: res.headers.get("content-type") ?? undefined,+ location: res.headers.get("location") ?? undefined,+ retryAfterS: Number(res.headers.get("retry-after")) || undefined,+ },+ link,+ );+}++async function comfyFetch(p: string, init: RequestInit = {}, worker: ComfyWorker = "main", o: { bytes?: number } = {}): Promise<Response> {// A ComfyUI on someone's own computer is never called from here: not the install's, not a link (every caller in that// scope goes through its task instead; this is the last guard).if (computerScope()) throw new ProviderError(ON_COMPUTER_ONLY);@@ -351,9 +395,10 @@ 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: { ...authHeaders(worker), ...(init.headers ?? {}) } }, { timeoutMs: 120_000, ...ownGpuLimits(p) });+ return await fetchPublic(`${base}${p}`, { ...init, headers: { "ngrok-skip-browser-warning": "1", ...authHeaders(worker), ...(init.headers ?? {}) } }, { timeoutMs: 120_000, ...ownGpuLimits(p) });} catch (e) {- throw new ProviderError(`Can't reach your ComfyUI at ${base} (${(e as Error).message}). Is it running, and is its tunnel up?`);+ // 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 });}}if (worker === "isolated" && !base) {@@ -395,13 +440,18 @@ const reasonOf = (text: string) => (/^\s*</.test(text) ? "" : text.trim().slice(async function comfyJson<T>(p: string, worker: ComfyWorker = "main"): Promise<T> {const res = await comfyFetch(p, {}, worker);const path = p.split("?")[0];+ const link = ownLink();if (!res.ok) {+ // An account's link: what the answer means for the person (a stopped pod, a GPU starting up), not its status code.+ if (link) throw await linkAnswer(res, { stage: stageOf(p) }, link);discardBody(res);throw worker === "isolated" ? isolatedAnswer(path, res.status) : new ProviderError(`ComfyUI ${path} answered HTTP ${res.status}`, res.status);}+ const text = await res.text().catch(() => "");try {- return (await res.json()) as T;+ return JSON.parse(text) as T;} catch {+ if (link) throw gpuTrouble({ stage: stageOf(p), status: res.status, body: text.slice(0, 4096), contentType: res.headers.get("content-type") ?? undefined }, link);throw worker === "isolated" ? isolatedAnswer(path) : new ProviderError(`ComfyUI ${path} sent something that isn't JSON (a proxy error page?)`);}}@@ -2281,7 +2331,13 @@ export function latentGone(body: PromptRefusalBody, manifest: Pick<ManifestWorkf* A /prompt refusal in words, with what was missing as a code its failed tile turns into "Fix it" (the GPU pre-flight's* guided fix). The same for the server's own ComfyUI, a link, and one on someone's computer (its tab reports the answer).*/-export function promptRefusal(body: PromptRefusalBody, status: number, manifest: ManifestWorkflow, loras: { file: string; url?: string }[], worker: ComfyWorker = "main"): { message?: string; fix?: ReturnType<typeof fixFromPromptError> } {+export function promptRefusal(+ body: PromptRefusalBody,+ status: number,+ manifest: ManifestWorkflow,+ loras: { file: string; url?: string }[],+ worker: ComfyWorker = "main",+): { message?: string; fix?: ReturnType<typeof fixFromPromptError>; details?: string; plain?: true } {// The index names the pack a missing class comes from, so the message names that pack, not every pack the workflow uses.let packOf: (cls: string) => string | undefined = () => undefined;try {@@ -2309,13 +2365,27 @@ export function promptRefusal(body: PromptRefusalBody, status: number, manifest:: undefined;// A LoRA it lacks: point at its model card (a civitai download URL answers 401 without the key) and the LoRA folder setting.// A 2K finish whose draft's saved latent is gone (someone's computer: its tab reports the refusal): plain words, no file.- if (latentGone(body, manifest)) return { message: REGEN_COPY.latentGone };+ if (latentGone(body, manifest)) return { message: REGEN_COPY.latentGone, plain: true };const loraModels = loras.map((l) => ({ file: l.file, folder: "loras", url: loraByFile(l.file)?.page ?? (l.url && !needsToken(l.url) ? l.url : undefined) }));let detail = body.node_errors && Object.keys(body.node_errors as object).length ? explainComfyError(body.node_errors, { ...manifest, models: [...manifest.models, ...loraModels] }) : (missingPack ?? (typeof body.error?.message === "string" ? body.error.message.slice(0, 1024) : undefined));// (Settings → LoRAs is the owner's page, for the server's own ComfyUI: an account's, or one on a computer, gets its LoRAs by hand.)if (detail && !ownGpu() && !computerScope() && loraModels.some((l) => detail!.includes(`"${l.file}"`))) detail = `${detail}\nSet the LoRA folder in Settings → LoRAs and Fuobe downloads LoRAs before a run`;void status;- return { message: detail, ...(fix && { fix }) };+ // An account's own GPU (a link or this computer): what is missing in plain words, with "Fix it"; ComfyUI's own words+ // (and the file's folder and download) go in the details line.+ if (ownGpu() && fix && (fix.code === "comfy_missing_node" || fix.code === "comfy_missing_model") && missingPack !== REGEN_COPY.missingVisitor && missingPack !== RTX_MISSING.visitor) {+ const first = fix.items[0];+ const name = fix.code === "comfy_missing_node" ? (first?.pack ?? first?.class) : first?.file;+ if (name) {+ const words =+ fix.code === "comfy_missing_node"+ ? `Your ComfyUI needs one add-on for this: ${name}. Press Fix it to add it.`+ : `Your ComfyUI needs one more file for this: ${name}. Press Fix it to see how to add it.`;+ return { message: words, fix, plain: true, ...(detail && detail !== words && { details: detail.replace(/\s*\(see scripts\/comfy\/README\.md\)/, "") }) };+ }+ }+ const plain = !!detail && (detail === REGEN_COPY.missingVisitor || detail === RTX_MISSING.visitor);+ return { message: detail, ...(fix && { fix }), ...(plain && { plain: true as const }) };}/** The NVIDIA RTX Video graphs (their pack is installed only on an NVIDIA RTX host). */@@ -2447,7 +2517,10 @@ async function uploadTo(worker: ComfyWorker, data: Buffer, contentType: string,form.append("image", new Blob([new Uint8Array(data)], { type: contentType }), `fuobe_${nanoid(8)}.${ext}`);form.append("type", "input");form.append("overwrite", "true");- const res = await comfyFetch("/upload/image", { method: "POST", body: form }, worker);+ const res = await comfyFetch("/upload/image", { method: "POST", body: form }, worker, { bytes: data.length });+ // An account's link: its answer read for the person (a stopped pod, the address's own size limit…).+ const link = ownLink();+ if (link && !res.ok) throw await linkAnswer(res, { stage: "upload", bytes: data.length }, link);if (res.status === 413) {discardBody(res);// ComfyUI's own limit (--max-upload-size, 100 MB unless it was started with more).@@ -2458,7 +2531,16 @@ async function uploadTo(worker: ComfyWorker, data: Buffer, contentType: string,const text = (await res.text().catch(() => "")).slice(0, 500);throw worker === "isolated" ? isolatedAnswer("an upload", res.status, reasonOf(text)) : new ProviderError(`ComfyUI upload failed: ${res.status} ${text}`);}- const j = (await res.json()) as { name: string; subfolder?: string };+ let j: { name: string; subfolder?: string };+ if (link) {+ // A web page instead of ComfyUI's answer (a proxy's or a tunnel's page): said as such, never a parser's words.+ const text = await res.text().catch(() => "");+ try {+ j = JSON.parse(text);+ } catch {+ throw gpuTrouble({ stage: "upload", status: res.status, body: text.slice(0, 4096), contentType: res.headers.get("content-type") ?? undefined }, link);+ }+ } else j = (await res.json()) as { name: string; subfolder?: string };const uploaded = j.subfolder ? `${j.subfolder}/${j.name}` : j.name;// Remember a clip's / track's header facts (length, size, fps, audio) for prepareWorkflow.rememberSent(uploaded, data, contentType, name);@@ -2616,16 +2698,27 @@ async function pollComputer(principal: Principal, meta: Record<string, unknown>,// Sent, and the computer's tab stopped answering (closed, asleep): not a run that looks alive for half an hour.const r = t.state === "waiting" || t.pools ? null : runnerFacts(principal);const away = !t.pools && t.state !== "waiting" && (!r || Date.now() - r.seenAt >= RELAY_TIMES.onlineMs);- const down = t.down_at ? (t.down_why === "setting" ? RELAY_WORDS.comfyNoSetting : RELAY_WORDS.comfyDown) : away ? RELAY_WORDS.computerAway : undefined;+ // A ComfyUI paired with a code runs the jobs itself (no Fuobe tab): one that is off is waited for in its own words.+ const paired = !t.pools && pairedRunner(principal);+ const down = t.down_at ? (t.down_why === "setting" ? RELAY_WORDS.comfyNoSetting : RELAY_WORDS.comfyDown) : away ? (paired ? RELAY_WORDS.pairedAway : RELAY_WORDS.computerAway) : undefined;+ const waitedTooLong = paired ? RELAY_WORDS.pairedWaitedTooLong(waitMs) : RELAY_WORDS.waitedTooLong(waitMs);switch (t.state) {case "waiting": {// The computer's tab is open, but its ComfyUI is closed or runs without Fuobe's setting: say that, not "open Fuobe".const f = runnerFacts(principal);- const message = f?.online ? RELAY_WORDS.starting : f?.comfy === "no-setting" ? RELAY_WORDS.comfyNoSetting : f?.comfy === "down" ? RELAY_WORDS.comfyDown : RELAY_WORDS.noComputer;- return { state: "queued", message, timeoutError: RELAY_WORDS.waitedTooLong(waitMs) };+ const message = f?.online+ ? RELAY_WORDS.starting+ : f?.comfy === "no-setting"+ ? RELAY_WORDS.comfyNoSetting+ : f?.comfy === "down"+ ? RELAY_WORDS.comfyDown+ : paired+ ? RELAY_WORDS.pairedAway+ : RELAY_WORDS.noComputer;+ return { state: "queued", message, timeoutError: waitedTooLong };}case "sending":- return { state: "queued", message: down ?? (t.note === "resent" ? RELAY_WORDS.resent : sendingWords(inputKinds(t))), timeoutError: RELAY_WORDS.waitedTooLong(waitMs), ...(sentAt && { sentAt }) };+ return { state: "queued", message: down ?? (t.note === "resent" ? RELAY_WORDS.resent : sendingWords(inputKinds(t))), timeoutError: waitedTooLong, ...(sentAt && { sentAt }) };case "queued":return { state: "queued", message: down ?? queueWords(p?.position), ...(sentAt && { sentAt }) };case "running": {@@ -2742,7 +2835,11 @@ export const comfyProvider: ProviderAdapter = {},worker,);- const body = (await res.json().catch(() => ({}))) as PromptRefusalBody & { prompt_id?: string };+ const answer = await res.text().catch(() => "");+ let body: PromptRefusalBody & { prompt_id?: string } = {};+ try {+ body = (JSON.parse(answer) ?? {}) as typeof body;+ } catch {}// A 2K finish whose draft's latent isn't on this ComfyUI any more (its output folder was cleaned): the draft's clip,// chained into the same run, is redrawn instead.if (!res.ok && latentGone(body, manifest) && typeof input.extra?.latentFrom === "string") {@@ -2755,6 +2852,16 @@ export const comfyProvider: ProviderAdapter = {if (manifest.id === IDOL_WORKFLOWS.clean || manifest.id === IDOL_VIEWS_WORKFLOW) forgetComfyClass(IDOL_PACK_CLASS, worker);const refusal = promptRefusal(body, res.status, manifest, input.loras ?? [], worker);if (!refusal.message && !res.ok && worker === "isolated") throw isolatedAnswer("the prompt", res.status);+ // An account's link: no words from ComfyUI (a stopped pod's or a proxy's page) is read for what it means; ComfyUI's+ // own refusal is said plainly, its words in the details line.+ const link = ownLink();+ if (link) {+ if (!refusal.message) throw gpuTrouble({ stage: "prompt", status: res.status, body: answer.slice(0, 4096), contentType: res.headers.get("content-type") ?? undefined }, link);+ const d: Diagnosis = refusal.plain+ ? { cause: "gpu-refused", words: refusal.message, ...(refusal.details && { details: refusal.details }), actions: [{ kind: "retry", label: "Retry" }], retryable: false }+ : diagnoseRefusal(refusal.message);+ throw Object.assign(troubleError(d, res.status), refusal.fix ? { fix: refusal.fix } : {});+ }throw Object.assign(new ProviderError(refusal.message ?? `ComfyUI /prompt failed (${res.status})`, res.status), refusal.fix ? { fix: refusal.fix } : {});}if (!PROMPT_ID.test(body.prompt_id)) {@@ -2784,6 +2891,19 @@ export const comfyProvider: ProviderAdapter = {if (manifest && CONTEXT_LOOP_IDS.has(manifest.id) && typeof meta.generationId === "string") void deleteRunFolder(runName(meta.generationId), worker);if (entry.status?.status_str === "error") {forget(externalId);+ const link = ownLink();+ if (link) {+ // An account's link: stopped there, out of memory, or an add-on's exception, said plainly (its words go in details).+ const err = executionError(entry);+ const said = explainExecutionError(err, manifest);+ const interrupted = !err && entry.status?.messages?.some(([type]) => type === "execution_interrupted");+ const d = interrupted+ ? diagnoseGpuJob({ kind: "interrupted" }, link)+ : err && said !== `${err.node_type}: ${(err.exception_message ?? "").trim()}`+ ? { cause: "gpu-job-error" as const, words: said, actions: [{ kind: "retry" as const, label: "Retry" }], retryable: false }+ : diagnoseGpuJob({ kind: "error", nodeType: err?.node_type, message: err?.exception_message }, link);+ return { state: "failed" as const, error: d.words, trouble: d };+ }return { state: "failed" as const, error: explainExecutionError(executionError(entry), manifest) };}let outputs = collectOutputs(entry, manifest, baseUrl(worker), authHeaders(worker));@@ -2827,8 +2947,14 @@ export const comfyProvider: ProviderAdapter = {const misses = globalThis.__fuobeComfyMisses ?? (globalThis.__fuobeComfyMisses = new Map());const n = (misses.get(externalId) ?? 0) + 1;misses.set(externalId, n);- if (n < 3) return { state: "running", message: "Checking on ComfyUI" };+ const link = ownLink();+ if (n < 3) return { state: "running", message: link ? "Checking on your GPU" : "Checking on ComfyUI" };forget(externalId);+ // An account's link: the runner may send it once more (generations.ts), as a computer's tab does.+ if (link) {+ const d = diagnoseGpuJob({ kind: "lost" }, link);+ return { state: "failed", error: d.words, trouble: d, lost: true };+ }return { state: "failed", error: "ComfyUI restarted and lost this run. Press Retry." };}globalThis.__fuobeComfyMisses?.delete(externalId);diff --git a/src/server/providers/fal.ts b/src/server/providers/fal.tsindex deddd1b4..828771f7 100644--- a/src/server/providers/fal.ts+++ b/src/server/providers/fal.ts@@ -326,6 +326,11 @@ export const falProvider: ProviderAdapter = {const draftId = /"draft_id"\s*:\s*"([^"]+)"/.exec(JSON.stringify(result))?.[1];return { state: "succeeded", outputs: draftId ? outputs.map((o) => ({ ...o, draftId })) : outputs };} catch (e) {+ // An account's finished (and paid) job isn't failed for a passing problem collecting it (busy, down, no answer):+ // the runner asks again with a growing wait (generations.ts healPoll).+ 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;return { state: "failed", error: (e as Error).message };}}diff --git a/src/server/providers/types.ts b/src/server/providers/types.tsindex 3cde0f8e..0568e529 100644--- a/src/server/providers/types.ts+++ b/src/server/providers/types.ts@@ -1,4 +1,5 @@import type { GenerationFix, GenInput, MediaKind, ModelDef, ModelRoute, ProviderId } from "@/lib/catalog/types";+import type { Diagnosis } from "@/lib/diagnose";export interface SubmitContext {generationId: string;@@ -37,7 +38,11 @@ export type PollResult =| { state: "queued"; progress?: number; message?: string; sentAt?: number; timeoutError?: string }| { state: "running"; progress?: number; message?: string; sentAt?: number }| { state: "succeeded"; outputs: RemoteOutput[]; message?: string }- | { state: "failed"; error: string; fix?: GenerationFix };+ /**+ * `trouble`: an account's own GPU, why in plain words with what helps (src/lib/diagnose.ts). `lost`: its ComfyUI+ * restarted and forgot the job, so the runner may send it once more.+ */+ | { state: "failed"; error: string; fix?: GenerationFix; trouble?: Diagnosis; lost?: true };export interface PollContext {externalId: string;diff --git a/tests/account-review-fixes.test.ts b/tests/account-review-fixes.test.tsindex 3aa56887..d4ef41b6 100644--- a/tests/account-review-fixes.test.ts+++ b/tests/account-review-fixes.test.ts@@ -260,7 +260,8 @@ describe("an answer that won't be read lets its connection go", () => {auth.setAccountGpu(a, { url: `http://127.0.0.1:${port}` });const own = accountRun(a, "comfyui");if (!("run" in own)) throw new Error(own.error);- await expect(own.run(() => comfyProvider.poll({ externalId: "abc", meta: {} } as never))).rejects.toThrow(/HTTP 500/);+ // In the account's words, the answer's status in the details line.+ await expect(own.run(() => comfyProvider.poll({ externalId: "abc", meta: {} } as never))).rejects.toMatchObject({ message: expect.stringMatching(/couldn't take this run/), trouble: { details: expect.stringMatching(/HTTP 500/) } });await new Promise((r) => setTimeout(r, 300));expect(closed).toBe(2);} finally {@@ -367,7 +368,8 @@ describe("one slow account can't hold every file send", () => {expect(r.status, await r.clone().text()).toBe(201);const g = await settle((await r.json()).items[0].id);expect(g?.status).toBe("failed");- expect(g?.error).toMatch(/upload/i);+ expect(g?.error).toMatch(/couldn't take this run/);+ expect(g?.trouble?.details).toMatch(/upload/i);expect(fake.log.filter((e) => e.path === "/upload/image")).toHaveLength(1);expect(accountSends()).toMatchObject({ total: 0, waiting: [] });});diff --git a/tests/account-tools.test.ts b/tests/account-tools.test.tsindex 0c0b51b2..bfeea059 100644--- a/tests/account-tools.test.ts+++ b/tests/account-tools.test.ts@@ -235,7 +235,8 @@ describe("an account's ComfyUI can't hold up the server", () => {const id = (await r.json()).items[0].id as string;const g = await settle(id);expect(g?.status).toBe("failed");- expect(g?.error).toMatch(/couldn't save this result/);+ // Said as what it is: a file over what a run on your GPU keeps.+ expect(g?.error).toBe("Your ComfyUI made a file over 2 MB. Try a shorter clip or a lower size.");expect(fs.readdirSync(scratchDir()).filter((f) => f.startsWith(`${id}-out-`))).toEqual([]);} finally {OWN_OUTPUT_LIMITS.maxBytes = was;diff --git a/tests/computer-relay.test.ts b/tests/computer-relay.test.tsindex 94a37136..a63b4bae 100644--- a/tests/computer-relay.test.ts+++ b/tests/computer-relay.test.ts@@ -164,6 +164,20 @@ describe("a run on the ComfyUI on the person's own computer", () => {expect(t.runner.view.jobs.find((j) => j.generationId === id)?.phase).toBe("done");});+ it("a ComfyUI paired with a code that is off: the run waits in words for that ComfyUI, not for a browser tab", async () => {+ expect((await gpuRoute.PUT(json("/api/account/gpu", "PUT", { mode: "computer" }))).status).toBe(200);+ // Its paired ComfyUI (Fuobe Connect, device "connect-…") beat a while ago, then went quiet: its pod stopped.+ db()+ .prepare("INSERT INTO relay_runners (principal, device, lease_until, seen_at, port, facts_json, comfy) VALUES (?, ?, ?, ?, NULL, '{}', 'ok')")+ .run(`acct:${a}`, "connect-pod-1", 0, Date.now() - 10 * 60_000);+ const pic = await uploadPng();+ const [id] = await run({ feature: "app", modelId: "oss-qwen-edit", presetId: "app-headshot-generator", prompt: "", inputs: { images: [pic.url] } });+ await handedOver(id);+ expect(getGeneration(id)).toMatchObject({ status: "queued", message: RELAY_WORDS.pairedAway });+ expect(RELAY_WORDS.pairedAway).not.toMatch(/Open Fuobe/);+ expect(RELAY_WORDS.pairedWaitedTooLong(30 * 60_000)).toBe("Your paired ComfyUI didn't come online for 30 minutes. Start it, then press Retry.");+ });+it("explains a refusal for a missing model or node with the guided fix, and running out of memory in plain words", async () => {const t = tab(routes, cookie, fake.port);await t.runner.beat();diff --git a/tests/helpers/fake-cloud.ts b/tests/helpers/fake-cloud.tsindex d1c5389f..5eb88273 100644--- a/tests/helpers/fake-cloud.ts+++ b/tests/helpers/fake-cloud.ts@@ -31,6 +31,11 @@ export interface FakeCloud {holdSubmits: Promise<void> | null;/** The jobs it was asked to cancel. */canceled: string[];+ /**+ * Answers a request before anything else when it returns one (busy, down, a model it doesn't have, an input it+ * 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;close(): Promise<void>;}@@ -44,13 +49,18 @@ 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: [] } as unknown as FakeCloud;+ const fake = { log: [], keys: {}, pollsToFinish: 2, holdSubmits: null, canceled: [], script: 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);+ const said = fake.script?.(r);+ if (said) {+ res.writeHead(said.status, { "Content-Type": "application/json", ...said.headers });+ return res.end(typeof said.body === "string" ? said.body : JSON.stringify(said.body ?? {}));+ }const m = new RegExp(`^${scheme} (.+)$`).exec(r.authorization ?? "");Promise.resolve(handle(fake, r, res, m ? m[1] : null)).catch((e) => json(res, 500, { detail: String(e) }));});diff --git a/tests/helpers/fake-comfy-runner.ts b/tests/helpers/fake-comfy-runner.tsindex 4c25f71c..68850a25 100644--- a/tests/helpers/fake-comfy-runner.ts+++ b/tests/helpers/fake-comfy-runner.ts@@ -49,6 +49,11 @@ export interface FakeComfyOptions {graph?: boolean;/** Every job answers a clip, a picture, a sound (a WAV) and a text (`text`, or "Done."): a chained tool's steps each take their kind. */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.+ */+ answer?: (method: string, path: string) => { status: number; body?: string; contentType?: string } | undefined;}/** A tiny but real WAV (mono, 16-bit, 8 kHz, 0.1 s of silence). */@@ -199,6 +204,11 @@ export function startFakeComfy(opts: FakeComfyOptions = {}, port = 0): Promise<Fres.end(JSON.stringify(value));};const p = url.pathname;+ const said = opts.answer?.(entry.method, p);+ if (said) {+ res.writeHead(said.status, { "content-type": said.contentType ?? "text/html" });+ 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 }] });if (p === "/models/loras") return json(200, opts.loras ?? []);if (p === "/object_info") return json(200, {});diff --git a/tests/own-gpu-graceful.test.ts b/tests/own-gpu-graceful.test.tsnew file mode 100644index 00000000..f6a9f6f5--- /dev/null+++ b/tests/own-gpu-graceful.test.ts@@ -0,0 +1,351 @@+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";+import http from "node:http";+import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";++/**+ * An account's own GPU at a web address that has a problem: Settings' Test and Check my GPU say what is wrong in plain+ * words with what helps; a run waits out a GPU that is off or starting up, asks it once more before it fails, and fails+ * in plain words with its buttons; a run its GPU lost is sent again once; a run whose account moved to another address+ * 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.+ */+const dir = tempDir("fuobe-own-gpu-graceful-");+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";+process.env.FUOBE_PUBLIC_SIGNUP = "1";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_ALLOW_PRIVATE_URLS;+globalThis.__fuobeTestDiskFree = 1e13;++// Plain fetch is the install's own ComfyUI: an account's runs never reach it.+const realFetch = globalThis.fetch;+const fetched: string[] = [];+globalThis.fetch = (async (input: RequestInfo | URL) => {+ fetched.push(String(input instanceof Request ? input.url : input));+ return new Response("not stubbed", { status: 599 });+}) as typeof fetch;++const auth = await import("@/server/auth");+const generationsRoute = await import("@/app/api/generations/route");+const uploadsRoute = await import("@/app/api/uploads/route");+const gpuRoute = await import("@/app/api/account/gpu/route");+const { getGeneration, SELF_HEAL } = await import("@/server/generations");+const { cleanGpuAddress, checkGpuAddress, visitorStatus } = await import("@/server/account-gpu");+const { comfyProvider, onOwnGpu } = await import("@/server/providers/comfyui");+const { db } = await import("@/server/db");+const { resetRates } = await import("@/server/rate");+const { runAsTenant } = await import("@/server/tenant");+const { ISOLATED_ON_GPU } = await import("@/lib/diagnose");++let fake: FakeComfy;+let a = "";+let cookie = "";+beforeAll(async () => {+ fake = await startFakeComfy({ loras: [], delayMs: 0 });+ globalThis.__fuobeTestGpuPort = fake.port;+ auth.setPassword("install password");+ a = auth.createAccount("[email protected]", "long enough").id;+ cookie = `${auth.SESSION_COOKIE}=${auth.createSession(a).value}`;+});+afterAll(async () => {+ globalThis.fetch = realFetch;+ globalThis.__fuobeTestGpuPort = undefined;+ globalThis.__fuobeTestDiskFree = undefined;+ SELF_HEAL.scale = 1;+ await fake.close();+});+beforeEach(() => {+ resetRates();+ SELF_HEAL.scale = 0.001;+ Object.assign(fake.opts, { loras: [], delayMs: 0, answer: undefined });+ fake.log.length = 0;+ auth.setAccountGpu(a, { url: fake.url });+ globalThis.__fuobeAccountGpus?.clear();+ globalThis.__fuobePollHeals?.clear();+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();+});++const headers = (extra: Record<string, string> = {}) => ({ cookie, host: "localhost:3000", ...extra });+const json = (url: string, method: string, body: unknown) => {+ const text = JSON.stringify(body);+ return new Request(`http://localhost:3000${url}`, { method, headers: headers({ "content-type": "application/json", "content-length": String(Buffer.byteLength(text)) }), body: text });+};+const put = async (body: unknown, test = true) => {+ const r = await gpuRoute.PUT(json(`/api/account/gpu${test ? "?test=1" : ""}`, "PUT", body));+ return { status: r.status, body: (await r.json()) as { error?: string; trouble?: { cause: string; words: string; details?: string; actions: { kind: string }[]; retryable: boolean }; note?: string; url?: string; offline?: true; gpu?: { url: string } }, headers: r.headers };+};+const html = (status: number, title = "Bad gateway") => ({ status, body: `<!DOCTYPE html><html><head><title>${title}</title></head><body>…</body></html>`, contentType: "text/html" });++async function uploadPng(): Promise<string> {+ const r = await uploadsRoute.POST(new Request("http://localhost:3000/api/uploads", { method: "POST", headers: headers({ "content-type": "image/png", "x-file-name": "me.png", "content-length": String(TINY_PNG.length) }), body: TINY_PNG }));+ expect(r.status).toBe(201);+ return ((await r.json()) as { url: string }).url;+}+async function startRun(): Promise<string> {+ 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] } }));+ expect(r.status, await r.clone().text()).toBe(201);+ return ((await r.json()) as { items: { id: string }[] }).items[0].id;+}+/** Tick the runner until the row is done (or the time is up), noting every message the tile showed on the way. */+async function settle(id: string, ms = 15_000, seen: string[] = []) {+ const end = Date.now() + ms;+ for (;;) {+ await globalThis.__fuobeRunner?.tick();+ const g = getGeneration(id, { includeDeleted: true });+ if (g?.message && seen.at(-1) !== g.message) seen.push(g.message);+ if (!g || (g.status !== "queued" && g.status !== "running") || Date.now() > end) return g;+ await new Promise((r) => setTimeout(r, 15));+ }+}+const kinds = (t: { actions: { kind: string }[] } | undefined) => (t?.actions ?? []).map((x) => x.kind);+/** No status code, program words, HTML or an address in what the person reads first. */+const plainWords = (s: string | null | undefined) => {+ expect(s).toBeTruthy();+ expect(s).not.toMatch(/HTTP|\b[1-5]\d\d\b|upload failed|\/prompt|<html|<!DOCTYPE|127\.0\.0\.1|ECONN|isn't JSON/);+};++describe("Settings → Your GPU: Test says what is wrong, in plain words, with what helps", () => {+ it("a GPU starting up (502), a password (401), a web page and another app's 404", async () => {+ fake.opts.answer = (_m, p) => (p === "/system_stats" ? html(502) : undefined);+ const starting = await put({ url: fake.url });+ expect(starting.status).toBe(422);+ expect(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`);+ plainWords(starting.body.error);+ // Today's wrong advice is gone.+ expect(starting.body.error).not.toMatch(/isn't a ComfyUI/);++ fake.opts.answer = (_m, p) => (p === "/system_stats" ? { status: 401, body: "" } : undefined);+ expect((await put({ url: fake.url })).body.trouble).toMatchObject({ cause: "gpu-password", words: "Your GPU asks for a password. Paste it in Access token." });+ expect((await put({ url: fake.url, token: "wrong" })).body.trouble).toMatchObject({ cause: "gpu-password-wrong" });++ fake.opts.answer = (_m, p) => (p === "/system_stats" ? html(200, "Jupyter") : undefined);+ expect((await put({ url: fake.url })).body.trouble).toMatchObject({ cause: "gpu-not-comfy", retryable: false });+ fake.opts.answer = (_m, p) => (p === "/system_stats" ? { status: 404, body: "not found", contentType: "text/plain" } : undefined);+ expect((await put({ url: fake.url })).body.trouble).toMatchObject({ cause: "gpu-not-comfy" });+ });++ it("a GPU that doesn't answer at all", async () => {+ // A port with nothing behind it (the stand-in's port is the one an account may use on this machine).+ const idle = http.createServer();+ await new Promise<void>((r) => idle.listen(0, "127.0.0.1", () => r()));+ const port = (idle.address() as { port: number }).port;+ await new Promise<void>((r) => idle.close(() => r()));+ globalThis.__fuobeTestGpuPort = port;+ try {+ const r = await put({ url: `http://127.0.0.1:${port}` });+ expect(r.status).toBe(422);+ expect(r.body.trouble).toMatchObject({ cause: "gpu-offline", retryable: true });+ expect(r.body.error).toMatch(/^Your GPU didn't answer\./);+ expect(r.body.trouble!.details).toMatch(/ECONNREFUSED/);+ plainWords(r.body.error);+ } finally {+ globalThis.__fuobeTestGpuPort = fake.port;+ }+ });++ it("makes a pasted address whole: https:// added, a ? or # part left out, a password refused", async () => {+ const pod = cleanGpuAddress(" abc123xyz-8188.proxy.runpod.net ");+ expect(pod.url.href).toBe("https://abc123xyz-8188.proxy.runpod.net/");+ expect(pod.fixed).toEqual(["scheme"]);+ const fixed: ("scheme" | "query")[] = [];+ expect(await checkGpuAddress("abc123xyz-8188.proxy.runpod.net/?token=x#queue", { resolve: async () => ["93.184.216.34"], fixed })).toBe("https://abc123xyz-8188.proxy.runpod.net");+ expect(fixed).toEqual(["scheme", "query"]);+ // Through the route: the address back as it was checked, and the note under the field.+ const r = await put({ url: `${fake.url}/?view=queue#x` });+ expect(r.status).toBe(200);+ expect(r.body).toMatchObject({ note: "We kept only the address part.", url: fake.url });+ const pw = await put({ url: "https://me:[email protected]" });+ expect(pw.status).toBe(422);+ expect(pw.body.trouble).toMatchObject({ cause: "address-credentials", words: "A password goes in the Access token box, not in the address." });+ });++ 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 });+ expect(last!.status).toBe(429);+ expect(last!.body.trouble).toMatchObject({ cause: "checks-too-fast", words: "Checking again in a few seconds.", retryable: true });+ expect(Number(last!.headers.get("retry-after"))).toBeGreaterThan(0);+ });++ it("Check my GPU asks the saved address again, and the status strip shows why it is offline without asking again", async () => {+ fake.opts.answer = (_m, p) => (p === "/system_stats" ? html(503, "Service unavailable") : undefined);+ const r = await put({ saved: true });+ expect(r.status).toBe(422);+ expect(r.body.trouble?.cause).toBe("gpu-starting");+ const asked = fake.log.filter((e) => e.path === "/system_stats").length;+ const s = await visitorStatus(auth.accountById(a)!);+ expect(s.viewer.gpu).toMatchObject({ connected: true, mode: "link", online: false, host: "web", trouble: { cause: "gpu-starting", retryable: true } });+ expect(s.viewer.gpu.trouble!.actions.map((x) => x.kind)).toContain("check-gpu");+ // The composer's check before Run reads this answer: nothing more was asked of the GPU.+ expect(fake.log.filter((e) => e.path === "/system_stats").length).toBe(asked);+ fake.opts.answer = undefined;+ expect((await put({ saved: true })).status).toBe(200);+ expect((await visitorStatus(auth.accountById(a)!)).viewer.gpu).toMatchObject({ online: true });+ });++ it("Save anyway keeps the address of a GPU that is off right now; an address that can't work can't be kept", async () => {+ auth.setAccountGpu(a, null);+ fake.opts.answer = (_m, p) => (p === "/system_stats" ? html(502) : undefined);+ const plainConnect = await put({ url: fake.url }, false);+ expect(plainConnect.status).toBe(422);+ expect(auth.accountGpu(a)).toBeNull();+ const kept = await put({ url: fake.url, anyway: true }, false);+ expect(kept.status).toBe(200);+ expect(kept.body).toMatchObject({ offline: true, gpu: { url: fake.url }, trouble: { cause: "gpu-starting" } });+ expect(auth.accountGpu(a)).toEqual({ url: fake.url });+ fake.opts.answer = (_m, p) => (p === "/system_stats" ? { status: 401, body: "" } : undefined);+ auth.setAccountGpu(a, null);+ expect((await put({ url: fake.url, anyway: true }, false)).status).toBe(422);+ expect(auth.accountGpu(a)).toBeNull();+ });+});++describe("a run on an account's own GPU heals itself, or fails in plain words with what helps", () => {+ it("waits while its GPU starts up, saying so, then runs", async () => {+ SELF_HEAL.scale = 0.01;+ let refused = 0;+ fake.opts.answer = (m, p) => (p === "/upload/image" && m === "POST" && refused++ < 2 ? html(502) : undefined);+ const id = await startRun();+ const seen: string[] = [];+ const g = await settle(id, 20_000, seen);+ expect(g?.status, g?.error ?? "").toBe("succeeded");+ expect(seen).toContain("Waiting for your GPU to start up");+ expect(fake.log.filter((e) => e.path === "/upload/image").length).toBeGreaterThanOrEqual(3);+ });++ it("asks its GPU once more before it fails, then says why in plain words, with its buttons and the details", async () => {+ fake.opts.answer = (_m, p) => (p === "/upload/image" || p === "/system_stats" ? html(502) : undefined);+ const id = await startRun();+ const g = await settle(id);+ expect(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(kinds(g?.trouble)).toEqual(expect.arrayContaining(["retry", "check-gpu", "gpu-settings"]));+ // Tried several times, then asked once more (/system_stats) before failing.+ const paths = fake.log.map((e) => e.path);+ expect(paths.filter((p) => p === "/upload/image").length).toBeGreaterThan(1);+ 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 () => {+ SELF_HEAL.scale = 0.01;+ fake.opts.answer = (_m, p) => (p === "/upload/image" ? 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 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` });+ 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.");+ });++ it("never waits out what waiting can't fix: a password, a web page instead of ComfyUI", async () => {+ fake.opts.answer = (_m, p) => (p === "/upload/image" ? { status: 401, body: "" } : undefined);+ const id = await startRun();+ const g = await settle(id);+ expect(g?.status).toBe("failed");+ expect(g?.trouble?.cause).toBe("gpu-password");+ expect(g?.error).toMatch(/asks for a password/);+ expect(fake.log.filter((e) => e.path === "/upload/image")).toHaveLength(1);++ fake.log.length = 0;+ fake.opts.answer = (_m, p) => (p === "/upload/image" ? html(200, "Sign in") : undefined);+ const page = await settle(await startRun());+ expect(page?.trouble?.cause).toBe("gpu-not-comfy");+ plainWords(page?.error);+ expect(fake.log.filter((e) => e.path === "/upload/image")).toHaveLength(1);+ });++ it("a GPU known to be off from its last status check waits at once, without sending files to it", async () => {+ SELF_HEAL.scale = 0.01;+ fake.opts.answer = (_m, p) => (p === "/system_stats" ? html(502) : undefined);+ expect((await put({ saved: true })).status).toBe(422);+ fake.log.length = 0;+ fake.opts.answer = undefined;+ const seen: string[] = [];+ const g = await settle(await startRun(), 20_000, seen);+ expect(g?.status).toBe("succeeded");+ expect(seen).toContain("Waiting for your GPU to start up");+ });++ it("its GPU going away mid-run: the tile says it waits, then the run stops in plain words", async () => {+ fake.opts.delayMs = 60_000;+ const id = await startRun();+ // Handed over: the job is on the GPU.+ for (let i = 0; i < 300 && !db().prepare("SELECT external_id FROM generations WHERE id = ?").pluck().get(id); i++) await new Promise((r) => setTimeout(r, 10));+ fake.opts.answer = () => html(502);+ const seen: string[] = [];+ const g = await settle(id, 20_000, seen);+ expect(seen).toContain("Your GPU stopped answering. Waiting for it to come back");+ expect(g?.status).toBe("failed");+ expect(g?.error).toBe("Your GPU stopped answering for 1 minute, so this run stopped. Start it again, then press Retry.");+ expect(kinds(g?.trouble)).toEqual(expect.arrayContaining(["retry", "check-gpu"]));+ });++ it("a run its GPU lost (ComfyUI restarted) is sent again once, and finishes", async () => {+ let prompts = 0;+ fake.opts.answer = (m, p) => {+ if (p === "/prompt" && m === "POST") {+ prompts++;+ return undefined;+ }+ // Until it is sent again: a ComfyUI that forgot everything.+ if (prompts < 2 && p === "/queue" && m === "GET") return { status: 200, body: JSON.stringify({ queue_running: [], queue_pending: [] }), contentType: "application/json" };+ if (prompts < 2 && p.startsWith("/history/")) return { status: 200, body: "{}", contentType: "application/json" };+ return undefined;+ };+ const seen: string[] = [];+ const g = await settle(await startRun(), 20_000, seen);+ expect(g?.status, g?.error ?? "").toBe("succeeded");+ expect(prompts).toBe(2);+ expect(seen).toContain("Your GPU restarted, so we sent this run again");+ });++ it("a run whose account moved to another address says so", async () => {+ fake.opts.delayMs = 60_000;+ const id = await startRun();+ for (let i = 0; i < 300 && !db().prepare("SELECT external_id FROM generations WHERE id = ?").pluck().get(id); i++) await new Promise((r) => setTimeout(r, 10));+ auth.setAccountGpu(a, { url: `${fake.url}/elsewhere` });+ 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.");+ });++ it("a graph that needs a second ComfyUI is refused before anything is sent", async () => {+ const r = await generationsRoute.POST(json("/api/generations", "POST", { feature: "audio", modelId: "oss-thinksound", prompt: "a door slams" }));+ expect(r.status).toBe(422);+ expect(((await r.json()) as { error: string }).error).toBe(ISOLATED_ON_GPU);+ });++ it("the owner's runs, and runs off an account's own GPU, keep their own detail", async () => {+ // The owner's ComfyUI (plain fetch): ComfyUI's own words as before.+ globalThis.fetch = (async (input: RequestInfo | URL) => {+ const url = String(input instanceof Request ? input.url : input);+ return url.endsWith("/upload/image") ? new Response("nope", { status: 500 }) : new Response("{}", { status: 200 });+ }) as typeof fetch;+ try {+ await expect(comfyProvider.prepareFile(Buffer.from("png"), "image/png", "a.png")).rejects.toThrow(/^ComfyUI upload failed: 500 nope$/);+ // An account's run on this install's GPUs (hosted runs: its tenant, not its own GPU) is the install's as well.+ await expect(runAsTenant({ kind: "account", id: a }, () => comfyProvider.prepareFile(Buffer.from("png"), "image/png", "a.png"))).rejects.toThrow(/^ComfyUI upload failed: 500 nope$/);+ } finally {+ globalThis.fetch = (async () => new Response("not stubbed", { status: 599 })) as typeof fetch;+ }+ // On the account's own GPU: the person's words, with what helps.+ fake.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(fetched.filter((u) => u.includes("owner-comfy.test") && !u.endsWith("/system_stats"))).toEqual([]);+ });+});diff --git a/tests/own-keys-graceful.test.ts b/tests/own-keys-graceful.test.tsnew file mode 100644index 00000000..402b02c2--- /dev/null+++ b/tests/own-keys-graceful.test.ts@@ -0,0 +1,249 @@+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";+import { startFakeFal, startFakeReplicate, type CloudRequest, type FakeCloud } from "./helpers/fake-cloud";+import { tempDir } from "./helpers/temp-dir";+import { TINY_PNG } from "./helpers/fake-comfy-runner";++/**+ * An account's run on its own fal.ai or Replicate key that has a problem: a busy or down provider is waited out (the tile+ * says so); a key refused, credit gone, a model gone or an input refused fails at once in plain words, the provider's own+ * words in the details line, with what helps (Replace key, Add credit, Run with your other key). A refusal while polling+ * fails the run at once, not half an hour later. The owner's runs keep the provider's words. Stand-ins only.+ */+const dir = tempDir("fuobe-own-keys-graceful-");+process.env.FUOBE_DATA_DIR = dir;+process.env.FUOBE_PUBLIC_SIGNUP = "1";+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_ENGINE_MODE;+globalThis.__fuobeTestDiskFree = 1e13;++const auth = await import("@/server/auth");+const keys = await import("@/server/account-keys");+const generationsRoute = await import("@/app/api/generations/route");+const uploadsRoute = await import("@/app/api/uploads/route");+const gens = await import("@/server/generations");+const { db } = await import("@/server/db");+const { setSetting } = await import("@/server/settings");+const { resetRates } = await import("@/server/rate");+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");++let fal: FakeCloud;+let rep: FakeCloud;+let A = "";+let D = "";+const cookies: Record<string, string> = {};++beforeAll(async () => {+ fal = await startFakeFal();+ rep = await startFakeReplicate();+ globalThis.__fuobeTestFalUrl = fal.url;+ globalThis.__fuobeTestReplicateUrl = rep.url;+ for (const k of ["owner-fal", "acct-fal-A"]) fal.keys[k] = "good";+ fal.keys["acct-fal-broke"] = "broke";+ rep.keys["acct-rep-A"] = "good";+ rep.keys["acct-rep-D"] = "good";+ setSetting("falKey", "owner-fal");+ auth.setPassword("install password");+ A = auth.createAccount("[email protected]", "long enough").id;+ D = auth.createAccount("[email protected]", "long enough").id;+ keys.saveAccountKey(A, "fal", "acct-fal-A");+ keys.saveAccountKey(A, "replicate", "acct-rep-A");+ keys.saveAccountKey(D, "replicate", "acct-rep-D");+ cookies.A = `${auth.SESSION_COOKIE}=${auth.createSession(A).value}`;+ cookies.D = `${auth.SESSION_COOKIE}=${auth.createSession(D).value}`;+ cookies.owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;+});+afterAll(async () => {+ globalThis.__fuobeTestFalUrl = undefined;+ globalThis.__fuobeTestReplicateUrl = undefined;+ globalThis.__fuobeTestDiskFree = undefined;+ gens.SELF_HEAL.scale = 1;+ await fal.close();+ await rep.close();+});+beforeEach(async () => {+ resetRates();+ gens.SELF_HEAL.scale = 0.01;+ globalThis.__fuobePollHeals?.clear();+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();+ await new Promise((r) => setTimeout(r, 100));+ for (const f of [fal, rep]) {+ f.log.length = 0;+ f.pollsToFinish = 2;+ f.script = null;+ f.canceled.length = 0;+ }+ keys.saveAccountKey(A, "fal", "acct-fal-A");+});++const run = async (cookie: string, body: Record<string, unknown>) => {+ const text = JSON.stringify({ feature: "image", prompt: "a quiet harbour at dawn", ...body });+ const r = await generationsRoute.POST(new Request("http://localhost:3000/api/generations", { method: "POST", headers: { cookie, host: "localhost:3000", "content-type": "application/json", "content-length": String(text.length) }, body: text }));+ const json = await r.json();+ if (r.status !== 201) throw new Error(`${r.status}: ${JSON.stringify(json)}`);+ return json.items[0] as { id: string; provider: string };+};+async function settle(id: string, ms = 15_000, seen: string[] = []) {+ const end = Date.now() + ms;+ for (;;) {+ await globalThis.__fuobeRunner?.tick();+ const g = gens.getGeneration(id, { includeDeleted: true })!;+ if (g.message && seen.at(-1) !== g.message) seen.push(g.message);+ if (!["queued", "running"].includes(g.status) || Date.now() > end) return g;+ await new Promise((r) => setTimeout(r, 15));+ }+}+/** A submit to a model (not a file's upload). */+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);++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 () => {+ let busy = 0;+ fal.script = (r) => (isSubmit(r) && busy++ < 2 ? { status: 429, body: { detail: "Too many requests" }, headers: { "Retry-After": "1" } } : null);+ const g = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" });+ const seen: string[] = [];+ const done = await settle(g.id, 15_000, seen);+ expect(done.status, done.error ?? "").toBe("succeeded");+ expect(seen).toContain("fal.ai is busy, trying again in a moment");+ expect(fal.log.filter(isSubmit)).toHaveLength(3);+ });++ 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);+ const g = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" });+ const seen: string[] = [];+ const done = await settle(g.id, 15_000, seen);+ expect(done.status, done.error ?? "").toBe("succeeded");+ expect(seen).toContain("Waiting for fal.ai to answer");+ });++ 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" });+ const done = await settle(g.id);+ expect(done.status).toBe("failed");+ expect(done.error).toBe("fal.ai is having trouble right now. Press Retry in a few minutes.");+ expect(done.trouble?.details).toBe("fal.ai answered 502 · 502 Bad gateway");+ expect(fal.log.filter(isSubmit)).toHaveLength(1);+ });+});++describe("what waiting can't fix fails at once, in plain words, with what helps", () => {+ it("a model gone (404): pick another, the provider's words in the details, not billed", async () => {+ fal.script = (r) => (isSubmit(r) ? { status: 404, body: { detail: "Application 'fal-ai/nano-banana-pro' not found" } } : null);+ const g = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" });+ const done = await settle(g.id);+ expect(done.status).toBe("failed");+ expect(done.error).toBe("This model isn't available on fal.ai right now. Pick another model.");+ expect(done.trouble?.details).toBe("fal.ai answered 404 · Application 'fal-ai/nano-banana-pro' not found");+ expect(kinds(done)).toContain("pick-model");+ expect(done.notBilled).toBe(true);+ expect(fal.log.filter(isSubmit)).toHaveLength(1);+ });++ it("an input refused (422): says which input, in its words", async () => {+ fal.script = (r) => (isSubmit(r) ? { status: 422, body: { detail: [{ loc: ["body", "prompt"], msg: "String should have at most 5000 characters" }] } } : null);+ const g = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" });+ const done = await settle(g.id);+ expect(done.error).toBe("fal.ai couldn't use these words. Change it, then run again.");+ expect(done.trouble?.details).toMatch(/^fal\.ai answered 422 · body\.prompt: String should have/);+ });++ it("credit gone: Add credit on fal.ai links to its billing page", async () => {+ keys.saveAccountKey(A, "fal", "acct-fal-broke");+ const g = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" });+ const done = await settle(g.id);+ 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);+ });++ it("a key refused while polling fails the run at once (not after half an hour), and stops the job", async () => {+ fal.pollsToFinish = Infinity;+ fal.script = (r) => (isStatus(r) ? { status: 401, body: { detail: "Unauthorized" } } : null);+ const g = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" });+ const started = Date.now();+ const done = await settle(g.id);+ expect(Date.now() - started).toBeLessThan(5000);+ expect(done.status).toBe("failed");+ expect(done.error).toBe("fal.ai didn't accept your key. Check it in Settings → Your keys.");+ expect(done.trouble?.actions[0]).toMatchObject({ kind: "key-settings", label: "Replace key", target: "/settings#your-keys" });+ // Its other key runs this model too.+ expect(done.trouble?.actions).toContainEqual({ kind: "run-with-key", label: "Run with your Replicate key", target: "replicate" });+ expect(fal.log.filter(isStatus)).toHaveLength(1);+ });++ it("a model the key may not run (403 that isn't about the key) says so, and the key stays good", async () => {+ fal.script = (r) => (isSubmit(r) ? { status: 403, body: { detail: "You do not have permission to access this application" } } : null);+ const g = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" });+ const done = await settle(g.id);+ expect(done.error).toBe("Your fal.ai account can't run this model yet. Pick another model, or turn it on in your fal.ai account.");+ expect(done.trouble?.details).toBe("fal.ai answered 403 · You do not have permission to access this application");+ expect(kinds(done)).toEqual(["pick-model", "run-with-key"]);+ expect(keys.accountKeyInfo(A).fal?.rejectedAt).toBeUndefined();+ });++ it("a key refused at submit: Replace key first, the provider's words (never the key) in details", async () => {+ fal.script = (r) => (isSubmit(r) ? { status: 401, body: { detail: "Invalid credentials: Key acct-fal-A" } } : null);+ const g = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" });+ const done = await settle(g.id);+ expect(done.error).toBe("fal.ai didn't accept your key. Check it in Settings → Your keys.");+ expect(done.trouble?.details).toBe("fal.ai answered 401 · Invalid credentials: Key ••••");+ expect(JSON.stringify(done)).not.toContain("acct-fal-A");+ expect(kinds(done)[0]).toBe("key-settings");+ });++ it("a job that failed at the provider: plain words, its own words in details", async () => {+ fal.script = (r) => (isStatus(r) ? { status: 200, body: { status: "COMPLETED", error: "Internal error: worker crashed" } } : null);+ const g = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" });+ const done = await settle(g.id);+ expect(done.error).toBe("fal.ai couldn't finish this one. Press Retry, or try different words or another picture.");+ expect(done.trouble?.details).toBe("Internal error: worker crashed");+ });+});++describe("the owner's runs keep the provider's own words", () => {+ it("a 404 on the owner's key reads as before", async () => {+ fal.script = (r) => (isSubmit(r) ? { status: 404, body: { detail: "Application not found" } } : null);+ const g = await run(cookies.owner, { modelId: "nano-banana-pro", engine: "cloud" });+ const done = await settle(g.id);+ expect(done.status).toBe("failed");+ expect(done.error).toBe("fal 404: Application not found");+ expect(done.trouble).toBeUndefined();+ });+});++describe("Run with your key: the cloud version of a tool on the account's GPU", () => {+ it("FPV Drone on MiniMax H3's open model runs on fal.ai's MiniMax H3; a Replicate-only account has none", () => {+ const preset = getPreset("motion-fpv-drone")!;+ const open = getModel("oss-minimax-h3");+ expect(gens.cloudTwin({ presetId: preset.id, modelId: "oss-minimax-h3" }, A)).toEqual({ modelId: "minimax-h3", provider: "fal", op: "i2v" });+ expect(gens.cloudTwin({ presetId: preset.id, modelId: "oss-minimax-h3" }, D)).toBeNull();+ // The composer's check before Run reads the same.+ const has = (id: string) => !!getModel(id);+ expect(cloudVersionKey(preset as never, open, ["fal", "replicate"], has, getModel)).toBe("fal");+ expect(cloudVersionKey(preset as never, open, ["replicate"], has, getModel)).toBeNull();+ // A Fuobe Original on both engines: the same model on the cloud.+ expect(gens.cloudTwin({ modelId: "fuobe-soul" }, D)).toEqual({ modelId: "fuobe-soul", provider: "replicate" });+ expect(cloudVersionKey(undefined, getModel("fuobe-soul"), ["replicate"], has, getModel)).toBe("replicate");+ });++ 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 }),+ );+ expect(up.status).toBe(201);+ const pic = ((await up.json()) as { url: string }).url;+ const open = { feature: "video" as const, modelId: "oss-minimax-h3", presetId: "motion-fpv-drone", op: "i2v" as const, prompt: "", inputs: { images: [pic] } };+ const twin = gens.cloudTwin(open, A)!;+ const g = await run(cookies.A, onCloudKey(open, twin) as unknown as Record<string, unknown>);+ expect(g.provider).toBe("fal");+ expect((await settle(g.id)).status).toBe("succeeded");+ });+});