The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Studio and Settings: show what is wrong with your GPU or key, and the buttons that fix it
Adarshe92cb8df9688
diff --git a/src/components/gpu/trouble.tsx b/src/components/gpu/trouble.tsxnew file mode 100644index 00000000..827fe10d--- /dev/null+++ b/src/components/gpu/trouble.tsx@@ -0,0 +1,163 @@+"use client";++import { useQueryClient, type QueryClient } from "@tanstack/react-query";+import { CreditCard, ExternalLink, KeyRound, Loader2, Play, RefreshCw, RotateCcw, Settings2, Shuffle, Stethoscope, Monitor } from "lucide-react";+import Link from "next/link";+import { useState } from "react";+import { toast } from "sonner";+import type { GpuTroubleView } from "@/lib/api";+import { backoffMs, retryPlan, type TroubleAction, type TroubleActionKind } from "@/lib/diagnose";+import { cn } from "@/lib/utils";++/**+ * What an account sees when its own GPU or key has a problem (src/lib/diagnose.ts): the plain sentence, a small details+ * line for the curious, and the buttons that help (Start your pod, Check my GPU, Settings → Your GPU or Your keys, Run+ * with your fal.ai key, Add credit, Retry). Used by a failed run's tile, Settings → Your GPU and the composer's check+ * before Run.+ */++/** What "Check my GPU" learnt: the GPU answered (and what it is), or why not, in plain words. */+export type GpuCheck = { ok: true; device?: string } | { ok: false; words: string; trouble?: GpuTroubleView; retryAfterS?: number };++/**+ * Check my GPU: the saved address asked again now (PUT /api/account/gpu?test=1 { saved: true }), the same check as+ * Settings' Test. The status strip, the composer and Settings learn its answer.+ */+export async function checkMyGpu(qc?: QueryClient): Promise<GpuCheck> {+ let res: Response;+ try {+ res = await fetch("/api/account/gpu?test=1", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ saved: true }) });+ } catch {+ return { ok: false, words: "We couldn't check right now. Check this computer's internet, then try again." };+ }+ const j = (await res.json().catch(() => ({}))) as { error?: string; trouble?: GpuTroubleView; info?: { device?: string } };+ void qc?.invalidateQueries({ queryKey: ["status"] });+ void qc?.invalidateQueries({ queryKey: ["account-gpu"] });+ if (res.ok) return { ok: true, device: j.info?.device };+ const retryAfterS = Number(res.headers.get("retry-after")) || undefined;+ return { ok: false, words: j.trouble?.words ?? j.error ?? "Your GPU didn't answer.", trouble: j.trouble, ...(retryAfterS && { retryAfterS }) };+}++const ICONS: Record<TroubleActionKind, typeof Play> = {+ retry: RotateCcw,+ "check-gpu": Stethoscope,+ "gpu-settings": Settings2,+ "key-settings": KeyRound,+ "run-with-key": Shuffle,+ "add-credit": CreditCard,+ "pick-model": Shuffle,+ "start-gpu": Play,+ pair: RefreshCw,+ "use-computer": Monitor,+};++/** The first button stands out (the one most likely to help); the rest are quieter. */+const PILL = "inline-flex h-7 w-fit items-center gap-1.5 rounded-full px-2.5 text-[12px] font-medium";+const MAIN = "bg-highlight text-highlight-foreground hover:opacity-90";+const QUIET = "bg-secondary hover:bg-accent";++export interface TroubleHandlers {+ onRetry?: () => void;+ /** "Run with your fal.ai key": the caller runs the cloud version (an explicit click: it spends the person's credit). */+ onRunWithKey?: (a: TroubleAction) => void;+ onPickModel?: () => void;+ /** "Use this computer": the caller switches runs to the ComfyUI on this computer. */+ onUseComputer?: () => void;+}++/**+ * The buttons of a diagnosis, in its order. A button with nothing to do here is left out (Retry without a run, Pick another+ * model without a picker). `max`: at most so many; `skip`: kinds the caller shows itself (a tile's own Retry).+ */+export function TroubleActions({ actions, handlers = {}, max, skip = [], className }: { actions: TroubleAction[]; handlers?: TroubleHandlers; max?: number; skip?: TroubleActionKind[]; className?: string }) {+ const qc = useQueryClient();+ const [checking, setChecking] = useState(false);+ const usable = actions.filter((a) => {+ if (skip.includes(a.kind)) return false;+ if (a.kind === "retry") return !!handlers.onRetry;+ if (a.kind === "run-with-key") return !!handlers.onRunWithKey;+ if (a.kind === "pick-model") return !!handlers.onPickModel;+ if (a.kind === "use-computer") return !!handlers.onUseComputer;+ return true;+ });+ const shown = max ? usable.slice(0, max) : usable;+ if (!shown.length) return null;+ const check = async () => {+ setChecking(true);+ try {+ const r = await checkMyGpu(qc);+ if (r.ok) toast.success(`Your GPU answered${r.device ? `: ${r.device}` : ""}. Press Retry to run it again.`);+ else toast(r.words, { id: "check-gpu" });+ } finally {+ setChecking(false);+ }+ };+ return (+ <div className={cn("flex flex-wrap gap-1.5", className)}>+ {shown.map((a, i) => {+ const Icon = ICONS[a.kind];+ const cls = cn(PILL, i === 0 && a.kind !== "retry" ? MAIN : QUIET);+ const stop = (e: React.MouseEvent) => e.stopPropagation();+ if ((a.kind === "start-gpu" || a.kind === "add-credit") && a.target) {+ return (+ <a key={a.kind} href={a.target} target="_blank" rel="noopener noreferrer" onClick={stop} className={cls}>+ <Icon className="size-3" /> {a.label}+ <ExternalLink className="size-3 opacity-60" aria-hidden />+ </a>+ );+ }+ if ((a.kind === "gpu-settings" || a.kind === "key-settings" || a.kind === "pair") && a.target) {+ return (+ <Link key={a.kind} href={a.target} onClick={stop} className={cls}>+ <Icon className="size-3" /> {a.label}+ </Link>+ );+ }+ const run =+ a.kind === "check-gpu"+ ? () => void check()+ : a.kind === "retry"+ ? handlers.onRetry+ : a.kind === "run-with-key"+ ? () => handlers.onRunWithKey?.(a)+ : a.kind === "pick-model"+ ? handlers.onPickModel+ : a.kind === "use-computer"+ ? handlers.onUseComputer+ : undefined;+ return (+ <button+ key={a.kind}+ type="button"+ disabled={a.kind === "check-gpu" && checking}+ onClick={(e) => {+ e.stopPropagation();+ run?.();+ }}+ className={cls}+ >+ {a.kind === "check-gpu" && checking ? <Loader2 className="size-3 animate-spin" /> : <Icon className="size-3" />} {a.label}+ </button>+ );+ })}+ </div>+ );+}++/** The small details line under the sentence: what came back, for the curious. */+export function TroubleDetails({ details, className }: { details?: string; className?: string }) {+ if (!details) return null;+ return (+ <p title={details} className={cn("line-clamp-2 font-mono text-[10.5px] leading-snug break-all text-muted-foreground/80", className)}>+ {details}+ </p>+ );+}++/** How long Settings waits before checking again by itself (diagnose.ts retryPlan "check"), or null: it doesn't. */+export function autoCheckIn(cause: GpuTroubleView["cause"], attempt: number, startedAt: number, now = Date.now()): number | null {+ const plan = retryPlan(cause, "check");+ if (!plan) return null;+ const wait = backoffMs(attempt, plan);+ return now - startedAt + wait > plan.budgetMs ? null : wait;+}diff --git a/src/components/gpu/your-gpu.tsx b/src/components/gpu/your-gpu.tsxindex 100010c2..9cdc19ca 100644--- a/src/components/gpu/your-gpu.tsx+++ b/src/components/gpu/your-gpu.tsx@@ -2,12 +2,15 @@import { useQuery, useQueryClient } from "@tanstack/react-query";import { Cpu, Loader2, Unplug } from "lucide-react";-import { useId, useState } from "react";+import { useEffect, useId, useRef, useState } from "react";import { toast } from "sonner";import { gib, isLocalAddress, TunnelSteps } from "@/components/gpu/comfy-finder";+import { TroubleActions, TroubleDetails, autoCheckIn } from "@/components/gpu/trouble";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";+import { useStatus, type GpuTroubleView } from "@/lib/api";+import { canSaveAnyway } from "@/lib/diagnose";import { responseError, toastError } from "@/lib/refusals";import { cn } from "@/lib/utils";@@ -20,6 +23,18 @@ interface GpuInfo {vramBytes?: number;version?: string;}+/** A PUT's answer: the GPU and what it is, or (422, 429, or saved anyway) why not in plain words with what helps. */+type PutAnswer = GpuState & { info?: GpuInfo; note?: string; url?: string; offline?: true; error?: string; trouble?: GpuTroubleView };++class CheckError extends Error {+ constructor(+ message: string,+ readonly answer: PutAnswer,+ readonly retryAfterS?: number,+ ) {+ super(message);+ }+}async function call<T>(method: string, body?: unknown, test = false): Promise<T> {const res = await fetch(`/api/account/gpu${test ? "?test=1" : ""}`, {@@ -27,52 +42,113 @@ async function call<T>(method: string, body?: unknown, test = false): Promise<T>headers: { "Content-Type": "application/json" },body: body === undefined ? undefined : JSON.stringify(body),});- const j = (await res.json().catch(() => ({}))) as T & { error?: string };- if (!res.ok) throw responseError(res, j.error ?? "Something went wrong. Please try again.");+ const j = (await res.json().catch(() => ({}))) as T & { error?: string; trouble?: GpuTroubleView };+ if (!res.ok) {+ if (method === "PUT" && (j.trouble || res.status === 429)) throw new CheckError(j.trouble?.words ?? j.error ?? "Something went wrong. Please try again.", j as unknown as PutAnswer, Number(res.headers.get("retry-after")) || undefined);+ throw responseError(res, j.error ?? "Something went wrong. Please try again.");+ }return j;}+/** A check that didn't pass, as shown under the field: its words, details and buttons, and when it checks again by itself. */+interface Failed {+ words: string;+ trouble?: GpuTroubleView;+ /** Checking again by itself at this time (a GPU that is off or starting up, too many checks). */+ againAt?: number;+ /** The check was a Connect (not a Test): "Save anyway" can keep the address. */+ connecting: boolean;+}+/*** "Your GPU" (public sign-up): an account's own ComfyUI, where its runs go (never this studio's keys* or GPU). The server calls it, so it needs a web address anyone can reach: cloudflared (or another tunnel) in front- * of a local ComfyUI. Nothing here looks for a ComfyUI on this device: it shows how to make that address (TunnelSteps),- * in words a visitor needs no dictionary for. 36rem wide at most- * from sm up, unless a wider page lifts that (className, as ConnectChoice's).+ * of a local ComfyUI, or a RunPod pod's address. Nothing here looks for a ComfyUI on this device: it shows how to make+ * that address (TunnelSteps), in words a visitor needs no dictionary for. A check that doesn't pass says why in plain+ * words, with what helps; a GPU that is off or starting up is checked again by itself, and its address can be saved+ * anyway. The saved GPU's card says whether it answers now. 36rem wide at most from sm up, unless a wider page lifts+ * that (className, as ConnectChoice's).*/export function YourGpu({ className, onLinked }: { className?: string; onLinked?: () => void } = {}) {const qc = useQueryClient();const id = useId();const q = useQuery({ queryKey: ["account-gpu"], queryFn: () => call<GpuState>("GET") });+ const live = useStatus().data?.viewer?.gpu;const [url, setUrl] = useState("");const [token, setToken] = useState("");- const [busy, setBusy] = useState<"test" | "save" | "remove" | null>(null);+ const [busy, setBusy] = useState<"test" | "save" | "anyway" | "remove" | null>(null);const [info, setInfo] = useState<GpuInfo | null>(null);- const [error, setError] = useState<string | null>(null);+ const [note, setNote] = useState<string | null>(null);+ const [failed, setFailed] = useState<Failed | null>(null);+ const [now, setNow] = useState(() => Date.now());+ // The self-check: when it started and how many checks it made (diagnose.ts retryPlan "check").+ const auto = useRef<{ startedAt: number; attempt: number; connecting: boolean } | null>(null);const local = !!url.trim() && isLocalAddress(/^[a-z]+:\/\//i.test(url.trim()) ? url.trim() : `http://${url.trim()}`);- const send = async (test: boolean) => {- setBusy(test ? "test" : "save");- setError(null);+ const linked = () => {+ // Runs go to the link now, not to a Fuobe tab on this computer, and its own files are taken (the status says so).+ void qc.invalidateQueries({ queryKey: ["viewer"] });+ void qc.invalidateQueries({ queryKey: ["status"] });+ };+ const send = async (mode: "test" | "save" | "anyway", again = false) => {+ setBusy(mode);+ if (!again) auto.current = null;try {- const r = await call<GpuState & { info: GpuInfo }>("PUT", { url: url.trim(), token: token.trim() || undefined }, test);- setInfo(r.info);- if (!test) {+ const r = await call<PutAnswer>("PUT", { url: url.trim(), token: token.trim() || undefined, ...(mode === "anyway" && { anyway: true }) }, mode === "test");+ auto.current = null;+ setFailed(null);+ setInfo(r.info ?? null);+ setNote(r.note ?? null);+ if (r.url && mode === "test") setUrl(r.url);+ if (mode !== "test") {qc.setQueryData(["account-gpu"], { gpu: r.gpu });- // Runs go to the link now, not to a Fuobe tab on this computer, and its own files are taken (the status says so).- void qc.invalidateQueries({ queryKey: ["viewer"] });- void qc.invalidateQueries({ queryKey: ["status"] });- toast.success("Your GPU is connected. Runs go to your ComfyUI now.");+ linked();+ if (r.offline) toast("Your address is saved. Your runs start as soon as your GPU answers.");+ else toast.success("Your GPU is connected. Runs go to your ComfyUI now.");setUrl("");setToken("");onLinked?.();}} catch (e) {setInfo(null);- setError((e as Error).message);+ if (!(e instanceof CheckError)) {+ setFailed({ words: (e as Error).message, connecting: mode !== "test" });+ return;+ }+ // The address as the check made it whole (https:// added, a "?…" left out) goes back in the field, said below it.+ if (e.answer.url) setUrl(e.answer.url);+ setNote(e.answer.note ?? null);+ const trouble = e.answer.trouble;+ const connecting = mode !== "test";+ // A GPU that is off or starting up (or too many checks): checked again by itself, with a growing wait.+ const run = (auto.current ??= { startedAt: Date.now(), attempt: 0, connecting });+ run.attempt++;+ const wait = trouble ? (e.retryAfterS ? e.retryAfterS * 1000 : autoCheckIn(trouble.cause, run.attempt, run.startedAt)) : null;+ if (wait === null) auto.current = null;+ setFailed({ words: e.message, trouble, connecting, ...(wait !== null && { againAt: Date.now() + wait }) });} finally {setBusy(null);}};+ // The self-check's clock: a countdown on the page, then the same check again (a Connect stays a Test until it answers).+ const againAt = failed?.againAt;+ useEffect(() => {+ if (!againAt) return;+ const t = setInterval(() => {+ setNow(Date.now());+ if (Date.now() >= againAt && auto.current) {+ clearInterval(t);+ void send(auto.current.connecting ? "save" : "test", true);+ }+ }, 1000);+ return () => clearInterval(t);+ // The check runs with the address and token in the fields now.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [againAt]);+ const stopAuto = () => {+ auto.current = null;+ setFailed((f) => (f ? { ...f, againAt: undefined } : f));+ };const remove = async () => {setBusy("remove");try {@@ -89,6 +165,9 @@ export function YourGpu({ className, onLinked }: { className?: string; onLinked?if (q.isError) return <p className="text-[13px] text-muted-foreground">{q.error.message}</p>;if (!q.data) return <Loader2 className="size-5 animate-spin text-muted-foreground" />;const gpu = q.data.gpu?.mode === "computer" ? null : q.data.gpu;+ // The saved link's last status check (every 30 s while the page is open): online, or why not.+ const offline = gpu && live?.connected && live.mode === "link" && live.online === false;+ const seconds = againAt ? Math.max(0, Math.ceil((againAt - now) / 1000)) : 0;return (<div className={cn("w-full min-w-0 space-y-4 sm:max-w-[36rem]", className)}>@@ -96,18 +175,33 @@ export function YourGpu({ className, onLinked }: { className?: string; onLinked?{gpu ? "Your runs go to your ComfyUI through this web address." : "Your runs reach your ComfyUI through a web address. Here's how to give it one:"}</p>{gpu ? (- <div className="flex items-start gap-2.5 rounded-xl bg-brand-faint px-3 py-2.5 text-[13px]">- <Cpu className="mt-0.5 size-4 shrink-0 text-brand-text" />- <div className="min-w-0 flex-1">- <p className="font-medium">Connected</p>- <p className="truncate font-mono text-[12px] text-muted-foreground">- {gpu.url}- {gpu.hasToken ? " · with a token" : ""}- </p>+ <div className={cn("space-y-2 rounded-xl px-3 py-2.5 text-[13px]", offline ? "border border-dashed" : "bg-brand-faint")}>+ <div className="flex items-start gap-2.5">+ <Cpu className={cn("mt-0.5 size-4 shrink-0", offline ? "text-muted-foreground" : "text-brand-text")} />+ <div className="min-w-0 flex-1">+ <p className="font-medium">{offline ? "Offline: your GPU isn't answering right now" : "Connected"}</p>+ <p className="truncate font-mono text-[12px] text-muted-foreground">+ {gpu.url}+ {gpu.hasToken ? " · with a token" : ""}+ </p>+ </div>+ <Button size="sm" variant="ghost" className="-my-1 h-7" onClick={() => void remove()} disabled={busy !== null}>+ {busy === "remove" ? <Loader2 className="animate-spin" /> : <Unplug />} Disconnect+ </Button></div>- <Button size="sm" variant="ghost" className="-my-1 h-7" onClick={() => void remove()} disabled={busy !== null}>- {busy === "remove" ? <Loader2 className="animate-spin" /> : <Unplug />} Disconnect- </Button>+ {offline && (+ <div className="space-y-1.5 pl-6.5">+ {live.trouble && <p className="text-[12px] text-muted-foreground">{live.trouble.words}</p>}+ <TroubleDetails details={live.trouble?.details} />+ <TroubleActions+ actions={[+ // Check now first, then what the check said helps (Start your pod…), without the address fields' own.+ { kind: "check-gpu", label: "Check now" },+ ...(live.trouble?.actions ?? []).filter((a) => a.kind !== "check-gpu" && a.kind !== "gpu-settings"),+ ]}+ />+ </div>+ )}</div>) : (<TunnelSteps />@@ -117,10 +211,21 @@ export function YourGpu({ className, onLinked }: { className?: string; onLinked?<Label htmlFor={`${id}-url`} className="text-[13px]">{gpu ? "Connect another address" : "Your ComfyUI's web address"}</Label>- <Input id={`${id}-url`} placeholder="https://your-address.trycloudflare.com" value={url} onChange={(e) => setUrl(e.target.value)} aria-invalid={!!error || local} />+ <Input+ id={`${id}-url`}+ placeholder="https://your-address.trycloudflare.com"+ value={url}+ onChange={(e) => {+ setUrl(e.target.value);+ setNote(null);+ stopAuto();+ }}+ aria-invalid={!!failed || local}+ />{local && (<p className="text-[12px] text-destructive">That address only works on your own computer or network. Paste the one cloudflared shows, ending in trycloudflare.com.</p>)}+ {note && <p className="text-[12px] text-muted-foreground">{note}</p>}</div><div className="space-y-1.5"><Label htmlFor={`${id}-token`} className="text-[13px]">@@ -131,7 +236,22 @@ export function YourGpu({ className, onLinked }: { className?: string; onLinked?Only if your ComfyUI or its web address asks for a password or token.</p></div>- {error && <p className="text-[12px] text-destructive">{error}</p>}+ {failed && (+ <div className="space-y-1.5" aria-live="polite">+ <p className={cn("text-[12px]", failed.trouble?.retryable ? "text-foreground" : "text-destructive")}>{failed.words}</p>+ <TroubleDetails details={failed.trouble?.details} />+ {failed.againAt && (+ <p className="flex items-center gap-1.5 text-[12px] text-muted-foreground">+ <Loader2 className="size-3 animate-spin" />+ {seconds > 0 ? `Waiting for your GPU · checking again in ${seconds} s` : "Checking again…"}+ <button type="button" onClick={stopAuto} className="underline underline-offset-2 hover:text-foreground">+ Stop+ </button>+ </p>+ )}+ {failed.trouble && <TroubleActions actions={failed.trouble.actions.filter((a) => a.kind !== "gpu-settings" && a.kind !== "check-gpu")} />}+ </div>+ )}{info && (<p className="text-[12px] text-muted-foreground">ComfyUI answered{info.device ? `: ${info.device}` : ""}@@ -140,12 +260,18 @@ export function YourGpu({ className, onLinked }: { className?: string; onLinked?</p>)}<div className="flex flex-wrap gap-2">- <Button size="sm" onClick={() => void send(false)} disabled={!url.trim() || local || busy !== null}>+ <Button size="sm" onClick={() => void send("save")} disabled={!url.trim() || local || busy !== null}>{busy === "save" && <Loader2 className="animate-spin" />} Connect</Button>- <Button size="sm" variant="secondary" onClick={() => void send(true)} disabled={!url.trim() || local || busy !== null}>+ <Button size="sm" variant="secondary" onClick={() => void send("test")} disabled={!url.trim() || local || busy !== null}>{busy === "test" && <Loader2 className="animate-spin" />} Test</Button>+ {/* A GPU that is off right now (a stopped pod, one starting up): keep the address, and runs wait for it. */}+ {failed?.trouble && canSaveAnyway(failed.trouble.cause) && !!url.trim() && !local && (+ <Button size="sm" variant="ghost" onClick={() => void send("anyway")} disabled={busy !== null}>+ {busy === "anyway" && <Loader2 className="animate-spin" />} Save anyway+ </Button>+ )}</div></div></div>diff --git a/src/components/library/asset-card.tsx b/src/components/library/asset-card.tsxindex 8cb7ac8b..273943e9 100644--- a/src/components/library/asset-card.tsx+++ b/src/components/library/asset-card.tsx@@ -11,6 +11,7 @@ import { coverOf, trashDaysLeft, userTitle, type LibraryEntry } from "@/lib/librimport { isLayered, shownOutputs } from "@/lib/output-actions";import { cn } from "@/lib/utils";import { PlaceholderChip } from "@/components/demo-mode";+import { TroubleActions, TroubleDetails } from "@/components/gpu/trouble";import { DRAG_TYPE } from "./folders";import { ReviewBadge } from "./review";import type { Layout } from "./view-options";@@ -63,6 +64,13 @@ export function StatusCover({ g }: { g: Generation }) {<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-4 text-[12px] leading-snug break-words text-muted-foreground">{g.error}</p>}+ {/* An account's own GPU or key: what came back (small), and the way out (Start your pod, Check my GPU, Replace key…). */}+ {g.status === "failed" && g.trouble && (+ <>+ <TroubleDetails details={g.trouble.details} />+ <TroubleActions className="pt-1" actions={g.trouble.actions} skip={["retry"]} max={2} />+ </>+ )}</div></div>);diff --git a/src/components/nav/status-chips.tsx b/src/components/nav/status-chips.tsxindex 5a6b9be6..7e3cff5f 100644--- a/src/components/nav/status-chips.tsx+++ b/src/components/nav/status-chips.tsx@@ -14,6 +14,7 @@ import { Skeleton } from "@/components/ui/skeleton";import { ownGpuOf, signInHref, useEngineMode, useHydrated, useStatus, useViewer, type EngineMode, type StatusInfo } from "@/lib/api";import { placeholdersOn } from "@/lib/demo-mode";import { deviceLabel } from "@/lib/gpu/readiness";+import { shortState } from "@/lib/diagnose";import { safeLink, useInterest } from "@/lib/hosted";import type { ViewerKind } from "@/lib/nav-model";import { cn } from "@/lib/utils";@@ -89,7 +90,7 @@ export function YourGpuChip({ gpu, guest, hosted, item }: { gpu: Viewer["gpu"];<><span className="flex w-full items-center gap-3"><DotSlot ok={g.online} /> Your GPU- <span className="ml-auto">{g.online ? "online" : g.comfy === "down" ? "ComfyUI not running" : g.comfy === "no-setting" ? "needs a setting" : "offline"}</span>+ <span className="ml-auto">{g.online ? "online" : g.comfy === "down" ? "ComfyUI not running" : g.comfy === "no-setting" ? "needs a setting" : shortState(g.trouble?.cause)}</span></span>{(g.device || vram || g.mode === "computer") && (<span className="truncate pl-7 text-[11px]">{[g.mode === "computer" && "Your computer", deviceLabel(g.device), vram && `${vram} VRAM`].filter(Boolean).join(" · ")}</span>diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsxindex 59f24634..77c12fc3 100644--- a/src/components/studio/composer.tsx+++ b/src/components/studio/composer.tsx@@ -90,6 +90,8 @@ import { H3_TIER_PARAM, h3TierNote } from "@/lib/gpu/h3-tier";import { formatCost } from "@/lib/format";import { toastError } from "@/lib/refusals";import { addKeyLabel, billedTo, CLOUD_KEY, needsKey, paidThrough, startingModel } from "@/lib/your-keys";+import { gpuBeforeRun } from "@/lib/before-run";+import { TroubleActions, TroubleDetails } from "@/components/gpu/trouble";import { cn } from "@/lib/utils";import { h3ReferenceProblem, openReferenceMode } from "@/lib/h3-references";import { badgeFor, badgeText, dropGpuRetry, openGpuSetup, setGpuRetry, useGpuBadges } from "@/hooks/use-gpu";@@ -756,6 +758,23 @@ export function Composer({ docked }: { docked: boolean }) {// An account's paid model it has no key for yet: Generate asks for the key (the note below says so too).const keyToAdd = model && status?.viewer?.paidAllowed !== false ? needsKey(model, status)?.[0] : undefined;+ // The check before Run: an account's own GPU at a web address that didn't answer its last status check (the status+ // strip's, every 30 s; nothing here asks the GPU) shows what is wrong and its fixes before Run. A run started anyway+ // waits for the GPU. One of the account's keys that runs this tool's cloud version is offered too (an explicit click:+ // it spends the person's own credit).+ const gpuDown = gpuBeforeRun({ viewer: status?.viewer, model, engine, onPool: hostedHere && runOn === "pool", preset, has, getModel: catalog.getModel });+ const [cloudRun, setCloudRun] = useState(false);+ // "Run with your fal.ai key": once the switch to Cloud has moved the tool to its cloud model, it runs (once).+ useEffect(() => {+ if (!cloudRun) return;+ const late = setTimeout(() => setCloudRun(false), 4000);+ if (engine === "cloud" && model && (model.engine !== "open" || dualEngine(model))) {+ setCloudRun(false);+ submitRef.current();+ }+ return () => clearTimeout(late);+ }, [cloudRun, engine, model]);+// `skip` is true only from the guided fix's "Run anyway" (a click handler passes its event here).const submit = (skip?: unknown) => {const skipGpu = skip === true;@@ -1727,6 +1746,24 @@ export function Composer({ docked }: { docked: boolean }) {</p>)}</div>+ {gpuDown && (+ <div role="note" aria-live="polite" className="mx-1 mt-2 space-y-1.5 rounded-xl border border-dashed px-3 py-2 text-[12px] leading-snug text-muted-foreground">+ <p>+ <span className="font-medium text-foreground">{gpuDown.words}</span> A run you start now waits for it.+ </p>+ <TroubleDetails details={gpuDown.details} />+ <TroubleActions+ actions={gpuDown.actions}+ skip={["retry"]}+ handlers={{+ onRunWithKey: () => {+ setEngine("cloud");+ setCloudRun(true);+ },+ }}+ />+ </div>+ )}{outcome && (<p className="px-2 pt-1 text-[12px] text-muted-foreground tabular-nums" aria-live="polite">{outcome}diff --git a/src/components/studio/feed.tsx b/src/components/studio/feed.tsxindex 0fca3d15..3f9c7c84 100644--- a/src/components/studio/feed.tsx+++ b/src/components/studio/feed.tsx@@ -16,6 +16,8 @@ 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 { placeholdersOn } from "@/lib/demo-mode";import { useSoulFinish } from "./soul-finish";@@ -126,12 +128,25 @@ export function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {}export function FailedTile({ g, ratio, onRetry }: { g: Generation; ratio: number; onRetry: () => void }) {+ const create = useCreateGeneration();+ const trouble = g.status === "failed" ? g.trouble : undefined;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} /></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 --git a/src/lib/api.ts b/src/lib/api.tsindex aec31504..050ddd43 100644--- a/src/lib/api.ts+++ b/src/lib/api.ts@@ -32,8 +32,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";+/** 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;@@ -881,7 +885,18 @@ export interface StatusInfo {*/viewer?: {kind: "guest" | "account";- gpu: { connected: boolean; mode?: "computer" | "link"; online?: boolean; comfy?: "down" | "no-setting"; device?: string; vramBytes?: number };+ gpu: {+ connected: boolean;+ mode?: "computer" | "link";+ online?: boolean;+ comfy?: "down" | "no-setting";+ device?: string;+ vramBytes?: number;+ /** A link that didn't answer its last status check: why, in plain words, and what helps (src/lib/diagnose.ts). */+ trouble?: GpuTroubleView;+ /** A link's kind: a RunPod pod's port gets "Start your pod". */+ host?: "runpod" | "tunnel" | "web";+ };keys?: CloudProvider[];paidAllowed?: boolean;/** Hosted runs (FUOBE_HOSTED_RUNS=1): runs may go to this studio's GPUs, so a GPU of one's own is optional. */diff --git a/tests/own-graceful-ui.test.ts b/tests/own-graceful-ui.test.tsnew file mode 100644index 00000000..7812f152--- /dev/null+++ b/tests/own-graceful-ui.test.ts@@ -0,0 +1,115 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { createElement, type ReactNode } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it, vi } from "vitest";++/**+ * What an account sees around a GPU or key problem, in the browser: the check before Run in the composer (the status+ * strip's answer, never a new call to the GPU), "Run with your fal.ai key" on the tool's cloud version, and the buttons+ * a failed run's tile and Settings show (Start your pod as a link to RunPod, Check my GPU, Settings, Add credit).+ */+vi.mock("next/navigation", () => ({+ useRouter: () => ({ prefetch: () => {}, push: () => {}, replace: () => {}, back: () => {}, refresh: () => {} }),+ usePathname: () => "/",+ useSearchParams: () => new URLSearchParams(),+}));++const { gpuBeforeRun, onCloudKey, GPU_OFF_WORDS } = await import("@/lib/before-run");+const { diagnoseGpu, RUNPOD_CONSOLE_URL, withKeyAction } = await import("@/lib/diagnose");+const { getModel, getPreset } = await import("@/lib/catalog");+const { TroubleActions, TroubleDetails, autoCheckIn } = await import("@/components/gpu/trouble");++const has = (id: string) => !!getModel(id);+const render = (node: ReactNode) => renderToStaticMarkup(createElement(QueryClientProvider, { client: new QueryClient() }, node));++const POD = "https://abc123xyz-8188.proxy.runpod.net";+const stopped = diagnoseGpu({ stage: "status", status: 404, body: "" }, { kind: "link", url: POD });+const offline = { connected: true, mode: "link" as const, online: false, trouble: stopped };+const account = (gpu: object, keys: ("fal" | "replicate")[] = []) => ({ kind: "account" as const, gpu: gpu as typeof offline, keys, paidAllowed: true });+const fpv = getPreset("motion-fpv-drone")!;+const h3 = getModel("oss-minimax-h3")!;++describe("the check before Run", () => {+ it("shows a stopped pod's words and buttons above Generate, read from the status strip's answer", () => {+ const shown = gpuBeforeRun({ viewer: account(offline), model: h3, engine: "open", preset: fpv, has, getModel })!;+ expect(shown.words).toBe(stopped.words);+ expect(shown.words).toMatch(/^Your RunPod pod isn't running, or ComfyUI isn't on port 8188/);+ expect(shown.details).toBe(stopped.details);+ expect(shown.actions.map((a) => a.kind)).toEqual(["start-gpu", "check-gpu", "gpu-settings"]);+ expect(shown.actions[0]).toMatchObject({ label: "Start your pod", target: RUNPOD_CONSOLE_URL });+ });++ it("offers the tool's cloud version on the account's own key, an explicit button", () => {+ const withFal = gpuBeforeRun({ viewer: account(offline, ["fal"]), model: h3, engine: "open", preset: fpv, has, getModel })!;+ expect(withFal.actions.at(-1)).toEqual(withKeyAction("fal"));+ expect(withFal.actions.at(-1)?.label).toBe("Run with your fal.ai key");+ // FPV Drone's cloud versions are on fal.ai only: a Replicate token runs none of them.+ expect(gpuBeforeRun({ viewer: account(offline, ["replicate"]), model: h3, engine: "open", preset: fpv, has, getModel })!.actions.map((a) => a.kind)).not.toContain("run-with-key");+ // A studio that is open-source only: no key is offered.+ expect(gpuBeforeRun({ viewer: { ...account(offline, ["fal"]), paidAllowed: false }, model: h3, engine: "open", preset: fpv, has, getModel })!.actions.map((a) => a.kind)).not.toContain("run-with-key");+ });++ it("says nothing when the run doesn't go to the account's own GPU at a web address, or the GPU answered", () => {+ const base = { model: h3, engine: "open" as const, preset: fpv, has, getModel };+ expect(gpuBeforeRun({ ...base, viewer: account({ ...offline, online: true }) })).toBeNull();+ expect(gpuBeforeRun({ ...base, viewer: { ...account(offline), kind: "guest" } })).toBeNull();+ // This computer and a paired ComfyUI have notes of their own.+ expect(gpuBeforeRun({ ...base, viewer: account({ connected: true, mode: "computer", online: false }) })).toBeNull();+ // This studio's GPUs (hosted runs), a cloud model, a Fuobe Original on the Cloud engine.+ expect(gpuBeforeRun({ ...base, viewer: account(offline), onPool: true })).toBeNull();+ expect(gpuBeforeRun({ ...base, viewer: account(offline), model: getModel("minimax-h3"), preset: undefined })).toBeNull();+ expect(gpuBeforeRun({ ...base, viewer: account(offline), model: getModel("fuobe-soul"), engine: "cloud", preset: undefined })).toBeNull();+ // An older answer without a reason still says the GPU isn't answering, with Check my GPU.+ const bare = gpuBeforeRun({ ...base, viewer: account({ connected: true, mode: "link", online: false }) })!;+ expect(bare.words).toBe(GPU_OFF_WORDS);+ expect(bare.actions.map((a) => a.kind)).toEqual(["check-gpu", "gpu-settings"]);+ });+});++describe("Run with your key on a failed run", () => {+ it("asks for the same run on the cloud version: its model and operation there, without the open graph's settings", () => {+ const req = { feature: "video" as const, modelId: "oss-minimax-h3", presetId: "motion-fpv-drone", op: "i2v" as const, prompt: "", inputs: { images: ["/files/a.png"] }, params: { duration: 6, extra: { quality: "draft" } } };+ expect(onCloudKey(req, { modelId: "minimax-h3", op: "i2v" })).toEqual({ ...req, engine: "cloud", modelId: "minimax-h3", op: "i2v", params: { duration: 6 } });+ // A Fuobe Original: the same model, on the cloud engine, with all its settings.+ const soul = { feature: "image" as const, modelId: "fuobe-soul", prompt: "a portrait", params: { extra: { look: "x" } } };+ expect(onCloudKey(soul, { modelId: "fuobe-soul" })).toEqual({ ...soul, engine: "cloud" });+ });+});++describe("the buttons", () => {+ it("Start your pod opens RunPod in a new tab; Settings is a link; Check my GPU is a button", () => {+ const html = render(createElement(TroubleActions, { actions: stopped.actions }));+ expect(html).toContain(`href="${RUNPOD_CONSOLE_URL}"`);+ expect(html).toContain('target="_blank"');+ expect(html).toContain("Start your pod");+ expect(html).toContain("Check my GPU");+ expect(html).toContain('href="/settings#your-gpu"');+ });++ it("leaves out what can't be done here, and shows at most so many", () => {+ const actions = [{ kind: "retry" as const, label: "Retry" }, withKeyAction("fal", "minimax-h3"), { kind: "pick-model" as const, label: "Pick another model" }, ...stopped.actions];+ // No run to retry, no key handler, no model picker: those buttons aren't drawn.+ const bare = render(createElement(TroubleActions, { actions }));+ expect(bare).not.toMatch(/Retry|Run with your|Pick another model/);+ const handled = render(createElement(TroubleActions, { actions, handlers: { onRetry: () => {}, onRunWithKey: () => {} }, skip: ["retry"], max: 2 }));+ expect(handled).toContain("Run with your fal.ai key");+ expect(handled).toContain("Start your pod");+ expect(handled).not.toMatch(/Retry|Check my GPU/);+ expect(render(createElement(TroubleActions, { actions: [] }))).toBe("");+ });++ it("the details line is small and only there when there is something to say", () => {+ expect(render(createElement(TroubleDetails, { details: "abc123xyz-8188.proxy.runpod.net · HTTP 404" }))).toContain("HTTP 404");+ expect(render(createElement(TroubleDetails, {}))).toBe("");+ });++ it("Settings checks again by itself with a growing wait, within the check's budget", () => {+ const start = 1_000_000;+ expect(autoCheckIn("gpu-stopped", 1, start, start)).toBe(15_000);+ expect(autoCheckIn("gpu-offline", 1, start, start)).toBe(5_000);+ expect(autoCheckIn("gpu-offline", 3, start, start)).toBe(20_000);+ // Past the budget (3 minutes for a GPU that doesn't answer), and never for what waiting can't fix.+ expect(autoCheckIn("gpu-offline", 9, start, start + 3 * 60_000)).toBeNull();+ expect(autoCheckIn("gpu-password", 1, start, start)).toBeNull();+ });+});