Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Merge main's newer work (runs on your own GPU or key wait out a passing problem and say why, Fuobe Connect path checks)

Adarsh4a28f1da2ce9
diff --cc src/app/api/generations/route.ts
index 72627a92,76e49d67..bca150d7
--- a/src/app/api/generations/route.ts
+++ b/src/app/api/generations/route.ts
@@@ -235,9 -220,14 +236,14 @@@ export async function POST(request: Req
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.
+ // this server under the account's limits (model3d-finish.ts). This install's GPUs take a 3D model only where a
+ // worker's CPU slot finishes it (computer/finish.ts poolFinishes3d): decidePlace and createGenerations say so.
const skip = (body as { gpuCheck?: unknown } | null)?.gpuCheck === "skip";
const gate = await gateGeneration(gpuTargetFor(request, "read"), { request: req, route: planned.route, op: planned.op, modelId: planned.model.id, gpu: planned.gpu, h3: planned.h3, skip, actor: account?.id ?? "owner" });
if (!gate.ok) {
diff --cc src/components/studio/feed.tsx
index 396db37d,3f9c7c84..6acb2fb4
--- a/src/components/studio/feed.tsx
+++ b/src/components/studio/feed.tsx
@@@ -18,7 -16,9 +18,9 @@@ import
} from "@/components/ui/dropdown-menu";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { OPERATION_LABELS, type Generation } from "@/lib/catalog/types";
+ import { onCloudKey } from "@/lib/before-run";
+ import { TroubleActions, TroubleDetails } from "@/components/gpu/trouble";
-import { useCreateGeneration, useGenerationActions, useStatus } from "@/lib/api";
+import { useCreateGeneration, useGenerationActions, useMakingPoolRuns, useStatus } from "@/lib/api";
import { placeholdersOn } from "@/lib/demo-mode";
import { useSoulFinish } from "./soul-finish";
import { elapsed, formatCost, leftLabel, notePace, ratioValue, timeAgo, timeLeft } from "@/lib/format";
@@@ -165,20 -128,25 +167,33 @@@ export function PendingTile({ g, ratio
}
export function FailedTile({ g, ratio, onRetry }: { g: Generation; ratio: number; onRetry: () => void }) {
+ const create = useCreateGeneration();
+ const trouble = g.status === "failed" ? g.trouble : undefined;
+ // A run on this studio's GPUs that couldn't finish: one plain sentence (the server's), nothing technical.
+ const poolFailed = g.place === "pool" && g.status === "failed";
return (
<div className="flex h-full max-w-full flex-col justify-between rounded-xl border border-dashed bg-background p-3" style={{ aspectRatio: Math.max(ratio, 0.8) }}>
<div className="min-h-0 space-y-1 overflow-hidden">
- <p className="text-[13px] font-medium">{g.status === "canceled" ? "Canceled" : "Couldn't generate this one"}</p>
- {g.error && <p className="line-clamp-5 text-[12px] leading-snug break-words whitespace-pre-line text-muted-foreground">{g.error}</p>}
- {/* An account's own GPU or key: what came back, small, for the curious. */}
- <TroubleDetails details={trouble?.details} />
+ {poolFailed ? (
+ <p className="line-clamp-5 text-[13px] leading-snug font-medium break-words">{g.error || POOL_WORDS.failed}</p>
+ ) : (
+ <>
+ <p className="text-[13px] font-medium">{g.status === "canceled" ? "Canceled" : "Couldn't generate this one"}</p>
+ {g.error && <p className="line-clamp-5 text-[12px] leading-snug break-words whitespace-pre-line text-muted-foreground">{g.error}</p>}
++ {/* An account's own GPU or key: what came back, small, for the curious. */}
++ <TroubleDetails details={trouble?.details} />
+ </>
+ )}
</div>
+ {trouble && (
+ <TroubleActions
+ className="mt-2"
+ actions={trouble.actions}
+ skip={["retry"]}
+ max={3}
+ handlers={{ onRunWithKey: (a) => create.mutate(onCloudKey(g.request, a), { onError: (e) => toastError(e) }) }}
+ />
+ )}
<div className="mt-2 flex flex-wrap gap-1.5">
{g.status === "failed" && g.fix && (
// Something was missing on the GPU: the guided fix shows what, and how to add it.
diff --cc src/lib/api.ts
index c09c129e,050ddd43..d895ae56
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@@ -35,8 -32,12 +35,12 @@@ import { postFile } from "./upload"
import type { ShareCreated, ShareInfo, ShareListItem, SharePatch, ShareRequest } from "./share";
import type { AccessSummary } from "./model-access";
import { ADD_KEY_HEADER, isCloudProvider, type CloudProvider } from "./your-keys";
+ import type { Diagnosis } from "./diagnose";
-import { BILLING_EVENT, BILLING_HEADER, type BillingAction, type BillingRefusalDetail, type HostedBalance } from "./hosted";
+import { BILLING_EVENT, BILLING_HEADER, refreshPriceChecks, type BillingAction, type BillingRefusalDetail, type HostedBalance } from "./hosted";
+ /** What the status strip says of a GPU that didn't answer (src/server/account-gpu.ts VisitorTrouble). */
+ export type GpuTroubleView = Pick<Diagnosis, "cause" | "words" | "actions" | "retryable" | "details">;
+
export interface Asset {
id: string;
kind: MediaKind;
diff --cc src/lib/relay.ts
index 115d1328,63b95217..5b55ec31
--- a/src/lib/relay.ts
+++ b/src/lib/relay.ts
@@@ -455,20 -337,11 +455,23 @@@ 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;
+/**
+ * What a run on this install's GPUs (hosted runs) shows an account: in line (with its place and wait, the row's queue
+ * block), working on it, then its result. Every recovery (a worker that paused, went quiet or restarted, a retry) is
+ * "in line" again in the same place. A run that can't finish says one plain sentence; the technical reason is kept for
+ * the owner only.
+ */
+export const POOL_WORDS = {
+ inLine: "In line",
+ working: "Working",
+ failed: "This one couldn't be made.",
+} as const;
+
/** A script's open-source run (an API token) while the owner's ComfyUI is on the owner's computer. */
export const RUNS_ON_COMPUTER_NOTE = "Runs when Fuobe is open on your computer.";
diff --cc src/server/account-gpu.ts
index 990201a8,ec3d9c74..a9bfaf87
--- a/src/server/account-gpu.ts
+++ b/src/server/account-gpu.ts
@@@ -7,15 -7,17 +7,19 @@@ import { accountGpu, type Account, typ
import type { OwnerGpuView } from "@/lib/connections";
import { runnerFacts, type Principal } from "./computer/tasks";
import { offeredSummary } from "./model-access";
-import { MODELS } from "@/lib/catalog";
-import { hostedUntestedSummary } from "@/lib/catalog/hosted-untested";
+import { getModel, PRESETS } from "@/lib/catalog";
+import { operationOutput } from "@/lib/catalog/types";
import { PROVIDERS } from "./providers";
- import { blockedForAccounts, fetchPublic, isLoopbackGpu } from "./remote-fetch";
+ import { blockedForAccounts, fetchPublic, isLoopbackGpu, peekText } from "./remote-fetch";
import { isInstallHost, REFUSED_ADDRESS } from "./gpu/hosts";
-import { balance as billingBalance, OPEN_POLICY, policy as billingPolicy, type Action, type Balance } from "./billing";
+import { balance as billingBalance, policy as billingPolicy, type Action, type Balance } from "./billing";
import { poolReady } from "./hosted";
+import { poolOwnModels } from "./pool-own-setup";
+import { poolRulesOf, type PoolRules, type PresetModel } from "@/lib/pool-rules";
+ import { diagnoseAddress, diagnoseGpu, gpuHostOf, type Diagnosis, type GpuFailure, type GpuPlace, type GpuStage } from "@/lib/diagnose";
+
+ /** A diagnosis as the status strip sends it. */
+ const visitorTrouble = (d: Diagnosis): VisitorTrouble => ({ cause: d.cause, words: d.words, actions: d.actions, retryable: d.retryable, ...(d.details && { details: d.details }) });
/**
* "Your GPU" (public sign-up): the ComfyUI an account connects, where its runs go. The server calls
@@@ -206,17 -328,9 +345,20 @@@ export interface VisitorView
notice?: { id: string; text: string; url?: string };
}
+declare global {
+ var __fuobePresetModels: PresetModel[] | undefined;
+}
+
+/** Every preset with the open model it runs on and the kind it makes (for the pickers' rules): made once. */
+const presetModels = (): PresetModel[] =>
+ (globalThis.__fuobePresetModels ??= PRESETS.map((p) => {
+ const m = p.open ? getModel(p.open.modelId) : undefined;
+ return m && p.open ? { id: p.id, model: { id: m.id, kind: operationOutput(p.open.op, m.kind) } } : { id: p.id };
+ }));
+
+ /** What the status strip and the composer show of a GPU that didn't answer: never more than the person's own GPU said. */
+ export type VisitorTrouble = Pick<Diagnosis, "cause" | "words" | "actions" | "retryable" | "details">;
+
/**
* GET /api/status for a guest or an account: ComfyUI is its own GPU (taken as there until it has one,
* so the studios offer Generate and the run asks it to connect one), fal.ai and Replicate are its own
diff --cc src/server/generations.ts
index 86706f39,14c75710..ed7a5643
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@@ -1,5 -1,5 +1,6 @@@
import "server-only";
+import { AsyncLocalStorage } from "node:async_hooks";
+ import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import { nanoid } from "nanoid";
@@@ -217,7 -219,8 +236,8 @@@ export function toGeneration(r: Row): G
folderId: lib.folder_id ?? null,
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)),
+ ...(r.status === "failed" && r.fix_json && !pool && { fix: parseFix(r.fix_json) }),
++ ...(r.status === "failed" && r.fix_json && !pool && 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.
@@@ -1984,6 -1835,317 +2014,321 @@@ async function submitNow
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 }) });
++ // (Only while the run still goes: one another app process saved meanwhile stays saved.)
++ updateLive(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 });
++ // (Only while the run still goes: one another app process saved or ended meanwhile is left as it is.)
++ const again = db().transaction((): boolean => {
++ if (!updateLive(r.id, { external_id: null, external_meta_json: null, status: "queued", progress: null, message: words })) return false;
+ db().prepare("DELETE FROM generation_runs WHERE id = ?").run(r.id);
++ return true;
+ })();
++ if (!again) return true;
+ 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 });
++ if (r.message !== words) updateLive(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);
@@@ -2597,17 -2728,32 +2956,34 @@@ async function pollOne(r: Row): Promise
});
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 });
+ // Back in line (a worker paused, went quiet or gave it back): no progress of the attempt before is kept.
+ updateLive(r.id, { status: res.state, progress: ownClocks && res.state === "queued" ? null : (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.
- updateLive(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");
++ updateLive(r.id, { status: "failed", error: (own && trouble?.words) || res.error, completed_at: Date.now(), message: null, ...(kept && { fix_json: kept }) });
+ // (A run on this install's GPUs says nothing about the account's own GPU.)
+ if (res.fix && !onPool) markStale(account ? `acct:${account}` : "install");
return;
}
// The Watermark Remover gave the original back (no clean repair was possible): no new result, the run says what to try.
@@@ -2656,9 -2799,8 +3032,10 @@@
} 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)));
+ // Still saving: the turn is still this process's.
+ claimFinish(r.id);
} catch (e) {
if (account) {
for (const kept of outputs) if (kept.assetId) deleteAsset(kept.assetId);
@@@ -2667,8 -2809,11 +3044,11 @@@
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.";
- updateLive(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 }) });
++ updateLive(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 --cc src/server/providers/comfyui.ts
index 9889899d,5d04c8f9..e799b01d
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@@ -34,43 -104,27 +34,45 @@@ 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 { addressKind } from "@/lib/page-place";
+import { graphProblem } from "@/lib/local-comfy";
+import { runStamp } from "../run-stamp";
- 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 { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskFloorBytes, diskFreeBytes, diskHasRoom, filesFullMessage } from "../account-files";
import { accountSend } from "../account-send";
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 {
+ makingWords,
+ META_BATCH_HISTORY,
+ POOL_WORDS,
+ queueWords,
+ RELAY_TIMES,
+ RELAY_WORDS,
+ savingWords,
+ sendingWords,
+ tabFailureWords,
+ type ComputerFacts,
+ type HistoryEntryLike,
+ type TabFailure,
+ type WantedFile,
+} from "@/lib/relay";
import type { GenerationFix } from "@/lib/catalog/types";
import {
checkClocks,
createTask,
extraOf,
- getTask,
inputKinds,
+ ownTask,
receivedFile,
+ freeInputs,
receivedOf,
refusalOf,
+ pairedRunner,
requestStop,
resultOf,
runnerFacts,
@@@ -381,10 -344,52 +383,52 @@@ function authHeaders(worker: ComfyWorke
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);
+ // scope goes through its task instead; this is the last guard). Nor is any from a run on this install's workers.
+ if (computerScope() || onPoolWorkers()) throw new ProviderError(ON_COMPUTER_ONLY);
const base = baseUrl(worker);
if (ownGpu()) {
// A visitor without a GPU of its own (a price check): nothing to reach, and never the install's.
@@@ -1570,11 -2706,19 +1655,19 @@@ async function pollTask(principal: Prin
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" && !t.pools ? 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 }) };
++ return { state: "queued", message: down ?? (t.note === "resent" && !t.pools ? RELAY_WORDS.resent : sendingWords(inputKinds(t))), timeoutError: waitedTooLong, ...(sentAt && { sentAt }) };
case "queued":
return { state: "queued", message: down ?? queueWords(p?.position), ...(sentAt && { sentAt }) };
case "running": {
diff --cc src/server/providers/types.ts
index 594bd173,0568e529..4a38c5ab
--- a/src/server/providers/types.ts
+++ b/src/server/providers/types.ts
@@@ -31,15 -32,17 +32,19 @@@ export interface RemoteOutput
/**
* What a poll found. A job on someone's own computer (comfyui.ts) also says when it reached their ComfyUI (`sentAt`: the
* queue clock starts there, not while it waited for their tab), what to say if it waits too long (`timeoutError`), and
- * what was missing when it failed (`fix`: the tile's "Fix it").
+ * what was missing when it failed (`fix`: the tile's "Fix it"). A job for the workers keeps its task's own clocks
+ * (`ownClocks`): the runner then sets no wait limit of its own, and ends it only past the deadline of the attempt a
+ * worker holds now (`deadline`: when, and how long that attempt may last).
*/
export type PollResult =
- | { state: "queued"; progress?: number; message?: string; sentAt?: number; timeoutError?: string }
- | { state: "running"; progress?: number; message?: string; sentAt?: number }
+ | { state: "queued"; progress?: number; message?: string; sentAt?: number; timeoutError?: string; ownClocks?: true; deadline?: { at: number; ms: number } }
+ | { state: "running"; progress?: number; message?: string; sentAt?: number; ownClocks?: true; deadline?: { at: number; ms: 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;