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.

Run on the place automatically when the person's GPU can't

Adarshdcf1ccb542e5
diff --git a/src/app/api/account/site-fallback/route.ts b/src/app/api/account/site-fallback/route.ts
new file mode 100644
index 00000000..9b329109
--- /dev/null
+++ b/src/app/api/account/site-fallback/route.ts
@@ -0,0 +1,35 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { requestAccount } from "@/server/auth";
+import { poolReady } from "@/server/hosted";
+import { setSiteFallback, siteFallbackFor } from "@/server/site-fallback";
+
+/**
+ * "Run on {Place} automatically when your GPU can't" (hosted runs on): the account's answer, kept for every device. The
+ * one-time question after its first "Run on {Place}" and Settings → Where your runs go write it (`{ on }`; Not now is
+ * `false`, and is kept as an answer too). GET reads it: `{ siteFallback: "on" | "off" | null }` (null: never asked).
+ * Accounts only, each its own. While hosted runs are off this route doesn't exist (404).
+ */
+const NO_STORE = { "Cache-Control": "no-store" };
+const answer = (status: number, body: Record<string, unknown>) => Response.json(body, { status, headers: NO_STORE });
+const notHere = () => answer(404, { error: "Not found" });
+
+const Body = z.object({ on: z.boolean() }).strict();
+
+export async function GET(request: Request): Promise<Response> {
+ await connection();
+ if (!poolReady()) return notHere();
+ const a = requestAccount(request);
+ if (!a) return notHere();
+ return answer(200, { siteFallback: siteFallbackFor(a.id) ?? null });
+}
+
+export async function PUT(request: Request): Promise<Response> {
+ if (!poolReady()) return notHere();
+ const a = requestAccount(request);
+ if (!a) return notHere();
+ const parsed = Body.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return answer(400, { error: "Say yes or not now." });
+ setSiteFallback(a.id, parsed.data.on);
+ return answer(200, { siteFallback: siteFallbackFor(a.id) ?? null });
+}
diff --git a/src/components/gpu/use-site-run.ts b/src/components/gpu/use-site-run.ts
new file mode 100644
index 00000000..4682187e
--- /dev/null
+++ b/src/components/gpu/use-site-run.ts
@@ -0,0 +1,48 @@
+"use client";
+
+import { useCreateGeneration, usePlaceName, useStatus } from "@/lib/api";
+import type { Generation } from "@/lib/catalog/types";
+import { runOnSiteAction, type TroubleAction } from "@/lib/diagnose";
+import { toastError } from "@/lib/refusals";
+import { askSiteFallback, useSetSiteFallback } from "@/lib/site-fallback";
+import { asksSiteFallback, movedWords, siteRunOf, siteRunRequest } from "@/lib/site-run";
+import type { TroubleHandlers } from "./trouble";
+
+/**
+ * "Run on {Place}" on a run that failed on the person's own GPU or key (hosted runs), the same on every card that shows a
+ * failed run (a studio's feed, the Library, a tool page): the button first among the run's own, while this studio's GPUs
+ * take it (src/lib/site-run.ts siteRunOf), and what a press does (the run made there once). After the first press on a
+ * run its own GPU couldn't make, the account is asked once whether it should go there by itself next time.
+ *
+ * `actions(own)`: the run's buttons with the offer first. `more`: the handler for RunTroubleActions. `moved`: the words
+ * for a run that went there by itself (null otherwise).
+ */
+export function useSiteRun(g: Generation): { actions: (own: TroubleAction[]) => TroubleAction[]; more: TroubleHandlers; moved: string | null } {
+ const create = useCreateGeneration();
+ const site = usePlaceName();
+ const viewer = useStatus().data?.viewer;
+ const setFallback = useSetSiteFallback();
+ const run = siteRunOf(g, !!site, viewer?.pool);
+ const offer = run && site ? runOnSiteAction(site.label) : null;
+ return {
+ actions: (own) => (offer ? [offer, ...own] : own),
+ more: {
+ onRunOnSite: () => {
+ if (!run) return;
+ create.mutate(siteRunRequest(g, run), {
+ onSuccess: () => {
+ if (site && asksSiteFallback(viewer, g)) askSiteFallback(site, (on) => setFallback.mutate(on));
+ },
+ onError: (e) => toastError(e),
+ });
+ },
+ },
+ moved: site ? movedWords(g, site.text) : null,
+ };
+}
+
+/** The words of a failed run that went to this studio's GPUs by itself (or is on its way there), else null. */
+export function useMovedWords(g: Pick<Generation, "movedTo" | "moving">): string | null {
+ const site = usePlaceName();
+ return site ? movedWords(g, site.text) : null;
+}
diff --git a/src/components/gpu/where-runs-go.tsx b/src/components/gpu/where-runs-go.tsx
index 8bf1afb9..6a925e11 100644
--- a/src/components/gpu/where-runs-go.tsx
+++ b/src/components/gpu/where-runs-go.tsx
@@ -1,20 +1,25 @@
"use client";
import { RunOnList } from "@/components/studio/run-on";
+import { Switch } from "@/components/ui/switch";
import { useStatus } from "@/lib/api";
import { placeOf } from "@/lib/place-name";
import { placeRows } from "@/lib/run-place";
import { useSetRunOn } from "@/lib/run-on";
+import { useSetSiteFallback } from "@/lib/site-fallback";
+import { siteFallbackLabel } from "@/lib/site-run";
import { cn } from "@/lib/utils";
/**
* Settings → Your GPU, at the top while hosted runs are on: "Where your runs go", the same rows as the Run on list (this
- * studio's GPUs, the account's GPU, its key), kept for every device. With nothing of its own, one line instead. Nothing
- * while hosted runs are off (self-hosters keep today's page).
+ * studio's GPUs, the account's GPU, its key), kept for every device. With nothing of its own, one line instead. With a GPU
+ * of its own, the switch for running on this studio's GPUs automatically when that GPU can't (src/server/site-fallback.ts).
+ * Nothing while hosted runs are off (self-hosters keep today's page).
*/
export function WhereRunsGo({ className }: { className?: string }) {
const v = useStatus().data?.viewer;
const setRunOn = useSetRunOn();
+ const setFallback = useSetSiteFallback();
if (!v?.hosted || v.kind !== "account") return null;
const place = placeOf(v.placeName);
const keys = v.paidAllowed === false ? [] : (v.keys ?? []);
@@ -34,6 +39,12 @@ export function WhereRunsGo({ className }: { className?: string }) {
disabled={setRunOn.isPending}
onPick={(id) => setRunOn.mutate({ runOn: id, ...(id === "key" && provider && { key: provider }) })}
/>
+ {v.gpu?.connected && (
+ <label className="flex cursor-pointer items-center justify-between gap-3 rounded-lg px-2.5 py-1.5 text-[13px] hover:bg-accent">
+ <span>{siteFallbackLabel(place.text)}</span>
+ <Switch checked={v.siteFallback === "on"} disabled={setFallback.isPending} onCheckedChange={(on) => setFallback.mutate(on)} aria-label={siteFallbackLabel(place.text)} />
+ </label>
+ )}
</>
) : (
<p className="px-2.5 text-[12px] text-muted-foreground">Your runs go to {place.text}. Connect a GPU or add a key to have a choice.</p>
diff --git a/src/components/library/asset-card.tsx b/src/components/library/asset-card.tsx
index 898f6afb..8fa5f917 100644
--- a/src/components/library/asset-card.tsx
+++ b/src/components/library/asset-card.tsx
@@ -17,6 +17,9 @@ import { cn } from "@/lib/utils";
import { PlaceholderChip } from "@/components/demo-mode";
import { TroubleActions, TroubleDetails } from "@/components/gpu/trouble";
import { RunTroubleActions } from "@/components/gpu/run-trouble-actions";
+import { useMovedWords, useSiteRun } from "@/components/gpu/use-site-run";
+import { usePlaceName } from "@/lib/api";
+import { shownTroubleActions } from "@/lib/site-run";
import { DRAG_TYPE } from "./folders";
import { ReviewBadge } from "./review";
import { autoLine } from "@/lib/auto-image";
@@ -100,6 +103,8 @@ export function StatusCover({ g, small, actionable }: { g: Generation; small?: b
);
}
if (small) return <div className="size-full border bg-muted/40" />;
+ // The account's own Library: "Run on {Place}" where its feed offers it, and the words of a run that went there.
+ if (actionable && !pool && g.status === "failed") return <OwnFailedCover g={g} />;
const trouble = g.status === "failed" ? g.trouble : undefined;
return (
<div className="flex size-full flex-col justify-between gap-2 border bg-muted/40 p-3" data-stage={g.status}>
@@ -126,6 +131,50 @@ export function StatusCover({ g, small, actionable }: { g: Generation; small?: b
);
}
+/**
+ * A failed run in the account's own Library, off this studio's GPUs: what came back and the way out, with "Run on
+ * {Place}" first where its feed offers it (src/components/gpu/use-site-run.ts); a run that went there by itself says so.
+ */
+function OwnFailedCover({ g }: { g: Generation }) {
+ const siteRun = useSiteRun(g);
+ const site = usePlaceName();
+ const trouble = g.trouble;
+ return (
+ <div className="flex size-full flex-col justify-between gap-2 border bg-muted/40 p-3" data-stage={g.status}>
+ <div className="flex min-h-0 flex-col gap-1 overflow-hidden">
+ {siteRun.moved ? (
+ <p className="line-clamp-5 shrink-0 text-[13px] leading-snug font-medium break-words">{siteRun.moved}</p>
+ ) : (
+ <>
+ <p className="shrink-0 text-[13px] font-medium">{"Couldn't generate this one"}</p>
+ {g.error && <p className="line-clamp-3 text-[12px] leading-snug break-words text-muted-foreground @[16rem]:line-clamp-4">{g.error}</p>}
+ </>
+ )}
+ {/* The details line goes first when the card is small. */}
+ {trouble && <TroubleDetails details={trouble.details} className="hidden @[16rem]:block" />}
+ </div>
+ {trouble && (
+ <RunTroubleActions g={g} className="shrink-0" actions={siteRun.actions(shownTroubleActions(trouble.actions, !!site))} more={siteRun.more} skip={["retry"]} max={2} compact context="run" />
+ )}
+ </div>
+ );
+}
+
+/** A failed run's buttons in a Library row, with "Run on {Place}" first where its feed offers it. */
+function RowFailedActions({ g }: { g: Generation }) {
+ const siteRun = useSiteRun(g);
+ const site = usePlaceName();
+ return (
+ <RunTroubleActions g={g} className="mt-1" actions={siteRun.actions(shownTroubleActions(g.trouble?.actions ?? [], !!site))} more={siteRun.more} skip={["retry"]} max={1} compact context="run" />
+ );
+}
+
+/** A failed run's line in a Library row once it went to this studio's GPUs by itself (nothing otherwise). */
+function RowMovedLine({ g }: { g: Generation }) {
+ const moved = useMovedWords(g);
+ return moved ? <p className="truncate text-[12px] text-muted-foreground">{moved}</p> : null;
+}
+
function Cover({ g, fit }: { g: Generation; fit: boolean }) {
if (g.status !== "succeeded" || !g.outputs.length) return <StatusCover g={g} actionable={!g.deletedAt} />;
if (isLayered(g)) return <LayersStack g={g} />;
@@ -309,13 +358,13 @@ export const AssetCard = memo(function AssetCard({
{!stack && autoLine(g) && <p className="truncate text-[12px] text-muted-foreground">{autoLine(g)}</p>}
{!stack && g.request.notice && <p className="truncate text-[12px] text-muted-foreground">{g.request.notice}</p>}
{/* An account's own GPU or key: the way out, in the row (its thumbnail is too small for it). */}
- {!stack && !trashed && (g.status === "failed" ? g.trouble : g.status === "queued" ? g.waiting : undefined) && (
- <RunTroubleActions g={g} className="mt-1" actions={(g.status === "failed" ? g.trouble : g.waiting)!.actions} skip={["retry"]} max={1} compact context={g.status === "failed" ? "run" : "other"} />
- )}
+ {!stack && !trashed && g.status === "failed" && g.place !== "pool" && <RowMovedLine g={g} />}
+ {!stack && !trashed && g.status === "failed" && g.trouble && <RowFailedActions g={g} />}
+ {!stack && !trashed && g.status === "queued" && g.waiting && <RunTroubleActions g={g} className="mt-1" actions={g.waiting.actions} skip={["retry"]} max={1} compact context="other" />}
</div>
{g.favorite && !stack && <Heart className="size-4 shrink-0 fill-highlight text-highlight" />}
{stack && <ChevronDown className={cn("size-4 shrink-0 text-muted-foreground transition-transform", expanded && "rotate-180")} />}
- {!stack && (g.status === "failed" || g.status === "canceled") && !trashed && (
+ {!stack && (g.status === "failed" || g.status === "canceled") && !trashed && !g.movedTo && !g.moving && (
<button
onClick={(e) => {
e.stopPropagation();
@@ -383,7 +432,7 @@ export const AssetCard = memo(function AssetCard({
)}
<SelectDot selected={selected} visible={selecting} onToggle={(s) => api.toggle(entry.key, ids, s)} label={`Select ${title}`} />
{actions}
- {!stack && (g.status === "failed" || g.status === "canceled") && !trashed && !selecting && (
+ {!stack && (g.status === "failed" || g.status === "canceled") && !trashed && !selecting && !g.movedTo && !g.moving && (
<button
onClick={(e) => {
e.stopPropagation();
diff --git a/src/components/studio/feed.tsx b/src/components/studio/feed.tsx
index 9e39f594..e33ddb57 100644
--- a/src/components/studio/feed.tsx
+++ b/src/components/studio/feed.tsx
@@ -28,9 +28,9 @@ import { runStage, shownMaking, STAGE_WORDS, tileBox, tileCount } from "@/lib/ru
import { RunAura, RunRing } from "./run-visuals";
import { reducedMotion } from "@/lib/ui-motion";
import { knownPlace } from "@/lib/place-name";
-import { runOnSiteAction } from "@/lib/diagnose";
import { retryRequest } from "@/lib/run-place";
-import { shownTroubleActions, siteRunOf, siteRunRequest } from "@/lib/site-run";
+import { shownTroubleActions } from "@/lib/site-run";
+import { useSiteRun } from "@/components/gpu/use-site-run";
import { placeholdersOn } from "@/lib/demo-mode";
import { useSoulFinish } from "./soul-finish";
import { elapsed, formatCost, leftLabel, notePace, ratioValue, timeAgo, timeLeft } from "@/lib/format";
@@ -276,10 +276,9 @@ export function FailedTile({ g, ratio, onRetry, onReuse }: { g: Generation; rati
const catalog = useOptionalCatalog();
const trouble = g.status === "failed" ? g.trouble : undefined;
// Hosted runs: a run that failed on the person's own GPU or key can run once on this studio's GPUs instead, when they
- // take it (on its key: its open version).
+ // take it (on its key: its open version); one that went there by itself says so.
const site = usePlaceName();
- const pool = useStatus().data?.viewer?.pool;
- const siteRun = trouble ? siteRunOf(g, !!site, pool) : null;
+ const siteRun = useSiteRun(g);
const actions = trouble ? shownTroubleActions(trouble.actions, !!site) : [];
// 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";
@@ -287,8 +286,9 @@ export function FailedTile({ g, ratio, onRetry, onReuse }: { g: Generation; rati
const shape = Math.max(ratio, FAILED_MIN_SHAPE);
const narrow = shape * 224 < NARROW_TILE_PX;
const [retrying, setRetrying] = useState(false);
- // Retry can't help a known ComfyUI problem or a missing model file: the same run would stop the same way.
- const retryHelps = !NO_RETRY_CAUSES.includes(trouble?.cause ?? "");
+ // Retry can't help a known ComfyUI problem or a missing model file: the same run would stop the same way. Nor is it
+ // offered for a run that went to this studio's GPUs by itself (it runs there now).
+ const retryHelps = !NO_RETRY_CAUSES.includes(trouble?.cause ?? "") && !siteRun.moved;
return (
<div className="flex h-full max-w-full flex-col justify-between overflow-hidden rounded-xl border bg-muted/40 p-3" style={{ aspectRatio: shape }} data-stage={g.status}>
<div className="flex min-h-0 flex-col gap-1 overflow-hidden">
@@ -298,6 +298,9 @@ export function FailedTile({ g, ratio, onRetry, onReuse }: { g: Generation; rati
{/* The cleaned technical reason, when this studio shows it (Settings → Failed runs). */}
<TroubleDetails details={g.errorDetail ? `Details: ${g.errorDetail}` : undefined} className="min-h-0" />
</>
+ ) : siteRun.moved ? (
+ // Its own GPU couldn't make it, so it went to this studio's GPUs by itself: the new run's card shows its progress.
+ <p className={cn("shrink-0 text-[13px] leading-snug font-medium break-words", narrow ? "line-clamp-4" : "line-clamp-5")}>{siteRun.moved}</p>
) : (
<>
<p className="shrink-0 text-[13px] font-medium">{g.status === "canceled" ? "Canceled" : "Couldn't generate this one"}</p>
@@ -318,12 +321,12 @@ export function FailedTile({ g, ratio, onRetry, onReuse }: { g: Generation; rati
reuse={feed?.reuse}
model={catalog?.getModel(g.modelId)}
className="mt-2 shrink-0"
- actions={siteRun && site ? [runOnSiteAction(site.label), ...actions] : actions}
+ actions={siteRun.actions(actions)}
skip={["retry"]}
max={narrow ? 2 : 3}
compact
context="run"
- more={{ onRunOnSite: () => siteRun && create.mutate(siteRunRequest(g, siteRun), { onError: (e) => toastError(e) }) }}
+ more={siteRun.more}
/>
)}
{/* A run on this studio's GPUs that didn't come out right: another model, a tap away, beside Retry. */}
diff --git a/src/instrumentation.ts b/src/instrumentation.ts
index e5cd1efb..461fb074 100644
--- a/src/instrumentation.ts
+++ b/src/instrumentation.ts
@@ -12,6 +12,10 @@ export async function register() {
// Sign-in data: an older install's auth.json moves into the database now, before the first request.
const { ensureAuthStore } = await import("./server/auth-store");
ensureAuthStore();
+ // The server's own context, kept before the runner starts: a run that failed on its account's GPU is sent to this
+ // install's GPUs from it (site-fallback-run.ts), never as the failed run.
+ const { keepRootContext } = await import("./server/site-fallback-run");
+ keepRootContext();
const { ensureRunner } = await import("./server/generations");
ensureRunner();
const { ensureTrashPurge } = await import("./server/library");
@@ -29,6 +33,9 @@ export async function register() {
// Its runs waiting to enter the line on this install's GPUs (hosted runs) go with it too.
const { clearHolds } = await import("./server/pool-holds");
onAccountDeleted(clearHolds);
+ // Its answer to "run on {Place} automatically when your GPU can't", and its runs moved that way.
+ const { clearSiteFallback } = await import("./server/site-fallback");
+ onAccountDeleted(clearSiteFallback);
// Faceless / Explainer renders whose narration was timed while the server was down continue with their scenes.
const { ensureFacelessRunner } = await import("./server/faceless");
ensureFacelessRunner();
diff --git a/src/lib/api.ts b/src/lib/api.ts
index e1a6be53..c9a8534c 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -44,6 +44,7 @@ import { BILLING_EVENT, BILLING_HEADER, freshBody, refreshPriceChecks, type Bill
import { knownPlace, notePlaceName, placeOf, type Place } from "./place-name";
import { noteServiceCopy, type ServiceCopy } from "./service-copy";
import { ENGINE_KEY, ENGINE_SLOT_KEY, engineSlot, SHARED_SLOT, slotToCache, storedEngine, type EngineSlot, type SlotFacts } from "./engine-pref";
+import type { SiteFallback } from "./site-run";
/** 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">;
@@ -1056,6 +1057,11 @@ export interface StatusInfo {
* one-time note (src/components/studio/place-intro.tsx) says where runs go now. Only with `hosted`.
*/
ranOwn?: true;
+ /**
+ * Its answer to "Run on {Place} automatically when your GPU can't" (src/server/site-fallback.ts): "on" or "off". Absent:
+ * never asked, so the question comes once after its first "Run on {Place}". Only with `hosted`.
+ */
+ siteFallback?: SiteFallback;
/** The words a preset card shows when its run would go to this studio's GPUs ("Try free"), from the server. None: no words. */
cardText?: string;
/** What this studio's GPUs keep off, for a viewer with no GPU of its own: its pickers leave it out (src/lib/pool-rules.ts). */
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index 090c45d4..da59005a 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -1578,6 +1578,13 @@ export interface Generation {
waiting?: RunTrouble & { until?: number };
/** Failed or stopped before its paid provider took the job (no external id): the card says "Not billed", not its price. */
notBilled?: true;
+ /**
+ * A run that failed on the account's own GPU and went to this install's GPUs by itself (the account's "run there
+ * automatically when your GPU can't", src/server/site-fallback.ts): the id of the run made there. Its card says so.
+ */
+ movedTo?: string;
+ /** The same, while that run is being made (a moment): its card says where it is going, and the page keeps looking. */
+ moving?: true;
/** Ran on this install's GPUs (hosted runs), not the account's own. */
place?: "pool";
/** The billing service's words for what a run on this install's GPUs costs ("7 units"); shown when it succeeded. */
diff --git a/src/lib/generation-stream.ts b/src/lib/generation-stream.ts
index 73230bbb..81e23352 100644
--- a/src/lib/generation-stream.ts
+++ b/src/lib/generation-stream.ts
@@ -186,11 +186,12 @@ export function sharePagesById(prev: unknown, next: unknown): unknown {
* How often a list with runs on their way asks for them again (null: none on its way, so it doesn't). The live stream
* brings every change at once; polling is the safety net that makes a missed change (a stream cut by an update of the
* site, a sleeping laptop, a proxy holding a stream open after its server went away) show within seconds anyway.
- * A run just sent is asked about most often; one that has been going a long while, less.
+ * A run just sent is asked about most often; one that has been going a long while, less. A failed run on its way to
+ * this studio's GPUs by itself (`moving`) counts as on its way: the run made there shows up the same way.
*/
-export function pollDelay(items: readonly Pick<Generation, "status" | "createdAt">[] | undefined, live: boolean, now?: number): number | null {
+export function pollDelay(items: readonly (Pick<Generation, "status" | "createdAt"> & Partial<Pick<Generation, "moving">>)[] | undefined, live: boolean, now?: number): number | null {
let youngest = -Infinity;
- for (const g of items ?? []) if ((g.status === "queued" || g.status === "running") && g.createdAt > youngest) youngest = g.createdAt;
+ for (const g of items ?? []) if ((g.status === "queued" || g.status === "running" || g.moving) && g.createdAt > youngest) youngest = g.createdAt;
if (youngest === -Infinity) return null;
// The clock is read only for a run on its way: a list read while a page is prerendered never reads it.
const age = Math.max(0, (now ?? Date.now()) - youngest);
diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.ts
index 109d15c0..b5febde9 100644
--- a/src/lib/guest-access.ts
+++ b/src/lib/guest-access.ts
@@ -206,6 +206,7 @@ export function accountOwnRead(pathname: string): boolean {
pathname === "/api/account/gpu" ||
pathname === "/api/account/keys" ||
pathname === "/api/account/run-on" ||
+ pathname === "/api/account/site-fallback" ||
pathname === "/api/key-info" ||
ACCOUNT_CANVASES.test(pathname) ||
GPU_READS.has(pathname) ||
@@ -261,6 +262,8 @@ export function accountMayChange(method: string, pathname: string, search: strin
if ((method === "PUT" || method === "DELETE") && /^\/api\/account\/keys\/(fal|replicate)$/.test(pathname)) return true;
// Where its runs go (hosted runs: the Run on list, Settings, the one-time note). The route keeps its own pick only.
if (method === "PUT" && pathname === "/api/account/run-on") return true;
+ // Its answer to running there automatically when its GPU can't (the one-time question, Settings): its own only.
+ if (method === "PUT" && pathname === "/api/account/site-fallback") return true;
// GPU pre-flight: checking its own ComfyUI (reads only; the routes check the target and the request themselves).
if ((method === "POST" && pathname === "/api/gpu/check") || (method === "PUT" && pathname === "/api/gpu/inventory")) return true;
// Running its own jobs on its own computer, and pairing (or unpairing) its own ComfyUI.
diff --git a/src/lib/site-fallback.ts b/src/lib/site-fallback.ts
new file mode 100644
index 00000000..44257a51
--- /dev/null
+++ b/src/lib/site-fallback.ts
@@ -0,0 +1,72 @@
+"use client";
+
+import { useMutation, useQueryClient, type QueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+import type { StatusInfo } from "./api";
+import type { Place } from "./place-name";
+import { siteFallbackQuestion, type SiteFallback } from "./site-run";
+
+/**
+ * The browser's side of "Run on {Place} automatically when your GPU can't" (hosted runs; src/server/site-fallback.ts):
+ * asked once after the account's first "Run on {Place}" on a run its own GPU couldn't make, and switched in Settings →
+ * Where your runs go. Kept on the server for every device; the page shows the answer at once.
+ */
+
+export const SITE_FALLBACK_PATH = "/api/account/site-fallback";
+
+/** The answer as the page shows it at once, before the server answers. */
+export function noteSiteFallback(qc: QueryClient, value: SiteFallback | undefined): void {
+ qc.setQueryData<StatusInfo>(["status"], (s) => {
+ if (!s?.viewer) return s;
+ const { siteFallback: _was, ...viewer } = s.viewer;
+ void _was;
+ return { ...s, viewer: { ...viewer, ...(value && { siteFallback: value }) } };
+ });
+}
+
+/** Keep the answer (PUT /api/account/site-fallback). Throws the server's words when it can't. */
+export async function putSiteFallback(on: boolean): Promise<SiteFallback | undefined> {
+ const res = await fetch(SITE_FALLBACK_PATH, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ on }) });
+ const b = (await res.json().catch(() => ({}))) as { siteFallback?: SiteFallback | null; error?: string };
+ if (!res.ok) throw new Error(b.error ?? "That didn't save. Try once more.");
+ return b.siteFallback ?? undefined;
+}
+
+/** Keep the answer: shown at once, kept on the server, and put back with the server's words when it can't be. */
+export function useSetSiteFallback() {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (on: boolean) => putSiteFallback(on),
+ onMutate: (on) => {
+ const was = qc.getQueryData<StatusInfo>(["status"])?.viewer?.siteFallback;
+ noteSiteFallback(qc, on ? "on" : "off");
+ return { was };
+ },
+ onSuccess: (value) => noteSiteFallback(qc, value),
+ onError: (e, _on, ctx) => {
+ noteSiteFallback(qc, ctx?.was);
+ toast((e as Error).message, { id: "site-fallback" });
+ },
+ onSettled: () => void qc.invalidateQueries({ queryKey: ["status"] }),
+ });
+}
+
+/**
+ * The one-time question, as a note that stays until it is answered: Yes, or Not now (kept as an answer too, so it is
+ * asked once; Settings changes it later). A note put away without a press counts as Not now.
+ */
+export function askSiteFallback(place: Place, keep: (on: boolean) => void): void {
+ let answered = false;
+ const answer = (on: boolean) => {
+ if (answered) return;
+ answered = true;
+ keep(on);
+ };
+ toast(siteFallbackQuestion(place.text), {
+ id: "site-fallback-ask",
+ duration: Infinity,
+ action: { label: "Yes", onClick: () => answer(true) },
+ cancel: { label: "Not now", onClick: () => answer(false) },
+ onDismiss: () => answer(false),
+ });
+}
diff --git a/src/lib/site-run.ts b/src/lib/site-run.ts
index 2ff1358a..1b2b1cc9 100644
--- a/src/lib/site-run.ts
+++ b/src/lib/site-run.ts
@@ -2,20 +2,21 @@ import { getModel, getPreset } from "@/lib/catalog";
import { dualEngine } from "@/lib/catalog/engines";
import { presetRoutes } from "@/lib/catalog/preset-recipe-routes";
import type { Generation } from "@/lib/catalog/types";
-import type { TroubleAction } from "./diagnose";
+import type { TroubleAction, TroubleCause } from "./diagnose";
import { CLOUD_KEY, isCloudProvider, type CloudProvider } from "./your-keys";
import { modelOwnSetup, poolRunsModel, poolRunsPreset, type PoolRules } from "./pool-rules";
-type FailedRun = Pick<Generation, "place" | "engine" | "status" | "modelId" | "op" | "presetId" | "kind" | "trouble">;
+type FailedRun = Pick<Generation, "place" | "engine" | "status" | "modelId" | "op" | "presetId" | "kind" | "trouble"> & Partial<Pick<Generation, "movedTo" | "moving">>;
/**
* "Run on {Place}" on a run that failed on the person's own GPU or key (hosted runs): the open version this studio's GPUs
* would run, once, named there; the account's pick stays as it was. A run on its own GPU: the same model. A run on its
* key: the item's open version (a Fuobe Original on Open source, an app's open route). Null when they don't take it (a
- * model or app their rules keep off, one that runs on an own setup only), or there is no open version.
+ * model or app their rules keep off, one that runs on an own setup only), or there is no open version. Never for a run
+ * that has moved there already, or is on its way (src/server/site-fallback.ts).
*/
export function siteRunOf(g: FailedRun, hosted: boolean, rules: PoolRules | undefined): { modelId: string; op?: string; engine?: "open" } | null {
- if (!hosted || g.place === "pool" || g.status !== "failed" || !g.trouble) return null;
+ if (!hosted || g.place === "pool" || g.status !== "failed" || !g.trouble || g.movedTo || g.moving) return null;
if (g.presetId && !poolRunsPreset(rules, g.presetId)) return null;
const takes = (id: string): boolean => {
const m = getModel(id);
@@ -64,3 +65,68 @@ export const keyTurnedDownWords = (provider: CloudProvider): string => `Your ${C
export function siteRunRequest(g: Pick<Generation, "request">, run: NonNullable<ReturnType<typeof siteRunOf>>): Generation["request"] {
return { ...g.request, modelId: run.modelId, ...(run.op && { op: run.op }), ...(run.engine && { engine: run.engine }), place: "pool" } as Generation["request"];
}
+
+/**
+ * The causes of a failure on the person's own GPU that "Run on {Place} automatically when your GPU can't" moves by
+ * itself (src/server/site-fallback.ts): the GPU off, stopped or out of reach, out of memory, a model file or add-on it
+ * lacks, a ComfyUI problem, a run it lost or couldn't finish. Never the person's own files (a file too big for the GPU's
+ * address, one too slow to send), and never a run the person stopped on the GPU.
+ */
+export const SITE_FALLBACK_CAUSES: ReadonlySet<TroubleCause> = new Set<TroubleCause>([
+ "gpu-stopped",
+ "gpu-starting",
+ "gpu-offline",
+ "gpu-not-found",
+ "gpu-certificate",
+ "gpu-password",
+ "gpu-password-wrong",
+ "gpu-sign-in",
+ "gpu-not-comfy",
+ "gpu-busy",
+ "gpu-refused",
+ "gpu-error",
+ "gpu-out-of-memory",
+ "gpu-job-error",
+ "gpu-model-file",
+ "gpu-comfy-known",
+ "gpu-restarted",
+ "gpu-moved",
+ "gpu-went-away",
+ "gpu-save-failed",
+ "gpu-isolated",
+ "gpu-too-long",
+]);
+
+/**
+ * A failed run that goes to {Place} by itself when the account said yes: one that ran on its own GPU (ComfyUI on the open
+ * engine, never its key), failed for one of SITE_FALLBACK_CAUSES, and that siteRunOf offers "Run on {Place}" for. The run
+ * as siteRunOf names it, or null.
+ */
+export function siteFallbackOf(g: FailedRun & Pick<Generation, "provider">, hosted: boolean, rules: PoolRules | undefined): ReturnType<typeof siteRunOf> {
+ if (g.provider !== "comfyui" || g.engine !== "open" || !g.trouble || !SITE_FALLBACK_CAUSES.has(g.trouble.cause)) return null;
+ return siteRunOf(g, hosted, rules);
+}
+
+/** The account's answer to "Next time, run on {Place} automatically when your GPU can't?" (absent: never asked). */
+export type SiteFallback = "on" | "off";
+
+/** The question, asked once after the first "Run on {Place}" on a run its own GPU couldn't make. */
+export const siteFallbackQuestion = (placeText: string): string => `Next time, run on ${placeText} automatically when your GPU can't?`;
+
+/** Settings → Where your runs go: the switch's words. */
+export const siteFallbackLabel = (placeText: string): string => `Run on ${placeText} automatically when your GPU can't`;
+
+/**
+ * Ask the question now? Once per account, after "Run on {Place}" on a run that failed on its own GPU (not its key), while
+ * hosted runs are on for it and it hasn't answered yet (either answer is kept).
+ */
+export function asksSiteFallback(v: { kind?: string; hosted?: boolean; siteFallback?: SiteFallback } | undefined, g: Pick<Generation, "provider">): boolean {
+ return !!v && v.kind === "account" && !!v.hosted && v.siteFallback === undefined && g.provider === "comfyui";
+}
+
+/** A failed run's card once its own GPU's failure moved it: where it runs now, or (`moving`) where it is going. */
+export function movedWords(g: Partial<Pick<Generation, "movedTo" | "moving">>, placeText: string): string | null {
+ if (g.movedTo) return `Your GPU couldn't run this, so it's running on ${placeText}.`;
+ if (g.moving) return `Your GPU couldn't run this, so it's going to ${placeText}.`;
+ return null;
+}
diff --git a/src/server/account-gpu.ts b/src/server/account-gpu.ts
index 8541ca45..129a7f97 100644
--- a/src/server/account-gpu.ts
+++ b/src/server/account-gpu.ts
@@ -22,6 +22,8 @@ import { placeName } from "./place-name";
import { helperKnown } from "./text-helper";
import { poolOwnModels, poolOwnPresets, type PresetPress } from "./pool-own-setup";
import { ranOwnFirst, runOnOf, type RunOn } from "./run-on";
+import { siteFallbackFor } from "./site-fallback";
+import type { SiteFallback } from "@/lib/site-run";
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";
@@ -360,6 +362,11 @@ export interface VisitorView {
* the one-time note says runs go to this install's GPUs now (only with `hosted`, only to that account).
*/
ranOwn?: true;
+ /**
+ * Its answer to "Run on {Place} automatically when your GPU can't" (site-fallback.ts; only with `hosted`, only to that
+ * account): "on" or "off". Absent: never asked (the question comes once, after its first "Run on {Place}").
+ */
+ siteFallback?: SiteFallback;
/**
* The words a preset card shows when its run would go to this install's GPUs (the billing service's policy, such as
* "Try free"; with no service, "Try free": those runs are free). Absent: the cards show none.
@@ -473,6 +480,8 @@ export async function visitorStatus(account: Account | null) {
viewer.runOn = pick.runOn;
if (pick.runKey) viewer.runKey = pick.runKey;
} else if ((gpu || keys.length) && ranOwnFirst(account.id)) viewer.ranOwn = true;
+ const fallback = siteFallbackFor(account.id);
+ if (fallback) viewer.siteFallback = fallback;
}
// What this studio's GPUs keep off, the open models they can't run right now among it: shown in the pickers with
// what the visitor needs to run them on its own setup. For every viewer, a GPU of its own or not: its runs go
diff --git a/src/server/db.ts b/src/server/db.ts
index 2ce2bf6c..9847fe01 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -1326,6 +1326,8 @@ function open(): Database.Database {
}
// Where an account's runs go, as it picked (run-on.ts): read only while hosted runs are on, empty otherwise.
db.exec(RUN_ON_TABLES);
+ // Runs that go to this install's GPUs when the account's own GPU can't make them (site-fallback.ts): empty otherwise.
+ db.exec(SITE_FALLBACK_TABLES);
// Runs on this install's GPUs waiting to enter the line (pool-holds.ts): empty unless hosted runs are on.
db.exec(POOL_HOLD_TABLES);
// A run held until the billing service says ready keeps its card (pool-holds.ts ready_json), for tables made before it.
@@ -1470,6 +1472,28 @@ const RUN_ON_TABLES = `CREATE TABLE IF NOT EXISTS account_run_on (
updated_at INTEGER NOT NULL
);`;
+/**
+ * "Run on {Place} automatically when your GPU can't" (site-fallback.ts), while hosted runs are on. account_site_fallback:
+ * the account's answer (a row: it was asked, or set it in Settings; `auto` 1 yes, 0 not now). site_fallback_runs: a run
+ * that failed on the account's own GPU (`run_id`) and the run made for it on this install's GPUs (`new_id`), once per
+ * failed run: `state` "sending" while it is made, "moved" once it is, "refused" when it wasn't taken. Empty on every
+ * install where hosted runs are off. Not a numbered migration.
+ */
+const SITE_FALLBACK_TABLES = `CREATE TABLE IF NOT EXISTS account_site_fallback (
+ account_id TEXT PRIMARY KEY,
+ auto INTEGER NOT NULL CHECK (auto IN (0, 1)),
+ updated_at INTEGER NOT NULL
+ );
+ CREATE TABLE IF NOT EXISTS site_fallback_runs (
+ run_id TEXT PRIMARY KEY,
+ account_id TEXT NOT NULL,
+ state TEXT NOT NULL CHECK (state IN ('sending', 'moved', 'refused')),
+ new_id TEXT,
+ at INTEGER NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS site_fallback_runs_new ON site_fallback_runs(new_id) WHERE new_id IS NOT NULL;
+ CREATE INDEX IF NOT EXISTS site_fallback_runs_account ON site_fallback_runs(account_id);`;
+
/**
* Runs on this install's GPUs that are made but wait to enter the line (pool-holds.ts): one row per row of the run, all
* sharing `run_id`. Made empty on every install, and written only while hosted runs are on. Not a numbered migration.
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 647d2763..792a728a 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -157,6 +157,7 @@ import { FILE_TROUBLE_WORDS, POOL_WORDS, RELAY_WORDS } from "@/lib/relay";
import { isPoolRunWords } from "@/lib/run-progress";
import { heldLine, placeInLine, poolOnWorkers, poolRunsProvider, poolWaitMs, requestFileKinds, runOnPool, type FileKind } from "./hosted";
import { hostedRunsOn } from "./hosted-switch";
+import { claimSiteFallback, movedFields } from "./site-fallback";
import { catalogVersion } from "./computer/catalog-version";
import { gettingReady, poolLane, queueOfGeneration, type LinePlace } from "./computer/pool";
import { ownerGpuMiss } from "./runs-here";
@@ -290,6 +291,8 @@ export function toGeneration(r: Row): Generation {
...(pool && (r.status === "failed" || r.status === "canceled") && failureDetailOf(r)),
...(r.status === "failed" && r.fix_json && !pool && { fix: parseFix(r.fix_json) }),
...(r.status === "failed" && r.fix_json && !pool && parseTrouble(r.fix_json)),
+ // Failed on its own GPU and gone to this install's GPUs by itself (site-fallback.ts): the run made there, or on its way.
+ ...(r.status === "failed" && !pool && stored.account && movedFields(r.id)),
// Waiting for its own GPU or key to come back: why, the buttons that help, and until when (never the owner's note).
...(r.status === "queued" && !r.external_id && r.external_meta_json && !pool && waitingOf(r)),
// Failed or stopped before a paid provider took the job (a refused key, an empty balance): nothing was billed. Not
@@ -2977,6 +2980,9 @@ function failRun(id: string, e: unknown, trouble: Diagnosis | undefined, account
if (!done) return false;
if (fix) markStale(account ? `acct:${account}` : "install");
if (own && account && facts) ownEvent(id, account, e, trouble, facts, "failed");
+ // The account said yes to "run on {Place} automatically when your GPU can't": a GPU's failure goes there now, made by
+ // this server (the page may be closed). Claimed here, so the run reads "going to {Place}" as soon as it reads failed.
+ if (claimSiteFallback(id, account, trouble)) void import("./site-fallback-run").then((m) => m.sendSoon(id));
return true;
}
diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.ts
index ca2788ce..297eb80e 100644
--- a/src/server/hosted-run.ts
+++ b/src/server/hosted-run.ts
@@ -63,6 +63,7 @@ import { ADD_KEY_HEADER } from "@/lib/your-keys";
import type { Place } from "@/lib/place-name";
import { placeFor, placeOfAccount } from "./place-name";
import { rememberedPlace } from "./run-on";
+import { siteFallbackOn } from "./site-fallback";
export { poolCardRefuses };
@@ -538,7 +539,7 @@ export function poolRequest(req: GenerationRequest, p: Pick<Policy, "limits"> |
* and every run this install's GPUs wouldn't take (hosted runs closed to it, a model or a kind not offered, LoRAs,
* inputs, a step no worker takes, 3D) goes to its own GPU, even while that GPU doesn't answer. Only a run this install's
* GPUs would take, that named no place, whose own GPU doesn't answer, is asked about (never moved there, and charged,
- * unasked). A run that goes to this install's GPUs is never moved to its own GPU because they are busy, away or being
+ * unasked), unless the account said yes to running there automatically when its GPU can't: then it goes there. A run that goes to this install's GPUs is never moved to its own GPU because they are busy, away or being
* updated, or because the billing service went quiet: it waits in line for them.
*
* One order (the place a run names, then what only one place can run, then the account's own pick, then the policy):
@@ -604,8 +605,9 @@ export async function decidePlace(account: Account, asked: GenerationRequest, wi
if (ownFallback) return OWN;
return gateRefusal(gate, placeFor(p));
}
- // Its own GPU didn't answer the check: asked, never moved to this install's GPUs (and charged) without a word.
- if (ownOffline) return { kind: "refuse", refusal: askPlace(placeFor(p)) };
+ // Its own GPU didn't answer the check: asked, never moved to this install's GPUs (and charged) without a word, unless
+ // the account said yes to running there automatically when its GPU can't (site-fallback.ts).
+ if (ownOffline && !siteFallbackOn(account.id)) return { kind: "refuse", refusal: askPlace(placeFor(p)) };
return { kind: "pool", planned, policy: p, steps: gate.steps ? pricedSteps(gate.steps) : undefined, req, capped, light: lightRun(gate.steps) };
}
@@ -1086,7 +1088,8 @@ export async function decideToolPlace(account: Account, steps: ToolRunStep[], wi
if (ownFallback) return OWN;
return gateRefusal(gate, placeFor(p));
}
- if (ownOffline) return { kind: "refuse", refusal: askPlace(placeFor(p)) };
+ // (As decidePlace: asked, unless the account said yes to running there automatically when its GPU can't.)
+ if (ownOffline && !siteFallbackOn(account.id)) return { kind: "refuse", refusal: askPlace(placeFor(p)) };
return { kind: "pool", policy: p, main: gate.main, steps: pricedSteps(gate.rows), light: lightRun(gate.rows) };
}
diff --git a/src/server/site-fallback-run.ts b/src/server/site-fallback-run.ts
new file mode 100644
index 00000000..7cc118be
--- /dev/null
+++ b/src/server/site-fallback-run.ts
@@ -0,0 +1,118 @@
+import "server-only";
+import { AsyncLocalStorage } from "node:async_hooks";
+import crypto from "node:crypto";
+import type { GenerationRequest } from "@/lib/catalog/types";
+import { siteFallbackOf, siteRunRequest } from "@/lib/site-run";
+import { accountInputProblem } from "./account-inputs";
+import { accountById, accountRequest } from "./auth";
+import { db } from "./db";
+import { cancelGeneration, getGeneration } from "./generations";
+import { poolReady } from "./hosted";
+import { hostedRunsOn } from "./hosted-switch";
+import { withoutStamp } from "./run-stamp";
+import { moveOf, noteMoved, noteRefused } from "./site-fallback";
+
+/**
+ * A run its own GPU couldn't make, made again on this install's GPUs (site-fallback.ts claimed it as it failed): the same
+ * request, sent as "Run on {Place}" sends it (src/lib/site-run.ts siteRunRequest), through the account's own Run (POST
+ * /api/generations) as if its page had sent it. So it meets every check a press meets (the limits, the moderation and
+ * billing services, the policy of this install's GPUs), priced and set aside the same way. Only a run taken into the line
+ * there now counts: one refused, or one that would wait to enter the line (held), leaves the failed run as it was.
+ */
+
+/** The account's Run: the run route's POST (loaded when first needed, so this module never imports a route itself). */
+export type SubmitRun = (request: Request) => Promise<Response>;
+
+const accountsRun: SubmitRun = async (request) => (await import("@/app/api/generations/route")).POST(request);
+
+/** Send the claimed move of failed run `id`. The run made for it (its ids), or null when it wasn't taken. */
+export async function sendToSite(id: string, submit: SubmitRun = accountsRun): Promise<{ ids: string[] } | null> {
+ let ids: string[] | null = null;
+ try {
+ ids = await send(id, submit);
+ } catch (e) {
+ console.warn(`[fuobe] A run couldn't move to this install's GPUs: ${(e as Error).message}`);
+ }
+ if (ids?.length) {
+ noteMoved(id, ids[0]);
+ return { ids };
+ }
+ noteRefused(id);
+ return null;
+}
+
+async function send(id: string, submit: SubmitRun): Promise<string[] | null> {
+ const move = moveOf(id);
+ if (!move || move.state !== "sending") return null;
+ if (!hostedRunsOn() || !poolReady()) return null;
+ const account = accountById(move.account_id);
+ if (!account || account.disabled) return null;
+ const g = getGeneration(id);
+ if (!g || g.status !== "failed") return null;
+ const run = siteFallbackOf({ ...g, moving: undefined, movedTo: undefined }, true, undefined);
+ if (!run) return null;
+ const row = db().prepare("SELECT batch_id, request_json FROM generations WHERE id = ?").get(id) as { batch_id: string | null; request_json: string } | undefined;
+ if (!row) return null;
+ // The request as its page sent it (the server's stamp and the account are set again by the Run).
+ const stored = JSON.parse(row.request_json) as GenerationRequest;
+ const base = withoutStamp(stored) as GenerationRequest & Record<string, unknown>;
+ delete base.account;
+ let req = siteRunRequest({ request: base as GenerationRequest }, run) as GenerationRequest & Record<string, unknown>;
+ // One job of a batch: its share of the outputs, not the whole batch's again.
+ if (row.batch_id) {
+ const jobs = db().prepare("SELECT COUNT(*) FROM generations WHERE batch_id = ? AND request_json = ? AND depends_on IS NULL").pluck().get(row.batch_id, row.request_json) as number;
+ const asked = Math.max(1, Number(stored.params?.numOutputs) || 1);
+ if (jobs > 1) req = { ...req, params: { ...req.params, numOutputs: Math.max(1, Math.ceil(asked / jobs)) } };
+ }
+ // Its files must still be here, and its own.
+ if (accountInputProblem(req, account.id)) return null;
+
+ const post = async (preview: boolean, extra: Record<string, unknown>) => {
+ const text = JSON.stringify({ ...req, place: "pool", ...extra });
+ const res = await submit(
+ accountRequest(account, `http://localhost/api/generations${preview ? "?preview=1" : ""}`, { method: "POST", headers: { "content-type": "application/json" }, body: text }),
+ );
+ return { status: res.status, json: (await res.json().catch(() => ({}))) as Record<string, unknown> };
+ };
+
+ // The price check its page would make first: taken there, into the line now (not refused, not waiting to enter it).
+ const check = await post(true, {});
+ const quote = check.json.quote as { allowed?: unknown; amount?: unknown; priceVersion?: unknown } | undefined;
+ const line = check.json.line as { held?: unknown } | undefined;
+ if (check.status !== 200 || check.json.place !== "pool" || quote?.allowed === false || line?.held) return null;
+ const shown = quote && typeof quote.amount === "number" && typeof quote.priceVersion === "string" ? { amount: quote.amount, priceVersion: quote.priceVersion } : undefined;
+
+ const made = await post(false, { requestId: crypto.randomUUID(), ...(shown && { shown }) });
+ const items = Array.isArray(made.json.items) ? (made.json.items as { id?: unknown; place?: unknown }[]) : [];
+ const ids = items.map((x) => x.id).filter((x): x is string => typeof x === "string");
+ if (made.status !== 201 || !ids.length) return null;
+ // Taken, but waiting to enter the line (a limit, or a service), or not on this install's GPUs after all: stopped again,
+ // and the failed run keeps its own buttons.
+ if (made.json.held || items.some((x) => x.place !== "pool")) {
+ for (const newId of ids) await cancelGeneration(newId).catch(() => {});
+ return null;
+ }
+ return ids;
+}
+
+declare global {
+ /** The server's own context as it started (instrumentation.ts): no run's account, GPU or stamp in scope. */
+ var __fuobeRootContext: (<R>(fn: () => R) => R) | undefined;
+}
+
+/** Keep the server's own context (called once as it starts), for work a run starts that must not run as that run. */
+export function keepRootContext(): void {
+ globalThis.__fuobeRootContext ??= AsyncLocalStorage.snapshot();
+}
+
+/**
+ * generations.ts failRun's side: the move it claimed goes out now, without holding the failing run up (the person's page
+ * may be closed: it is made all the same). Outside the failed run's own scope (its account's GPU, its stamp), as a press
+ * from the page would be.
+ */
+export function sendSoon(id: string): void {
+ const go = () => setTimeout(() => void sendToSite(id), 0);
+ const root = globalThis.__fuobeRootContext;
+ if (root) root(go);
+ else go();
+}
diff --git a/src/server/site-fallback.ts b/src/server/site-fallback.ts
new file mode 100644
index 00000000..ba095ffb
--- /dev/null
+++ b/src/server/site-fallback.ts
@@ -0,0 +1,145 @@
+import "server-only";
+import type { RunTrouble } from "@/lib/diagnose";
+import { siteFallbackOf as siteFallbackOfRun, type SiteFallback } from "@/lib/site-run";
+import { db } from "./db";
+import { hostedRunsOn } from "./hosted-switch";
+
+/**
+ * "Run on {Place} automatically when your GPU can't" (hosted runs only): the account's answer, asked once after its first
+ * "Run on {Place}" on a run its own GPU couldn't make, and changeable in Settings → Where your runs go. With it on, a run
+ * that fails on the account's own GPU for a GPU's reason (src/lib/site-run.ts siteFallbackOf) is made again on this
+ * install's GPUs by the server, at once, through the account's own Run (site-fallback-run.ts), and a run sent while its
+ * GPU doesn't answer goes there instead of asking (hosted-run.ts). Tables made in db.ts (SITE_FALLBACK_TABLES).
+ *
+ * Each failed run moves once: its row here is claimed as it fails ("sending"), and says the run made for it ("moved") or
+ * that it wasn't taken ("refused": the failed run stays as it was, with its own buttons). A run made this way is never
+ * moved again, and neither is a run on this install's GPUs.
+ */
+
+/** A move still "sending" this long after it was claimed (a server stopped in the middle) counts as not made. */
+export const SENDING_MS = 2 * 60_000;
+
+/** The account's answer: "on", "off" (Not now, or switched off), or undefined (never asked). */
+export function siteFallbackFor(accountId: string): SiteFallback | undefined {
+ const r = db().prepare("SELECT auto FROM account_site_fallback WHERE account_id = ?").get(accountId) as { auto: number } | undefined;
+ return r ? (r.auto ? "on" : "off") : undefined;
+}
+
+/** Keep the account's answer (asked once: either answer counts as asked). */
+export function setSiteFallback(accountId: string, on: boolean, now = Date.now()): void {
+ db()
+ .prepare(
+ `INSERT INTO account_site_fallback (account_id, auto, updated_at) VALUES (?, ?, ?)
+ ON CONFLICT(account_id) DO UPDATE SET auto = excluded.auto, updated_at = excluded.updated_at`,
+ )
+ .run(accountId, on ? 1 : 0, now);
+}
+
+/** Is it on for this account now (hosted runs on, and it said yes)? */
+export const siteFallbackOn = (accountId: string): boolean => hostedRunsOn() && siteFallbackFor(accountId) === "on";
+
+/** A deleted account's answer and its moves go with it. */
+export function clearSiteFallback(accountId: string): void {
+ db().prepare("DELETE FROM account_site_fallback WHERE account_id = ?").run(accountId);
+ db().prepare("DELETE FROM site_fallback_runs WHERE account_id = ?").run(accountId);
+}
+
+type MoveState = "sending" | "moved" | "refused";
+
+interface MoveRow {
+ run_id: string;
+ account_id: string;
+ state: MoveState;
+ new_id: string | null;
+ at: number;
+}
+
+/** The move of failed run `id`, if one was claimed. */
+export function moveOf(id: string): MoveRow | undefined {
+ return db().prepare("SELECT * FROM site_fallback_runs WHERE run_id = ?").get(id) as MoveRow | undefined;
+}
+
+/** The failed run a run was made for (it went to this install's GPUs when its own GPU couldn't make it), if any. */
+export function movedFromOf(newId: string): string | undefined {
+ return (db().prepare("SELECT run_id FROM site_fallback_runs WHERE new_id = ?").pluck().get(newId) as string | undefined) ?? undefined;
+}
+
+/** A failed run's card fields (Generation.movedTo, Generation.moving): where it went, or that it is going. */
+export function movedFields(id: string, now = Date.now()): { movedTo: string } | { moving: true } | Record<string, never> {
+ const m = moveOf(id);
+ if (!m) return {};
+ if (m.state === "moved" && m.new_id) return { movedTo: m.new_id };
+ if (m.state === "sending" && now - m.at < SENDING_MS) return { moving: true };
+ return {};
+}
+
+/** The stored request's facts the claim reads. */
+interface FailedRow {
+ id: string;
+ status: string;
+ provider: string;
+ engine: string;
+ model_id: string;
+ op: string;
+ kind: string;
+ preset_id: string | null;
+ request_json: string;
+ depends_on: string | null;
+}
+
+/**
+ * A run failed on account `accountId`'s own GPU (generations.ts failRun), with what it ran into: claim its move to this
+ * install's GPUs when the account said yes and the failure is one of its GPU's (src/lib/site-run.ts siteFallbackOf), for
+ * a run made on its own (not a step of a longer run), never one made this way or on this install's GPUs. True when it was
+ * claimed now (the caller sends it: site-fallback-run.ts). Synchronous, so the failed run reads "going to {Place}" from
+ * the moment it reads failed.
+ */
+export function claimSiteFallback(id: string, accountId: string | undefined, trouble: RunTrouble | undefined, now = Date.now()): boolean {
+ if (!accountId || !trouble || !siteFallbackOn(accountId)) return false;
+ const r = db().prepare("SELECT id, status, provider, engine, model_id, op, kind, preset_id, request_json, depends_on FROM generations WHERE id = ?").get(id) as FailedRow | undefined;
+ if (!r || r.status !== "failed") return false;
+ let req: { account?: string; place?: string };
+ try {
+ req = JSON.parse(r.request_json) as { account?: string; place?: string };
+ } catch {
+ return false;
+ }
+ if (req.account !== accountId) return false;
+ const g = {
+ status: "failed" as const,
+ provider: r.provider as never,
+ engine: r.engine as never,
+ modelId: r.model_id,
+ op: r.op as never,
+ kind: r.kind as never,
+ presetId: r.preset_id,
+ trouble,
+ ...(req.place === "pool" && { place: "pool" as const }),
+ };
+ // (This install's rules are checked by the Run it is sent through: a run they don't take is left as it is.)
+ if (!siteFallbackOfRun(g, true, undefined)) return false;
+ // Made this way already: never again (a run there that failed is never one of its own GPU's, but nothing loops).
+ if (movedFromOf(id)) return false;
+ // A step of a longer run (it waits for another, or another waits for it) stays with its run.
+ if (r.depends_on) return false;
+ if (db().prepare("SELECT 1 FROM generations WHERE depends_on = @id OR (substr(depends_on, 1, 1) = '[' AND instr(depends_on, @quoted) > 0) LIMIT 1").get({ id, quoted: JSON.stringify(id) })) return false;
+ return db().prepare("INSERT INTO site_fallback_runs (run_id, account_id, state, new_id, at) VALUES (?, ?, 'sending', NULL, ?) ON CONFLICT(run_id) DO NOTHING").run(id, accountId, now).changes > 0;
+}
+
+
+/** The move was made: the run made for it. */
+export function noteMoved(id: string, newId: string, now = Date.now()): void {
+ db().prepare("UPDATE site_fallback_runs SET state = 'moved', new_id = ?, at = ? WHERE run_id = ?").run(newId, now, id);
+ touch(id, now);
+}
+
+/** The move wasn't taken (refused, held, or this install's GPUs off): the failed run stays as it was. */
+export function noteRefused(id: string, now = Date.now()): void {
+ db().prepare("UPDATE site_fallback_runs SET state = 'refused', at = ? WHERE run_id = ? AND state = 'sending'").run(now, id);
+ touch(id, now);
+}
+
+/** The failed run's card changed (moved, or not): the lists read it again. */
+function touch(id: string, now: number): void {
+ db().prepare("UPDATE generations SET updated_at = ? WHERE id = ?").run(now, id);
+}
diff --git a/tests/site-fallback.test.ts b/tests/site-fallback.test.ts
new file mode 100644
index 00000000..f6f0c946
--- /dev/null
+++ b/tests/site-fallback.test.ts
@@ -0,0 +1,345 @@
+import crypto from "node:crypto";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { startFakeBilling, FAKE_POLICY, type FakeBilling } from "./helpers/fake-billing";
+import { startFakeComfy, type FakeComfy } from "./helpers/fake-comfy-runner";
+import { tempDir } from "./helpers/temp-dir";
+
+/**
+ * "Run on {Place} automatically when your GPU can't" (hosted runs): the account's answer, kept once on the server; a run
+ * that fails on its own GPU for a GPU's reason made again by the server on this install's GPUs (through the account's own
+ * Run, linked both ways, once), never for the person's own files and never twice; a run they won't take left as it was;
+ * and a run sent while its GPU doesn't answer going there instead of asking. A stand-in ComfyUI as the account's GPU, a
+ * stand-in worker as this install's GPUs.
+ */
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+vi.setConfig({ testTimeout: 60_000 });
+
+const dir = tempDir("fuobe-site-fallback-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:7";
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_ALLOW_PRIVATE_URLS;
+delete process.env.FUOBE_BILLING_URL;
+delete process.env.FUOBE_MODERATION_URL;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+const realFetch = globalThis.fetch;
+let allowed: string[] = [];
+globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input instanceof Request ? input.url : input);
+ if (allowed.some((a) => url.startsWith(a))) return realFetch(input, init);
+ return new Response("not reachable in this test", { status: 599 });
+}) as typeof fetch;
+
+const auth = await import("@/server/auth");
+const generationsRoute = await import("@/app/api/generations/route");
+const fallbackRoute = await import("@/app/api/account/site-fallback/route");
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const { setSetting } = await import("@/server/settings");
+const pool = await import("@/server/computer/pool");
+const { catalogVersion } = await import("@/server/computer/catalog-version");
+const billing = await import("@/server/billing");
+const { visitorStatus } = await import("@/server/account-gpu");
+const { loadManifest } = await import("@/server/providers/comfyui");
+const { loadIndex } = await import("@/server/gpu/index-file");
+const { allLanes } = await import("@/lib/lanes");
+const { PLACE_ASK_HEADER } = await import("@/lib/guest-access");
+const { getGeneration, SELF_HEAL } = await import("@/server/generations");
+const fallback = await import("@/server/site-fallback");
+const { sendToSite } = await import("@/server/site-fallback-run");
+
+const HOST = "localhost:3000";
+const SITE_HEADERS = { host: HOST, "sec-fetch-site": "same-origin", origin: `http://${HOST}` };
+const sha = (s: string) => crypto.createHash("sha256").update(s).digest("hex");
+const IMAGE = { feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse at dusk", params: { aspectRatio: "16:9", seed: 3 } };
+
+let fake: FakeBilling;
+let comfy: FakeComfy;
+let n = 0;
+
+/** A new account with its own GPU (the stand-in ComfyUI), and its cookie. */
+function account(o: { gpu?: boolean } = { gpu: true }) {
+ const a = auth.createAccount(`fallback-${++n}@example.com`, "long enough");
+ if (o.gpu) auth.setAccountGpu(a.id, { url: comfy.url });
+ return { id: a.id, cookie: `${auth.SESSION_COOKIE}=${auth.createSession(a.id).value}` };
+}
+
+const post = async (body: Record<string, unknown>, cookie: string) => {
+ const text = JSON.stringify(body);
+ const r = await generationsRoute.POST(
+ new Request(`http://${HOST}/api/generations`, { method: "POST", headers: { ...SITE_HEADERS, cookie, "content-type": "application/json", "content-length": String(Buffer.byteLength(text)) }, body: text }),
+ );
+ return { status: r.status, headers: r.headers, body: (await r.json()) as { items?: { id: string; place?: string }[]; code?: string; error?: string } };
+};
+const answer = async (cookie: string, method: "GET" | "PUT", body?: unknown) => {
+ const r = await fallbackRoute[method](
+ new Request(`http://${HOST}/api/account/site-fallback`, { method, headers: { ...SITE_HEADERS, cookie, "content-type": "application/json" }, ...(body !== undefined && { body: JSON.stringify(body) }) }),
+ );
+ return { status: r.status, body: (await r.json()) as { siteFallback?: string | null } };
+};
+
+/** A worker as the owner adds it, connected once (this install's GPUs). */
+function standInWorker() {
+ const w = pool.addWorker(`stand-in-${++n}`);
+ const lanes = allLanes(loadIndex(), sha);
+ pool.patchWorker(w.id, { paused: false, hours: { always: true }, allow: Object.fromEntries(lanes.map((l) => [l.lane, { delayMs: 0 }])), claimAfterMs: 0 });
+ db()
+ .prepare("UPDATE relay_workers SET lanes_json = ?, facts_json = ?, catalog_version = ?, protocol = 3 WHERE id = ?")
+ .run(JSON.stringify({ lanes: lanes.map((l) => l.lane), workflows: loadManifest().workflows.map((x) => x.id) }), JSON.stringify({ vramBytes: 96 * 2 ** 30 }), catalogVersion(), w.id);
+ db().prepare("UPDATE relay_workers SET seen_at = ?, paused_local = 0 WHERE id = ?").run(Date.now(), w.id);
+ return w;
+}
+
+const withBilling = (policy: Record<string, unknown> = {}) => {
+ process.env.FUOBE_BILLING_URL = fake.url;
+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";
+ fake.policy = { ...FAKE_POLICY, ...policy, limits: { ...FAKE_POLICY.limits, outputsPerRun: 4, ...((policy.limits as object) ?? {}) }, ttlS: 0 };
+ billing.resetBillingCache();
+};
+
+/** The account's own GPU answers this run's job with an error from its node (`message`), as ComfyUI's history says it. */
+const failsWith = (message: string) => (m: string, p: string) => {
+ if (m !== "GET" || !p.startsWith("/history/")) return undefined;
+ const id = decodeURIComponent(p.slice("/history/".length));
+ const error = { prompt_id: id, node_id: "3", node_type: "KSampler", executed: [], exception_message: message, exception_type: "RuntimeError", traceback: [], current_inputs: {}, current_outputs: {} };
+ return { status: 200, contentType: "application/json", body: JSON.stringify({ [id]: { prompt: [1, id, {}, {}, []], status: { status_str: "error", completed: false, messages: [["execution_start", {}], ["execution_error", error]] }, outputs: {} } }) };
+};
+
+/** Tick the runner until `ok` holds (or the time is up). */
+async function until<T>(fn: () => T, ms = 20_000): Promise<T> {
+ const end = Date.now() + ms;
+ let v = fn();
+ while (!v && Date.now() < end) {
+ await globalThis.__fuobeRunner?.tick();
+ await new Promise((r) => setTimeout(r, 20));
+ v = fn();
+ }
+ return v;
+}
+
+/** A run of the account's on its own GPU, made through its Run. */
+async function ownRun(cookie: string): Promise<string> {
+ const r = await post({ ...IMAGE, place: "own" }, cookie);
+ expect(r.status, JSON.stringify(r.body)).toBe(201);
+ expect(r.body.items![0].place).toBeUndefined();
+ return r.body.items![0].id;
+}
+
+/** The run ended failed on its own GPU, with what it ran into (as the runner keeps it). */
+function failOwn(id: string, cause: string): void {
+ const trouble = { cause, words: "Your GPU ran into a problem.", actions: [{ kind: "retry", label: "Retry" }], retryable: false };
+ db().prepare("UPDATE generations SET status = 'failed', error = ?, fix_json = ?, completed_at = ? WHERE id = ?").run(trouble.words, JSON.stringify({ trouble }), Date.now(), id);
+}
+const troubleOf = (cause: string) => ({ cause, actions: [] }) as never;
+
+/** Runs on this install's GPUs an account has made. */
+const poolRuns = (id: string) =>
+ (db().prepare("SELECT COUNT(*) AS n FROM generations WHERE json_extract(request_json, '$.account') = ? AND json_extract(request_json, '$.place') = 'pool'").get(id) as { n: number }).n;
+
+beforeAll(async () => {
+ fake = await startFakeBilling();
+ comfy = await startFakeComfy({ output: "image", delayMs: 0 });
+ globalThis.__fuobeTestGpuPort = comfy.port;
+ allowed = [fake.url];
+ auth.setPassword("install password");
+});
+afterAll(async () => {
+ globalThis.fetch = realFetch;
+ globalThis.__fuobeTestDiskFree = undefined;
+ globalThis.__fuobeTestGpuPort = undefined;
+ SELF_HEAL.scale = 1;
+ for (const k of ["FUOBE_HOSTED_RUNS", "FUOBE_HOSTED_FREE", "FUOBE_BILLING_URL", "FUOBE_BILLING_TOKEN", "FUOBE_PUBLIC_SIGNUP"]) delete process.env[k];
+ await fake.close();
+ await comfy.close();
+});
+beforeEach(() => {
+ resetRates();
+ billing.resetBillingCache();
+ SELF_HEAL.scale = 0.001;
+ process.env.FUOBE_HOSTED_RUNS = "1";
+ process.env.FUOBE_HOSTED_FREE = "1";
+ delete process.env.FUOBE_BILLING_URL;
+ delete process.env.FUOBE_BILLING_TOKEN;
+ fake.policy = { ...FAKE_POLICY };
+ fake.price = { amount: 7, version: "v7" };
+ Object.assign(comfy.opts, { answer: undefined, delayMs: 0 });
+ setSetting("comfyWhere", "workers");
+ setSetting("comfyUrl", "");
+ setSetting("engineMode", "open");
+ setSetting("demoMode", "off");
+ db().prepare("DELETE FROM relay_workers").run();
+ db().prepare("UPDATE relay_tasks SET state = 'canceled' WHERE state IN ('waiting','sending','queued','running','collecting')").run();
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();
+ standInWorker();
+});
+
+describe("the account's answer", () => {
+ it("is kept once on the server, Not now too, and can be changed; the status says it to that account only", async () => {
+ const a = account();
+ expect((await answer(a.cookie, "GET")).body.siteFallback).toBeNull();
+ expect((await visitorStatus(auth.accountById(a.id)!)).viewer.siteFallback).toBeUndefined();
+ // Not now: kept, so the question isn't asked again.
+ expect((await answer(a.cookie, "PUT", { on: false })).body.siteFallback).toBe("off");
+ expect(fallback.siteFallbackFor(a.id)).toBe("off");
+ expect((await visitorStatus(auth.accountById(a.id)!)).viewer.siteFallback).toBe("off");
+ expect(fallback.siteFallbackOn(a.id)).toBe(false);
+ // Switched on later (Settings).
+ expect((await answer(a.cookie, "PUT", { on: true })).body.siteFallback).toBe("on");
+ expect(fallback.siteFallbackOn(a.id)).toBe(true);
+ // Each account its own.
+ expect(fallback.siteFallbackFor(account().id)).toBeUndefined();
+ expect((await answer(a.cookie, "PUT", { on: "yes" })).status).toBe(400);
+ // Off with hosted runs off: never on.
+ delete process.env.FUOBE_HOSTED_RUNS;
+ expect(fallback.siteFallbackOn(a.id)).toBe(false);
+ });
+
+ it("goes with a deleted account", () => {
+ const a = account();
+ fallback.setSiteFallback(a.id, true);
+ fallback.clearSiteFallback(a.id);
+ expect(fallback.siteFallbackFor(a.id)).toBeUndefined();
+ });
+});
+
+describe("a run its own GPU couldn't make", () => {
+ it("goes to this install's GPUs by itself when the account said yes: made by the server, linked both ways, once", async () => {
+ const a = account();
+ fallback.setSiteFallback(a.id, true);
+ comfy.opts.answer = failsWith("CUDA error: out of memory");
+ const id = await ownRun(a.cookie);
+ // It fails on its own GPU (the runner's own path), and the server sends it on.
+ const moved = await until(() => fallback.moveOf(id)?.state === "moved" && fallback.moveOf(id));
+ expect(moved, JSON.stringify(fallback.moveOf(id))).toBeTruthy();
+ const failed = getGeneration(id)!;
+ expect(failed.status).toBe("failed");
+ expect(failed.trouble?.cause).toBe("gpu-out-of-memory");
+ const newId = (moved && moved.new_id) || "";
+ expect(failed.movedTo).toBe(newId);
+ expect(fallback.movedFromOf(newId)).toBe(id);
+ // The new run: the same request, on this install's GPUs, going as any run there goes.
+ const made = getGeneration(newId)!;
+ expect(made.place).toBe("pool");
+ expect(["queued", "running"]).toContain(made.status);
+ expect(made.request).toMatchObject({ prompt: IMAGE.prompt, modelId: IMAGE.modelId, params: { aspectRatio: "16:9", seed: 3 } });
+ expect(made.movedTo).toBeUndefined();
+ // Never twice: a second claim of the same run takes nothing.
+ expect(fallback.claimSiteFallback(id, a.id, troubleOf("gpu-out-of-memory"))).toBe(false);
+ expect(poolRuns(a.id)).toBe(1);
+ });
+
+ it("is left as it was when the account hasn't said yes", async () => {
+ const a = account();
+ comfy.opts.answer = failsWith("CUDA error: out of memory");
+ const id = await ownRun(a.cookie);
+ const g = await until(() => getGeneration(id)?.status === "failed" && getGeneration(id));
+ expect(g && g.trouble?.cause).toBe("gpu-out-of-memory");
+ await new Promise((r) => setTimeout(r, 100));
+ expect(fallback.moveOf(id)).toBeUndefined();
+ expect(poolRuns(a.id)).toBe(0);
+ // Not now: the same.
+ fallback.setSiteFallback(a.id, false);
+ expect(fallback.claimSiteFallback(id, a.id, troubleOf("gpu-out-of-memory"))).toBe(false);
+ });
+
+ it("only for its GPU's troubles: never the person's own files or a run they stopped", async () => {
+ const a = account();
+ fallback.setSiteFallback(a.id, true);
+ for (const cause of ["bad-input", "content-flag", "gpu-too-big", "gpu-stopped-run", "key-balance"]) {
+ const id = await ownRun(a.cookie);
+ failOwn(id, cause);
+ expect(fallback.claimSiteFallback(id, a.id, troubleOf(cause)), cause).toBe(false);
+ }
+ // No trouble kept at all (a run with nothing of its GPU's to say).
+ const plain = await ownRun(a.cookie);
+ failOwn(plain, "gpu-offline");
+ expect(fallback.claimSiteFallback(plain, a.id, undefined)).toBe(false);
+ expect(poolRuns(a.id)).toBe(0);
+ });
+
+ it("never moves a run on this install's GPUs, or one that was itself moved there", async () => {
+ const a = account();
+ fallback.setSiteFallback(a.id, true);
+ const first = await ownRun(a.cookie);
+ failOwn(first, "gpu-offline");
+ expect(fallback.claimSiteFallback(first, a.id, troubleOf("gpu-offline"))).toBe(true);
+ const made = await sendToSite(first, generationsRoute.POST);
+ expect(made?.ids).toHaveLength(1);
+ // The run made there fails too: it stays as it is (it ran on this install's GPUs).
+ db().prepare("UPDATE generations SET status = 'failed' WHERE id = ?").run(made!.ids[0]);
+ expect(fallback.claimSiteFallback(made!.ids[0], a.id, troubleOf("gpu-offline"))).toBe(false);
+ // Even a run made that way that ended on its own GPU is never moved again.
+ const other = await ownRun(a.cookie);
+ failOwn(other, "gpu-offline");
+ db().prepare("INSERT INTO site_fallback_runs (run_id, account_id, state, new_id, at) VALUES ('earlier-run', ?, 'moved', ?, ?)").run(a.id, other, Date.now());
+ expect(fallback.claimSiteFallback(other, a.id, troubleOf("gpu-offline"))).toBe(false);
+ // Another account's run is never claimed for this one.
+ const b = account();
+ fallback.setSiteFallback(b.id, true);
+ const theirs = await ownRun(a.cookie);
+ failOwn(theirs, "gpu-offline");
+ expect(fallback.claimSiteFallback(theirs, b.id, troubleOf("gpu-offline"))).toBe(false);
+ });
+
+ it("is left as it was when this install's GPUs refuse it: its card keeps its own buttons", async () => {
+ const a = account();
+ fallback.setSiteFallback(a.id, true);
+ // Closed to the account.
+ withBilling({ hosted: false });
+ const closed = await ownRun(a.cookie);
+ failOwn(closed, "gpu-offline");
+ expect(fallback.claimSiteFallback(closed, a.id, troubleOf("gpu-offline"))).toBe(true);
+ expect(getGeneration(closed)!.moving).toBe(true);
+ expect(await sendToSite(closed, generationsRoute.POST)).toBeNull();
+ expect(fallback.moveOf(closed)?.state).toBe("refused");
+ const g = getGeneration(closed)!;
+ expect(g.movedTo).toBeUndefined();
+ expect(g.moving).toBeUndefined();
+ expect(g.trouble?.cause).toBe("gpu-offline");
+ // A model the policy doesn't offer there.
+ withBilling({ pool: { deny: ["oss-z-image-turbo"] } });
+ const denied = await ownRun(a.cookie);
+ failOwn(denied, "gpu-offline");
+ expect(fallback.claimSiteFallback(denied, a.id, troubleOf("gpu-offline"))).toBe(true);
+ expect(await sendToSite(denied, generationsRoute.POST)).toBeNull();
+ expect(fallback.moveOf(denied)?.state).toBe("refused");
+ // A limit: it would wait to enter the line, so it isn't made at all.
+ withBilling({ limits: { activeRuns: 0, waiting: 5, runsPerHour: 1 } });
+ const filler = await post({ ...IMAGE, place: "pool", shown: { amount: 7, priceVersion: "v7" } }, a.cookie);
+ expect(filler.status, JSON.stringify(filler.body)).toBe(201);
+ const before = poolRuns(a.id);
+ const limited = await ownRun(a.cookie);
+ failOwn(limited, "gpu-offline");
+ expect(fallback.claimSiteFallback(limited, a.id, troubleOf("gpu-offline"))).toBe(true);
+ expect(await sendToSite(limited, generationsRoute.POST)).toBeNull();
+ expect(fallback.moveOf(limited)?.state).toBe("refused");
+ expect(poolRuns(a.id)).toBe(before);
+ // And never again for those runs.
+ expect(fallback.claimSiteFallback(limited, a.id, troubleOf("gpu-offline"))).toBe(false);
+ });
+});
+
+describe("a run sent while the account's own GPU doesn't answer", () => {
+ it("is asked about without the answer, and goes to this install's GPUs with it", async () => {
+ const a = account();
+ // Its GPU doesn't answer.
+ comfy.opts.answer = () => ({ status: 502, body: "<html>Bad gateway</html>", contentType: "text/html" });
+ globalThis.__fuobeAccountGpus?.clear();
+ const asked = await post(IMAGE, a.cookie);
+ expect(asked.status, JSON.stringify(asked.body)).toBe(409);
+ expect(asked.body.code).toBe("own-gpu-offline");
+ expect(asked.headers.get(PLACE_ASK_HEADER)).toBe("1");
+ expect(poolRuns(a.id)).toBe(0);
+ fallback.setSiteFallback(a.id, true);
+ const went = await post(IMAGE, a.cookie);
+ expect(went.status, JSON.stringify(went.body)).toBe(201);
+ expect(went.body.items![0].place).toBe("pool");
+ expect(poolRuns(a.id)).toBe(1);
+ // Not now: asked again.
+ fallback.setSiteFallback(a.id, false);
+ expect((await post(IMAGE, a.cookie)).body.code).toBe("own-gpu-offline");
+ });
+});
diff --git a/tests/site-run.test.ts b/tests/site-run.test.ts
index 3a2d31eb..84bf790b 100644
--- a/tests/site-run.test.ts
+++ b/tests/site-run.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
import type { Generation } from "@/lib/catalog/types";
import { withKeyAction, type TroubleAction } from "@/lib/diagnose";
import type { PoolRules } from "@/lib/pool-rules";
-import { shownTroubleActions, siteRunOf } from "@/lib/site-run";
+import { asksSiteFallback, movedWords, shownTroubleActions, SITE_FALLBACK_CAUSES, siteFallbackLabel, siteFallbackOf, siteFallbackQuestion, siteRunOf } from "@/lib/site-run";
/** "Run on {Place}" on a failed run (hosted runs): offered only for what this studio's GPUs take, on its open version. */
const trouble = { cause: "gpu-offline", words: "Your GPU isn't answering.", actions: [], retryable: false } as unknown as Generation["trouble"];
@@ -77,3 +77,68 @@ describe("a run refused there only for its LoRAs", () => {
expect(poolRunState({ quote: { ...quote, withoutLoras: undefined } } as never)?.withoutLoras).toBeUndefined();
});
});
+
+describe("Run on the place: the same offer on every card", () => {
+ it("never on a run that went there by itself, or is on its way", () => {
+ expect(siteRunOf(run({ movedTo: "g2" }), true, undefined)).toBeNull();
+ expect(siteRunOf(run({ moving: true }), true, undefined)).toBeNull();
+ });
+});
+
+describe("running there automatically when the person's GPU can't", () => {
+ const own = (cause: string, o: Partial<Generation> = {}) => ({ ...run({ trouble: { cause, actions: [] } as unknown as Generation["trouble"], ...o }), provider: "comfyui" }) as Parameters<typeof siteFallbackOf>[0];
+
+ it("takes the GPU's own troubles: off, stopped, out of memory, a missing model or add-on, a ComfyUI problem", () => {
+ for (const cause of ["gpu-offline", "gpu-stopped", "gpu-went-away", "gpu-out-of-memory", "gpu-model-file", "gpu-refused", "gpu-job-error", "gpu-comfy-known", "gpu-error", "gpu-restarted"]) {
+ expect(siteFallbackOf(own(cause), true, undefined), cause).toEqual({ modelId: "oss-z-image-turbo" });
+ }
+ for (const cause of ["gpu-offline", "gpu-out-of-memory", "gpu-model-file"]) expect(SITE_FALLBACK_CAUSES.has(cause as never)).toBe(true);
+ });
+
+ it("never for the person's own files or words, a run they stopped, or anything off their own GPU", () => {
+ for (const cause of ["bad-input", "content-flag", "gpu-too-big", "gpu-slow-upload", "gpu-stopped-run", "key-balance", "key-rejected", "unknown"]) {
+ expect(siteFallbackOf(own(cause), true, undefined), cause).toBeNull();
+ }
+ // Its key, not its GPU.
+ expect(siteFallbackOf({ ...own("gpu-offline"), provider: "fal", engine: "cloud" } as never, true, undefined)).toBeNull();
+ // On this install's GPUs already, off hosted runs, no trouble, or moved already.
+ expect(siteFallbackOf(own("gpu-offline", { place: "pool" }), true, undefined)).toBeNull();
+ expect(siteFallbackOf(own("gpu-offline"), false, undefined)).toBeNull();
+ expect(siteFallbackOf({ ...own("gpu-offline"), trouble: undefined }, true, undefined)).toBeNull();
+ expect(siteFallbackOf(own("gpu-offline", { movedTo: "g2" }), true, undefined)).toBeNull();
+ // What their rules keep off is never sent there.
+ expect(siteFallbackOf(own("gpu-offline"), true, { deny: ["oss-z-image-turbo"] } as PoolRules)).toBeNull();
+ });
+
+ it("asks once: an account with hosted runs on that never answered, after a run on its own GPU", () => {
+ const g = { provider: "comfyui" } as Generation;
+ expect(asksSiteFallback({ kind: "account", hosted: true }, g)).toBe(true);
+ // Answered either way: never again.
+ expect(asksSiteFallback({ kind: "account", hosted: true, siteFallback: "off" }, g)).toBe(false);
+ expect(asksSiteFallback({ kind: "account", hosted: true, siteFallback: "on" }, g)).toBe(false);
+ // Not for a run on its key, a guest, or with hosted runs off.
+ expect(asksSiteFallback({ kind: "account", hosted: true }, { provider: "fal" } as Generation)).toBe(false);
+ expect(asksSiteFallback({ kind: "guest", hosted: true }, g)).toBe(false);
+ expect(asksSiteFallback({ kind: "account", hosted: false }, g)).toBe(false);
+ expect(asksSiteFallback(undefined, g)).toBe(false);
+ });
+
+ it("says plainly where a moved run went, with no price or usage words", () => {
+ expect(siteFallbackQuestion("our GPUs")).toBe("Next time, run on our GPUs automatically when your GPU can't?");
+ expect(movedWords({ movedTo: "g2" }, "our GPUs")).toBe("Your GPU couldn't run this, so it's running on our GPUs.");
+ expect(movedWords({ moving: true }, "our GPUs")).toBe("Your GPU couldn't run this, so it's going to our GPUs.");
+ expect(movedWords({}, "our GPUs")).toBeNull();
+ for (const w of [siteFallbackQuestion("our GPUs"), siteFallbackLabel("our GPUs"), movedWords({ movedTo: "x" }, "our GPUs")!]) {
+ expect(w).not.toMatch(/\d|%|price|cost|uses|credit|\$/i);
+ }
+ });
+});
+
+describe("a list keeps asking while a failed run is on its way there", () => {
+ it("counts a moving run as on its way, and stops once it moved", async () => {
+ const { pollDelay } = await import("@/lib/generation-stream");
+ const now = 1_000_000;
+ expect(pollDelay([{ status: "failed", createdAt: now - 1000 }], false, now)).toBeNull();
+ expect(pollDelay([{ status: "failed", createdAt: now - 1000, moving: true }], false, now)).toBe(1500);
+ });
+});