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
Hosted runs: the price check before Run asks again by itself
Adarshc56afb1f480c
diff --git a/src/components/billing-card.tsx b/src/components/billing-card.tsxindex 9ad0f590..72007977 100644--- a/src/components/billing-card.tsx+++ b/src/components/billing-card.tsx@@ -6,7 +6,7 @@ import Link from "next/link";import { useEffect, useState } from "react";import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";-import { BILLING_EVENT, safeLink, useInterest, type BillingRefusalDetail } from "@/lib/hosted";+import { BILLING_EVENT, refreshPriceChecks, safeLink, useInterest, type BillingRefusalDetail } from "@/lib/hosted";/*** One card for a run the billing service refused (x-fuobe-billing; src/server/billing.ts): the service's own words,@@ -25,7 +25,7 @@ export function BillingCard() {setRefusal(d);setOpen(true);// A new price (or the balance it was refused for): the composer and the chip ask again.- void qc.invalidateQueries({ queryKey: ["hosted-quote"] });+ refreshPriceChecks(qc);void qc.invalidateQueries({ queryKey: ["status"] });};window.addEventListener(BILLING_EVENT, onRefusal);diff --git a/src/components/guest-prompt.tsx b/src/components/guest-prompt.tsxindex 6c7aa976..c9d7ecd9 100644--- a/src/components/guest-prompt.tsx+++ b/src/components/guest-prompt.tsx@@ -28,6 +28,7 @@ import { ConnectField, useSettings } from "@/components/connect-field";import { FAL_KEYS_URL } from "@/lib/connections";import { CLOUD_KEY } from "@/lib/your-keys";import { RUNS_CHANGED_EVENT } from "@/lib/guest-access";+import { refreshPriceChecks } from "@/lib/hosted";/*** The cards a public studio shows when something is refused (watchGuestRefusals): "Create a free@@ -120,6 +121,7 @@ export function GuestPrompt() {// A run started from a toast (not a page's own button): the lists show it.const runs = () => {for (const key of ["generations", "library", "library-facets"]) void qc.invalidateQueries({ queryKey: [key] });+ refreshPriceChecks(qc);};window.addEventListener(CONNECT_GPU_EVENT, gpu);window.addEventListener(RUNS_CHANGED_EVENT, runs);diff --git a/src/components/studio/feed.tsx b/src/components/studio/feed.tsxindex 6c6c746c..a2c4deea 100644--- a/src/components/studio/feed.tsx+++ b/src/components/studio/feed.tsx@@ -1,7 +1,9 @@"use client";import { Cloud, Copy, Cpu, Download, FolderDown, Heart, MoreHorizontal, RotateCcw, Sparkles, Trash2, Wrench, X } from "lucide-react";+import { useQueryClient } from "@tanstack/react-query";import { lineWords } from "@/lib/pool-line";+import { refreshPriceChecks } from "@/lib/hosted";import { openGpuSetup } from "@/hooks/use-gpu";import { useLocalJob } from "@/components/gpu/computer-runner";import { jobFraction, jobWords, POOL_WORDS } from "@/lib/relay";@@ -57,6 +59,10 @@ export function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {// recovery, its place kept, with no progress from an earlier attempt), then "Working" with its progress.const pool = g.place === "pool";const inLine = pool && g.status === "queued";+ // Its tile leaves once it is done (its result, or one plain sentence): the price check before the next Run asks again,+ // so a refusal for runs going (or the line's wait) doesn't outlast it.+ const qc = useQueryClient();+ useEffect(() => (pool ? () => refreshPriceChecks(qc) : undefined), [pool, qc]);const label = pool? inLine? g.queuediff --git a/src/lib/api.ts b/src/lib/api.tsindex a89319d7..60cbf300 100644--- a/src/lib/api.ts+++ b/src/lib/api.ts@@ -35,7 +35,7 @@ import { postFile } from "./upload";import type { ShareCreated, ShareInfo, ShareListItem, SharePatch, ShareRequest } from "./share";import type { AccessSummary } from "./model-access";import { ADD_KEY_HEADER, isCloudProvider, type CloudProvider } from "./your-keys";-import { BILLING_EVENT, BILLING_HEADER, type BillingAction, type BillingRefusalDetail, type HostedBalance } from "./hosted";+import { BILLING_EVENT, BILLING_HEADER, refreshPriceChecks, type BillingAction, type BillingRefusalDetail, type HostedBalance } from "./hosted";export interface Asset {id: string;@@ -543,6 +543,8 @@ export function useCreateGeneration() {for (const g of items) applyEvent(qc, { type: "generation", generation: { ...g, deletedAt: null } });void qc.invalidateQueries({ queryKey: ["generations"] });void qc.invalidateQueries({ queryKey: ["library-facets"] });+ // The runs going and the line changed: the price check before the next Run asks again.+ refreshPriceChecks(qc);},});}diff --git a/src/lib/hosted.ts b/src/lib/hosted.tsindex f76b9142..4e95e1a3 100644--- a/src/lib/hosted.ts+++ b/src/lib/hosted.ts@@ -1,7 +1,7 @@"use client";import { useEffect, useState } from "react";-import { useMutation, useQuery } from "@tanstack/react-query";+import { useMutation, useQuery, type QueryClient } from "@tanstack/react-query";import { toast } from "sonner";import type { GenerationRequest } from "./catalog/types";import { lineWords } from "./pool-line";@@ -99,23 +99,49 @@ export interface HostedCheck {line?: HostedLine;}+/** The price checks' cache key: every check starts with it, so one call asks them all again. */+export const HOSTED_QUOTE_KEY = "hosted-quote";+/**- * The price of a run on this studio's GPUs: `?preview=1` with `place: "pool"`. `body` is the request as JSON (null:- * nothing to price). The answer's `quote` is absent when the run would go to the person's own GPU or key.+ * How often the price check is asked again with no change to the draft: soon while it refuses the run (a limit, busy,+ * paused: Run comes back on its own once that passes), less often while it shows a place in line (the place and the+ * wait stay current), never otherwise.*/-export function useHostedQuote(body: string | null) {- return useQuery({- queryKey: ["hosted-quote", body],+export function quoteRefetchMs(check: HostedCheck | null | undefined): number | false {+ if (check?.quote?.allowed === false) return 15_000;+ if (check?.place === "pool" && check.line) return 30_000;+ return false;+}++/** The query behind useHostedQuote, for a body (the request as JSON; null: nothing to price). */+export function hostedQuoteQuery(body: string | null) {+ return {+ queryKey: [HOSTED_QUOTE_KEY, body] as const,enabled: !!body,staleTime: 10_000,retry: false,+ refetchInterval: (q: { state: { data: HostedCheck | null | undefined } }) => quoteRefetchMs(q.state.data),queryFn: async (): Promise<HostedCheck | null> => {const res = await fetch("/api/generations?preview=1", { method: "POST", headers: { "Content-Type": "application/json" }, body: body! });if (!res.ok) return null;const b = (await res.json()) as HostedCheck;return { place: b.place, quote: b.quote, ...(b.line && { line: b.line }) };},- });+ };+}++/**+ * The price of a run on this studio's GPUs: `?preview=1` with `place: "pool"`. `body` is the request as JSON (null:+ * nothing to price). The answer's `quote` is absent when the run would go to the person's own GPU or key. It is asked+ * again by itself (quoteRefetchMs), and at once when a run starts or one on this studio's GPUs ends (refreshPriceChecks).+ */+export function useHostedQuote(body: string | null) {+ return useQuery(hostedQuoteQuery(body));+}++/** Ask every price check again now: a run started or ended, so the runs going, the line and its wait have changed. */+export function refreshPriceChecks(qc: QueryClient): void {+ void qc.invalidateQueries({ queryKey: [HOSTED_QUOTE_KEY] });}/**diff --git a/tests/hosted-quote-refresh.test.ts b/tests/hosted-quote-refresh.test.tsnew file mode 100644index 00000000..058e5c63--- /dev/null+++ b/tests/hosted-quote-refresh.test.ts@@ -0,0 +1,95 @@+import fs from "node:fs";+import path from "node:path";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it, vi } from "vitest";++/*+ * The price check before Run on this studio's GPUs (hosted runs) asks again by itself: soon while it refuses the run (a+ * limit on runs going, busy, paused), so Run comes back once that passes with no change to the draft; less often while+ * it shows a place in line, so the place and the wait stay current; and at once when a run starts or one ends.+ */++// A browser page: the query library runs its timers only outside a server.+vi.stubGlobal("window", new EventTarget());++const { QueryClient, QueryClientProvider, QueryObserver } = await import("@tanstack/react-query");+const { HOSTED_QUOTE_KEY, hostedQuoteQuery, poolRunState, quoteRefetchMs, refreshPriceChecks } = await import("@/lib/hosted");+const { useCreateGeneration } = await import("@/lib/api");++const body = JSON.stringify({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox", place: "pool" });+const limit = { place: "pool" as const, quote: { allowed: false, amount: 0, priceVersion: "", text: "You have 2 runs going. Start this one when one finishes.", code: "limit" }, line: { place: 1, etaSeconds: null } };+const free = { place: "pool" as const, quote: { allowed: true, amount: 0, priceVersion: "v1", text: "Free" }, line: { place: 2, etaSeconds: 40 } };++describe("the price check asks again by itself", () => {+ it("soon while refused, less often while it shows a place in line, never for a run elsewhere", () => {+ expect(quoteRefetchMs(limit)).toBe(15_000);+ for (const code of ["busy", "paused", "not-offered"]) expect(quoteRefetchMs({ ...limit, quote: { ...limit.quote, code } })).toBe(15_000);+ expect(quoteRefetchMs(free)).toBe(30_000);+ expect(quoteRefetchMs({})).toBe(false);+ expect(quoteRefetchMs(null)).toBe(false);+ });++ it("a refused check is asked again with no change to the draft, and Run turns on once the runs going finish", async () => {+ vi.useFakeTimers();+ const answers: unknown[] = [limit, free];+ const sent: string[] = [];+ vi.stubGlobal("fetch", async (_url: string, init: RequestInit) => {+ sent.push(String(init.body));+ return Response.json(answers.shift() ?? free);+ });+ try {+ const qc = new QueryClient();+ const observer = new QueryObserver(qc, hostedQuoteQuery(body));+ const stop = observer.subscribe(() => {});+ await vi.advanceTimersByTimeAsync(0);+ expect(poolRunState(observer.getCurrentResult().data)).toMatchObject({ refused: true, text: limit.quote.text });+ // Both runs finish; nothing about the draft changes: the check is asked again, and Run is on.+ await vi.advanceTimersByTimeAsync(15_000);+ expect(sent).toEqual([body, body]);+ expect(poolRunState(observer.getCurrentResult().data)).toMatchObject({ refused: false, text: "Free", wait: "In line · 2nd · about 40 s" });+ // A run starts or ends: asked again at once, not only on the next tick.+ refreshPriceChecks(qc);+ await vi.advanceTimersByTimeAsync(0);+ expect(sent).toHaveLength(3);+ // While it shows a place in line, every 30 s.+ await vi.advanceTimersByTimeAsync(30_000);+ expect(sent).toHaveLength(4);+ stop();+ } finally {+ vi.useRealTimers();+ vi.unstubAllGlobals();+ vi.stubGlobal("window", new EventTarget());+ }+ });++ it("a run on this studio's GPUs that ends, or one started from a toast, asks it again too", () => {+ const src = (f: string) => fs.readFileSync(path.join(process.cwd(), f), "utf8");+ // The run's tile (In line, Working) leaves once it is done: as it goes, the checks ask again.+ const feed = src("src/components/studio/feed.tsx");+ const tile = feed.slice(feed.indexOf("export function PendingTile"), feed.indexOf("export function FailedTile"));+ expect(tile).toContain("useEffect(() => (pool ? () => refreshPriceChecks(qc) : undefined), [pool, qc]);");+ const toast = src("src/components/guest-prompt.tsx");+ expect(toast.slice(toast.indexOf("const runs = () => {"), toast.indexOf("window.addEventListener(CONNECT_GPU_EVENT"))).toContain("refreshPriceChecks(qc)");+ });++ it("a run made from a composer asks it again (the runs going and the line changed)", async () => {+ vi.stubGlobal("fetch", async () => Response.json({ items: [] }, { status: 201 }));+ try {+ const qc = new QueryClient();+ qc.setQueryData([HOSTED_QUOTE_KEY, body], limit);+ let create: ReturnType<typeof useCreateGeneration> | undefined;+ function Probe() {+ create = useCreateGeneration();+ return null;+ }+ renderToStaticMarkup(createElement(QueryClientProvider, { client: qc }, createElement(Probe)));+ expect(qc.getQueryState([HOSTED_QUOTE_KEY, body])?.isInvalidated).toBe(false);+ await create!.mutateAsync({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" });+ expect(qc.getQueryState([HOSTED_QUOTE_KEY, body])?.isInvalidated).toBe(true);+ } finally {+ vi.unstubAllGlobals();+ vi.stubGlobal("window", new EventTarget());+ }+ });+});