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 Library: a run's fixes act wherever the run is shown
Adarsh679fe4e051fc
diff --git a/src/components/gpu/run-trouble-actions.tsx b/src/components/gpu/run-trouble-actions.tsxnew file mode 100644index 00000000..1229ee34--- /dev/null+++ b/src/components/gpu/run-trouble-actions.tsx@@ -0,0 +1,69 @@+"use client";++import { useRouter } from "next/navigation";+import { useSyncExternalStore } from "react";+import { toast } from "sonner";+import { TroubleActions } from "./trouble";+import { useCreateGeneration } from "@/lib/api";+import type { Generation, ModelDef } from "@/lib/catalog/types";+import type { TroubleAction, TroubleActionKind } from "@/lib/diagnose";+import { openModelPicker } from "@/lib/open-model-picker";+import { toastError } from "@/lib/refusals";+import { batchKeyOf, failedRunHandlers, movingRun, subscribeMoving, waitingRunHandlers, type RunTroubleDeps } from "@/lib/run-trouble";++/** The Library reads a run's model only when Try one size smaller is pressed (the catalog isn't on its page). */+const loadModel = (id: string) => import("@/lib/catalog").then((m) => m.getModel(id));++/**+ * A run's trouble buttons with what they do (src/lib/run-trouble.ts): a waiting run's Run with your key (its batch's+ * other tiles stop offering it while one press is on its way), a failed run's Run with your key, Pick another model, Try+ * one size smaller and Send a smaller copy. In a studio (`reuse`) the run comes back into its composer; elsewhere (the+ * Library) its studio opens with it.+ */+export function RunTroubleActions({+ g,+ actions,+ reuse,+ model,+ skip = [],+ ...rest+}: {+ g: Generation;+ actions: TroubleAction[];+ reuse?: (g: Generation) => void;+ model?: Pick<ModelDef, "options" | "defaults">;+ skip?: TroubleActionKind[];+ max?: number;+ compact?: boolean;+ context?: "run" | "other";+ className?: string;+}) {+ const create = useCreateGeneration();+ const router = useRouter();+ const key = batchKeyOf(g);+ // (Nothing moves before the page is live: the server's answer is the same, empty one.)+ const moving = () => movingRun(key);+ const movingId = useSyncExternalStore(subscribeMoving, moving, moving);+ const waiting = g.status === "queued" || g.status === "running";+ const deps: RunTroubleDeps = {+ run: (request, done) =>+ create.mutateAsync(request).then(+ () => {+ if (done) toast.success(done);+ return true;+ },+ (e) => {+ toastError(e);+ return false;+ },+ ),+ onError: (e, next) => (next ? toast.error((e as Error).message || "That didn't work.", { action: next }) : toastError(e)),+ model,+ ...(model ? {} : { loadModel }),+ ...(reuse ? { reuse, openPicker: openModelPicker } : { go: (href: string) => router.push(href) }),+ };+ const handlers = waiting ? waitingRunHandlers(g, deps) : failedRunHandlers(g, deps);+ // Another tile of the same batch is moving it to a key right now: this one doesn't offer it again.+ const hide: TroubleActionKind[] = waiting && movingId && movingId !== g.id ? [...skip, "run-with-key"] : skip;+ return <TroubleActions actions={actions} handlers={handlers} skip={hide} {...rest} />;+}diff --git a/src/components/library/asset-card.tsx b/src/components/library/asset-card.tsxindex 9ead3206..38999ea4 100644--- a/src/components/library/asset-card.tsx+++ b/src/components/library/asset-card.tsx@@ -12,6 +12,7 @@ import { 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 { RunTroubleActions } from "@/components/gpu/run-trouble-actions";import { DRAG_TYPE } from "./folders";import { ReviewBadge } from "./review";import type { Layout } from "./view-options";@@ -48,7 +49,7 @@ const idsOf = (e: LibraryEntry) => (e.type === "single" ? [e.g.id] : e.items.map* (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 }) {+export function StatusCover({ g, small, actionable }: { g: Generation; small?: boolean; /** The account's own Library: the buttons act (Pick another model opens the run's studio with it). */ actionable?: 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;@@ -63,7 +64,12 @@ export function StatusCover({ g, small }: { g: Generation; small?: boolean }) {{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 />}+ {waiting &&+ (actionable ? (+ <RunTroubleActions g={g} actions={waiting.actions} skip={["retry"]} max={2} compact />+ ) : (+ <TroubleActions actions={waiting.actions} skip={["retry", "run-with-key"]} max={2} compact />+ ))}</div>)}</div>@@ -79,13 +85,18 @@ export function StatusCover({ g, small }: { g: Generation; small?: boolean }) {{/* 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 />}+ {trouble &&+ (actionable ? (+ <RunTroubleActions g={g} className="shrink-0" actions={trouble.actions} skip={["retry"]} max={2} compact context="run" />+ ) : (+ <TroubleActions className="shrink-0" actions={trouble.actions} skip={["retry"]} max={2} compact />+ ))}</div>);}function Cover({ g, fit }: { g: Generation; fit: boolean }) {- if (g.status !== "succeeded" || !g.outputs.length) return <StatusCover g={g} />;+ if (g.status !== "succeeded" || !g.outputs.length) return <StatusCover g={g} actionable={!g.deletedAt} />;if (isLayered(g)) return <LayersStack g={g} />;return <MediaThumb output={g.outputs[0]} g={g} fit={fit} className={cn(fit && "bg-muted")} />;}@@ -263,7 +274,7 @@ export const AssetCard = memo(function AssetCard({</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 />+ <RunTroubleActions g={g} className="mt-1" actions={(g.status === "failed" ? g.trouble : g.waiting)!.actions} skip={["retry"]} max={1} compact context={g.status === "failed" ? "run" : "other"} />)}</div>{g.favorite && !stack && <Heart className="size-4 shrink-0 fill-highlight text-highlight" />}diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsxindex c6f52974..e749ae2d 100644--- a/src/components/studio/composer.tsx+++ b/src/components/studio/composer.tsx@@ -90,7 +90,7 @@ 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, cloudVersion, needsKey, paidThrough, startingModel } from "@/lib/your-keys";-import { beforeRunTail, gpuBeforeRun, onCloudKey } from "@/lib/before-run";+import { beforeRunTail, gpuBeforeRun, runOnceOnKey } 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";@@ -778,9 +778,8 @@ export function Composer({ docked }: { docked: boolean }) {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.`),+ return runOnceOnKey(withVoiceFirst, a, (r) => create.mutateAsync(r)).then(+ (words) => void toast.success(words),(e) => toastError(e),);};diff --git a/src/components/studio/feed.tsx b/src/components/studio/feed.tsxindex a9a0d9a4..ed6ff011 100644--- a/src/components/studio/feed.tsx+++ b/src/components/studio/feed.tsx@@ -16,11 +16,9 @@ import {} from "@/components/ui/dropdown-menu";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { OPERATION_LABELS, type Generation } from "@/lib/catalog/types";-import { onCloudKey } from "@/lib/before-run";-import { openModelPicker } from "@/lib/open-model-picker";-import { smallerRun } from "@/lib/smaller-run";import { useOptionalCatalog } from "./catalog";-import { TroubleActions, TroubleDetails } from "@/components/gpu/trouble";+import { TroubleDetails } from "@/components/gpu/trouble";+import { RunTroubleActions } from "@/components/gpu/run-trouble-actions";import { useCreateGeneration, useGenerationActions, useStatus } from "@/lib/api";import { placeholdersOn } from "@/lib/demo-mode";import { useSoulFinish } from "./soul-finish";@@ -75,7 +73,6 @@ export function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {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@@ -109,19 +106,8 @@ export function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {{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)),- }}- />- )}+ {/* Run with your key moves this run (and the rest of its batch not handed over yet) to the key, in one server call. */}+ {waiting && <RunTroubleActions g={g} className="mt-1.5" actions={waiting.actions} skip={["retry"]} max={2} compact />}</div><Tooltip><TooltipTrigger asChild>@@ -151,14 +137,6 @@ 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);@@ -166,12 +144,6 @@ export function FailedTile({ g, ratio, onRetry }: { g: Generation; ratio: numberconst 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: shape }}>@@ -181,30 +153,18 @@ export function FailedTile({ g, ratio, onRetry }: { g: Generation; ratio: number{/* 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>+ {/* In a studio, Pick another model brings its settings back into the composer and opens its model picker. */}{trouble && (- <TroubleActions+ <RunTroubleActions+ g={g}+ reuse={feed?.reuse}+ model={catalog?.getModel(g.modelId)}className="mt-2 shrink-0"actions={trouble.actions}skip={["retry"]}max={narrow ? 2 : 3}compactcontext="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 shrink-0 flex-wrap gap-1.5">diff --git a/src/components/studio/studio-page.tsx b/src/components/studio/studio-page.tsxindex e3b98aac..4a07d823 100644--- a/src/components/studio/studio-page.tsx+++ b/src/components/studio/studio-page.tsx@@ -16,6 +16,8 @@ import { claimStartToken, followEngineDefault, handoffKey, mergeHandoff, promptSimport { presetGpuKey } from "@/lib/catalog/preset-recipe-routes";import { editableLayout, EDIT_LAYOUT_PARAM, readEditLayoutParam } from "@/lib/output-actions";import { movedAppRequest } from "@/lib/catalog/plan";+import { openModelPicker } from "@/lib/open-model-picker";+import { PICK_PARAM, REUSE_PARAM } from "@/lib/run-trouble";import { migrateRequest } from "@/lib/catalog/replaced";import { SoulPresetCards } from "@/components/moodboards/soul-preset-cards";import type { StudioCatalog } from "@/lib/studio-catalog";@@ -818,6 +820,48 @@ function LayoutHandoff() {return null;}+/**+ * `?reuse=<run id>` (a run's fixes in the Library: Pick another model, or another size): that run's settings come into+ * the composer, as its tile's Reuse brings them, and with `pick=1` the model picker opens on them. Taken out of the address+ * once read, so a reload doesn't load it again.+ */+function ReuseHandoff() {+ const sp = useSearchParams();+ const id = sp.get(REUSE_PARAM);+ const pick = sp.get(PICK_PARAM) === "1";+ const { config, setDraft } = useStudioActions();+ const catalog = useCatalog();+ const [engine, setEngine] = useEngine();+ const opened = useRef<string | null>(null);+ useEffect(() => {+ if (!id) opened.current = null;+ if (!id || opened.current === id || !catalog.ready) return;+ opened.current = id;+ void fetch(`/api/generations/${encodeURIComponent(id)}`)+ .then(async (res) => {+ if (!res.ok) throw new Error("That run isn't in your library any more.");+ const g = (await res.json()) as Generation;+ setDraft(draftFromGeneration(g, config, catalog.getModel, catalog.getPreset));+ // A run on a model Fuobe retired comes back on what replaced it: said, as Reuse says it.+ const retired = migrateRequest(g.request);+ const moved = retired.note ?? movedAppRequest(retired.request, catalog.getModel, catalog.getPreset).note;+ if (moved) toast(moved);+ if (g.engine !== engine) setEngine(g.engine);+ // Once the draft is in, the picker opens on its model.+ if (pick) setTimeout(openModelPicker, 0);+ else requestAnimationFrame(() => document.querySelector<HTMLTextAreaElement>("[data-composer] textarea")?.focus());+ })+ .catch((err: Error) => toast.error(err.message, { id: "reuse-run" }))+ .finally(() => {+ const u = new URL(window.location.href);+ u.searchParams.delete(REUSE_PARAM);+ u.searchParams.delete(PICK_PARAM);+ window.history.replaceState(null, "", `${u.pathname}${u.search}${u.hash}`);+ });+ }, [id, pick, catalog, config, engine, setDraft, setEngine]);+ return null;+}+/*** One draft's page: the studio and its hand-off. The start request resets with the draft (a new epoch).*@@ -852,6 +896,9 @@ function StudioSession({<Suspense fallback={null}><LayoutHandoff /></Suspense>+ <Suspense fallback={null}>+ <ReuseHandoff />+ </Suspense></StartRequestCtx.Provider>);}diff --git a/src/lib/before-run.ts b/src/lib/before-run.tsindex d595163c..922567e6 100644--- a/src/lib/before-run.ts+++ b/src/lib/before-run.ts@@ -8,7 +8,7 @@import { dualEngine } from "./catalog/engines";import type { Engine, GenerationRequest } from "./catalog/types";import { beforeRunWords, withKeyAction, type Diagnosis, type TroubleAction } from "./diagnose";-import { cloudVersion, isCloudProvider, type CloudProvider } from "./your-keys";+import { CLOUD_KEY, cloudVersion, isCloudProvider, type CloudProvider } from "./your-keys";type Routed = { id: string; engine: string; engines?: Engine[]; routes: { provider: string }[] };@@ -86,3 +86,14 @@ export function onCloudKey(request: GenerationRequest, a: Pick<TroubleAction, "mvoid _extra;return { ...request, engine: "cloud", modelId, params, ...(a.op && { op: a.op as GenerationRequest["op"] }), ...prefer };}++/**+ * "Run with your fal.ai key" from the composer: this run, once, on the tool's cloud version and that key (`start` sends+ * it). Nothing else changes: the engine switch stays where it was, so the next run goes to the GPU again. Resolves with+ * the words to say once it has started.+ */+export async function runOnceOnKey(request: GenerationRequest, a: Pick<TroubleAction, "modelId" | "op" | "target">, start: (r: GenerationRequest) => Promise<unknown>): Promise<string> {+ await start(onCloudKey(request, a));+ const label = isCloudProvider(a.target) ? CLOUD_KEY[a.target].label : "your key";+ return `Running once on ${label} with your key. Your next runs go to your GPU again.`;+}diff --git a/src/lib/run-trouble.ts b/src/lib/run-trouble.tsnew file mode 100644index 00000000..5914304e--- /dev/null+++ b/src/lib/run-trouble.ts@@ -0,0 +1,155 @@+import type { TroubleAction } from "./diagnose";+import type { Generation, ModelDef } from "./catalog/types";+import { onCloudKey } from "./before-run";+import { smallerRun } from "./smaller-run";++/**+ * What the buttons under a run's GPU or key problem do (src/components/gpu/trouble.tsx), wherever the run is shown: a+ * studio's feed (its tile) or the Library (its card). A studio loads a run into its composer itself; the Library opens the+ * run's studio with the run loaded (`?reuse=<id>`, and `pick=1` to open its model picker there).+ */++/** `?reuse=<run id>`: a studio loads that run's settings into its composer, once. */+export const REUSE_PARAM = "reuse";+/** With `reuse`: its model picker opens too ("Pick another model"). */+export const PICK_PARAM = "pick";++/** The studio a run belongs to, by what it was made with (its feature), else by what it made. */+export function studioHrefFor(g: Pick<Generation, "feature" | "kind">): string {+ const f = g.feature;+ if (f.startsWith("app:")) return `/apps/${encodeURIComponent(f.slice(4))}`;+ if (f === "video" || f.startsWith("motion:") || f.startsWith("effect:")) return "/video";+ if (f === "image" || f === "edit" || f === "lipsync" || f === "upscale" || f === "audio") return `/${f}`;+ if (f.startsWith("character:")) return "/image";+ return g.kind === "video" ? "/video" : g.kind === "audio" ? "/audio" : "/image";+}++/** The run's studio with the run loaded into its composer (and its model picker open, `pick`). */+export function reuseHref(g: Pick<Generation, "id" | "feature" | "kind">, pick = false): string {+ const q = new URLSearchParams({ [REUSE_PARAM]: g.id, ...(pick && { [PICK_PARAM]: "1" }) });+ return `${studioHrefFor(g)}?${q}`;+}++/** "Send a smaller copy": the run's file made smaller on the server; the run's request comes back with it, and the words to say. */+export async function smallerCopyRequest(g: Pick<Generation, "id">): 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." };+}++/** What the handlers need from the page they are on. */+export interface RunTroubleDeps {+ /** Start a run (`done`: the words once it has started). True when it started; a refusal is said by `run` itself. */+ run: (request: Generation["request"], done?: string) => Promise<boolean>;+ /** In a studio: the run's settings back into its composer. */+ reuse?: (g: Generation) => void;+ /** In a studio: its composer's model picker opens. */+ openPicker?: () => void;+ /** Elsewhere (the Library): go to this address (the run's studio, with the run loaded). */+ go?: (href: string) => void;+ /** The run's model (its sizes and lengths, for Try one size smaller). */+ model?: Pick<ModelDef, "options" | "defaults">;+ /** Without `model`: read the run's model when Try one size smaller is pressed (the Library doesn't hold the catalog). */+ loadModel?: (id: string) => Promise<Pick<ModelDef, "options" | "defaults"> | undefined>;+ /** Say what went wrong (a smaller copy that couldn't be made), with the next thing to try as a button, if any. */+ onError: (e: unknown, next?: { label: string; onClick: () => void }) => void;+ /** Make a smaller copy (tests stand in for the server). */+ smallerCopy?: typeof smallerCopyRequest;+}++/** The handlers a run's trouble buttons take (TroubleActions' `handlers`). */+export interface RunTroubleHandlers {+ onRunWithKey?: (a: TroubleAction) => Promise<unknown>;+ onPickModel?: () => void;+ onTrySmaller?: () => Promise<unknown>;+ onSendSmaller?: () => Promise<unknown>;+}++/** Pick another model: in a studio, the run back in its composer with the picker open; elsewhere, its studio so. */+function pickModel(g: Generation, d: RunTroubleDeps): (() => void) | undefined {+ if (d.reuse && d.openPicker) {+ const { reuse, openPicker } = d;+ return () => {+ reuse(g);+ openPicker();+ };+ }+ if (d.go) {+ const go = d.go;+ return () => go(reuseHref(g, true));+ }+ return undefined;+}++/** A failed run's buttons: run it on a key, pick another model, one size smaller, or a smaller copy of its file. */+export function failedRunHandlers(g: Generation, d: RunTroubleDeps): RunTroubleHandlers {+ const copy = d.smallerCopy ?? smallerCopyRequest;+ const pick = pickModel(g, d);+ const smaller = smallerRun(g.request, d.model);+ const { loadModel } = d;+ const trySmaller = smaller+ ? () => d.run(smaller.request, `Running it again at ${smaller.what}.`)+ : loadModel+ ? async () => {+ const s = smallerRun(g.request, await loadModel(g.modelId).catch(() => undefined));+ if (s) return d.run(s.request, `Running it again at ${s.what}.`);+ // No smaller size or length: another model, in the run's studio.+ pick?.();+ return false;+ }+ : undefined;+ return {+ onRunWithKey: (a) => d.run(onCloudKey(g.request, a)),+ onPickModel: pick,+ onTrySmaller: trySmaller,+ onSendSmaller: () =>+ copy(g).then(+ ({ request, note }) => d.run(request, note),+ // No smaller copy could be made: the next thing to try, a press away.+ (e) =>+ d.onError(+ e,+ trySmaller ? { label: "Try one size smaller", onClick: () => void trySmaller() } : pick ? { label: "Pick another model", onClick: pick } : undefined,+ ),+ ),+ };+}++// A waiting run's "Run with your key" moves its whole batch (the server stops every job of it not handed over yet):+// while one tile's press is on its way, the batch's other tiles don't offer it again.+const moving = new Map<string, string>();+const listeners = new Set<() => void>();++/** A run's batch (its jobs share it), or the run itself. */+export const batchKeyOf = (g: Pick<Generation, "id" | "batchId">): string => g.batchId ?? g.id;++export function subscribeMoving(fn: () => void): () => void {+ listeners.add(fn);+ return () => void listeners.delete(fn);+}++/** The run whose press moves this batch to a key right now, if any. */+export const movingRun = (key: string): string | undefined => moving.get(key);++function setMoving(key: string, id: string | null): void {+ if (id) moving.set(key, id);+ else moving.delete(key);+ for (const fn of listeners) fn();+}++/** A waiting run's buttons: Run with your key takes its place (and its batch's), once. */+export function waitingRunHandlers(g: Generation, d: RunTroubleDeps): RunTroubleHandlers {+ const key = batchKeyOf(g);+ return {+ onRunWithKey: async (a) => {+ const was = moving.get(key);+ if (was && was !== g.id) return false;+ setMoving(key, g.id);+ const started = await d.run({ ...onCloudKey(g.request, a), replaces: g.id } as Generation["request"]);+ // Started: the batch's jobs stop, so their tiles go. Refused: the button comes back.+ if (!started) setMoving(key, null);+ return started;+ },+ };+}diff --git a/tests/own-graceful-ui.test.ts b/tests/own-graceful-ui.test.tsindex 397553bf..608de29b 100644--- a/tests/own-graceful-ui.test.ts+++ b/tests/own-graceful-ui.test.ts@@ -14,7 +14,11 @@ vi.mock("next/navigation", () => ({useSearchParams: () => new URLSearchParams(),}));-const { beforeRunTail, gpuBeforeRun, onCloudKey, GPU_OFF_WORDS } = await import("@/lib/before-run");+const { beforeRunTail, gpuBeforeRun, onCloudKey, runOnceOnKey, GPU_OFF_WORDS } = await import("@/lib/before-run");+const { failedRunHandlers, movingRun, reuseHref, studioHrefFor, waitingRunHandlers } = await import("@/lib/run-trouble");+const { RunTroubleActions } = await import("@/components/gpu/run-trouble-actions");+const { StatusCover } = await import("@/components/library/asset-card");+type RunTroubleDeps = import("@/lib/run-trouble").RunTroubleDeps;const { diagnoseGpu, RUNPOD_CONSOLE_URL, troubleOf, withKeyAction, withOfferAfterFirst } = await import("@/lib/diagnose");const { getModel, getPreset } = await import("@/lib/catalog");const { TroubleActions, TroubleDetails, autoCheckIn, fitActions } = await import("@/components/gpu/trouble");@@ -152,19 +156,100 @@ describe("the buttons", () => {});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");+ it("sends this run on the cloud version and that key, and changes nothing else: the next run goes to the GPU again", async () => {+ // The engine switch is remembered in the browser (useEngine): a press that wrote it would move every later run.+ const written: string[] = [];+ const store = { getItem: () => null, setItem: (k: string) => void written.push(k), removeItem: (k: string) => void written.push(k), clear: () => {}, key: () => null, length: 0 };+ vi.stubGlobal("localStorage", store);+ try {+ const sent: unknown[] = [];+ const mutate = vi.fn(async (r: unknown) => void sent.push(r));+ 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" } } };+ const words = await runOnceOnKey(req, withKeyAction("fal", "minimax-h3", "i2v"), mutate);+ expect(mutate).toHaveBeenCalledTimes(1);+ expect(sent[0]).toEqual({ ...req, engine: "cloud", modelId: "minimax-h3", op: "i2v", params: { duration: 6 }, prefer: "fal" });+ expect(words).toBe("Running once on fal.ai with your key. Your next runs go to your GPU again.");+ expect(written).toEqual([]);+ // A refusal comes back to the composer (its toast), and nothing is said as started.+ await expect(runOnceOnKey(req, withKeyAction("fal", "minimax-h3", "i2v"), async () => Promise.reject(new Error("no")))).rejects.toThrow("no");+ } finally {+ vi.unstubAllGlobals();+ }+ // The composer's own handler is this one, and never flips the switch.+ const src = readFileSync("src/components/studio/composer.tsx", "utf8").replace(/\r\n/g, "\n");const handler = /const runOnceWithKey = \(a: TroubleAction\) => \{([\s\S]*?)\n {2}\};/.exec(src)?.[1] ?? "";- expect(handler).toContain("onCloudKey(");- expect(handler).toContain("create.mutateAsync(");+ expect(handler).toContain("runOnceOnKey(");expect(handler).not.toMatch(/setEngine|preferEngine|localStorage/);- expect(src).not.toMatch(/setCloudRun|cloudRun/);expect(src).toMatch(/onRunWithKey: runOnceWithKey/);});});+describe("a run's buttons, in a studio and in the Library", () => {+ const failed = { id: "run1", batchId: null, feature: "video", kind: "video", status: "failed", modelId: "oss-minimax-h3", request: { feature: "video", modelId: "oss-minimax-h3", prompt: "", params: { resolution: "720p" } } } as never;+ const deps = (more: Partial<RunTroubleDeps> = {}) => {+ const ran: unknown[] = [];+ const d: RunTroubleDeps = { run: async (r) => (ran.push(r), true), onError: vi.fn(), ...more };+ return { ran, d };+ };++ it("Pick another model: in a studio the run comes back into the composer and the picker opens; in the Library its studio opens so", () => {+ const reuse = vi.fn();+ const openPicker = vi.fn();+ failedRunHandlers(failed, deps({ reuse, openPicker }).d).onPickModel!();+ expect(reuse).toHaveBeenCalledWith(failed);+ expect(openPicker).toHaveBeenCalledTimes(1);+ const go = vi.fn();+ failedRunHandlers(failed, deps({ go }).d).onPickModel!();+ expect(go).toHaveBeenCalledWith("/video?reuse=run1&pick=1");+ // Nowhere to pick one: no button.+ expect(failedRunHandlers(failed, deps().d).onPickModel).toBeUndefined();+ expect(studioHrefFor({ feature: "app:app-outfit-swap", kind: "image" })).toBe("/apps/app-outfit-swap");+ expect(studioHrefFor({ feature: "effect:fpv", kind: "video" })).toBe("/video");+ expect(studioHrefFor({ feature: "translate", kind: "audio" })).toBe("/audio");+ expect(reuseHref({ id: "run1", feature: "image", kind: "image" })).toBe("/image?reuse=run1");+ });++ it("Try one size smaller in the Library reads the run's model when pressed; a copy that can't be made offers the next thing to try", async () => {+ const model = { options: { resolutions: ["480p", "720p"] }, defaults: { resolution: "720p" } };+ const { ran, d } = deps({ loadModel: async () => model as never, go: vi.fn() });+ const h = failedRunHandlers(failed, { ...d, smallerCopy: async () => Promise.reject(new Error("This file is as small as we can make it here.")) });+ await h.onTrySmaller!();+ expect(ran[0]).toMatchObject({ params: { resolution: "480p" } });+ await h.onSendSmaller!();+ expect(d.onError).toHaveBeenCalledWith(expect.any(Error), expect.objectContaining({ label: "Try one size smaller" }));+ });++ it("Run with your key on a waiting tile takes the run's place, and the batch's other tiles don't offer it while it goes", async () => {+ const waiting = { ...(failed as object), id: "job1", batchId: "b1", status: "queued" } as never;+ let release: (v: boolean) => void = () => {};+ const sent: unknown[] = [];+ const run = (r: unknown) => (sent.push(r), new Promise<boolean>((res) => (release = res)));+ const press = waitingRunHandlers(waiting, { run, onError: vi.fn() }).onRunWithKey!(withKeyAction("fal", "minimax-h3", "i2v"));+ expect(sent[0]).toMatchObject({ replaces: "job1", engine: "cloud" });+ expect(movingRun("b1")).toBe("job1");+ // Its batch's other job: drawn without the button, and a press anyway sends nothing.+ const other = { ...(waiting as object), id: "job2" } as never;+ const html = render(createElement(RunTroubleActions, { g: other, actions: [withKeyAction("fal", "minimax-h3", "i2v"), { kind: "check-gpu", label: "Check my GPU" }] }));+ expect(html).not.toContain("Run with your fal.ai key");+ await waitingRunHandlers(other, { run, onError: vi.fn() }).onRunWithKey!(withKeyAction("fal", "minimax-h3", "i2v"));+ expect(sent).toHaveLength(1);+ // Refused: the button comes back.+ release(false);+ await press;+ expect(movingRun("b1")).toBeUndefined();+ });++ it("a Library card acts: a waiting run offers Run with your key, a failed one Pick another model", () => {+ const actions = [withKeyAction("fal", "minimax-h3", "i2v"), { kind: "pick-model" as const, label: "Pick another model" }];+ const waitingCard = { ...(failed as object), id: "w1", status: "queued", outputs: [], createdAt: Date.now(), waiting: { cause: "gpu-stopped", words: "x", actions, retryable: true } } as never;+ expect(render(createElement(StatusCover, { g: waitingCard, actionable: true }))).toContain("Run with your fal.ai key");+ // The owner's view of an account's runs only shows them.+ expect(render(createElement(StatusCover, { g: waitingCard }))).not.toContain("Run with your fal.ai key");+ const failedCard = { ...(failed as object), id: "f1", outputs: [], error: "x", trouble: { cause: "gpu-isolated", words: "x", actions: [{ kind: "pick-model", label: "Pick another model" }], retryable: false } } as never;+ expect(render(createElement(StatusCover, { g: failedCard, actionable: true }))).toContain("Pick another model");+ });+});+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 } };