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.

Studio, Library and Settings: a waiting run shows what helps, and Run with your key runs once

Adarsh05ac10a5ab1e
diff --git a/src/components/gpu/computer-runner.tsx b/src/components/gpu/computer-runner.tsx
index 7f313a58..dda2bf7a 100644
--- a/src/components/gpu/computer-runner.tsx
+++ b/src/components/gpu/computer-runner.tsx
@@ -168,6 +168,8 @@ type Note = { text: string; action?: string; go?: () => void; problem: boolean }
/** What the note says now, or nothing: something for the person to do (only while there is work), or the GPU working. */
function noteOf(s: ComputerState): Note | null {
const v = s.view;
+ // This tab's sign-in ended: runs can't go on here until the person logs in again.
+ if (s.holder === "this" && v?.stopped === "signed-out") return { text: "You're signed out on this computer. Log in to keep running your runs here.", action: "Log in", go: () => window.location.assign(new URL("/login", window.location.origin).href), problem: true };
if (s.holder !== "this" || !v || v.stopped) return null;
const working = v.jobs.some((j) => j.phase !== "done" && j.phase !== "failed");
const wanted = working || v.waiting > 0;
diff --git a/src/components/gpu/trouble.tsx b/src/components/gpu/trouble.tsx
index 827fe10d..c8600beb 100644
--- a/src/components/gpu/trouble.tsx
+++ b/src/components/gpu/trouble.tsx
@@ -1,12 +1,13 @@
"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 { CreditCard, ExternalLink, KeyRound, Loader2, Minimize2, Monitor, Play, RefreshCw, RotateCcw, Settings2, Shuffle, Stethoscope } from "lucide-react";
import Link from "next/link";
-import { useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import type { GpuTroubleView } from "@/lib/api";
import { backoffMs, retryPlan, type TroubleAction, type TroubleActionKind } from "@/lib/diagnose";
+import { deviceLabel } from "@/lib/gpu/readiness";
import { cn } from "@/lib/utils";
/**
@@ -49,73 +50,151 @@ const ICONS: Record<TroubleActionKind, typeof Play> = {
"start-gpu": Play,
pair: RefreshCw,
"use-computer": Monitor,
+ "send-smaller": Minimize2,
+ "try-smaller": Minimize2,
};
-/** 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";
+/** The first button stands out (the one most likely to help); the rest are quieter. One line each, cut short when narrow. */
+const PILL = "inline-flex h-7 max-w-full min-w-0 items-center gap-1.5 rounded-full px-2.5 text-[12px] font-medium whitespace-nowrap";
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;
+ onRunWithKey?: (a: TroubleAction) => void | Promise<unknown>;
onPickModel?: () => void;
/** "Use this computer": the caller switches runs to the ComfyUI on this computer. */
- onUseComputer?: () => void;
+ onUseComputer?: () => void | Promise<unknown>;
+ /** "Send a smaller copy": the run made again with a smaller copy of its file. */
+ onSendSmaller?: () => void | Promise<unknown>;
+ /** "Try one size smaller": the run made again one size or length smaller. */
+ onTrySmaller?: () => void | Promise<unknown>;
+}
+
+/**
+ * When some buttons must go (a small tile), the ones that help least go first: Settings (Check my GPU leads there too),
+ * Pair with a code, then the rest. The first button (the one most likely to help) always stays, and the order is kept.
+ */
+const DROP_FIRST: TroubleActionKind[] = ["gpu-settings", "pair", "use-computer", "pick-model", "retry", "check-gpu", "key-settings", "try-smaller", "send-smaller", "add-credit", "run-with-key", "start-gpu"];
+
+export function fitActions(actions: TroubleAction[], max?: number): TroubleAction[] {
+ if (!max || actions.length <= max) return actions;
+ const out = [...actions];
+ for (const kind of DROP_FIRST) {
+ for (let i = out.length - 1; i > 0 && out.length > max; i--) if (out[i].kind === kind) out.splice(i, 1);
+ if (out.length <= max) break;
+ }
+ return out.slice(0, max);
+}
+
+/** A button's words where there is little room (a tile): the long Settings links get their short names. */
+function shortLabel(a: TroubleAction): string {
+ if (a.kind === "gpu-settings" && a.label.startsWith("Open Settings")) return "Settings";
+ if (a.kind === "key-settings" && a.label.startsWith("Open Settings")) return "Your keys";
+ return a.label;
}
/**
* 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).
+ * model without a picker). `max`: at most so many (those that help least go first); `skip`: kinds the caller shows itself
+ * (a tile's own Retry); `compact`: a tile (short words, no Settings beside Check my GPU); `context` "run": a run's tile
+ * (Check my GPU's answer then says to press Retry). A button that starts something stays pressed until it has.
*/
-export function TroubleActions({ actions, handlers = {}, max, skip = [], className }: { actions: TroubleAction[]; handlers?: TroubleHandlers; max?: number; skip?: TroubleActionKind[]; className?: string }) {
+export function TroubleActions({
+ actions,
+ handlers = {},
+ max,
+ skip = [],
+ compact,
+ context = "other",
+ className,
+}: {
+ actions: TroubleAction[];
+ handlers?: TroubleHandlers;
+ max?: number;
+ skip?: TroubleActionKind[];
+ compact?: boolean;
+ context?: "run" | "other";
+ className?: string;
+}) {
const qc = useQueryClient();
- const [checking, setChecking] = useState(false);
+ const [busy, setBusy] = useState<TroubleActionKind | null>(null);
+ const [waiting, setWaiting] = useState(false);
+ const again = useRef<ReturnType<typeof setTimeout> | null>(null);
+ useEffect(
+ () => () => {
+ if (again.current) clearTimeout(again.current);
+ },
+ [],
+ );
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;
+ if (a.kind === "send-smaller") return !!handlers.onSendSmaller;
+ if (a.kind === "try-smaller") return !!handlers.onTrySmaller;
+ // On a tile, Check my GPU leads to Settings when that is what helps: one button fewer.
+ if (compact && a.kind === "gpu-settings" && actions.some((x) => x.kind === "check-gpu") && a.label.startsWith("Open Settings")) return false;
return true;
});
- const shown = max ? usable.slice(0, max) : usable;
+ const shown = fitActions(usable, max);
if (!shown.length) return null;
- const check = async () => {
- setChecking(true);
+ // Something that takes a moment (a run on a key, a check): pressed until it is done, so a second click starts nothing.
+ const press = async (kind: TroubleActionKind, fn: () => void | Promise<unknown>) => {
+ if (busy) return;
+ setBusy(kind);
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" });
+ await fn();
} finally {
- setChecking(false);
+ setBusy(null);
}
};
+ const check = async (): Promise<void> => {
+ const r = await checkMyGpu(qc);
+ if (r.ok) {
+ const what = r.device ? `: ${deviceLabel(r.device)}` : "";
+ toast.success(context === "run" ? `Your GPU answered${what}. Press Retry to run it again.` : `Your GPU answered${what}.`, { id: "check-gpu" });
+ } else if (r.retryAfterS) {
+ // Too many checks in a minute: one more goes by itself once the wait is over.
+ const s = Math.max(1, Math.round(r.retryAfterS));
+ toast(`Too many checks. Checking again in ${s} s.`, { id: "check-gpu" });
+ if (again.current) clearTimeout(again.current);
+ setWaiting(true);
+ again.current = setTimeout(() => {
+ again.current = null;
+ setWaiting(false);
+ void press("check-gpu", check);
+ }, s * 1000);
+ } else toast(r.words, { id: "check-gpu" });
+ };
return (
- <div className={cn("flex flex-wrap gap-1.5", className)}>
+ <div className={cn("flex min-w-0 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 words = <span className="truncate">{compact ? shortLabel(a) : a.label}</span>;
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 key={a.kind} href={a.target} target="_blank" rel="noopener noreferrer" onClick={stop} title={a.label} className={cls}>
+ <Icon className="size-3 shrink-0" /> {words}
+ <ExternalLink className="size-3 shrink-0 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 key={a.kind} href={a.target} onClick={stop} title={a.label} className={cls}>
+ <Icon className="size-3 shrink-0" /> {words}
</Link>
);
}
- const run =
+ const run: (() => void | Promise<unknown>) | undefined =
a.kind === "check-gpu"
- ? () => void check()
+ ? check
: a.kind === "retry"
? handlers.onRetry
: a.kind === "run-with-key"
@@ -124,19 +203,26 @@ export function TroubleActions({ actions, handlers = {}, max, skip = [], classNa
? handlers.onPickModel
: a.kind === "use-computer"
? handlers.onUseComputer
- : undefined;
+ : a.kind === "send-smaller"
+ ? handlers.onSendSmaller
+ : a.kind === "try-smaller"
+ ? handlers.onTrySmaller
+ : undefined;
+ const pending = busy === a.kind || (a.kind === "check-gpu" && waiting);
return (
<button
key={a.kind}
type="button"
- disabled={a.kind === "check-gpu" && checking}
+ disabled={!!busy || (a.kind === "check-gpu" && waiting)}
+ aria-busy={pending || undefined}
+ title={a.label}
onClick={(e) => {
e.stopPropagation();
- run?.();
+ if (run) void press(a.kind, run);
}}
- className={cls}
+ className={cn(cls, "disabled:opacity-70")}
>
- {a.kind === "check-gpu" && checking ? <Loader2 className="size-3 animate-spin" /> : <Icon className="size-3" />} {a.label}
+ {pending ? <Loader2 className="size-3 shrink-0 animate-spin" /> : <Icon className="size-3 shrink-0" />} {words}
</button>
);
})}
diff --git a/src/components/gpu/your-gpu.tsx b/src/components/gpu/your-gpu.tsx
index 9cdc19ca..06ea66f0 100644
--- a/src/components/gpu/your-gpu.tsx
+++ b/src/components/gpu/your-gpu.tsx
@@ -10,7 +10,8 @@ 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 { canSaveAnyway, diagnoseAddress, testWords } from "@/lib/diagnose";
+import { useComputerSupport } from "@/components/gpu/open-connect";
import { responseError, toastError } from "@/lib/refusals";
import { cn } from "@/lib/utils";
@@ -80,6 +81,9 @@ export function YourGpu({ className, onLinked }: { className?: string; onLinked?
const [info, setInfo] = useState<GpuInfo | null>(null);
const [note, setNote] = useState<string | null>(null);
const [failed, setFailed] = useState<Failed | null>(null);
+ // A Test's own check by itself found the GPU answering: Connect is what is left to press.
+ const [answered, setAnswered] = useState(false);
+ const support = useComputerSupport();
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);
@@ -97,6 +101,7 @@ export function YourGpu({ className, onLinked }: { className?: string; onLinked?
const r = await call<PutAnswer>("PUT", { url: url.trim(), token: token.trim() || undefined, ...(mode === "anyway" && { anyway: true }) }, mode === "test");
auto.current = null;
setFailed(null);
+ setAnswered(mode === "test" && again);
setInfo(r.info ?? null);
setNote(r.note ?? null);
if (r.url && mode === "test") setUrl(r.url);
@@ -125,7 +130,11 @@ export function YourGpu({ className, onLinked }: { className?: string; onLinked?
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 }) });
+ // A Test saves nothing, so nothing connects by itself: its words say to press Connect once the GPU answers. A
+ // Connect's promise ("we connect as soon as it answers") holds while it checks by itself; after that, it says so.
+ const words = !trouble?.retryable ? e.message : !connecting ? testWords(e.message, wait === null && run.attempt > 1) : wait === null ? testWords(e.message, true) : e.message;
+ setAnswered(false);
+ setFailed({ words, trouble, connecting, ...(wait !== null && { againAt: Date.now() + wait }) });
} finally {
setBusy(null);
}
@@ -149,6 +158,18 @@ export function YourGpu({ className, onLinked }: { className?: string; onLinked?
auto.current = null;
setFailed((f) => (f ? { ...f, againAt: undefined } : f));
};
+ // "Use this computer": runs go to the ComfyUI on this computer (its Fuobe tab runs them), not a web address.
+ const useComputer = async () => {
+ try {
+ await call("PUT", { mode: "computer" });
+ void qc.invalidateQueries({ queryKey: ["account-gpu"] });
+ linked();
+ toast.success("Your runs go to the ComfyUI on this computer now. Keep a Fuobe tab open here.");
+ setUrl("");
+ } catch (e) {
+ toastError(e);
+ }
+ };
const remove = async () => {
setBusy("remove");
try {
@@ -223,7 +244,11 @@ export function YourGpu({ className, onLinked }: { className?: string; onLinked?
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>
+ <div className="space-y-1.5">
+ <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>
+ {/* Or the ways that need no web address: the ComfyUI on this computer (where this browser can reach it), or a code. */}
+ <TroubleActions actions={diagnoseAddress("local").actions} handlers={support === "ok" ? { onUseComputer: useComputer } : {}} />
+ </div>
)}
{note && <p className="text-[12px] text-muted-foreground">{note}</p>}
</div>
@@ -250,10 +275,17 @@ export function YourGpu({ className, onLinked }: { className?: string; onLinked?
</p>
)}
{failed.trouble && <TroubleActions actions={failed.trouble.actions.filter((a) => a.kind !== "gpu-settings" && a.kind !== "check-gpu")} />}
+ {/* The checks by itself stopped: check again now (its wait starts over). */}
+ {!failed.againAt && failed.trouble?.retryable && !!url.trim() && !local && (
+ <button type="button" onClick={() => void send(failed.connecting ? "save" : "test")} disabled={busy !== null} className="text-[12px] font-medium text-brand-text underline-offset-2 hover:underline">
+ Check again
+ </button>
+ )}
</div>
)}
{info && (
<p className="text-[12px] text-muted-foreground">
+ {answered && <span className="font-medium text-foreground">Your GPU answers now. </span>}
ComfyUI answered{info.device ? `: ${info.device}` : ""}
{gib(info.vramBytes) ? ` · ${gib(info.vramBytes)} VRAM` : ""}
{info.version ? ` · ComfyUI ${info.version}` : ""}
@@ -261,7 +293,7 @@ export function YourGpu({ className, onLinked }: { className?: string; onLinked?
)}
<div className="flex flex-wrap gap-2">
<Button size="sm" onClick={() => void send("save")} disabled={!url.trim() || local || busy !== null}>
- {busy === "save" && <Loader2 className="animate-spin" />} Connect
+ {busy === "save" && <Loader2 className="animate-spin" />} {answered ? "Connect now" : "Connect"}
</Button>
<Button size="sm" variant="secondary" onClick={() => void send("test")} disabled={!url.trim() || local || busy !== null}>
{busy === "test" && <Loader2 className="animate-spin" />} Test
diff --git a/src/components/library/asset-card.tsx b/src/components/library/asset-card.tsx
index 273943e9..9ead3206 100644
--- a/src/components/library/asset-card.tsx
+++ b/src/components/library/asset-card.tsx
@@ -43,35 +43,43 @@ const LIST_MENU ="grid size-8 shrink-0 place-items-center rounded-lg text-muted-
const idsOf = (e: LibraryEntry) => (e.type === "single" ? [e.g.id] : e.items.map((g) => g.id));
-export function StatusCover({ g }: { g: Generation }) {
+/**
+ * A run's cover while it goes or after it failed. An account's own GPU or key: what came back (small) and the way out
+ * (Start your pod, Check my GPU, Replace key…), the buttons kept in view first (the words give way on a small card).
+ * `small`: a list row's thumbnail (the row's own text says the rest).
+ */
+export function StatusCover({ g, small }: { g: Generation; small?: boolean }) {
if (g.status === "queued" || g.status === "running") {
const pct = g.progress != null ? Math.round(g.progress * 100) : null;
+ const waiting = g.status === "queued" ? g.waiting : undefined;
return (
<div className="relative size-full bg-muted">
<div className="skeleton-sweep absolute inset-0 animate-skeleton" />
- <div className="absolute inset-x-0 bottom-0 p-3">
- <p className="shimmer-text animate-shimmer-text truncate text-[13px] font-medium">{g.message ?? (g.status === "queued" ? "Queued" : "Generating…")}</p>
- <p className="font-mono text-[11px] text-muted-foreground">
- {pct != null ? `${pct}% · ` : ""}
- {elapsed(g.createdAt)}
- </p>
- </div>
+ {!small && (
+ <div className="absolute inset-x-0 bottom-0 space-y-1 p-3">
+ <p className="shimmer-text animate-shimmer-text truncate text-[13px] font-medium">{g.message ?? (g.status === "queued" ? "Queued" : "Generating…")}</p>
+ <p className="font-mono text-[11px] text-muted-foreground">
+ {pct != null ? `${pct}% · ` : ""}
+ {elapsed(g.createdAt)}
+ </p>
+ {/* Waiting for its own GPU or key: what helps meanwhile (it goes on by itself). */}
+ {waiting && <TroubleActions actions={waiting.actions} skip={["retry", "run-with-key"]} max={2} compact />}
+ </div>
+ )}
</div>
);
}
+ if (small) return <div className="size-full border border-dashed bg-background" />;
+ const trouble = g.status === "failed" ? g.trouble : undefined;
return (
- <div className="flex size-full flex-col justify-between border border-dashed bg-background p-3">
- <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 className="flex size-full flex-col justify-between gap-2 border border-dashed bg-background p-3">
+ <div className="flex min-h-0 flex-col gap-1 overflow-hidden">
+ <p className="shrink-0 text-[13px] font-medium">{g.status === "canceled" ? "Canceled" : "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 && <TroubleActions className="shrink-0" actions={trouble.actions} skip={["retry"]} max={2} compact />}
</div>
);
}
@@ -237,7 +245,7 @@ export const AssetCard = memo(function AssetCard({
>
{target}
<div className="relative size-14 shrink-0 overflow-hidden rounded-lg bg-muted">
- {stack ? cover ? <SmallThumb output={cover.o} g={cover.g} /> : <StatusCover g={g} /> : done ? <SmallThumb output={g.outputs[0]} g={g} /> : <StatusCover g={g} />}
+ {stack ? cover ? <SmallThumb output={cover.o} g={cover.g} /> : <StatusCover g={g} small /> : done ? <SmallThumb output={g.outputs[0]} g={g} /> : <StatusCover g={g} small />}
<SelectDot selected={selected} visible={selecting} onToggle={(s) => api.toggle(entry.key, ids, s)} label={`Select ${title}`} />
</div>
<div className="min-w-0 flex-1">
@@ -253,6 +261,10 @@ export const AssetCard = memo(function AssetCard({
{/* "Rendering", as the Status filter calls it: "In progress" is a review status. */}
{!stack && g.status !== "succeeded" && ` · ${g.status === "failed" ? "Failed" : g.status === "canceled" ? "Canceled" : g.status === "queued" ? "Queued" : "Rendering"}`}
</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) && (
+ <TroubleActions className="mt-1" actions={(g.status === "failed" ? g.trouble : g.waiting)!.actions} skip={["retry", "run-with-key"]} max={1} compact />
+ )}
</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")} />}
diff --git a/src/components/studio/catalog.tsx b/src/components/studio/catalog.tsx
index 10bfb839..0211f0b3 100644
--- a/src/components/studio/catalog.tsx
+++ b/src/components/studio/catalog.tsx
@@ -57,6 +57,11 @@ export interface CatalogApi {
const Ctx = createContext<CatalogApi | null>(null);
+/** The studio's catalog, or null outside a studio (a tile shown on another page). */
+export function useOptionalCatalog(): CatalogApi | null {
+ return useContext(Ctx);
+}
+
export function useCatalog(): CatalogApi {
const c = useContext(Ctx);
if (!c) throw new Error("useCatalog outside CatalogProvider");
diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsx
index 77c12fc3..c6f52974 100644
--- a/src/components/studio/composer.tsx
+++ b/src/components/studio/composer.tsx
@@ -89,8 +89,10 @@ import { qwen21Note } from "@/lib/qwen21-speed";
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 { addKeyLabel, billedTo, CLOUD_KEY, cloudVersion, needsKey, paidThrough, startingModel } from "@/lib/your-keys";
+import { beforeRunTail, gpuBeforeRun, onCloudKey } from "@/lib/before-run";
+import { BILLING_URL, ISOLATED_ON_GPU_WHY, withKeyAction, type TroubleAction } from "@/lib/diagnose";
+import { openModelPicker } from "@/lib/open-model-picker";
import { TroubleActions, TroubleDetails } from "@/components/gpu/trouble";
import { cn } from "@/lib/utils";
import { h3ReferenceProblem, openReferenceMode } from "@/lib/h3-references";
@@ -763,17 +765,25 @@ export function Composer({ docked }: { docked: boolean }) {
// 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]);
+ // A graph that needs a second ComfyUI (LatentSync 1.6, ThinkSound) can't run on an account's single GPU at a web address:
+ // said before Run, with what runs it instead (its cloud version on a key, or another model).
+ const viewerGpu = status?.viewer?.kind === "account" ? status.viewer.gpu : undefined;
+ const isolatedHere = !!model && model.worker === "isolated" && model.engine === "open" && !!viewerGpu?.connected && viewerGpu.mode === "link" && !(hostedHere && runOn === "pool");
+ const isolatedTwin =
+ isolatedHere && status?.viewer?.paidAllowed !== false ? cloudVersion(preset, model, status?.viewer?.usableKeys ?? status?.viewer?.keys ?? [], has, catalog.getModel) : null;
+ // "Run with your fal.ai key": this run, once, on the tool's cloud version and that key. The engine switch stays where it
+ // was, so the next run goes to the GPU again (the person picks Cloud themselves to stay there).
+ const runOnceWithKey = (a: TroubleAction) => {
+ const sent = signature.apply(
+ buildRequest(config.feature, songDraft(draft, model, config.slots), resolvesOnServer ? studioOp : op, config.promptSuffix, config.multiRef?.kind, framesCtx, targetFor(draft.modelId)),
+ );
+ const withVoiceFirst = cleanFirst ? { ...sent.request, params: { ...sent.request.params, extra: { ...sent.request.params?.extra, [VOICE_FIRST_PARAM]: true } } } : sent.request;
+ const label = a.target && (a.target === "fal" || a.target === "replicate") ? CLOUD_KEY[a.target].label : "your key";
+ return create.mutateAsync(onCloudKey(withVoiceFirst, a)).then(
+ () => void toast.success(`Running once on ${label} with your key. Your next runs go to your GPU again.`),
+ (e) => toastError(e),
+ );
+ };
// `skip` is true only from the guided fix's "Run anyway" (a click handler passes its event here).
const submit = (skip?: unknown) => {
@@ -936,6 +946,8 @@ export function Composer({ docked }: { docked: boolean }) {
const ownCostText = costLabel({ demo, cost: cost ?? (engine === "open" && model ? 0 : null), unknown: loraPriceUnknown, gpu: gpuRun }, formatCost);
// An account's paid run is billed to its own provider account (Your keys), or still needs that key.
const payer = paidThrough(model, status);
+ // Its provider account's balance ran out on a run: said before the next one, with Add credit.
+ const emptyPayer = payer && status?.viewer?.emptyKeys?.includes(payer) ? payer : null;
const missingKey = needsKey(model, status)?.[0];
const ownPayerText = payer && cost ? ` · ${billedTo(payer)}` : missingKey ? ` · ${addKeyLabel(missingKey).toLowerCase()}` : "";
// On this studio's GPUs: the quote's words (none from the server: free, as the open engine always is).
@@ -1556,6 +1568,7 @@ export function Composer({ docked }: { docked: boolean }) {
{!lockedModel || appChoice ? (
catalog.ready ? (
<ModelPicker
+ listens
models={appChoice ? appPickerModels : models}
value={model}
engine={engine}
@@ -1749,21 +1762,30 @@ export function Composer({ docked }: { docked: boolean }) {
{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.
+ <span className="font-medium text-foreground">{gpuDown.words}</span> {beforeRunTail(gpuDown.waits)}
</p>
<TroubleDetails details={gpuDown.details} />
+ <TroubleActions actions={gpuDown.actions} skip={["retry"]} handlers={{ onRunWithKey: runOnceWithKey }} />
+ </div>
+ )}
+ {isolatedHere && !gpuDown && (
+ <div role="note" 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">{ISOLATED_ON_GPU_WHY}</span>{" "}
+ {isolatedTwin ? "Run it with your key instead, or pick another model." : "Pick another model to run it now."}
+ </p>
<TroubleActions
- actions={gpuDown.actions}
- skip={["retry"]}
- handlers={{
- onRunWithKey: () => {
- setEngine("cloud");
- setCloudRun(true);
- },
- }}
+ actions={[...(isolatedTwin ? [withKeyAction(isolatedTwin.provider, isolatedTwin.modelId, isolatedTwin.op)] : []), { kind: "pick-model", label: "Pick another model" }]}
+ handlers={{ onRunWithKey: runOnceWithKey, onPickModel: openModelPicker }}
/>
</div>
)}
+ {emptyPayer && model && (
+ <div role="note" className="mx-1 mt-2 flex flex-wrap items-center gap-x-3 gap-y-1.5 rounded-xl border border-dashed px-3 py-2 text-[12px] leading-snug text-muted-foreground">
+ <p className="min-w-0 flex-1 basis-56">Your {CLOUD_KEY[emptyPayer].label} balance ran out on your last run. Add credit there, then run.</p>
+ <TroubleActions actions={[{ kind: "add-credit", label: `Add credit on ${CLOUD_KEY[emptyPayer].label}`, target: BILLING_URL[emptyPayer] }]} />
+ </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.tsx
index 3f9c7c84..a9a0d9a4 100644
--- a/src/components/studio/feed.tsx
+++ b/src/components/studio/feed.tsx
@@ -17,6 +17,9 @@ import {
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { OPERATION_LABELS, type Generation } from "@/lib/catalog/types";
import { onCloudKey } from "@/lib/before-run";
+import { openModelPicker } from "@/lib/open-model-picker";
+import { smallerRun } from "@/lib/smaller-run";
+import { useOptionalCatalog } from "./catalog";
import { TroubleActions, TroubleDetails } from "@/components/gpu/trouble";
import { useCreateGeneration, useGenerationActions, useStatus } from "@/lib/api";
import { placeholdersOn } from "@/lib/demo-mode";
@@ -70,6 +73,10 @@ export function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {
// The bar: the steps, or how much of the result has reached the studio.
const bar = saving ? Math.round((local.job.phase === "done" ? 1 : (local.job.saved ?? 0)) * 100) : pct;
const where = local ? (local.here ? "Keep this tab open" : "Running in another Fuobe tab") : null;
+ // Waiting for its own GPU or key to come back: what helps meanwhile, and until when it waits.
+ const waiting = g.status === "queued" ? g.waiting : undefined;
+ const create = useCreateGeneration();
+ const until = waiting?.until && waiting.until > now ? new Date(waiting.until).toLocaleTimeString([], { hour: "numeric", minute: "2-digit" }) : null;
return (
// max-w-full: in a grid row stretched by a taller neighbour (a card with a footer), h-full + aspect-ratio would
// otherwise make the tile wider than its column and spill over the next card.
@@ -100,7 +107,21 @@ export function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {
{pct != null && <span>{pct}%</span>}
<span className={cn(pct != null && "before:mr-1.5 before:content-['·']")}>{elapsed(g.createdAt, Math.max(now, g.createdAt))}</span>
{left != null && <span className="before:mr-1.5 before:content-['·']">{leftLabel(left)}</span>}
+ {until && <span className="before:mr-1.5 before:content-['·']">waits until {until}</span>}
</p>
+ {waiting && (
+ <TroubleActions
+ className="mt-1.5"
+ actions={waiting.actions}
+ skip={["retry"]}
+ max={2}
+ compact
+ handlers={{
+ // This run moves to the key: it stops waiting, and the cloud run takes its place (one server call).
+ onRunWithKey: (a) => create.mutateAsync({ ...onCloudKey(g.request, a), replaces: g.id } as Generation["request"]).catch((e) => toastError(e)),
+ }}
+ />
+ )}
</div>
<Tooltip>
<TooltipTrigger asChild>
@@ -127,27 +148,66 @@ export function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {
);
}
+/** A failed tile narrower than this (in px, at the feed's 224 px height) shows two trouble buttons, not three. */
+const NARROW_TILE_PX = 260;
+
+/** "Send a smaller copy": the run's file made smaller on the server, then the run started again with it. */
+async function smallerCopyRequest(g: Generation): Promise<{ request: Generation["request"]; note: string }> {
+ const res = await fetch(`/api/generations/${encodeURIComponent(g.id)}/smaller`, { method: "POST" });
+ const j = (await res.json().catch(() => ({}))) as { request?: Generation["request"]; note?: string; error?: string };
+ if (!res.ok || !j.request) throw new Error(j.error ?? "We couldn't make a smaller copy. Press Retry.");
+ return { request: j.request, note: j.note ?? "Sent a smaller copy." };
+}
+
export function FailedTile({ g, ratio, onRetry }: { g: Generation; ratio: number; onRetry: () => void }) {
const create = useCreateGeneration();
+ const feed = useContext(FeedCtx);
+ const catalog = useOptionalCatalog();
const trouble = g.status === "failed" ? g.trouble : undefined;
+ const shape = Math.max(ratio, 0.8);
+ const narrow = shape * 224 < NARROW_TILE_PX;
+ const run = (request: Generation["request"], done?: string) =>
+ create.mutateAsync(request).then(
+ () => void (done && toast.success(done)),
+ (e) => toastError(e),
+ );
+ const smaller = trouble ? smallerRun(g.request, catalog?.getModel(g.modelId)) : null;
+ const [retrying, setRetrying] = useState(false);
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 className="flex h-full max-w-full flex-col justify-between rounded-xl border border-dashed bg-background p-3" style={{ aspectRatio: shape }}>
+ <div className="flex min-h-0 flex-col gap-1 overflow-hidden">
+ <p className="shrink-0 text-[13px] font-medium">{g.status === "canceled" ? "Canceled" : "Couldn't generate this one"}</p>
+ {g.error && <p className={cn("shrink-0 text-[12px] leading-snug break-words whitespace-pre-line text-muted-foreground", narrow ? "line-clamp-4" : "line-clamp-5")}>{g.error}</p>}
+ {/* An account's own GPU or key: what came back, small, for the curious (the first thing cut when room is short). */}
+ <TroubleDetails details={trouble?.details} className="min-h-0" />
</div>
{trouble && (
<TroubleActions
- className="mt-2"
+ className="mt-2 shrink-0"
actions={trouble.actions}
skip={["retry"]}
- max={3}
- handlers={{ onRunWithKey: (a) => create.mutate(onCloudKey(g.request, a), { onError: (e) => toastError(e) }) }}
+ max={narrow ? 2 : 3}
+ compact
+ context="run"
+ handlers={{
+ onRunWithKey: (a) => run(onCloudKey(g.request, a)),
+ // In a studio: its settings come back into the composer, and its model picker opens.
+ onPickModel: feed?.reuse
+ ? () => {
+ feed.reuse?.(g);
+ openModelPicker();
+ }
+ : undefined,
+ onTrySmaller: smaller ? () => run(smaller.request, `Running it again at ${smaller.what}.`) : undefined,
+ onSendSmaller: () =>
+ smallerCopyRequest(g).then(
+ ({ request, note }) => run(request, note),
+ (e) => toastError(e),
+ ),
+ }}
/>
)}
- <div className="mt-2 flex flex-wrap gap-1.5">
+ <div className="mt-2 flex shrink-0 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.
<button
@@ -161,11 +221,15 @@ export function FailedTile({ g, ratio, onRetry }: { g: Generation; ratio: number
</button>
)}
<button
+ disabled={create.isPending || retrying}
onClick={(e) => {
e.stopPropagation();
+ // A second click a moment later starts nothing more (each run is billed or uses the GPU).
+ setRetrying(true);
+ setTimeout(() => setRetrying(false), 3000);
onRetry();
}}
- className="inline-flex h-7 w-fit items-center gap-1.5 rounded-full bg-secondary px-2.5 text-[12px] font-medium hover:bg-accent"
+ className="inline-flex h-7 w-fit items-center gap-1.5 rounded-full bg-secondary px-2.5 text-[12px] font-medium hover:bg-accent disabled:opacity-70"
>
<RotateCcw className="size-3" /> Retry
</button>
diff --git a/src/components/studio/model-picker.tsx b/src/components/studio/model-picker.tsx
index 6fa8aef6..bec28416 100644
--- a/src/components/studio/model-picker.tsx
+++ b/src/components/studio/model-picker.tsx
@@ -4,6 +4,7 @@ import { ChevronDown, Cloud, Cpu, SearchX, Sparkles, Star } from "lucide-react";
import Link from "next/link";
import { useEffect, useMemo, useRef, useState } from "react";
import { KEY_ADDED_EVENT, openAddKey } from "@/components/keys/your-keys";
+import { OPEN_MODEL_PICKER_EVENT } from "@/lib/open-model-picker";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Command, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
@@ -185,6 +186,8 @@ function ModelRow({
}
interface PickerProps {
+ /** Opens when a failed run's tile asks for another model (open-model-picker.ts): the studio's own composer's picker. */
+ listens?: boolean;
models: ModelDef[];
value: ModelDef | undefined;
onChange: (m: ModelDef) => void;
@@ -219,6 +222,13 @@ export function phoneName(name: string): string {
export function ModelPicker(props: PickerProps) {
const [open, setOpen] = useState(false);
+ const listens = !!props.listens;
+ useEffect(() => {
+ if (!listens) return;
+ const show = () => setOpen(true);
+ window.addEventListener(OPEN_MODEL_PICKER_EVENT, show);
+ return () => window.removeEventListener(OPEN_MODEL_PICKER_EVENT, show);
+ }, [listens]);
const { value, models, onChange } = props;
const made = !!value && value.id === props.madeWith;
// The model a dimmed row was chosen for (by this picker only): picked once its key is saved and the studio knows it
diff --git a/src/lib/api.ts b/src/lib/api.ts
index 050ddd43..d87403ce 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -898,6 +898,10 @@ export interface StatusInfo {
host?: "runpod" | "tunnel" | "web";
};
keys?: CloudProvider[];
+ /** Of those, the ones a run would be taken on now (not refused, balance not known to be empty). */
+ usableKeys?: CloudProvider[];
+ /** Keys whose provider account's balance ran out on a run (Add credit before the next one). */
+ emptyKeys?: CloudProvider[];
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. */
hosted?: boolean;
diff --git a/src/lib/before-run.ts b/src/lib/before-run.ts
index 6cd27e7f..d595163c 100644
--- a/src/lib/before-run.ts
+++ b/src/lib/before-run.ts
@@ -2,12 +2,13 @@
* The check before Run (public sign-up): an account whose own GPU at a web address didn't answer its last status check
* (the status strip's, every 30 s; nothing here asks the GPU) sees what is wrong and its fixes above Generate, instead
* of starting a run that can only wait. When one of its keys runs the tool's cloud version, "Run with your fal.ai key"
- * is offered too: an explicit click, because it spends the person's own credit. Pure, for the composer and its tests.
+ * is offered too: an explicit click, for that run only (the engine switch stays where it was), because it spends the
+ * person's own credit. Pure, for the composer and its tests.
*/
import { dualEngine } from "./catalog/engines";
import type { Engine, GenerationRequest } from "./catalog/types";
-import { withKeyAction, type Diagnosis, type TroubleAction } from "./diagnose";
-import { cloudVersionKey, type CloudProvider } from "./your-keys";
+import { beforeRunWords, withKeyAction, type Diagnosis, type TroubleAction } from "./diagnose";
+import { cloudVersion, isCloudProvider, type CloudProvider } from "./your-keys";
type Routed = { id: string; engine: string; engines?: Engine[]; routes: { provider: string }[] };
@@ -15,6 +16,8 @@ export interface BeforeRunViewer {
kind: "guest" | "account";
gpu: { connected: boolean; mode?: "computer" | "link"; online?: boolean; trouble?: Pick<Diagnosis, "cause" | "words" | "actions" | "retryable" | "details"> };
keys?: CloudProvider[];
+ /** The keys a run would be taken on now (not refused, balance not known to be empty): the ones offered. */
+ usableKeys?: CloudProvider[];
paidAllowed?: boolean;
}
@@ -23,11 +26,16 @@ export interface BeforeRun {
words: string;
details?: string;
actions: TroubleAction[];
+ /** Waiting can fix it: a run started now waits for the GPU (else runs can't reach it until this is fixed). */
+ waits: boolean;
}
/** The words when the status check gave no reason (an older answer). */
export const GPU_OFF_WORDS = "Your GPU isn't answering right now.";
+/** What follows the sentence before Run: a run started now waits, or can't reach the GPU until it is fixed. */
+export const beforeRunTail = (waits: boolean) => (waits ? "A run you start now waits for it." : "Runs can't reach your GPU until this is fixed.");
+
/**
* The check before Run, or null when there is nothing to say: not an account, the tool doesn't run on its own GPU (a
* cloud model, the Cloud engine, this studio's GPUs), its GPU isn't a web address (this computer and a paired ComfyUI
@@ -39,7 +47,7 @@ export function gpuBeforeRun(o: {
engine: Engine;
/** The run goes to this studio's GPUs (hosted runs), not the account's own. */
onPool?: boolean;
- preset?: Parameters<typeof cloudVersionKey>[0];
+ preset?: Parameters<typeof cloudVersion>[0];
has: (id: string) => boolean;
getModel: (id: string) => Routed | undefined;
}): BeforeRun | null {
@@ -49,26 +57,32 @@ export function gpuBeforeRun(o: {
const toOwnGpu = dualEngine(model) ? o.engine === "open" : model.engine === "open";
const gpu = viewer.gpu;
if (!toOwnGpu || !gpu.connected || gpu.mode !== "link" || gpu.online !== false) return null;
- const key = viewer.paidAllowed !== false ? cloudVersionKey(o.preset, model, viewer.keys ?? [], o.has, o.getModel) : null;
+ const twin = viewer.paidAllowed !== false ? cloudVersion(o.preset, model, viewer.usableKeys ?? viewer.keys ?? [], o.has, o.getModel) : null;
const base: TroubleAction[] = gpu.trouble?.actions ?? [
{ kind: "check-gpu", label: "Check my GPU" },
{ kind: "gpu-settings", label: "Open Settings → Your GPU", target: "/settings#your-gpu" },
];
+ const fixes = base.filter((a) => a.kind !== "retry" && a.kind !== "run-with-key");
+ // The key's run right after the first fix (Start your pod), so a narrow composer keeps it.
+ const offer = twin ? [withKeyAction(twin.provider, twin.modelId, twin.op)] : [];
return {
- words: gpu.trouble?.words ?? GPU_OFF_WORDS,
+ words: gpu.trouble ? beforeRunWords(gpu.trouble.words) : GPU_OFF_WORDS,
...(gpu.trouble?.details && { details: gpu.trouble.details }),
- actions: [...base.filter((a) => a.kind !== "retry" && a.kind !== "run-with-key"), ...(key ? [withKeyAction(key)] : [])],
+ actions: [...fixes.slice(0, 1), ...offer, ...fixes.slice(1)],
+ waits: gpu.trouble ? gpu.trouble.retryable : true,
};
}
/**
- * A failed run's request again, on the cloud version its trouble names ("Run with your fal.ai key"): the same words and
- * inputs on the cloud engine. A preset's open-graph settings (`extra`) stay behind when the model changes.
+ * A request again, on the cloud version a trouble names ("Run with your fal.ai key"): the same words and inputs on the
+ * cloud engine, on that provider's key (`prefer`: a model on fal.ai and Replicate goes where the button said). A preset's
+ * open-graph settings (`extra`) stay behind when the model changes. For this one run: nothing else changes.
*/
-export function onCloudKey(request: GenerationRequest, a: Pick<TroubleAction, "modelId" | "op">): GenerationRequest {
+export function onCloudKey(request: GenerationRequest, a: Pick<TroubleAction, "modelId" | "op" | "target">): GenerationRequest {
+ const prefer = isCloudProvider(a.target) ? { prefer: a.target } : {};
const modelId = a.modelId ?? request.modelId;
- if (modelId === request.modelId) return { ...request, engine: "cloud" };
+ if (modelId === request.modelId) return { ...request, engine: "cloud", ...prefer };
const { extra: _extra, ...params } = request.params ?? {};
void _extra;
- return { ...request, engine: "cloud", modelId, params, ...(a.op && { op: a.op as GenerationRequest["op"] }) };
+ return { ...request, engine: "cloud", modelId, params, ...(a.op && { op: a.op as GenerationRequest["op"] }), ...prefer };
}
diff --git a/src/lib/open-model-picker.ts b/src/lib/open-model-picker.ts
new file mode 100644
index 00000000..ff699c28
--- /dev/null
+++ b/src/lib/open-model-picker.ts
@@ -0,0 +1,9 @@
+/**
+ * "Pick another model" from somewhere else on a studio's page (a failed run's tile): the studio's composer opens its model
+ * picker. The composer listens; with none on the page, nothing happens (the tile shows the button only inside a studio).
+ */
+export const OPEN_MODEL_PICKER_EVENT = "fuobe:open-model-picker";
+
+export function openModelPicker(): void {
+ window.dispatchEvent(new Event(OPEN_MODEL_PICKER_EVENT));
+}
diff --git a/src/lib/smaller-run.ts b/src/lib/smaller-run.ts
new file mode 100644
index 00000000..27d5efbf
--- /dev/null
+++ b/src/lib/smaller-run.ts
@@ -0,0 +1,34 @@
+import type { GenerationRequest, ModelDef } from "./catalog/types";
+
+/** A size as a number to compare ("720p" 720, "2K" 2048, "1024x768" 1024). */
+function sizeOf(r: string): number {
+ const p = /^(\d+)p$/i.exec(r);
+ if (p) return Number(p[1]);
+ const k = /^(\d+(?:\.\d+)?)k$/i.exec(r);
+ if (k) return Number(k[1]) * 1024;
+ const wh = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(r);
+ if (wh) return Math.max(Number(wh[1]), Number(wh[2]));
+ return NaN;
+}
+
+/**
+ * "Try one size smaller" (a run that ran out of graphics memory, or took too long): the same run one size down among the
+ * model's sizes, or else one length down among its lengths. Null when neither has a smaller step (Pick another model then).
+ */
+export function smallerRun(req: GenerationRequest, model: Pick<ModelDef, "options" | "defaults"> | undefined): { request: GenerationRequest; what: string } | null {
+ if (!model) return null;
+ const params = req.params ?? {};
+ const now = params.resolution ?? model.defaults?.resolution;
+ const sizes = (model.options.resolutions ?? []).filter((r) => Number.isFinite(sizeOf(r)));
+ if (now && Number.isFinite(sizeOf(now))) {
+ const lower = sizes.filter((r) => sizeOf(r) < sizeOf(now)).sort((a, b) => sizeOf(b) - sizeOf(a))[0];
+ if (lower) return { request: { ...req, params: { ...params, resolution: lower } }, what: lower };
+ }
+ const length = params.duration ?? model.defaults?.duration;
+ const lengths = model.options.durations ?? [];
+ if (typeof length === "number") {
+ const shorter = lengths.filter((d) => d < length).sort((a, b) => b - a)[0];
+ if (shorter) return { request: { ...req, params: { ...params, duration: shorter } }, what: `${shorter} s` };
+ }
+ return null;
+}
diff --git a/tests/own-graceful-ui.test.ts b/tests/own-graceful-ui.test.ts
index 7812f152..397553bf 100644
--- a/tests/own-graceful-ui.test.ts
+++ b/tests/own-graceful-ui.test.ts
@@ -14,10 +14,13 @@ vi.mock("next/navigation", () => ({
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 { beforeRunTail, gpuBeforeRun, onCloudKey, GPU_OFF_WORDS } = await import("@/lib/before-run");
+const { diagnoseGpu, RUNPOD_CONSOLE_URL, troubleOf, withKeyAction, withOfferAfterFirst } = await import("@/lib/diagnose");
const { getModel, getPreset } = await import("@/lib/catalog");
-const { TroubleActions, TroubleDetails, autoCheckIn } = await import("@/components/gpu/trouble");
+const { TroubleActions, TroubleDetails, autoCheckIn, fitActions } = await import("@/components/gpu/trouble");
+const { FailedTile } = await import("@/components/studio/feed");
+const { smallerRun } = await import("@/lib/smaller-run");
+const { readFileSync } = await import("node:fs");
const has = (id: string) => !!getModel(id);
const render = (node: ReactNode) => renderToStaticMarkup(createElement(QueryClientProvider, { client: new QueryClient() }, node));
@@ -32,17 +35,28 @@ 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/);
+ // Settings' "we connect as soon as it answers" becomes what happens to runs.
+ expect(shown.words).toBe("Your RunPod pod isn't running, or ComfyUI isn't on port 8188. Start your pod, and your runs start as soon as it answers.");
+ expect(shown.waits).toBe(true);
+ expect(beforeRunTail(shown.waits)).toBe("A run you start now waits for it.");
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", () => {
+ it("offers the tool's cloud version on the account's own key, an explicit button right after Start your pod", () => {
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");
+ expect(withFal.actions.map((a) => a.kind)).toEqual(["start-gpu", "run-with-key", "check-gpu", "gpu-settings"]);
+ // The cloud version itself (its model and operation there), so one click runs it, once.
+ expect(withFal.actions[1]).toEqual(withKeyAction("fal", "minimax-h3", "i2v"));
+ expect(withFal.actions[1].label).toBe("Run with your fal.ai key");
+ // A key the provider refused (or whose balance ran out) isn't offered.
+ expect(gpuBeforeRun({ viewer: { ...account(offline, ["fal"]), usableKeys: [] }, model: h3, engine: "open", preset: fpv, has, getModel })!.actions.map((a) => a.kind)).not.toContain("run-with-key");
+ // What waiting can't fix doesn't say a run waits.
+ const password = gpuBeforeRun({ viewer: account({ ...offline, trouble: diagnoseGpu({ stage: "status", status: 401 }, { kind: "link", url: POD }) }), model: h3, engine: "open", preset: fpv, has, getModel })!;
+ expect(password.waits).toBe(false);
+ expect(password.words).toBe("Your GPU asks for a password. Add it in Settings → Your GPU.");
+ expect(beforeRunTail(password.waits)).toBe("Runs can't reach your GPU until this is fixed.");
// 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.
@@ -70,6 +84,8 @@ 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 } });
+ // On the key the button named.
+ expect(onCloudKey(req, { modelId: "minimax-h3", op: "i2v", target: "fal" })).toMatchObject({ engine: "cloud", prefer: "fal" });
// 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" });
@@ -98,8 +114,29 @@ describe("the buttons", () => {
expect(render(createElement(TroubleActions, { actions: [] }))).toBe("");
});
+ it("when few fit, the ones that help least go first, never the first; a tile's Settings gives way to Check my GPU", () => {
+ const run = [{ kind: "start-gpu" as const, label: "Start your pod" }, { kind: "retry" as const, label: "Retry" }, { kind: "check-gpu" as const, label: "Check my GPU" }, { kind: "gpu-settings" as const, label: "Open Settings → Your GPU" }];
+ expect(fitActions(run, 2).map((a) => a.kind)).toEqual(["start-gpu", "check-gpu"]);
+ expect(fitActions(run, 3).map((a) => a.kind)).toEqual(["start-gpu", "retry", "check-gpu"]);
+ const tile = render(createElement(TroubleActions, { actions: run, skip: ["retry"], compact: true }));
+ expect(tile).toContain("Check my GPU");
+ expect(tile).not.toContain("Settings");
+ // One line each, cut short when narrow (never wrapping out of the pill).
+ expect(tile).toMatch(/whitespace-nowrap/);
+ });
+
+ it("the stopped pod's failed tile keeps Run with your fal.ai key among its buttons (the server's real order)", () => {
+ const end = diagnoseGpu({ stage: "poll", status: 404 }, { kind: "link", url: POD });
+ const trouble = troubleOf({ ...end, actions: withOfferAfterFirst(end.actions, withKeyAction("fal", "minimax-h3", "i2v")) });
+ const g = { id: "g1", status: "failed", error: end.words, trouble, request: { feature: "video", modelId: "oss-minimax-h3", presetId: "motion-fpv-drone" }, modelId: "oss-minimax-h3", op: "i2v" };
+ const html = render(createElement(FailedTile, { g: g as never, ratio: 9 / 16, onRetry: () => {} }));
+ expect(html).toContain("Start your pod");
+ expect(html).toContain("Run with your fal.ai key");
+ expect(html).toContain(end.words.replaceAll("'", "&#x27;"));
+ });
+
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, { details: "RunPod pod, port 8188 · HTTP 404" }))).toContain("HTTP 404");
expect(render(createElement(TroubleDetails, {}))).toBe("");
});
@@ -113,3 +150,27 @@ describe("the buttons", () => {
expect(autoCheckIn("gpu-password", 1, start, start)).toBeNull();
});
});
+
+describe("Run with your key from the composer runs once", () => {
+ it("leaves the engine switch alone: the next run goes to the GPU again", () => {
+ // The composer's handler builds this run's request on the cloud version and starts it; it never flips the switch
+ // (useEngine's setter writes the remembered engine, which every later run would follow).
+ const src = readFileSync("src/components/studio/composer.tsx", "utf8");
+ const handler = /const runOnceWithKey = \(a: TroubleAction\) => \{([\s\S]*?)\n {2}\};/.exec(src)?.[1] ?? "";
+ expect(handler).toContain("onCloudKey(");
+ expect(handler).toContain("create.mutateAsync(");
+ expect(handler).not.toMatch(/setEngine|preferEngine|localStorage/);
+ expect(src).not.toMatch(/setCloudRun|cloudRun/);
+ expect(src).toMatch(/onRunWithKey: runOnceWithKey/);
+ });
+});
+
+describe("Try one size smaller", () => {
+ it("steps the size down first, then the length, and offers nothing when neither can", () => {
+ const model = { options: { resolutions: ["480p", "720p", "1080p"], durations: [5, 10] }, defaults: { resolution: "1080p", duration: 10 } };
+ const req = { feature: "video", modelId: "m", prompt: "x" };
+ expect(smallerRun(req, model as never)).toMatchObject({ request: { params: { resolution: "720p" } }, what: "720p" });
+ expect(smallerRun({ ...req, params: { resolution: "480p", duration: 10 } }, model as never)).toMatchObject({ request: { params: { duration: 5 } }, what: "5 s" });
+ expect(smallerRun({ ...req, params: { resolution: "480p", duration: 5 } }, model as never)).toBeNull();
+ });
+});