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
Tool pages: a run on this install's GPUs says their price and place in line, and every press sends its id
Adarsh6c373551d7a1
diff --git a/src/components/audio-tools/audio-tools.tsx b/src/components/audio-tools/audio-tools.tsxindex bcb59152..07251143 100644--- a/src/components/audio-tools/audio-tools.tsx+++ b/src/components/audio-tools/audio-tools.tsx@@ -30,6 +30,7 @@ import { parseCueTime } from "@/lib/av/cue-edit";import type { Engine } from "@/lib/catalog/types";import { cn } from "@/lib/utils";import { toastError } from "@/lib/refusals";+import { usePoolRun } from "@/components/studio/pool-price";import { useAudioToolPreview, useAudioToolRun, useSettled, type AudioToolBody } from "./hooks";/**@@ -233,6 +234,8 @@ function RunBar({const error = preview.error ? (preview.error as Error).message : null;const p = preview.data;const shown = blocker ?? error;+ // A run on this studio's GPUs: the service's price and the place in line, and Run off when it is refused.+ const { pool, off, go } = usePoolRun(p);return (<div className="space-y-2">{!shown && p && (@@ -257,13 +260,13 @@ function RunBar({<>{p.length !== null && <span className="font-mono text-foreground">{clock(p.length)}</span>}{p.length !== null && " · "}- <span className="font-mono text-foreground">{money(p, engine)}</span>+ <span className="font-mono text-foreground">{pool?.text ?? money(p, engine)}</span></>) : ("Pricing…"))}</p>- <Button size="lg" className={cn("rounded-full", (blocker || error) && "bg-muted text-subtle-foreground hover:bg-muted")} onClick={onRun} disabled={pending}>+ <Button size="lg" className={cn("rounded-full", (blocker || error) && "bg-muted text-subtle-foreground hover:bg-muted")} onClick={() => go(onRun)} disabled={pending || (off && !shown)}>{pending ? <Loader2 className="size-4 animate-spin" /> : <Icon className="size-4" />} {label}</Button></div>diff --git a/src/components/audio-tools/clean-voice-switch.tsx b/src/components/audio-tools/clean-voice-switch.tsxindex 71751869..e6866e5a 100644--- a/src/components/audio-tools/clean-voice-switch.tsx+++ b/src/components/audio-tools/clean-voice-switch.tsx@@ -1,6 +1,7 @@"use client";import { AudioLines, Loader2, Sparkles } from "lucide-react";+import { nanoid } from "nanoid";import { useCallback, useEffect, useId, useRef, useState, useSyncExternalStore } from "react";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";import { Switch } from "@/components/ui/switch";@@ -121,7 +122,7 @@ export const cleanedName = (name?: string) => `${(name ?? "Recording").replace(//** Clean one audio file on the open engine; resolves with the clean file's address. */export async function cleanVoiceFile(media: string, name: string | undefined, signal: AbortSignal): Promise<{ url: string; generation: Generation }> {- const run = await post<{ result: Generation }>({ tool: "clean", engine: "open", media, kind: "audio", ...(name && { name: name.slice(0, 200) }), strength: "full", level: "match", quality: "auto", background: "remove" });+ const run = await post<{ result: Generation }>({ tool: "clean", engine: "open", media, kind: "audio", ...(name && { name: name.slice(0, 200) }), strength: "full", level: "match", quality: "auto", background: "remove", requestId: nanoid(16) });const g = await settle(run.result.id, signal);const out = g.outputs.find((o) => o.kind === "audio");if (!out) throw new Error("The clean voice didn't come back");diff --git a/src/components/audio-tools/hooks.ts b/src/components/audio-tools/hooks.tsindex e91ca905..67f7aa86 100644--- a/src/components/audio-tools/hooks.ts+++ b/src/components/audio-tools/hooks.ts@@ -1,6 +1,7 @@"use client";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { nanoid } from "nanoid";import { useEffect, useState } from "react";import type { AudioToolPreview } from "@/lib/av/audio-tools";import type { Engine, Generation } from "@/lib/catalog/types";@@ -69,7 +70,7 @@ export type AudioToolBody =sourceDuration?: number;};-async function post<T>(url: string, body: AudioToolBody): Promise<T> {+async function post<T>(url: string, body: AudioToolBody & { requestId?: string }): Promise<T> {const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });const j = (await res.json().catch(() => ({}))) as T & { error?: string };if (!res.ok) throw responseError(res, j.error ?? "Something went wrong. Please try again.");@@ -100,7 +101,8 @@ export function useAudioToolPreview(body: AudioToolBody | null) {export function useAudioToolRun() {const qc = useQueryClient();return useMutation({- mutationFn: (body: AudioToolBody) => post<{ batchId: string; result: Generation; items: Generation[] }>("/api/audio-tools", body),+ // Each press carries its own id: a resend of it gets the first run (src/server/account-tool-run.ts onceForAccount).+ mutationFn: (body: AudioToolBody & { requestId?: string }) => post<{ batchId: string; result: Generation; items: Generation[] }>("/api/audio-tools", { ...body, requestId: body.requestId ?? nanoid(16) }),onSuccess: () => {// The tab that runs this person's jobs on the ComfyUI on this computer (an account's "Your GPU") asks at once.window.dispatchEvent(new Event(COMPUTER_KICK_EVENT));diff --git a/src/components/audio-tools/split-tool.tsx b/src/components/audio-tools/split-tool.tsxindex 1ec5b06f..3dc32633 100644--- a/src/components/audio-tools/split-tool.tsx+++ b/src/components/audio-tools/split-tool.tsx@@ -58,6 +58,8 @@ import { downloadHref } from "@/lib/library";import { probeUrl } from "@/lib/media-probe";import { cn } from "@/lib/utils";import { responseError, toastError } from "@/lib/refusals";+import { usePoolRun } from "@/components/studio/pool-price";+import { toolPoolPrice } from "@/lib/run-place";import { useAudioToolPreview, useAudioToolRun, useSettled, type AudioToolBody } from "./hooks";import { CleanDialoguePanel } from "./clean-dialogue-panel";import { CLEAN_DIALOGUE_PRESET, mixPresetFor } from "@/lib/av/clean-dialogue";@@ -594,7 +596,11 @@ function Mixer({ stems, source, engine, initial = ORIGINAL_MIX }: { stems: Stem[}return backgroundLowered(peak);}, [bed]);- const remuxCost = remuxPrice.data ? (remuxPrice.data.demo ? "Placeholder · free" : engine === "open" ? "Free · your GPU" : remuxPrice.data.costUsd !== null && remuxPrice.data.costUsd < 0.01 ? "under $0.01" : `≈ $${remuxPrice.data.costUsd?.toFixed(2)}`) : null;+ // On this studio's GPUs: the service's price and the place in line ("Free · your GPU" is for the person's own GPU).+ const remuxCost = remuxPrice.data+ ? (toolPoolPrice(remuxPrice.data)?.text ??+ (remuxPrice.data.demo ? "Placeholder · free" : engine === "open" ? "Free · your GPU" : remuxPrice.data.costUsd !== null && remuxPrice.data.costUsd < 0.01 ? "under $0.01" : `≈ $${remuxPrice.data.costUsd?.toFixed(2)}`))+ : null;return (<section aria-labelledby="mixer" className="space-y-3">@@ -753,17 +759,22 @@ export function SplitSoundtrackTool() {const cloudProblem = mode === "cloud" ? CLOUD_ONLY_PROBLEM : CLOUD_SPLIT_PROBLEM;const blocker = !source ? "Add a soundtrack to split" : source.uploading ? "Uploading…" : engine === "cloud" ? cloudProblem : null;const error = preview.error ? (preview.error as Error).message : null;+ // A run on this studio's GPUs: nothing is sent while the service refuses it now; its own setup opens instead of it.+ const poolRun = usePoolRun(p);const go = () => {if (blocker) return void toast(blocker);if (error) return void toast.error(error);if (!body) return;- run.mutate(body, {- onSuccess: (r) => {- setResultId(r.result.id);- toast.success("Splitting…");- },- onError: (e) => toastError(e),- });+ if (poolRun.off) return void toast(poolRun.pool!.text);+ poolRun.go(() =>+ run.mutate(body, {+ onSuccess: (r) => {+ setResultId(r.result.id);+ toast.success("Splitting…");+ },+ onError: (e) => toastError(e),+ }),+ );};const g = result.data;const stems = useMemo(() => (g?.status === "succeeded" ? stemsOf(g.outputs) : []), [g]);diff --git a/src/components/cinema/hooks.ts b/src/components/cinema/hooks.tsindex 74889b63..2eb86288 100644--- a/src/components/cinema/hooks.ts+++ b/src/components/cinema/hooks.ts@@ -1,6 +1,7 @@"use client";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { nanoid } from "nanoid";import { useEffect, useState } from "react";import type { CinemaFolder, CinemaGenerateInput, CinemaProject, CinemaTile, DirectorMessage, DirectorSettings } from "@/lib/catalog/cinema";import type { Generation } from "@/lib/catalog/types";@@ -244,7 +245,8 @@ export function useItemActions(projectId: string) {await fetch(`/api/generations/${g.id}/cancel`, { method: "POST" }).finally(settle);},retry: async (g: CinemaGeneration) => {- await send(`/api/cinema/projects/${g.projectId ?? projectId}/items/${g.id}/retry`, "POST").finally(settle);+ // Its own id: a resend of this press gets the first retry (src/server/account-tool-run.ts onceForAccount).+ await send(`/api/cinema/projects/${g.projectId ?? projectId}/items/${g.id}/retry`, "POST", { requestId: nanoid(16) }).finally(settle);kick();},/** Finish in 2K: a MiniMax H3 take made again at 2K (fal) or redrawn at 2K on your GPU, in the same folder. */@@ -260,13 +262,14 @@ export function useItemActions(projectId: string) {};}-export type GenerateBody = { input: Omit<CinemaGenerateInput, "brief">; folderId: string | null };+export type GenerateBody = { input: Omit<CinemaGenerateInput, "brief">; folderId: string | null; requestId?: string };export type GenerateResult = { items: Generation[]; folderId: string | null; plan: { notes: string[]; costUsd: number | null; outputs: number; modelId: string } };export function useCinemaGenerate(projectId: string) {const qc = useQueryClient();return useMutation({- mutationFn: (body: GenerateBody) => send<GenerateResult>(`/api/cinema/projects/${projectId}/generate`, "POST", body),+ // Each press carries its own id: a resend of it gets the first take (src/server/account-tool-run.ts onceForAccount).+ mutationFn: (body: GenerateBody) => send<GenerateResult>(`/api/cinema/projects/${projectId}/generate`, "POST", { ...body, requestId: body.requestId ?? nanoid(16) }),onSuccess: (res, body) => {kick();// New takes appear at once (where the server filed them); the stream and polling take over.diff --git a/src/components/content-factory/hooks.ts b/src/components/content-factory/hooks.tsindex 9b2b8e22..47ba96b0 100644--- a/src/components/content-factory/hooks.ts+++ b/src/components/content-factory/hooks.ts@@ -1,6 +1,7 @@"use client";import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { nanoid } from "nanoid";import type { ClaudePrompt, SeriesCard, SeriesEstimate, SeriesSettings, SeriesView, StyleBrief } from "@/lib/catalog/content-factory";import type { NarratorVoice } from "@/lib/catalog/faceless";import type { Engine } from "@/lib/catalog/types";@@ -30,7 +31,9 @@ async function json<T>(res: Response): Promise<T> {const ASKS = /\/(estimate|claude)$/;const send = async <T,>(url: string, method: string, body?: unknown) => {- const out = await json<T>(await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) }));+ // Each POST is one press: its own id, so a resend of it gets the first run (src/server/account-tool-run.ts onceForAccount).+ const press: Record<string, string> = method === "POST" ? { "x-request-id": nanoid(16) } : {};+ const out = await json<T>(await fetch(url, { method, headers: { "Content-Type": "application/json", ...press }, body: body === undefined ? undefined : JSON.stringify(body) }));// A run may have started (a render, a reading, a picture): the tab that runs this person's jobs on the ComfyUI on this// computer (an account's "Your GPU") asks for them at once, as after a studio run.if (method === "POST" && !ASKS.test(url) && !(url.endsWith("/change") && !(body as { apply?: boolean } | undefined)?.apply)) window.dispatchEvent(new Event(COMPUTER_KICK_EVENT));diff --git a/src/components/dub/dub-studio.tsx b/src/components/dub/dub-studio.tsxindex 4c6b176d..c1398b4e 100644--- a/src/components/dub/dub-studio.tsx+++ b/src/components/dub/dub-studio.tsx@@ -45,7 +45,9 @@ import {} from "@/lib/av/dub";import { languageByCode, supportsTarget, type DubRoute } from "@/lib/av/languages";import type { Cue } from "@/lib/cues";+import { toolPoolPrice } from "@/lib/run-place";import { cn } from "@/lib/utils";+import { usePoolRun } from "@/components/studio/pool-price";import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";import { toastError } from "@/lib/refusals";import { useDubActions, useDubPrice, useDubSessions, useVoicePrice } from "./hooks";@@ -163,9 +165,12 @@ function NewDub({ onStarted }: { onStarted: (id: string) => void }) {? { engine, mode: oneShot ? ("oneshot" as const) : ("steps" as const), model: oneShot ? model : undefined, video: video.ref, source, targets: usable, duration, ...(engine === "open" && { voiceSplit: split }) }: null;const price = useDubPrice(body);+ // A run on this studio's GPUs: nothing is sent while the service refuses it now; its own setup opens instead of it.+ const poolRun = usePoolRun(price.data);const start = () => {if (blocker || !body) return void toast(blocker, { id: "dub-blocker" });- create.mutate(+ if (poolRun.off) return void toast(poolRun.pool!.text, { id: "dub-blocker" });+ poolRun.go(() => create.mutate({ ...body, title: video!.name?.replace(/\.[a-z0-9]+$/i, "") },{onSuccess: (s) => {@@ -176,7 +181,7 @@ function NewDub({ onStarted }: { onStarted: (id: string) => void }) {},onError: (e) => toastError(e),},- );+ ));};return (<div className="pb-10">@@ -346,7 +351,10 @@ function NewDub({ onStarted }: { onStarted: (id: string) => void }) {);}-/** The price of the next step, next to its button: "≈ $8.13 + ElevenLabs v4", "Placeholder · free", "Free on your GPU". */+/**+ * The price of the next step, next to its button: "≈ $8.13 + ElevenLabs v4", "Placeholder · free", "Free on your GPU"; on+ * this studio's GPUs, the service's price and the place in line.+ */function PriceNote({ price, loading, error, hint }: { price?: DubPrice; loading?: boolean; error?: Error | null; hint?: string }) {if (loading) return <Skeleton className="h-4 w-20" aria-label="Pricing" />;if (error) return <span className="max-w-[16rem] text-right text-[12px] leading-snug text-muted-foreground">{error.message}</span>;@@ -354,7 +362,7 @@ function PriceNote({ price, loading, error, hint }: { price?: DubPrice; loading?const extra = price.unpriced.length ? `${price.unpriced.join(" and ")} bill${price.unpriced.length === 1 ? "s" : ""} by the provider's own rate (per character or token).` : undefined;return (<span className="text-right text-[12px] leading-snug" title={[extra, hint].filter(Boolean).join(" ") || undefined}>- <span className="font-medium tabular-nums">{priceLine(price)}</span>+ <span className="font-medium tabular-nums">{toolPoolPrice(price)?.text ?? priceLine(price)}</span>{price.steps > 1 && <span className="block text-muted-foreground">{price.steps} steps</span>}</span>);@@ -638,11 +646,17 @@ function Review({ s, lang, time, onSeek }: { s: DubSessionView; lang: string; ticonst crowded = useMemo(() => crowdedLines(cues, s.duration), [cues, s.duration]);const price = useVoicePrice(s.id, lang, lipsync, cues, stage !== "preparing" && !problems.length);const name = languageByCode(lang)?.name ?? lang;- const start = (c: Cue[]) =>- voice.mutate(- { id: s.id, lang, cues: c, lipsync },- { onSuccess: () => toast.success(`Voicing ${name}`), onError: (e) => toastError(e) },+ // A run on this studio's GPUs: nothing is sent while the service refuses it now; its own setup opens instead of it.+ const poolRun = usePoolRun(price.data);+ const start = (c: Cue[]) => {+ if (poolRun.off) return void toast(poolRun.pool!.text, { id: "dub-blocker" });+ poolRun.go(() =>+ voice.mutate(+ { id: s.id, lang, cues: c, lipsync },+ { onSuccess: () => toast.success(`Voicing ${name}`), onError: (e) => toastError(e) },+ ),);+ };return (<><Paneldiff --git a/src/components/dub/hooks.ts b/src/components/dub/hooks.tsindex de254c5f..432ad61a 100644--- a/src/components/dub/hooks.ts+++ b/src/components/dub/hooks.ts@@ -1,6 +1,7 @@"use client";import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { nanoid } from "nanoid";import { useEffect, useState } from "react";import { COMPUTER_KICK_EVENT, useGenerationEvents } from "@/lib/api";import type { DubPrice, DubSessionView, OneShotModel, VoiceSplit } from "@/lib/av/dub";@@ -91,7 +92,8 @@ export function useDubActions() {const qc = useQueryClient();const put = (s: DubSessionView) => qc.setQueryData<DubSessionView[]>(["dub"], (xs) => (xs ? [s, ...xs.filter((x) => x.id !== s.id)] : [s]));const create = useMutation({- mutationFn: async (body: NewDub) => json<DubSessionView>(await fetch("/api/dub", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) })),+ // Each press carries its own id: a resend of it gets the first dub (src/server/account-tool-run.ts onceForAccount).+ mutationFn: async (body: NewDub) => json<DubSessionView>(await fetch("/api/dub", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...body, requestId: nanoid(16) }) })),onSuccess: (s) => {kick();put(s);@@ -110,7 +112,7 @@ export function useDubActions() {});const voice = useMutation({mutationFn: async ({ id, lang, cues, lipsync }: { id: string; lang: string; cues?: Cue[]; lipsync?: boolean }) =>- json<DubSessionView>(await fetch(`/api/dub/${id}/voice`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ lang, cues, lipsync }) })),+ json<DubSessionView>(await fetch(`/api/dub/${id}/voice`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ lang, cues, lipsync, requestId: nanoid(16) }) })),onSuccess: (s) => {kick();put(s);diff --git a/src/components/faceless/hooks.ts b/src/components/faceless/hooks.tsindex 7e0828bf..061743f3 100644--- a/src/components/faceless/hooks.ts+++ b/src/components/faceless/hooks.ts@@ -1,6 +1,7 @@"use client";import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { nanoid } from "nanoid";import { useEffect, useRef, useState } from "react";import { COMPUTER_KICK_EVENT, useGenerationEvents } from "@/lib/api";import type {@@ -34,7 +35,9 @@ async function json<T>(res: Response): Promise<T> {const ASKS = /\/(estimate|topics|link)$/;const send = async <T,>(url: string, method: string, body?: unknown) => {- const out = await json<T>(await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) }));+ // Each POST is one press: its own id, so a resend of it gets the first run (src/server/account-tool-run.ts onceForAccount).+ const press: Record<string, string> = method === "POST" ? { "x-request-id": nanoid(16) } : {};+ const out = await json<T>(await fetch(url, { method, headers: { "Content-Type": "application/json", ...press }, body: body === undefined ? undefined : JSON.stringify(body) }));// A run may have started (a render, a reading, a picture): the tab that runs this person's jobs on the ComfyUI on this// computer (an account's "Your GPU") asks for them at once, as after a studio run.if (method === "POST" && !ASKS.test(url) && !(url.endsWith("/change") && !(body as { apply?: boolean } | undefined)?.apply)) window.dispatchEvent(new Event(COMPUTER_KICK_EVENT));diff --git a/src/components/fashion/character-sheet.tsx b/src/components/fashion/character-sheet.tsxindex f1ca28ba..c22abc3b 100644--- a/src/components/fashion/character-sheet.tsx+++ b/src/components/fashion/character-sheet.tsx@@ -240,6 +240,8 @@ export function CharacterSheetView({ fields, defaults }: { fields: CastFieldDataaskRun(() => {if (mode === "reference" && !photos.length) return toast("Upload at least 1 image");if (!body) return toast(mode === "describe" ? "Describe your character first" : "Wait for the uploads to finish");+ // Not taken now (the price check said why): nothing is sent.+ if (preview.data?.error) return toast(preview.data.error);run.mutate(body, {// The run line already says which model runs and why (its notes), so no toast here.onSuccess: (r) => setIds((xs) => [...r.items.map((g) => g.id), ...xs]),diff --git a/src/components/fly-around-run.ts b/src/components/fly-around-run.tsindex dfe41822..b85abb8f 100644--- a/src/components/fly-around-run.ts+++ b/src/components/fly-around-run.ts@@ -1,6 +1,7 @@"use client";import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { nanoid } from "nanoid";import type { CameraKey } from "@/lib/camera-path";import type { ExactOrbit } from "@/lib/exact-orbit";import type { Engine, Generation } from "@/lib/catalog/types";@@ -63,7 +64,8 @@ export function useFlyAround(body: FlyAroundBody | null) {staleTime: 15_000,});const run = useMutation({- mutationFn: (b: FlyAroundBody) => post<{ items: Generation[]; final: Generation }>("/api/fly-around", b),+ // Each press carries its own id: a resend of it gets the first run (src/server/account-tool-run.ts onceForAccount).+ mutationFn: (b: FlyAroundBody) => post<{ items: Generation[]; final: Generation }>("/api/fly-around", { ...b, requestId: nanoid(16) }),onSuccess: () => {// The tab that runs this person's jobs on the ComfyUI on this computer (an account's "Your GPU") asks for them at once.window.dispatchEvent(new Event(COMPUTER_KICK_EVENT));diff --git a/src/components/genjutsu/hooks.ts b/src/components/genjutsu/hooks.tsindex 7292e791..db07e544 100644--- a/src/components/genjutsu/hooks.ts+++ b/src/components/genjutsu/hooks.ts@@ -2,6 +2,7 @@import type { OriginalSound } from "@/lib/av/original-sound";import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { nanoid } from "nanoid";import type { CharacterOptions } from "@/lib/catalog/character-swap";import type { FinishOptions, GenjutsuLook, GenjutsuMode, GenjutsuTarget, GenjutsuTier, MakerSource, ObjectEdit, PictureOptions } from "@/lib/catalog/genjutsu";import type { Engine, Generation, PixelPoint } from "@/lib/catalog/types";@@ -109,14 +110,15 @@ export function useDescribeCharacter() {export function useDescribeScene() {return useMutation({mutationFn: (b: { engine: "open"; source: { url: string; duration?: number }; range: { start: number; end: number }; frame?: string; ownPerson?: boolean }) =>- send<{ id: string; modelId: string }>("/api/genjutsu/scene", "POST", b),+ // Its own id for this press: a resend of it gets the first run (src/server/account-tool-run.ts onceForAccount).+ send<{ id: string; modelId: string }>("/api/genjutsu/scene", "POST", b, { "x-request-id": nanoid(16) }),onSuccess: kick,});}/** The clip's words (one transcription; the page takes the part's lines from its cues). */export function useTranscribeClip() {- return useMutation({ mutationFn: (b: { engine: Engine; source: { url: string; duration?: number }; cleanVoiceFirst?: boolean }) => send<{ id: string; modelId: string }>("/api/genjutsu/transcribe", "POST", b), onSuccess: kick });+ return useMutation({ mutationFn: (b: { engine: Engine; source: { url: string; duration?: number }; cleanVoiceFirst?: boolean }) => send<{ id: string; modelId: string }>("/api/genjutsu/transcribe", "POST", b, { "x-request-id": nanoid(16) }), onSuccess: kick });}/** Waits for one generation to finish (polling; the page's helpers that fill a field from it). */diff --git a/src/components/influencer/influencer-builder.tsx b/src/components/influencer/influencer-builder.tsxindex c3a722e8..3b791ed9 100644--- a/src/components/influencer/influencer-builder.tsx+++ b/src/components/influencer/influencer-builder.tsx@@ -17,6 +17,7 @@ import { Button } from "@/components/ui/button";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { Textarea } from "@/components/ui/textarea";import { useAskBeforeUpload, useEngine, useGenerations, useModelAccess } from "@/lib/api";+import { toolPoolPrice } from "@/lib/run-place";import { keepOffered, offered } from "@/lib/model-access";import {categoriesFor,@@ -99,7 +100,8 @@ function RunInfo({ preview, loading, blocker }: { preview?: RunPreview & { stepsif (blocker) return <p className="text-[12.5px] text-destructive">{blocker}</p>;if (!preview) return <p className="h-5 text-[12.5px] text-muted-foreground">{loading ? "Pricing…" : ""}</p>;if (preview.error) return <p className="text-[12.5px] text-destructive">{preview.error}</p>;- const cost = preview.demo ? "Placeholder · free" : preview.costUsd === 0 ? "Free · your GPU" : preview.costUsd == null ? "price unknown" : `≈ $${preview.costUsd.toFixed(2)}`;+ // On this studio's GPUs: the service's price and the place in line ("Free · your GPU" is for the person's own GPU).+ const cost = toolPoolPrice(preview)?.text ?? (preview.demo ? "Placeholder · free" : preview.costUsd === 0 ? "Free · your GPU" : preview.costUsd == null ? "price unknown" : `≈ $${preview.costUsd.toFixed(2)}`);return (<div className="space-y-0.5 text-[12.5px] text-muted-foreground" aria-live="polite"><p>@@ -200,6 +202,8 @@ export function InfluencerBuilder() {askRun(() => {if (blocker) return toast(blocker);if (!body) return toast("Wait for the uploads to finish");+ // Not taken now (the price check said why): nothing is sent.+ if (preview.data?.error) return toast(preview.data.error);run.mutate(body, {onSuccess: (r) => setIds((xs) => [...r.items.map((g) => g.id), ...xs]),onError: (e) => toastError(e, "Couldn't start the sheet"),diff --git a/src/components/katana/hooks.ts b/src/components/katana/hooks.tsindex cdd47b0c..c1712e97 100644--- a/src/components/katana/hooks.ts+++ b/src/components/katana/hooks.ts@@ -1,6 +1,7 @@"use client";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { nanoid } from "nanoid";import { COMPUTER_KICK_EVENT, useGenerationEvents } from "@/lib/api";import type { KatanaJobView, Segment } from "@/lib/av/katana";import type { Engine } from "@/lib/catalog/types";@@ -34,7 +35,8 @@ export interface KatanaPreview {model: string;}-const post = async <T>(url: string, body: KatanaBody) => json<T>(await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }));+/** A press of Run carries its own id (x-request-id): a resend of it gets the first run (src/server/account-tool-run.ts onceForAccount). */+const post = async <T>(url: string, body: KatanaBody) => json<T>(await fetch(url, { method: "POST", headers: { "Content-Type": "application/json", "x-request-id": nanoid(16) }, body: JSON.stringify(body) }));export function useKatanaJobs() {const qc = useQueryClient();@@ -85,7 +87,7 @@ export function useKatanaActions() {});/** Retry the failed steps (all: the whole run again, as a new run). */const retry = useMutation({- mutationFn: async ({ id, all }: { id: string; all?: boolean }) => json<KatanaJobView>(await fetch(`/api/katana/${id}/retry${all ? "?all=1" : ""}`, { method: "POST" })),+ mutationFn: async ({ id, all }: { id: string; all?: boolean }) => json<KatanaJobView>(await fetch(`/api/katana/${id}/retry${all ? "?all=1" : ""}`, { method: "POST", headers: { "x-request-id": nanoid(16) } })),onSuccess: (job, { all }) => {kick();qc.setQueryData<KatanaJobView[]>(["katana"], (xs) => (all ? [job, ...(xs ?? [])] : (xs ?? []).map((j) => (j.id === job.id ? job : j))));diff --git a/src/components/katana/katana-studio.tsx b/src/components/katana/katana-studio.tsxindex c45169fd..2abcc66a 100644--- a/src/components/katana/katana-studio.tsx+++ b/src/components/katana/katana-studio.tsx@@ -27,6 +27,7 @@ import { keepOffered, offered } from "@/lib/model-access";import type { ExampleRowData } from "@/lib/examples/types";import { cn } from "@/lib/utils";import { toastError } from "@/lib/refusals";+import { usePoolRun } from "@/components/studio/pool-price";import { useKatanaActions, useKatanaJobs, useKatanaPreview, type KatanaBody } from "./hooks";type SplitMode = "fixed" | "scenes";@@ -113,6 +114,8 @@ export function KatanaStudio({ examples }: { examples?: ExampleRowData | null })}: null;const preview = useKatanaPreview(useDeferredValue(body));+ // A run on this studio's GPUs: the service's price and the place in line, and Run off when it is refused.+ const poolRun = usePoolRun(preview.data);const shown = segments ?? preview.data?.segments ?? null;const setupBlocker = !reference? "Add the reference edit"@@ -305,13 +308,13 @@ export function KatanaStudio({ examples }: { examples?: ExampleRowData | null }){preview.data ? (<>{preview.data.segments.length} segment{preview.data.segments.length === 1 ? "" : "s"} · {preview.data.steps} steps ·{" "}- <span className="font-mono text-foreground">{money(preview.data.costUsd, preview.data.demo, engine === "open")}</span>+ <span className="font-mono text-foreground">{poolRun.pool?.text ?? money(preview.data.costUsd, preview.data.demo, engine === "open")}</span></>) : ((blocker ?? "Pricing…"))}</p>- <Button size="lg" className={cn("rounded-full", blocker && "bg-muted text-muted-foreground hover:bg-muted")} onClick={go} disabled={start.isPending || scanning !== null}>+ <Button size="lg" className={cn("rounded-full", blocker && "bg-muted text-muted-foreground hover:bg-muted")} onClick={() => poolRun.go(go)} disabled={start.isPending || scanning !== null || (poolRun.off && !blocker)}>{start.isPending ? <Loader2 className="size-4 animate-spin" /> : <Sparkles className="size-4" />} Recreate</Button></div>diff --git a/src/components/model3d/hooks.ts b/src/components/model3d/hooks.tsindex 85553590..81016141 100644--- a/src/components/model3d/hooks.ts+++ b/src/components/model3d/hooks.ts@@ -1,6 +1,7 @@"use client";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { nanoid } from "nanoid";import { useEffect, useState } from "react";import { toast } from "sonner";import { COMPUTER_KICK_EVENT, useCreateGeneration, useIsOwner } from "@/lib/api";@@ -15,7 +16,8 @@ function useAccountRun3d() {const qc = useQueryClient();return useMutation({mutationFn: async (req: GenerationRequest): Promise<Generation[]> => {- const res = await fetch("/api/image-to-3d", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(req) });+ // Its own id for this press: a resend of it gets the first run (src/server/account-tool-run.ts onceForAccount).+ const res = await fetch("/api/image-to-3d", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...req, requestId: nanoid(16) }) });const body = (await res.json().catch(() => ({}))) as { items?: Generation[]; notes?: string[]; gpuWarning?: string; error?: string; code?: unknown };// Stopped by the GPU pre-flight: the guided fix opens (watchGuestRefusals), so no error toast on top of it.if (res.status === 409 && res.headers.get("x-fuobe-gpu-setup") === "1") throw Object.assign(new Error(body.error ?? "This tool needs setting up on your GPU"), { gpuSetup: true });diff --git a/src/components/palettes/use-signature.ts b/src/components/palettes/use-signature.tsindex 584e7937..044049b8 100644--- a/src/components/palettes/use-signature.ts+++ b/src/components/palettes/use-signature.ts@@ -1,10 +1,11 @@"use client";import { useMutation, useQueryClient } from "@tanstack/react-query";+import { nanoid } from "nanoid";import { useCallback } from "react";import { applySignature, withSignatureWords, type Signature, type SignedRequest } from "@/lib/catalog/palettes";import type { Generation, GenerationRequest } from "@/lib/catalog/types";-import { useIsGuest } from "@/lib/api";+import { useIsGuest, useIsVisitor } from "@/lib/api";import { responseError } from "@/lib/refusals";import { useCatalog } from "@/components/studio/catalog";import { usePalettes } from "./hooks";@@ -13,14 +14,16 @@ import { usePalettes } from "./hooks";* The composer's hook for the style signature (Color signature + Moodboard chips): `apply` routes a* request for the picked palette and moodboard (pure, src/lib/catalog/palettes.ts) — the composer* plans and prices with it while you type and sends what it returns. `lock` sends a run whose- * images are recolored afterwards (open engine) through POST /api/palettes/lock: the owner's or an account's run- * (with the place and price the composer shows), so only a guest's request never carries a lock.+ * images are recolored afterwards (open engine) through POST /api/palettes/lock: the owner's, or an account's run on+ * this install's GPUs (`onPool`: the composer's price check says the run goes there; it is sent there by name, with+ * the price shown). Anyone else's colours stay in the prompt: a guest's, and an account's run on its own GPU or key.*/-export function useSignature(enabled: boolean, signature: Signature | undefined) {+export function useSignature(enabled: boolean, signature: Signature | undefined, onPool = false) {const { getModel } = useCatalog();// The palette list carries which models take a palette natively; the chip has usually loaded it already.const { caps } = usePalettes(enabled && !!signature?.palette);- const visitor = useIsGuest();+ const guest = useIsGuest();+ const visitor = useIsVisitor() && (guest || !onPool);const apply = useCallback((req: GenerationRequest): SignedRequest & { worded: GenerationRequest } => {const signed = enabled && signature ? applySignature(req, signature, { caps, getModel, visitor }) : { request: req, modelId: req.modelId, notes: [] };@@ -32,7 +35,8 @@ export function useSignature(enabled: boolean, signature: Signature | undefined)const qc = useQueryClient();const lock = useMutation({mutationFn: async (b: { request: GenerationRequest; colors: string[]; place?: "own" | "pool"; shown?: { amount: number; priceVersion: string } }) => {- const res = await fetch("/api/palettes/lock", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(b) });+ // Each press carries its own id: a resend of it gets the first run (src/server/account-tool-run.ts onceForAccount).+ const res = await fetch("/api/palettes/lock", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...b, requestId: nanoid(16) }) });const body = (await res.json().catch(() => ({}))) as { items?: Generation[]; error?: string };if (!res.ok) throw responseError(res, body.error ?? "Something went wrong. Please try again.");return body.items ?? [];diff --git a/src/components/photodump/hooks.ts b/src/components/photodump/hooks.tsindex b791cbbf..17d616d4 100644--- a/src/components/photodump/hooks.ts+++ b/src/components/photodump/hooks.ts@@ -1,10 +1,12 @@"use client";import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { nanoid } from "nanoid";import { COMPUTER_KICK_EVENT, useElements, useSaveElement, useViewer } from "@/lib/api";import type { StudioElement } from "@/lib/catalog/elements";import type { Generation } from "@/lib/catalog/types";import { responseError } from "@/lib/refusals";+import { toolPoolPrice } from "@/lib/run-place";/*** A run started: the tab that runs this person's jobs on the ComfyUI on this computer (an account's "Your GPU") asks for@@ -43,7 +45,13 @@ export interface UserPack {export function useRunPreview(url: string, body: unknown | null) {return useQuery({queryKey: ["run-preview", url, body],- queryFn: () => post<RunPreview>(`${url}?preview=1`, body),+ queryFn: async () => {+ const p = await post<RunPreview>(`${url}?preview=1`, body);+ // A run on this studio's GPUs that isn't taken now (or runs on the person's own setup): said as the reason it+ // can't run, so Run is off with the service's words.+ const pool = toolPoolPrice(p);+ return pool?.refused ? { ...p, error: pool.text } : p;+ },enabled: body !== null,placeholderData: keepPreviousData,staleTime: 15_000,@@ -54,7 +62,8 @@ export function useRunPreview(url: string, body: unknown | null) {export function useRun<B>(url: string) {const qc = useQueryClient();return useMutation({- mutationFn: (body: B) => post<{ batchId?: string; items: Generation[]; notes?: string[] }>(url, body),+ // Each press carries its own id: a resend of it gets the first run (src/server/account-tool-run.ts onceForAccount).+ mutationFn: (body: B) => post<{ batchId?: string; items: Generation[]; notes?: string[] }>(url, { ...(body as object), requestId: nanoid(16) }),onSuccess: () => {kick();void qc.invalidateQueries({ queryKey: ["generations"] });@@ -67,7 +76,7 @@ export function useRun<B>(url: string) {export function useRetryPhoto() {const qc = useQueryClient();return useMutation({- mutationFn: (id: string) => post<{ items: Generation[] }>("/api/photodump/retry", { id }),+ mutationFn: (id: string) => post<{ items: Generation[] }>("/api/photodump/retry", { id, requestId: nanoid(16) }),onSuccess: () => {kick();void qc.invalidateQueries({ queryKey: ["generations"] });diff --git a/src/components/photodump/steps.tsx b/src/components/photodump/steps.tsxindex 606a15f3..60b46ba6 100644--- a/src/components/photodump/steps.tsx+++ b/src/components/photodump/steps.tsx@@ -2,6 +2,7 @@import { Check } from "lucide-react";import { cn } from "@/lib/utils";+import { toolPoolPrice } from "@/lib/run-place";/** Numbered wizard steps; steps already reached can be revisited. */export function Steps({ steps, current, reached, onGo }: { steps: string[]; current: number; reached: number; onGo?: (i: number) => void }) {@@ -39,12 +40,13 @@ export function Steps({ steps, current, reached, onGo }: { steps: string[]; curr/*** "Runs on Nano Banana Pro · 10 photos · ≈ $1.50" (or the reason it can't run). An account's run is priced on its own GPU- * or key ("Free · your GPU" on its GPU).+ * or key ("Free · your GPU" on its GPU), or on this studio's GPUs (their price and the place in line).*/export function RunLine({ preview, loading }: { preview?: { modelName?: string; count?: number; costUsd?: number | null; demo?: boolean; notes: string[]; error?: string }; loading?: boolean }) {if (!preview) return <p className="h-5 text-[12.5px] text-muted-foreground">{loading ? "Pricing…" : ""}</p>;if (preview.error) return <p className="text-[12.5px] text-destructive">{preview.error}</p>;- const cost = preview.demo ? "Placeholder · free" : preview.costUsd === 0 ? "Free · your GPU" : preview.costUsd == null ? "price unknown" : `≈ $${preview.costUsd.toFixed(2)}`;+ // On this studio's GPUs: the service's price and the place in line ("Free · your GPU" is for the person's own GPU).+ const cost = toolPoolPrice(preview)?.text ?? (preview.demo ? "Placeholder · free" : preview.costUsd === 0 ? "Free · your GPU" : preview.costUsd == null ? "price unknown" : `≈ $${preview.costUsd.toFixed(2)}`);return (<div className="space-y-0.5 text-[12.5px] text-muted-foreground"><p>diff --git a/src/components/shorts/hooks.ts b/src/components/shorts/hooks.tsindex b77d17cb..d35c7268 100644--- a/src/components/shorts/hooks.ts+++ b/src/components/shorts/hooks.ts@@ -24,8 +24,9 @@ async function json<T>(res: Response): Promise<T> {return body;}-export const send = async <T>(url: string, method: string, body?: unknown) =>- json<T>(await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) }));+/** `headers`: any the request adds (a press's id, for a tool whose body has no field for it). */+export const send = async <T>(url: string, method: string, body?: unknown, headers: Record<string, string> = {}) =>+ json<T>(await fetch(url, { method, headers: { "Content-Type": "application/json", ...headers }, body: body === undefined ? undefined : JSON.stringify(body) }));export interface ShortsBody {engine: Engine;diff --git a/src/components/shorts/shorts-studio.tsx b/src/components/shorts/shorts-studio.tsxindex c57cd97e..2f69eccd 100644--- a/src/components/shorts/shorts-studio.tsx+++ b/src/components/shorts/shorts-studio.tsx@@ -34,6 +34,7 @@ import { cn } from "@/lib/utils";import { onAttr, TAB_PILL, TabRow, useSwapFade } from "@/components/ui/tab-row";import { toastError } from "@/lib/refusals";import { CustomPresetDialog } from "./custom-preset-dialog";+import { usePoolRun } from "@/components/studio/pool-price";import { useShortsActions, useShortsEstimate, useShortsPresets, useSubmitGuard, type ShortsBody } from "./hooks";import { CreateCard, CustomCard, LookCard } from "./preset-card";import { ShortsHistory } from "./history";@@ -361,6 +362,8 @@ function SetupPanel({: null;const estimate = useShortsEstimate(estimateBody);const est = estimate.data;+ // A run on this studio's GPUs: Run off when the service refuses it now, or opening the person's own setup.+ const poolRun = usePoolRun(est);const blocker = !presetId? "Pick a preset first"@@ -380,7 +383,9 @@ function SetupPanel({: "Reading the clip…": estimate.error? (estimate.error as Error).message- : null;+ : poolRun.off+ ? poolRun.pool!.text+ : null;const guard = useSubmitGuard();const [leaving, setLeaving] = useState(false);@@ -390,13 +395,15 @@ function SetupPanel({if (busy || !estimateBody) return;// One session per click: a second click while this one is on its way does nothing (and the// server answers a repeated request id with the session it already started).- void guard(JSON.stringify(estimateBody), (requestId) => actions.create.mutateAsync({ ...estimateBody, requestId }), { hold: true })- .then((s) => {- if (!s) return;- setLeaving(true);- router.push(`/shorts/${s.id}`);- })- .catch((e: Error) => toastError(e));+ poolRun.go(() =>+ void guard(JSON.stringify(estimateBody), (requestId) => actions.create.mutateAsync({ ...estimateBody, requestId }), { hold: true })+ .then((s) => {+ if (!s) return;+ setLeaving(true);+ router.push(`/shorts/${s.id}`);+ })+ .catch((e: Error) => toastError(e)),+ );};return (diff --git a/src/components/shorts/ui.tsx b/src/components/shorts/ui.tsxindex f8700cb7..0d161638 100644--- a/src/components/shorts/ui.tsx+++ b/src/components/shorts/ui.tsx@@ -6,6 +6,7 @@ import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popoverimport { LibraryGrid } from "@/components/studio/media-slot";import { radioKeys, radioTab } from "@/components/studio/radio-keys";import { useAskBeforeUpload } from "@/lib/api";+import { toolPoolPrice } from "@/lib/run-place";import { cn } from "@/lib/utils";import type { SourceClip } from "./use-source-clip";@@ -239,10 +240,13 @@ export function Steps({ steps, current, className }: { steps: string[]; current:/*** "≈ $0.42", "Placeholder · free", "Free · your GPU". visitor: a guest or an account, whose GPU these tools don't run on yet- * (the page says why): "Not available here", a demo's price too, since its button is off.+ * (the page says why): "Not available here", a demo's price too, since its button is off. A run on this studio's GPUs+ * (the estimate says so): the service's price and the place in line.*/export function costText(e: { costUsd: number | null; demo: boolean } | undefined, engine: "cloud" | "open", visitor?: boolean): string {if (!e) return "…";+ const pool = toolPoolPrice(e);+ if (pool) return pool.text;if (visitor && (e.demo || engine === "open")) return "Not available here";if (e.demo) return "Placeholder · free";if (engine === "open") return "Free · your GPU";diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsxindex 895a7ac1..9ded77df 100644--- a/src/components/studio/composer.tsx+++ b/src/components/studio/composer.tsx@@ -637,8 +637,11 @@ export function Composer({ docked }: { docked: boolean }) {};}, [bridgeRef, attach.attachFiles]);- // A picked palette / moodboard routes the request (and can move it to another model) before anything else.- const signature = useSignature(!!config.signature, draft.signature);+ // A picked palette / moodboard routes the request (and can move it to another model) before anything else. An account's+ // palette lock runs on this studio's GPUs only (on its own GPU or key its colours go in the prompt): where the price+ // check last said this run goes (poolPrice, below).+ const [lockOnPool, setLockOnPool] = useState(false);+ const signature = useSignature(!!config.signature, draft.signature, lockOnPool);const prepare = (draftIn: typeof draft) => {const d = songDraft(draftIn, catalog.getModel(draftIn.modelId), config.slots);const signed = signature.apply(buildRequest(config.feature, d, studioOp, config.promptSuffix, config.multiRef?.kind, framesCtx, targetFor(d.modelId)));@@ -673,6 +676,7 @@ export function Composer({ docked }: { docked: boolean }) {// A run on this studio's GPUs (their price and line, no pre-flight of the account's own GPU, the price shown sent with// it): named there, or the check says the server sends it there. What they don't take runs on its own GPU, as before.const poolPrice = askPool && composerOnPool(runPlace, hostedCheck, lastOnPool);+ if (poolPrice !== lockOnPool) setLockOnPool(poolPrice);// Where the place switch says it runs.const shownOn: RunOn = runOn === "pool" && hostedHere && !poolPrice ? "own" : runOn;// The price check has answered for the draft as it is now (not one typed a moment ago).@@ -875,7 +879,8 @@ export function Composer({ docked }: { docked: boolean }) {// Hosted runs: where it should go, and the price shown (the server checks both; a higher price comes back to confirm).const hosted = viewerInfo?.hosted ? { ...(runPlace && { place: runPlace }), ...(poolPrice && hostedQuote && { shown: { amount: hostedQuote.amount, priceVersion: hostedQuote.priceVersion } }) } : {};// Open palette lock: the images are recoloured to the palette by a chained step (POST /api/palettes/lock).- if (sent.lock) return signature.lock.mutate({ request: sent.request, colors: sent.lock.colors, ...hosted }, { onError: (e) => toastError(e) });+ // (An account's lock runs on this studio's GPUs only: sent there by name.)+ if (sent.lock) return signature.lock.mutate({ request: sent.request, colors: sent.lock.colors, ...hosted, ...(poolPrice && { place: "pool" as const }) }, { onError: (e) => toastError(e) });// If the server's pre-flight stops it (409 gpu-setup), the guided fix that opens can try again, or run it anyway.setGpuRetry(() => submitRef.current(),diff --git a/src/components/studio/pool-price.ts b/src/components/studio/pool-price.tsnew file mode 100644index 00000000..9ce9b2ad--- /dev/null+++ b/src/components/studio/pool-price.ts@@ -0,0 +1,25 @@+"use client";++import { useOwnSetupPress } from "@/components/own-setup";+import { toolPoolPrice, type ToolPoolPrice } from "@/lib/run-place";++/**+ * A tool page's Run for a run on this studio's GPUs, from the tool's own price check (`?preview=1` or its estimate,+ * which adds `{ place: "pool", quote, line }` when the run goes there): `pool` says what the price slot shows instead of+ * the page's own words (null: the run goes to the person's own GPU or key, so the page says its own), `off` turns Run off+ * (refused, in the service's words), `go` opens the person's own setup instead of running when that is the answer, and+ * `headers` carry the price shown with Run.+ */+export function usePoolRun(check: unknown): { pool: ToolPoolPrice | null; off: boolean; go: (run: () => void) => void; headers: Record<string, string> } {+ const press = useOwnSetupPress();+ const pool = toolPoolPrice(check);+ return {+ pool,+ off: !!pool?.refused && !pool.setup,+ go: (run) => {+ if (pool?.setup) press(pool.setup, run);+ else run();+ },+ headers: pool?.headers ?? {},+ };+}diff --git a/src/lib/run-place.ts b/src/lib/run-place.tsindex ad9675b4..3b442d05 100644--- a/src/lib/run-place.ts+++ b/src/lib/run-place.ts@@ -1,3 +1,4 @@+import { RUN_SHOWN_HEADER, shownHeader } from "./guest-access";import { ownSetupDetail, ownSetupLabel, type OwnSetup } from "./own-setup";import { lineWords } from "./pool-line";import { billedTo, CLOUD_KEY, type CloudProvider } from "./your-keys";@@ -257,3 +258,36 @@ export function checkedPool(if (check.quote.allowed === false) return { text, ...(sub && { sub }), refused: true, ...(ownSetup && { setup: ownSetup }) };return { text: count > 1 && text ? `${text} each` : text, ...(sub && { sub }), ...(check.line && { wait: lineWords(check.line) }) };}++/** What a tool page's price slot and Run say for a run on this studio's GPUs (toolPoolPrice). */+export interface ToolPoolPrice {+ /** The service's words for the price, then where the run would stand in line ("Free · In line · 2nd · about 3 min"). */+ text: string;+ /** The run wouldn't be taken now: Run is off, and `text` says why (unless `setup` runs it instead). */+ refused: boolean;+ /** Refused because it runs on the person's own setup: Run opens it. */+ setup?: OwnSetup;+ /** The price shown, sent with Run (the header a tool's run reads it from), so a changed price is asked about first. */+ headers: Record<string, string>;+}++/**+ * A tool's own price check (`?preview=1` or its estimate route) as its page shows it: when the server adds `{ place:+ * "pool", quote, line }` (the run goes to this studio's GPUs), the service's price and the place in line instead of the+ * page's own words ("Free · your GPU" is for the person's own GPU), Run off when it is refused, and the price shown to+ * send with Run. Null when the run goes to the person's own GPU or key (the page says its own words).+ */+export function toolPoolPrice(check: unknown): ToolPoolPrice | null {+ if (!check || typeof check !== "object") return null;+ const c = check as { place?: unknown; quote?: { allowed?: boolean; amount?: number; priceVersion?: string; text?: string; sub?: string; ownSetup?: OwnSetup }; line?: { place: number; etaSeconds: number | null } };+ if (c.place !== "pool" || !c.quote || typeof c.quote.text !== "string") return null;+ const pool = checkedPool({ place: "pool", quote: { ...c.quote, text: c.quote.text }, ...(c.line && { line: c.line }) });+ if (!pool) return null;+ if (pool.refused) return { text: pool.text, refused: true, ...(pool.setup && { setup: pool.setup }), headers: {} };+ const shown = typeof c.quote.amount === "number" && typeof c.quote.priceVersion === "string" ? { amount: c.quote.amount, priceVersion: c.quote.priceVersion } : null;+ return {+ text: [pool.text, pool.wait].filter(Boolean).join(" · "),+ refused: false,+ headers: shown ? { [RUN_SHOWN_HEADER]: shownHeader(shown) } : {},+ };+}diff --git a/tests/run-place.test.ts b/tests/run-place.test.tsindex 510efa92..03b330ad 100644--- a/tests/run-place.test.ts+++ b/tests/run-place.test.ts@@ -1,6 +1,8 @@import { describe, expect, it } from "vitest";import { quoteBody } from "@/lib/hosted";-import { checkedPool, composerOnPool, composerPlace, IN_BROWSER, mainModel, openCheckPlace, placePrice, runPlace, type RunPlaceInput } from "@/lib/run-place";+import { checkedPool, composerOnPool, composerPlace, IN_BROWSER, mainModel, openCheckPlace, placePrice, runPlace, toolPoolPrice, type RunPlaceInput } from "@/lib/run-place";+import { RUN_SHOWN_HEADER, shownHeader } from "@/lib/guest-access";+import { lineWords } from "@/lib/pool-line";/** Where a run happens and what it costs, for each audience and engine (the composers' place chip and send button). */const fmt = (usd: number) => `$${usd.toFixed(2)}`;@@ -259,3 +261,31 @@ describe("checkedPool", () => {expect(p).toMatchObject({ where: "gpu", label: "Your GPU", needs: "gpu" });});});++describe("a tool page's own price check, for a run on this studio's GPUs", () => {+ const line = { place: 2, etaSeconds: 180 };+ it("says the service's price and the place in line instead of the page's own words, and carries the price shown", () => {+ const p = toolPoolPrice({ costUsd: 0, demo: false, notes: [], place: "pool", quote: { allowed: true, amount: 0, priceVersion: "v1", text: "Free" }, line });+ expect(p?.text).toBe(`Free · ${lineWords(line)}`);+ expect(p?.text).not.toMatch(/GPU/);+ expect(p?.refused).toBe(false);+ expect(p?.headers).toEqual({ [RUN_SHOWN_HEADER]: shownHeader({ amount: 0, priceVersion: "v1" }) });+ });++ it("is refused in the service's words (Run off), or with the person's own setup that runs it", () => {+ expect(toolPoolPrice({ place: "pool", quote: { allowed: false, amount: 0, priceVersion: "", text: "You have 2 runs going. Start this one when one finishes." }, line })).toEqual({+ text: "You have 2 runs going. Start this one when one finishes.",+ refused: true,+ headers: {},+ });+ const setup = { need: "gpu" as const, vramGb: 24 };+ expect(toolPoolPrice({ place: "pool", quote: { allowed: false, amount: 0, priceVersion: "", text: "Runs on your own GPU · 24 GB", ownSetup: setup } })).toMatchObject({ refused: true, setup });+ });++ it("is nothing for a run on the person's own GPU or key, or no answer yet", () => {+ expect(toolPoolPrice({ costUsd: 0, demo: false, notes: [] })).toBeNull();+ expect(toolPoolPrice({ place: "own" })).toBeNull();+ expect(toolPoolPrice(undefined)).toBeNull();+ expect(toolPoolPrice(null)).toBeNull();+ });+});