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
Runs: a changed price can be accepted from its card, from any page
Adarsha0ae521dcfd2
diff --git a/src/components/billing-card.tsx b/src/components/billing-card.tsxindex 72007977..355f3ca7 100644--- a/src/components/billing-card.tsx+++ b/src/components/billing-card.tsx@@ -34,6 +34,17 @@ export function BillingCard() {const r = refusal;const link = safeLink(r?.action?.url);const changed = r?.code === "price-changed";+ const [sending, setSending] = useState(false);+ const runAgain = changed ? r?.runAgain : undefined;+ const sendAgain = async () => {+ if (!runAgain) return;+ setSending(true);+ const started = await runAgain().finally(() => setSending(false));+ if (started) {+ setOpen(false);+ void qc.invalidateQueries({ queryKey: ["generations"] });+ }+ };return (<Dialog open={open} onOpenChange={setOpen}><DialogContent className="sm:max-w-sm">@@ -46,7 +57,7 @@ export function BillingCard() {{changed && r?.quote?.text && (<p className="text-[13px] text-muted-foreground">Now: <span className="font-medium text-foreground">{r.quote.text}</span>- {r.quote.sub ? ` · ${r.quote.sub}` : ""}. Press Generate again to run it at this price.+ {r.quote.sub ? ` · ${r.quote.sub}` : ""}.{runAgain ? "" : " Press Generate again to run it at this price."}</p>)}{r?.offer && <p className="text-[13px] text-muted-foreground">{r.offer.text}</p>}@@ -71,7 +82,12 @@ export function BillingCard() {</a></Button>)}- {!link && !r?.offer && (+ {runAgain && (+ <Button size="sm" disabled={sending} onClick={() => void sendAgain()}>+ Run at this price+ </Button>+ )}+ {!link && !r?.offer && !runAgain && (<Button size="sm" onClick={() => setOpen(false)}>OK</Button>diff --git a/src/lib/api.ts b/src/lib/api.tsindex 74682e1d..8faf7f12 100644--- a/src/lib/api.ts+++ b/src/lib/api.ts@@ -28,7 +28,7 @@ import {import { fetchWithin, READ_LIMIT_MS } from "./fetch-within";import { cursorAfter, filterToSearch, type AssetUse, type FeedFilter, type Folder } from "./library";import { markRefusalShown, refusalShown, responseError } from "./refusals";-import { PLACE_ASK_HEADER, RUNS_CHANGED_EVENT } from "./guest-access";+import { PLACE_ASK_HEADER, RUN_PLACE_HEADER, RUN_SHOWN_HEADER, RUNS_CHANGED_EVENT, shownHeader } from "./guest-access";import type { PoolRules } from "./pool-rules";import { HoldFilesCtx } from "./held-files";import { postFile } from "./upload";@@ -1434,6 +1434,29 @@ async function runOnPool(sent: string): Promise<void> {}}+/**+ * A run sent again as it was first sent, with headers added (a changed price shown, or this studio's GPUs asked for):+ * every tool reads them (RUN_SHOWN_HEADER, RUN_PLACE_HEADER), whatever its body. True when it started.+ */+export async function sendRunAgain(input: RequestInfo | URL, init: RequestInit | undefined, add: Record<string, string>): Promise<boolean> {+ const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));+ for (const [k, v] of Object.entries(add)) headers.set(k, v);+ try {+ const res = await window.fetch(input instanceof Request ? input.url : input, { ...init, method: init?.method ?? "POST", headers });+ if (res.ok) {+ window.dispatchEvent(new Event(RUNS_CHANGED_EVENT));+ return true;+ }+ await json(res).catch((e: unknown) => void (refusalShown(e) || toast.error((e as Error).message)));+ } catch {+ toast.error("That didn't start. Try again.");+ }+ return false;+}++/** A body a run can be sent again with (a string: a form or a stream is read once). */+const resendable = (input: RequestInfo | URL, init: RequestInit | undefined): boolean => !(input instanceof Request) && (init?.body === undefined || typeof init.body === "string");+export function watchGuestRefusals(): void {const w = window as typeof window & { __fuobeGuestFetch?: boolean };if (w.__fuobeGuestFetch) return;@@ -1471,18 +1494,26 @@ export function watchGuestRefusals(): void {res.clone().json()- .then((b: Omit<BillingRefusalDetail, "code">) => window.dispatchEvent(new CustomEvent<BillingRefusalDetail>(BILLING_EVENT, { detail: { ...b, code: billing } })))+ .then((b: Omit<BillingRefusalDetail, "code">) => {+ // A changed price: the card offers to run it at the new price (the same run, sent again with that price shown).+ const q = b.quote;+ const again =+ billing === "price-changed" && method === "POST" && q && resendable(input, init) ? () => sendRunAgain(input, init, { [RUN_SHOWN_HEADER]: shownHeader(q) }) : undefined;+ window.dispatchEvent(new CustomEvent<BillingRefusalDetail>(BILLING_EVENT, { detail: { ...b, code: billing, ...(again && { runAgain: again }) } }));+ }).catch(() => {});}// A run that named no place, whose account's own GPU didn't answer: offered on this studio's GPUs, never moved there// by itself.- if (res.status === 409 && res.headers.get(PLACE_ASK_HEADER) === "1" && method === "POST" && requestPath(input) === "/api/generations" && typeof init?.body === "string") {+ if (res.status === 409 && res.headers.get(PLACE_ASK_HEADER) === "1" && method === "POST" && resendable(input, init)) {markRefusalShown(res);- const sent = init.body;+ const sent = init?.body;+ // The studios' runs carry the place in their body; a tool's run in a header (every tool reads it).+ const again = requestPath(input) === "/api/generations" && typeof sent === "string" ? () => void runOnPool(sent) : () => void sendRunAgain(input, init, { [RUN_PLACE_HEADER]: "pool" });res.clone().json()- .then((b: { error?: string }) => toast(b.error ?? "Your GPU isn't answering right now.", { action: { label: "Run on this studio's GPUs", onClick: () => void runOnPool(sent) } }))+ .then((b: { error?: string }) => toast(b.error ?? "Your GPU isn't answering right now.", { action: { label: "Run on this studio's GPUs", onClick: again } })).catch(() => {});}// A run the GPU pre-flight stopped (something missing on the viewer's ComfyUI): the guided fix opens with its plan.diff --git a/src/lib/hosted.ts b/src/lib/hosted.tsindex 7ca0d0d9..bdf52b29 100644--- a/src/lib/hosted.ts+++ b/src/lib/hosted.ts@@ -54,6 +54,8 @@ export interface BillingRefusalDetail {action?: BillingAction;offer?: BillingOffer;quote?: HostedQuote;+ /** A changed price: the same run sent again at the new price (true when it started). */+ runAgain?: () => Promise<boolean>;}/** Fired for every refusal marked x-fuobe-billing (watchGuestRefusals): the billing card opens. */diff --git a/tests/run-again.test.ts b/tests/run-again.test.tsnew file mode 100644index 00000000..dabed93a--- /dev/null+++ b/tests/run-again.test.ts@@ -0,0 +1,100 @@+import { afterEach, describe, expect, it, vi } from "vitest";++// A run refused for a changed price, or offered on this studio's GPUs because the account's own GPU didn't answer, is+// sent again as it was first sent, from any page (a result's Upscale, a retry, a tool), with the new price shown or the+// place asked for in its headers.++const toasts = vi.hoisted(() => ({ shown: [] as { message: string; action?: { label: string; onClick: () => void } }[] }));+vi.mock("sonner", () => ({+ toast: Object.assign((message: string, o?: { action?: { label: string; onClick: () => void } }) => void toasts.shown.push({ message, action: o?.action }), { error: () => {}, warning: () => {} }),+}));++import { sendRunAgain, watchGuestRefusals } from "@/lib/api";+import { PLACE_ASK_HEADER, RUN_PLACE_HEADER, RUN_SHOWN_HEADER, RUNS_CHANGED_EVENT } from "@/lib/guest-access";+import { BILLING_EVENT, BILLING_HEADER, type BillingRefusalDetail } from "@/lib/hosted";++const answer = (status: number, body: Record<string, unknown>, headers: Record<string, string> = {}) =>+ new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json", ...headers } });++const sent: { url: string; init?: RequestInit }[] = [];+const events: { type: string; detail: unknown }[] = [];+let server: (url: string, init?: RequestInit) => Response = () => answer(201, {});++function page() {+ vi.stubGlobal("window", globalThis);+ vi.stubGlobal("location", { pathname: "/apps/influencer", search: "", href: "http://localhost/apps/influencer" });+ vi.stubGlobal("dispatchEvent", (e: Event) => void events.push({ type: e.type, detail: (e as CustomEvent).detail ?? null }));+ vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = input instanceof Request ? new URL(input.url).pathname : String(input);+ sent.push({ url, init });+ return server(url, init);+ });+ (globalThis as { __fuobeGuestFetch?: boolean }).__fuobeGuestFetch = false;+ watchGuestRefusals();+}++afterEach(() => {+ vi.unstubAllGlobals();+ sent.length = 0;+ events.length = 0;+ toasts.shown.length = 0;+});++const settle = () => new Promise((r) => setTimeout(r, 0));++describe("a changed price", () => {+ it("the card can send the same run again at the new price, whatever tool sent it", async () => {+ page();+ const quote = { allowed: true, amount: 9, priceVersion: "v9", text: "9 units" };+ server = (url, init) => (new Headers(init?.headers).get(RUN_SHOWN_HEADER) ? answer(201, { items: [] }) : answer(409, { error: "The price is now 9 units.", quote }, { [BILLING_HEADER]: "price-changed" }));+ const body = JSON.stringify({ engine: "open", state: {} });+ const r = await window.fetch("/api/influencer", { method: "POST", headers: { "Content-Type": "application/json" }, body });+ expect(r.status).toBe(409);+ await settle();+ const card = events.find((e) => e.type === BILLING_EVENT)?.detail as BillingRefusalDetail;+ expect(card.code).toBe("price-changed");+ expect(card.runAgain).toBeTypeOf("function");+ expect(await card.runAgain!()).toBe(true);+ const again = sent.at(-1)!;+ expect(again.url).toBe("/api/influencer");+ expect(again.init?.body).toBe(body);+ expect(JSON.parse(decodeURIComponent(new Headers(again.init?.headers).get(RUN_SHOWN_HEADER)!))).toEqual({ amount: 9, priceVersion: "v9" });+ expect(new Headers(again.init?.headers).get("content-type")).toBe("application/json");+ expect(events.some((e) => e.type === RUNS_CHANGED_EVENT)).toBe(true);+ });++ it("any other refusal, or a body that can't be sent twice, offers nothing to send again", async () => {+ page();+ server = () => answer(402, { error: "Not enough." }, { [BILLING_HEADER]: "balance" });+ await window.fetch("/api/influencer", { method: "POST", body: "{}" });+ await settle();+ expect((events.find((e) => e.type === BILLING_EVENT)?.detail as BillingRefusalDetail).runAgain).toBeUndefined();+ events.length = 0;+ server = () => answer(409, { error: "Now 9.", quote: { allowed: true, amount: 9, priceVersion: "v9", text: "9" } }, { [BILLING_HEADER]: "price-changed" });+ await window.fetch("/api/uploads", { method: "POST", body: new Blob(["x"]) });+ await settle();+ expect((events.find((e) => e.type === BILLING_EVENT)?.detail as BillingRefusalDetail).runAgain).toBeUndefined();+ });+});++describe("an account's own GPU that didn't answer", () => {+ it("a tool's run is offered on this studio's GPUs and sent again with that place in a header", async () => {+ page();+ server = (url, init) => (new Headers(init?.headers).get(RUN_PLACE_HEADER) === "pool" ? answer(201, {}) : answer(409, { error: "Your GPU isn't answering right now." }, { [PLACE_ASK_HEADER]: "1" }));+ await window.fetch("/api/turnaround", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" });+ await settle();+ const offer = toasts.shown.at(-1)!;+ expect(offer.action?.label).toBe("Run on this studio's GPUs");+ offer.action!.onClick();+ await settle();+ await settle();+ expect(sent.at(-1)!.url).toBe("/api/turnaround");+ expect(new Headers(sent.at(-1)!.init?.headers).get(RUN_PLACE_HEADER)).toBe("pool");+ });++ it("sendRunAgain says when the run still didn't start", async () => {+ page();+ server = () => answer(500, { error: "Something went wrong" });+ expect(await sendRunAgain("/api/turnaround", { method: "POST", body: "{}" }, { [RUN_PLACE_HEADER]: "pool" })).toBe(false);+ });+});