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
Composers say where a run happens and what it costs
Adarsh61bdc95be7c4
diff --git a/src/components/ads/ad-chat.tsx b/src/components/ads/ad-chat.tsxindex bb6bca34..82530b4f 100644--- a/src/components/ads/ad-chat.tsx+++ b/src/components/ads/ad-chat.tsx@@ -7,7 +7,7 @@ import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTriggeimport { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from "@/components/ui/popover";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import type { BrandKit, Product } from "@/lib/catalog/marketing";-import { formatCost } from "@/lib/format";+import { useRunPlace } from "@/components/studio/run-place-chip";import { cn } from "@/lib/utils";import { toastError } from "@/lib/refusals";import { useBrandChat, useEstimate, type ChatMessage } from "@/components/marketing/hooks";@@ -49,7 +49,10 @@ function Proposal({ msg, brand, products, engine, onConfirmed }: { msg: ChatMessconst { confirm } = useBrandChat(brand.id);const p = msg.proposal!;const total = p.items.reduce((n, i) => n + i.count, 0);- const est = useEstimate<{ costUsd: number | null; demo: boolean }>("/api/ads/estimate", msg.batchId ? null : { brandId: brand.id, engine, items: p.items, direction: p.direction });+ const est = useEstimate<{ costUsd: number | null; demo: boolean; modelName?: string; blocker?: string }>("/api/ads/estimate", msg.batchId ? null : { brandId: brand.id, engine, items: p.items, direction: p.direction });+ // The button says where the ads are made and their price, as the studios' send buttons do.+ const priced = est.data && !est.data.blocker ? est.data : undefined;+ const place = useRunPlace({ engine, models: priced?.modelName ? [priced.modelName] : undefined, costUsd: priced?.costUsd, demo: priced?.demo, ownerOnly: "Ads Studio" });const names = p.items.map((i) => products.find((x) => x.id === i.productId)?.name).filter(Boolean);return (<div className="mt-2 rounded-xl border bg-background p-3">@@ -75,7 +78,7 @@ function Proposal({ msg, brand, products, engine, onConfirmed }: { msg: ChatMessclassName="mt-2 inline-flex h-8 items-center gap-1.5 rounded-full bg-primary px-3 text-[12px] font-medium text-primary-foreground hover:bg-primary/90">{confirm.isPending ? <Loader2 className="size-3.5 animate-spin" /> : <Sparkles className="size-3.5" />}- Create {total} ads{est.data ? ` · ${est.data.demo ? "demo" : est.data.costUsd == null ? "" : `≈ ${formatCost(est.data.costUsd)}`}` : ""}+ Create {total} ads{place?.send ? ` · ${place.send}` : ""}</button></>)}diff --git a/src/components/ads/brand-workspace.tsx b/src/components/ads/brand-workspace.tsxindex 099711a2..5ab80f8c 100644--- a/src/components/ads/brand-workspace.tsx+++ b/src/components/ads/brand-workspace.tsx@@ -150,7 +150,7 @@ export function BrandWorkspace({ brandId }: { brandId: string }) {<BrandKitForm key={brand.id} brand={brand} /></>)}- {current === "new" && <NewAds brand={brand} products={products} engine={engine} onCreated={() => setStep("ads")} />}+ {current === "new" && <NewAds brand={brand} products={products} engine={engine} onEngine={setEngine} onCreated={() => setStep("ads")} />}{current === "ads" &&(creatives.isLoading ? (<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">diff --git a/src/components/ads/multiplier.tsx b/src/components/ads/multiplier.tsxindex 649cd450..04e404df 100644--- a/src/components/ads/multiplier.tsx+++ b/src/components/ads/multiplier.tsx@@ -14,7 +14,8 @@ import { ExampleRow } from "@/components/studio/example-row";import { fileToSlot, LibraryGrid, type SlotValue } from "@/components/studio/media-slot";import { VideoTrimmer } from "@/components/studio/video-trimmer";import { initialClip, mentionedImages, MULTIPLIER, MULTIPLIER_MODELS, multiplierResolution, type ClipRange as Range, type MarketingRun, type RunEstimate } from "@/lib/catalog/marketing";-import { formatCost } from "@/lib/format";+import { RunPlaceChip, useRunPlace } from "@/components/studio/run-place-chip";+import { mainModel } from "@/lib/run-place";import { probeBlob, probeUrl } from "@/lib/media-probe";import { useAskBeforeUpload, useModelAccess } from "@/lib/api";import { keepOffered, offered } from "@/lib/model-access";@@ -274,7 +275,11 @@ export function AdMultiplier({ models, examples }: { models: Record<string, Modeconst estBody = useMemo(() => (body && sections ? { ...body, firstFrame: hookOn ? body.video : undefined, lastFrame: ctaOn ? body.video : undefined } : body), [body, sections, hookOn, ctaOn]);const est = useEstimate<RunEstimate>("/api/ads/multiplier/estimate", estBody);const blocker = !video ? "Upload a reference video" : video.uploading ? "Uploading the video…" : duration == null ? "Reading the video…" : length < MULTIPLIER.minSeconds - 0.05 || length > MULTIPLIER.maxSeconds + 0.05 ? "Video duration: 4-30 seconds" : est.data?.blocker;- const cost = est.data && !est.data.blocker ? (est.data.demo ? "Placeholder · free" : est.data.costUsd == null ? "" : `≈ ${formatCost(est.data.costUsd)}`) : "";+ // Where the new versions are made and their price (the studios' words); a guest or an account is told it isn't+ // available here (its run would be refused), with no price.+ const priced = est.data && !est.data.blocker ? est.data : undefined;+ const place = useRunPlace({ engine, models: priced?.steps.map((s) => s.modelName), model: mainModel(priced?.steps), costUsd: priced?.costUsd, demo: priced?.demo, ownerOnly: "Ad Multiplier" });+ const runLabel = versions > 1 ? `Generate ${versions} versions` : "Generate";const mention = (n: number) => {const tag = `@image_${n}`;@@ -295,6 +300,7 @@ export function AdMultiplier({ models, examples }: { models: Record<string, Modeconst missing = mentionedImages(prompt).filter((n) => n > images.length);const generate = async () => {+ if (place?.where === "unavailable") return void toast(place.tip, { id: "mult-blocker" });if (blocker || !body || !video || !cut) return void toast(blocker ?? "Upload a reference video", { id: "mult-blocker" });setBusy(sections ? "Reading the frames…" : "Starting…");try {@@ -482,9 +488,15 @@ export function AdMultiplier({ models, examples }: { models: Record<string, Mode<div className="flex flex-wrap items-center justify-end gap-3 border-t pt-4"><p className="mr-auto text-[12px] text-muted-foreground">{est.data?.steps.length ? est.data.steps.map((s) => s.label).join(" → ") : "New versions keep the reference's length and framing"}</p>- {cost && <span className="font-mono text-[13px] text-muted-foreground">{cost}</span>}- <Button size="lg" onClick={() => void generate()} aria-disabled={!!blocker || !!busy} className={cn(blocker && "bg-muted text-muted-foreground hover:bg-muted")} title={blocker}>- {busy ? <Loader2 className="animate-spin" /> : <Sparkles />} {busy ?? (versions > 1 ? `Generate ${versions} versions` : "Generate")}+ <RunPlaceChip place={place} steps={priced?.steps} engine={engine} onEngine={setEngine} pending={!!estBody && est.isFetching && !est.data} />+ <Button+ size="lg"+ onClick={() => void generate()}+ aria-disabled={!!blocker || !!busy}+ className={cn(blocker && "bg-muted text-muted-foreground hover:bg-muted")}+ title={blocker ?? (place?.where === "unavailable" ? place.tip : place?.send ? `${runLabel} · ${place.send}` : undefined)}+ >+ {busy ? <Loader2 className="animate-spin" /> : <Sparkles />} {busy ?? runLabel}</Button></div>{blocker && video && <p className="-mt-3 text-right text-[12px] text-muted-foreground">{blocker}</p>}diff --git a/src/components/ads/new-ads.tsx b/src/components/ads/new-ads.tsxindex 63ed318c..4625f7c4 100644--- a/src/components/ads/new-ads.tsx+++ b/src/components/ads/new-ads.tsx@@ -11,6 +11,7 @@ import { AD_VISUAL_MODELS, DRAWN_WORDS_LABEL, DRAWN_WORDS_MODELS, MAX_ADS_PER_PRimport { useModelAccess } from "@/lib/api";import { keepOffered, offered } from "@/lib/model-access";import { formatCost } from "@/lib/format";+import { RunPlaceChip, useRunPlace } from "@/components/studio/run-place-chip";import { toastError } from "@/lib/refusals";import { useCreativeActions, useEstimate, useProductActions } from "@/components/marketing/hooks";@@ -48,7 +49,20 @@ function Stepper({ value, onChange, label }: { value: number; onChange: (n: numb}/** Select products (≤10) → "How many ads to create?" (≤20 each, total price first) → Create. */-export function NewAds({ brand, products, engine, onCreated }: { brand: BrandKit; products: Product[]; engine: "cloud" | "open"; onCreated: (batchId: string) => void }) {+export function NewAds({+ brand,+ products,+ engine,+ onEngine,+ onCreated,+}: {+ brand: BrandKit;+ products: Product[];+ engine: "cloud" | "open";+ /** Switching engine from the place chip (the header's switch). */+ onEngine?: (e: "cloud" | "open") => void;+ onCreated: (batchId: string) => void;+}) {const { createBatch } = useCreativeActions(brand.id);const { remove } = useProductActions();const [selected, setSelected] = useState<string[]>(() => products.slice(0, MAX_PRODUCTS_PER_RUN).map((p) => p.id));@@ -86,7 +100,9 @@ export function NewAds({ brand, products, engine, onCreated }: { brand: BrandKitonError: (e) => toastError(e),});};- const price = est.data ? (est.data.demo ? "Placeholder · free" : est.data.costUsd == null ? "price unknown" : est.data.costUsd === 0 ? (engine === "open" ? "Free · your GPU" : "Free") : `≈ ${formatCost(est.data.costUsd)}`) : "";+ // Where the ads are made and their price, as the studios say it.+ const priced = est.data && !est.data.blocker ? est.data : undefined;+ const place = useRunPlace({ engine, models: priced ? [priced.modelName] : undefined, costUsd: priced?.costUsd, demo: priced?.demo, ownerOnly: "Ads Studio" });return (<div className="space-y-6"><section className="rounded-2xl border bg-background p-4 sm:p-5">@@ -199,8 +215,8 @@ export function NewAds({ brand, products, engine, onCreated }: { brand: BrandKit</p></div><div className="flex items-center gap-3">- <span className="font-mono text-[14px] font-medium tabular-nums">{est.isFetching && !est.data ? "…" : price}</span>- <Button size="lg" onClick={create} disabled={createBatch.isPending || !!est.data?.blocker}>+ <RunPlaceChip place={place} engine={engine} onEngine={onEngine} pending={est.isFetching && !est.data} className="bg-background" />+ <Button size="lg" onClick={create} disabled={createBatch.isPending || !!est.data?.blocker} title={place?.send ? `Create ${total} ads · ${place.send}` : undefined}>{createBatch.isPending ? <Loader2 className="animate-spin" /> : <Sparkles />} Create {total} ads</Button></div>diff --git a/src/components/any-angle/any-angle-tool.tsx b/src/components/any-angle/any-angle-tool.tsxindex e96ff6aa..aaffbe3c 100644--- a/src/components/any-angle/any-angle-tool.tsx+++ b/src/components/any-angle/any-angle-tool.tsx@@ -10,6 +10,8 @@ import { Segmented } from "@/components/faceless/controls";import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";import { useGeneration, useGenerationList } from "@/components/av/use-generation";import { ACCEPT, LibraryGrid } from "@/components/studio/media-slot";+import { RunPlaceChip, useOpenRunPlace } from "@/components/studio/run-place-chip";+import { getModel } from "@/lib/catalog";import { loadModelViewer } from "@/components/model3d/model-viewer";import { askToSignUp, uploadFile, useAskBeforeUpload, useCreateGeneration, useEngine, useGenerations, useIsGuest, useIsOwner, useStatus } from "@/lib/api";import { ACTIVE_RUNS_CODE } from "@/lib/guest-access";@@ -535,6 +537,8 @@ export function AnyAngleTool({ app }: { app?: { name: string } }) {const shots = useMemo(() => (ref ? (results.data ?? []).filter((g) => photoOf(g) === ref) : []), [results.data, ref]);const cloudOnly = mode === "cloud";+ // Where the angles are made and their price, as the studios say it (the 3D view, then one picture per angle).+ const place = useOpenRunPlace([getModel(ANY_ANGLE.buildModel)?.name, getModel(ANY_ANGLE.shotModel)?.name].filter((x): x is string => !!x), null);const ready = !!view && !!ref;// A build that failed takes the angles waiting for it with it.const waiting = build?.status === "failed" || build?.status === "canceled" ? null : asked;@@ -726,10 +730,11 @@ export function AnyAngleTool({ app }: { app?: { name: string } }) {><AngleChips picks={picked} options={options} onToggle={toggle} /><div className="mt-3 flex flex-col-reverse gap-2 sm:flex-row sm:items-center sm:justify-end">+ <RunPlaceChip place={place} className="self-center sm:mr-auto" /><Button variant="outline" size="lg" className="rounded-full" disabled={!(ready || building) || !!waiting || sending} onClick={() => start("all")}><LayoutGrid className="size-4" /> All angles</Button>- <Button size="lg" className="rounded-full" disabled={!(ready || building) || !n || !!waiting || sending} onClick={() => start("picked")}>+ <Button size="lg" className="rounded-full" disabled={!(ready || building) || !n || !!waiting || sending} onClick={() => start("picked")} title={place?.send || undefined}>{sending || waiting ? <Loader2 className="size-4 animate-spin" /> : <Sparkles className="size-4" />}{" "}{waiting ? "Starts when your 3D view is ready" : n > 1 ? `Make ${n} angles` : "Make this angle"}</Button>diff --git a/src/components/marketing/click-to-ad.tsx b/src/components/marketing/click-to-ad.tsxindex 0f60d427..7dc3ef64 100644--- a/src/components/marketing/click-to-ad.tsx+++ b/src/components/marketing/click-to-ad.tsx@@ -17,7 +17,8 @@ import { useCoverPlayback } from "@/components/template-cover";import type { SlotValue } from "@/components/studio/media-slot";import { uploadFile, useLikelyVisitor } from "@/lib/api";import { AD_STYLES, END_CARD, KIT_LABELS, type AdStyle, type BrandKit, type MarketingRun, type Product, type RunEstimate } from "@/lib/catalog/marketing";-import { formatCost } from "@/lib/format";+import { RunPlaceChip, useRunPlace } from "@/components/studio/run-place-chip";+import { IN_BROWSER, mainModel } from "@/lib/run-place";import type { StarterCardData } from "@/lib/starters/types";import { cn } from "@/lib/utils";import { toastError } from "@/lib/refusals";@@ -281,7 +282,9 @@ export function ClickToAd({ models, starters = [] }: { models: Record<string, Mo: withEndCard && motion.overflow.length? motion.overflow[0]: est.data?.blocker;- const cost = est.data && !est.data.blocker ? (visitor && (est.data.demo || est.data.costUsd === 0) ? "Not available here" : est.data.demo ? "Placeholder · free" : est.data.costUsd == null ? "" : `≈ ${formatCost(est.data.costUsd)}`) : "";+ // Where the video is made and its price (the studios' words); a guest or an account is told it isn't available here.+ const priced = est.data && !est.data.blocker ? est.data : undefined;+ const place = useRunPlace({ engine, models: priced?.steps.map((s) => s.modelName), model: mainModel(priced?.steps), costUsd: priced?.costUsd, demo: priced?.demo, ownerOnly: "Click to Ad" });const writeScript = async () => {if (!productId) return;@@ -355,11 +358,15 @@ export function ClickToAd({ models, starters = [] }: { models: Record<string, Mo{!product && (<section aria-labelledby="c2a-end-card-try" className="min-w-0 space-y-3 rounded-2xl border p-4 sm:p-5">- <div>- <h3 id="c2a-end-card-try" className="text-[15px] font-semibold">- Your ad ends on your brand- </h3>- <p className="mt-0.5 text-[13px] text-muted-foreground">An animated end card in your brand's colours and fonts, in five styles. Try one with your words.</p>+ <div className="flex min-w-0 flex-wrap items-start justify-between gap-2">+ <div className="min-w-0">+ <h3 id="c2a-end-card-try" className="text-[15px] font-semibold">+ Your ad ends on your brand+ </h3>+ <p className="mt-0.5 text-[13px] text-muted-foreground">An animated end card in your brand's colours and fonts, in five styles. Try one with your words.</p>+ </div>+ {/* Drawn in this browser, for everyone: instant and free. */}+ <RunPlaceChip place={IN_BROWSER} className="h-7 px-2.5 text-[12px]" /></div><div className="grid min-w-0 gap-2 sm:grid-cols-2"><input value={sampleBrand} onChange={(e) => setSampleBrand(e.target.value.slice(0, 40))} className="h-11 w-full min-w-0 rounded-xl border bg-background px-3 text-[14px] outline-none focus-visible:ring-2 focus-visible:ring-ring" aria-label="Brand name on the end card" placeholder="Brand name" />@@ -507,8 +514,15 @@ export function ClickToAd({ models, starters = [] }: { models: Record<string, Mo9:16 · up to 12 s · voiceover and captions{withEndCard ? ` · ${END_CARD.seconds} s end card` : ""}{est.data?.steps.length ? ` · ${est.data.steps.length} steps` : ""}</p>- {cost && <span className="font-mono text-[13px] text-muted-foreground">{cost}</span>}- <Button size="lg" onClick={() => void generate()} disabled={visitor} aria-disabled={!!blocker || busy} className={cn(blocker && "bg-muted text-muted-foreground hover:bg-muted")} title={blocker}>+ <RunPlaceChip place={place} steps={priced?.steps} engine={engine} onEngine={setEngine} pending={est.isFetching && !est.data} />+ <Button+ size="lg"+ onClick={() => void generate()}+ disabled={visitor}+ aria-disabled={!!blocker || busy}+ className={cn(blocker && "bg-muted text-muted-foreground hover:bg-muted")}+ title={blocker ?? (place?.send ? `Generate video · ${place.send}` : undefined)}+ >{busy ? <Loader2 className="animate-spin" /> : <Wand2 />} Generate video</Button></div>diff --git a/src/components/marketing/kinetic-template.tsx b/src/components/marketing/kinetic-template.tsxindex e38e643e..14ae5e86 100644--- a/src/components/marketing/kinetic-template.tsx+++ b/src/components/marketing/kinetic-template.tsx@@ -10,11 +10,13 @@ import { KINETIC_FEATURE, MadeStrip } from "@/components/motion/made-strip";import { MotionPlayer, useMotionInputs, usePlan, useScene } from "@/components/motion/player";import { phaseLine, useMotionSave } from "@/components/motion/save";import { MediaSlot, type SlotValue } from "@/components/studio/media-slot";+import { RunPlaceChip } from "@/components/studio/run-place-chip";import { useIsOwner } from "@/lib/api";import type { BrandKit, MarketingTemplate } from "@/lib/catalog/marketing";import { SHOWCASE_PRODUCTS } from "@/lib/motion/showcase";import type { SizePreset } from "@/lib/motion/sizes";import { initialState, ownFiles, templateLengths, templateRecipe, templateSizes, templateWords, type TemplateBrand, type TemplateState } from "@/lib/motion/template";+import { IN_BROWSER } from "@/lib/run-place";import { cn } from "@/lib/utils";import { renderRecipe } from "./end-card-motion";import { useBrands } from "./hooks";@@ -132,6 +134,7 @@ export function KineticTemplate({ template: t, onClose, kitId, onKit }: { templa<span className="inline-flex items-center gap-1 rounded-full bg-brand-faint px-2 py-0.5 text-[11px] font-medium text-brand-text"><Zap className="size-3" /> Instant</span>+ <RunPlaceChip place={IN_BROWSER} className="h-7 px-2.5 text-[12px]" /></div><p className="mt-1 text-[13px] text-pretty text-muted-foreground">Your exact words in your brand's fonts and colours. It plays as you type; saving keeps the clip in Fuobe, ready to download.</p></div>diff --git a/src/components/marketing/marketing-studio.tsx b/src/components/marketing/marketing-studio.tsxindex bf68aa73..0b7e7d0f 100644--- a/src/components/marketing/marketing-studio.tsx+++ b/src/components/marketing/marketing-studio.tsx@@ -9,6 +9,8 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltipimport { chipBase, chipIdle, chipOn } from "@/components/studio/chip";import { MediaSlot, type SlotValue } from "@/components/studio/media-slot";import { ResponsivePanel } from "@/components/studio/responsive-panel";+import { RunPlaceChip, useRunPlace } from "@/components/studio/run-place-chip";+import { mainModel } from "@/lib/run-place";import { BrandChip } from "@/components/brand/brand-dialog";import { inputCls } from "@/components/brand/fields";import { withoutOwnGpu } from "@/lib/catalog/engines";@@ -16,7 +18,6 @@ import { Switch } from "@/components/ui/switch";import { DRAWN_WORDS_HINT, DRAWN_WORDS_LABEL, FORMATS, formatModels, isCodeTemplate, looksLikeWebsite, pickable, MAX_PROMPT, openingAspect, TEMPLATE_INDEX, type FormatId, type MarketingCategory, type MarketingTemplate, type RunEstimate } from "@/lib/catalog/marketing";import { SelfHostNote } from "@/components/self-host-note";import { StarterSection } from "@/components/starters/starter-section";-import { formatCost } from "@/lib/format";import { useIsOwner, useLikelyVisitor, useModelAccess } from "@/lib/api";import { keepOffered, offered } from "@/lib/model-access";import type { StarterCardData } from "@/lib/starters/types";@@ -391,7 +392,25 @@ export function MarketingStudio({ models, starters = [] }: { models: Record<stri: badSite? "Enter a valid website URL": est.data?.blocker;- const cost = est.data && !est.data.blocker ? (visitor && (est.data.demo || est.data.costUsd === 0) ? "Not available here" : est.data.demo ? "Placeholder · free" : est.data.costUsd == null ? "" : est.data.costUsd === 0 ? "Free" : `≈ ${formatCost(est.data.costUsd)}`) : "";+ // Where the run happens and its price, as the studios say it (the chip by the send button); a guest or an account is+ // told the tool isn't available here, with no price.+ const priced = est.data && !est.data.blocker ? est.data : undefined;+ // Until the run is priced (no product yet), the chip names the model Settings has picked, as the studios' model chip does.+ const access = useModelAccess();+ const picked = useMemo(() => {+ const choices = keepOffered(pickable(formatModels(f, engine, { product: !!draft.product, avatar: !!draft.avatar }, !!draft.drawnWords)), (c) => offered(access, c.id, engine));+ const c = choices.find((x) => x.id === draft.modelId) ?? choices[0];+ return c ? (models[c.id]?.name ?? undefined) : undefined;+ }, [f, engine, draft.product, draft.avatar, draft.drawnWords, draft.modelId, access, models]);+ const place = useRunPlace({+ engine,+ models: priced ? priced.steps.map((s) => s.modelName) : picked ? [picked] : undefined,+ model: mainModel(priced?.steps) ?? picked,+ costUsd: priced?.costUsd,+ demo: priced?.demo,+ ownerOnly: "Marketing Studio",+ });+ const sendTip = place?.send ? ` · ${place.send}` : "";// Until a template is picked or you start on the composer it stays slim (the attachment tiles fold// away), so the template gallery behind it stays in view.@@ -562,7 +581,7 @@ export function MarketingStudio({ models, starters = [] }: { models: Record<stri{f.brandKit && <BrandChip value={brandId} onChange={pickBrand} />}<SettingsPanel draft={draft} set={set} models={models} engine={engine} /></div>- <span className="hidden shrink-0 font-mono text-[12px] text-muted-foreground tabular-nums sm:inline">{est.isFetching && !est.data ? "…" : cost}</span>+ <RunPlaceChip place={place} steps={priced?.steps} engine={engine} onEngine={setEngine} pending={est.isFetching && !est.data} className="max-sm:max-w-[11rem]" /><Tooltip><TooltipTrigger asChild><button@@ -576,15 +595,14 @@ export function MarketingStudio({ models, starters = [] }: { models: Record<stri{busy ? <Loader2 className="size-4 animate-spin" /> : <ArrowUp className="size-4" />}</button></TooltipTrigger>- <TooltipContent>{blocker ?? (template ? `Recreate template${cost ? ` · ${cost}` : ""}` : `Generate${cost ? ` · ${cost}` : ""}`)}</TooltipContent>+ <TooltipContent>{blocker ?? (template ? `Recreate template${sendTip}` : `Generate${sendTip}`)}</TooltipContent></Tooltip></div>{est.data?.notes.length && !blocker ? <p className="hidden truncate px-2 pt-1 text-[11px] text-muted-foreground sm:block">{est.data.notes[0]}</p> : null}- {/* Phones have no hover: the price (and what blocks Generate) sit under the composer. */}- {(blocker || cost || est.data?.notes.length) && (- <p className="flex min-w-0 items-baseline justify-between gap-2 px-2 pt-1 text-[11px] text-muted-foreground sm:hidden" aria-live="polite">- <span className="min-w-0 truncate">{blocker ?? est.data?.notes[0] ?? ""}</span>- {!blocker && cost && <span className="shrink-0 font-mono tabular-nums">{cost}</span>}+ {/* Phones have no hover: what blocks Generate sits under the composer (the chip says where it runs and its price). */}+ {(blocker || est.data?.notes.length) && (+ <p className="min-w-0 truncate px-2 pt-1 text-[11px] text-muted-foreground sm:hidden" aria-live="polite">+ {blocker ?? est.data?.notes[0] ?? ""}</p>)}</div>diff --git a/src/components/recolor/recolor-tool.tsx b/src/components/recolor/recolor-tool.tsxindex 19484378..1dad7ed9 100644--- a/src/components/recolor/recolor-tool.tsx+++ b/src/components/recolor/recolor-tool.tsx@@ -10,9 +10,11 @@ import { Segmented } from "@/components/faceless/controls";import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";import { FrameStage, type Frame } from "@/components/remove-object/frame-stage";import { fileToSlot, kindOfFile, LibraryGrid, type SlotValue } from "@/components/studio/media-slot";+import { RunPlaceChip, useOpenRunPlace } from "@/components/studio/run-place-chip";+import { getModel } from "@/lib/catalog";import { askToSignUp, useAskBeforeUpload, useCreateGeneration, useGenerations, useIsGuest } from "@/lib/api";import { colourChip, ITEMS, normaliseHex, RECOLOR, recolorRequest, SWATCHES } from "@/lib/catalog/recolor";-import type { PixelPoint } from "@/lib/catalog/types";+import type { GenerationRequest, PixelPoint } from "@/lib/catalog/types";import { toastError } from "@/lib/refusals";import { postFile } from "@/lib/upload";import { cn } from "@/lib/utils";@@ -246,6 +248,15 @@ export function RecolorTool({ app }: { app: { name: string; description: stringconst ready = photo && !photo.uploading && (photo.ref || example) ? photo : null;const taps = points.filter((p) => p.label !== "negative").length;const blocker = !ready ? "Add a photo" : !taps ? "Tap the piece you want in a new colour." : !colours.length ? "Pick a colour" : null;+ // Where it runs and its price, as the studios say it (one run per colour).+ let quoteReq: GenerationRequest | null = null;+ try {+ if (!blocker && ready?.ref && frame) quoteReq = recolorRequest({ image: ready.ref, points, frame, colour: colours[0], item });+ } catch {+ // A colour that can't be read yet: nothing to price.+ }+ const place = useOpenRunPlace([getModel(RECOLOR.modelId)?.name ?? "Qwen Image"], quoteReq, { count: colours.length });+ const runLabel = colours.length > 1 ? `Recolor in ${colours.length} colours` : "Recolor";const go = async () => {if (blocker || !ready || !frame) return void toast(blocker ?? "Add a photo");@@ -357,9 +368,19 @@ export function RecolorTool({ app }: { app: { name: string; description: string<ColourPicker picked={colours} onPicked={setColours} custom={custom} onCustom={setCustom} /></Step><div className="space-y-2">- <Button size="lg" className="h-11 w-full rounded-full text-[15px]" onClick={go} disabled={sending || !ready || !frame} aria-describedby="recolor-blocker">+ <div className="flex justify-center">+ <RunPlaceChip place={place} />+ </div>+ <Button+ size="lg"+ className="h-11 w-full rounded-full text-[15px]"+ onClick={go}+ disabled={sending || !ready || !frame}+ aria-describedby="recolor-blocker"+ title={place?.send ? `${runLabel} · ${place.send}` : undefined}+ >{sending ? <Loader2 className="size-4 animate-spin" /> : <Palette className="size-4" />}- {colours.length > 1 ? `Recolor in ${colours.length} colours` : "Recolor"}+ {runLabel}</Button>{blocker && ready && (<p id="recolor-blocker" className="text-center text-[12px] text-muted-foreground" aria-live="polite">diff --git a/src/components/relight/relight-tool.tsx b/src/components/relight/relight-tool.tsxindex 2ef14e7c..993e0cda 100644--- a/src/components/relight/relight-tool.tsx+++ b/src/components/relight/relight-tool.tsx@@ -16,7 +16,8 @@ import { Slider } from "@/components/ui/slider";import { Switch } from "@/components/ui/switch";import { Textarea } from "@/components/ui/textarea";import { askToSignUp, uploadFile, useCreateGeneration, useGenerations, useHydrated, useIsAccount, useIsGuest, useIsOwner, useStatus } from "@/lib/api";-import { getPreset } from "@/lib/catalog";+import { RunPlaceChip, useOpenRunPlace } from "@/components/studio/run-place-chip";+import { getModel, getPreset } from "@/lib/catalog";import type { Generation, GenerationRequest } from "@/lib/catalog/types";import { DEFAULT_DEMO, type RelightDemo } from "@/lib/relight/demo";import {@@ -614,6 +615,8 @@ export function RelightTool({ app }: { app?: { name: string; description: stringconst sceneBusy = !!sceneId && sceneRun.data?.status !== "succeeded" && sceneRun.data?.status !== "failed";const line = busy ? "Lighting your photo…" : aligning ? "Lining it up…" : sceneBusy ? "Reading the scene…" : photo.uploading ? "Uploading…" : null;const keeper = owner || (account && gpu);+ // Where the lighting is made and its price, as the studios say it: on your GPU, free (an account connects its own).+ const place = useOpenRunPlace([getModel(RELIGHT_MODEL)?.name ?? "Qwen Image 2.1"], null, { ownGpuOnly: true });const changed = anyResult && !current;// "Again" only once this viewer has generated on this photo.const again = made ? "Generate again" : "Generate";@@ -805,7 +808,16 @@ export function RelightTool({ app }: { app?: { name: string; description: string</details><div className="space-y-2">- <Button size="lg" className="h-12 w-full rounded-full" onClick={() => void generate()} disabled={busy || !lights.length || photo.uploading}>+ <div className="flex justify-center">+ <RunPlaceChip place={place} />+ </div>+ <Button+ size="lg"+ className="h-12 w-full rounded-full"+ onClick={() => void generate()}+ disabled={busy || !lights.length || photo.uploading}+ title={place?.send ? `Generate lighting · ${place.send}` : undefined}+ >{busy ? <Loader2 className="size-4 animate-spin" /> : current ? <Check className="size-4" /> : <Sparkles className="size-4" />}{busy ? "Lighting your photo…" : current ? "Lit with these lights" : changed && made ? "Generate again" : "Generate lighting"}</Button>diff --git a/src/components/studio/run-place-chip.tsx b/src/components/studio/run-place-chip.tsxnew file mode 100644index 00000000..4e4106ed--- /dev/null+++ b/src/components/studio/run-place-chip.tsx@@ -0,0 +1,167 @@+"use client";++import { Cloud, Cpu, Lock, MonitorPlay, Server } from "lucide-react";+import Link from "next/link";+import { usePathname } from "next/navigation";+import { useState } from "react";+import { openAddKey } from "@/components/keys/your-keys";+import { Button } from "@/components/ui/button";+import { useIsMobile } from "@/hooks/use-mobile";+import type { Engine, GenerationRequest } from "@/lib/catalog/types";+import { CONNECT_GPU_EVENT, signInHref, useHydrated, useStatus, useViewer } from "@/lib/api";+import { formatCost } from "@/lib/format";+import { quoteBody, useHostedQuote, useSettled } from "@/lib/hosted";+import { runPlace, type RunAudience, type RunPlace, type RunPlaceInput } from "@/lib/run-place";+import { cn } from "@/lib/utils";+import { chipBase, chipIdle } from "./chip";+import { EngineSwitch } from "./engine-switch";+import { ResponsivePanel } from "./responsive-panel";++const ICONS: Record<RunPlace["where"], typeof Cloud> = { cloud: Cloud, gpu: Cpu, pool: Server, browser: MonitorPlay, unavailable: Lock };++/**+ * Who is looking, once known (after hydration and the viewer read): the studio's owner, an account, or a guest. Null+ * before, so a chip never says "Not available here" to the owner and then takes it back. With it, the account's own GPU+ * and its first key (who its paid runs are billed to).+ */+export function useRunViewer(): { audience: RunAudience; gpu: boolean; hosted: boolean; payer: RunPlaceInput["payer"] } | null {+ const hydrated = useHydrated();+ const viewer = useViewer().data;+ const status = useStatus().data;+ if (!hydrated || !viewer) return null;+ const audience: RunAudience = viewer.owner ? "owner" : viewer.account ? "account" : "guest";+ const keys = status?.viewer?.keys ?? [];+ return { audience, gpu: !!status?.viewer?.gpu.connected, hosted: !!status?.viewer?.hosted, payer: keys.includes("fal") ? "fal" : (keys[0] ?? null) };+}++/** The place and price for this viewer (null until the viewer is known). */+export function useRunPlace(input: Omit<RunPlaceInput, "audience" | "format" | "gpu" | "hosted" | "payer">): RunPlace | null {+ const who = useRunViewer();+ return who ? runPlace({ ...input, ...who, format: formatCost }) : null;+}++/**+ * The place and price of an open-model run sent through the studios' generations (an app's own tool): your GPU, free;+ * with hosted runs on, an account with no GPU of its own runs on this studio's GPUs at the price the server quotes for+ * `request` (null: not quoted yet). `count`: runs one press starts (the quote is for one, said "each"). `ownGpuOnly`: a+ * tool that asks an account to connect its GPU instead (Relight), so it is never sent to this studio's GPUs.+ */+export function useOpenRunPlace(models: readonly string[], request: GenerationRequest | null, o: { count?: number; ownGpuOnly?: boolean } = {}): RunPlace | null {+ const viewer = useRunViewer();+ const who = viewer && o.ownGpuOnly ? { ...viewer, hosted: false } : viewer;+ const onPool = !!who && who.audience === "account" && who.hosted && !who.gpu;+ const quote = useHostedQuote(useSettled(onPool ? quoteBody(request, "pool") : null)).data?.quote;+ if (!who) return null;+ const pool = quote ? { text: (o.count ?? 1) > 1 && quote.text ? `${quote.text} each` : quote.text, sub: quote.sub } : undefined;+ return runPlace({ engine: "open", models, ...who, pool, format: formatCost });+}++/**+ * The composer's place chip: where the run happens (your GPU, the cloud model, your browser) and its price, as the+ * studio composer's model chip and price say it. It opens a panel with the whole answer: the steps and their models,+ * who pays, what this viewer does first, and the engine switch where switching exists (`onEngine`).+ */+export function RunPlaceChip({+ place,+ steps,+ engine,+ onEngine,+ pending,+ className,+}: {+ place: RunPlace | null;+ /** The planned steps (a pipeline's script, picture, clip, voice): listed in the panel. */+ steps?: readonly { label: string; modelName: string; costUsd: number | null }[];+ engine?: Engine;+ /** Switching engine from here (the same switch as the header's). */+ onEngine?: (e: Engine) => void;+ /** The price is being worked out. */+ pending?: boolean;+ className?: string;+}) {+ const [open, setOpen] = useState(false);+ const pathname = usePathname();+ // A phone's sheet says the title and the tip in its own header; the desktop popover says them here.+ const mobile = useIsMobile();+ if (!place) return null;+ const Icon = ICONS[place.where];+ const price = pending && !place.price ? "…" : place.price;+ const canSwitch = !!(engine && onEngine && (place.where === "cloud" || place.where === "gpu" || place.where === "pool"));+ const many = (steps?.length ?? 0) > 1;+ return (+ <ResponsivePanel+ open={open}+ onOpenChange={setOpen}+ title={place.title}+ description={place.tip}+ align="end"+ trigger={+ <button+ type="button"+ data-run-place={place.where}+ aria-label={`${place.title}${place.where === "cloud" ? ` on ${place.label}` : ""}${place.price ? `, ${place.price}` : ""}. ${canSwitch ? "Details and engine" : "Details"}`}+ className={cn(chipBase, chipIdle, "max-w-full min-w-0", className)}+ >+ <Icon className="size-3.5 shrink-0" />+ <span className="min-w-0 truncate max-sm:max-w-[9rem]">{place.label}</span>+ {price && (+ <>+ <span aria-hidden className="opacity-50">+ ·+ </span>+ <span className="shrink-0 tabular-nums">{price}</span>+ </>+ )}+ </button>+ }+ >+ <div className="space-y-3 text-[13px]">+ {!mobile && (+ <div>+ <p className="font-semibold">{place.title}</p>+ <p className="mt-0.5 text-[12px] leading-snug text-pretty text-muted-foreground">{place.tip}</p>+ </div>+ )}+ {many && (+ <ul className="space-y-1">+ {steps!.map((s) => (+ <li key={`${s.label}-${s.modelName}`} className="flex min-w-0 items-baseline justify-between gap-3">+ <span className="min-w-0 truncate">+ <span className="text-muted-foreground">{s.label}</span> · {s.modelName}+ </span>+ {place.where === "cloud" && s.costUsd != null && <span className="shrink-0 font-mono text-[12px] text-muted-foreground tabular-nums">{s.costUsd === 0 ? "Free" : `≈ ${formatCost(s.costUsd)}`}</span>}+ </li>+ ))}+ </ul>+ )}+ {place.price && (+ <p className="flex items-baseline justify-between gap-3 border-t pt-2 font-medium">+ <span>{many ? "In all" : "Price"}</span>+ <span className="font-mono tabular-nums">{place.price}</span>+ </p>+ )}+ {place.needs === "signup" && (+ <Button asChild size="sm" className="w-full">+ <Link href={signInHref("signup", pathname)}>Sign up free</Link>+ </Button>+ )}+ {place.needs === "gpu" && (+ <Button size="sm" className="w-full" onClick={() => (setOpen(false), window.dispatchEvent(new Event(CONNECT_GPU_EVENT)))}>+ Connect your GPU+ </Button>+ )}+ {place.needs === "key" && (+ <Button size="sm" className="w-full" onClick={() => (setOpen(false), openAddKey("fal"))}>+ Add your key+ </Button>+ )}+ {canSwitch && (+ <div className="flex flex-wrap items-center justify-between gap-2 border-t pt-3">+ <span className="text-[12px] font-medium text-muted-foreground">Engine</span>+ <EngineSwitch value={engine!} onChange={onEngine!} size="sm" compact={false} />+ </div>+ )}+ </div>+ </ResponsivePanel>+ );+}diff --git a/src/lib/run-place.ts b/src/lib/run-place.tsnew file mode 100644index 00000000..ce8281e8--- /dev/null+++ b/src/lib/run-place.ts@@ -0,0 +1,169 @@+import { billedTo, CLOUD_KEY, type CloudProvider } from "./your-keys";++/**+ * Where a run happens and what it costs, in the words a composer's place chip, its price and its send button use+ * (src/components/studio/run-place-chip.tsx). Pure: tests/run-place.test.ts covers every audience and engine.+ *+ * The same words as the studio composer: an open model runs on your GPU, free; a paid model runs in the cloud at the+ * provider's price, billed to the key that runs it; a Kinetic template is drawn in your browser, instant and free.+ * A tool that runs for the studio's owner only says so to anyone else, with no price (never a "free" it can't keep).+ */++/** Who is looking: the studio's owner, a signed-in account (public sign-up), or a signed-out guest. */+export type RunAudience = "owner" | "account" | "guest";++export interface RunPlaceInput {+ audience: RunAudience;+ /** cloud: paid models through a provider key; open: open models on a GPU; browser: drawn here, no model at all. */+ engine: "cloud" | "open" | "browser";+ /** The models the run uses, in the order they run (the planned steps' model names). */+ models?: readonly string[];+ /** The model the chip names in the cloud (the run's main one). Defaults to the first of `models`. */+ model?: string;+ /** The run's price in USD: undefined while it is being priced, null when the provider publishes none. */+ costUsd?: number | null;+ /** Placeholder results are on (Settings): every output is a free stand-in. */+ demo?: boolean;+ /** The tool's name when it runs for the studio's owner only (the Marketing suite): anyone else is told so. */+ ownerOnly?: string;+ /** An account's own GPU is connected (Your GPU). */+ gpu?: boolean;+ /** Hosted runs are on: an open model may run on this studio's GPUs when the viewer has no GPU of its own. */+ hosted?: boolean;+ /** The price of a run on this studio's GPUs (the billing service's words; empty text: free), undefined while pricing. */+ pool?: { text: string; sub?: string } | null;+ /** The provider an account's paid run is billed to (its own key), or null when it has no key for this model. */+ payer?: CloudProvider | null;+ /** How a price reads: "$0.04". */+ format: (usd: number) => string;+}++export interface RunPlace {+ /** What the chip's icon shows. */+ where: "cloud" | "gpu" | "pool" | "browser" | "unavailable";+ /** The chip's words: "Your GPU", "This studio's GPUs", the cloud model's name, "Your browser", "Not available here". */+ label: string;+ /** "Free", "≈ $0.04", "Placeholder · free", "Price unknown", or "" (not priced yet, or nothing to price). */+ price: string;+ /** The chip's panel heading: "Runs on your GPU". */+ title: string;+ /** One or two plain sentences: where it runs, with what, and who pays. */+ tip: string;+ /** After "Generate · " on the send button's tooltip: the price and the place, "Free · your GPU", "≈ $0.04 · cloud". */+ send: string;+ /** What this viewer does before the run can start: create an account, connect a GPU, or add a key. */+ needs?: "signup" | "gpu" | "key";+}++const list = (names: readonly string[]) => (names.length < 2 ? (names[0] ?? "") : `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`);++/** Unique names, in order. */+const uniq = (names: readonly string[] | undefined) => [...new Set((names ?? []).filter(Boolean))];++/** The price's words (the studio composer's costLabel, without the place: the chip says that). */+export function placePrice(s: { demo?: boolean; costUsd?: number | null; open: boolean }, format: (usd: number) => string): string {+ if (s.demo) return "Placeholder · free";+ // Every run on the open engine is free on the GPU: said before the run is priced too.+ if (s.open) return "Free";+ if (s.costUsd === undefined) return "";+ if (s.costUsd === null) return "Price unknown";+ return s.costUsd === 0 ? "Free" : `≈ ${format(s.costUsd)}`;+}++export function runPlace(input: RunPlaceInput): RunPlace {+ const { audience, engine } = input;+ if (engine === "browser") {+ return {+ where: "browser",+ label: "Your browser",+ price: "Free",+ title: "Runs in your browser",+ tip: "It plays as you type, instantly and free. No model and no GPU are used.",+ send: "Free · in your browser",+ };+ }+ if (input.ownerOnly && audience !== "owner") {+ return {+ where: "unavailable",+ label: "Not available here",+ price: "",+ title: "Not available here",+ tip: `${input.ownerOnly} isn't available here. Try the Image, Video or Audio studio.`,+ send: "",+ };+ }+ const models = uniq(input.models);+ const open = engine === "open";+ const price = placePrice({ demo: input.demo, costUsd: input.costUsd, open }, input.format);+ const withModels = models.length ? ` with ${list(models)}` : "";+ // Hosted runs: an account (or a guest, once signed up) with no GPU of its own runs open models on this studio's GPUs,+ // at the billing service's price (the studio composer's "This studio's GPUs" chip).+ if (open && input.hosted && audience !== "owner" && !input.gpu) {+ const signup = audience === "guest";+ const poolPrice = input.demo ? price : input.pool ? input.pool.text || "Free" : "";+ const tip = input.demo+ ? "Placeholder results are on (Settings), so outputs are free stand-ins."+ : `${input.pool?.sub ?? `Runs on this studio's GPUs${withModels}.`}${signup ? " Create a free account to run it." : ""}`;+ return {+ where: "pool",+ label: "This studio's GPUs",+ price: poolPrice,+ title: "Runs on this studio's GPUs",+ tip,+ send: input.demo ? price : [poolPrice, signup ? "this studio's GPUs, after sign-up" : "this studio's GPUs"].filter(Boolean).join(" · "),+ ...(signup && { needs: "signup" as const }),+ };+ }+ if (open) {+ const needs = audience === "guest" ? "signup" : audience === "account" && !input.gpu ? "gpu" : undefined;+ const then = needs === "signup" ? " Create a free account and connect your GPU to run it." : needs === "gpu" ? " Connect your GPU to run it." : "";+ return {+ where: "gpu",+ label: "Your GPU",+ price,+ title: "Runs on your GPU",+ tip: input.demo ? "Placeholder results are on (Settings), so outputs are free stand-ins." : `Runs on your own GPU${withModels}. Free.${then}`,+ send: input.demo ? price : `${price} · ${needs === "signup" ? "your GPU, after sign-up" : needs === "gpu" ? "connect your GPU first" : "your GPU"}`,+ ...(needs && { needs }),+ };+ }+ const model = input.model ?? models[0];+ const inCloud = `Runs in the cloud${withModels}.`;+ let tip: string;+ let needs: RunPlace["needs"];+ let who = "cloud";+ if (input.demo) tip = "Placeholder results are on (Settings), so outputs are free stand-ins.";+ else if (audience === "owner") tip = `${inCloud} Estimated cost, billed by the provider to your key.`;+ else if (audience === "guest") {+ needs = "signup";+ who = "cloud, after sign-up";+ tip = `${inCloud} Billed to your own ${CLOUD_KEY.fal.label} or ${CLOUD_KEY.replicate.label} account: create a free account and add your key to run it.`;+ } else if (input.payer) tip = `${inCloud} Estimated cost, billed to ${billedTo(input.payer)}.`;+ else {+ needs = "key";+ who = "add your key";+ tip = `${inCloud} Billed to your own ${CLOUD_KEY.fal.label} or ${CLOUD_KEY.replicate.label} account: add your key in Settings → Your keys.`;+ }+ return {+ where: "cloud",+ label: model || "Cloud",+ price,+ title: "Runs in the cloud",+ tip,+ send: input.demo ? price : [price, who].filter(Boolean).join(" · "),+ ...(needs && { needs }),+ };+}++/**+ * The model a multi-step run is named by in the cloud: its costliest step (the picture or the clip, not the script or+ * the join), the first on a tie. Undefined with no steps.+ */+export function mainModel(steps: readonly { modelName: string; costUsd: number | null }[] | undefined): string | undefined {+ let best: { modelName: string; costUsd: number | null } | undefined;+ for (const s of steps ?? []) if (!best || (s.costUsd ?? -1) > (best.costUsd ?? -1)) best = s;+ return best?.modelName;+}++/** Drawn in this browser (a Kinetic template, Click to Ad's end card): the same place and price whoever looks. */+export const IN_BROWSER: RunPlace = runPlace({ audience: "guest", engine: "browser", format: String });diff --git a/tests/e2e/where-it-runs.mjs b/tests/e2e/where-it-runs.mjsnew file mode 100644index 00000000..e29ee779--- /dev/null+++ b/tests/e2e/where-it-runs.mjs@@ -0,0 +1,223 @@+// Where a run happens and what it costs, in the Marketing suite's composers, for every audience, end to end.+// Starts a stand-in fal.ai (tests/helpers/fake-cloud.ts) on WIR_PORT+2 and `next dev` on WIR_PORT (3900) with a+// throwaway data folder and ComfyUI on a dead port. No real key, no paid call, no GPU. Everything is stopped at the end.+//+// node tests/e2e/where-it-runs.mjs [screenshots folder]+//+// Audiences: the owner; an account with its own fal.ai key; an account with no key and no GPU; a guest. Each at 390+// and 1440 wide. Checks, per surface (Marketing Studio, Click to Ad, Ad Multiplier, Ads Studio's New ads, a Kinetic+// template): the composer has a place chip; the owner's says your GPU or the cloud (never "Not available here") and opens+// a panel with the engine switch; anyone else is told the tool isn't available here, with no price and never "Free";+// a Kinetic template and Click to Ad's end card say they run in your browser, free, to everyone; no horizontal scroll on+// a phone. The apps with tools of their own: Tap to Recolor (everyone) and Relight (the owner, before its GPU check)+// say your GPU, free, and what a guest (sign up) or an account with no GPU (connect it) does first.+import { spawn, execSync } from "node:child_process";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { DESKTOP, launch, PHONE, root } from "./_browser.mjs";+import { startFakeFal } from "../helpers/fake-cloud.ts";+import { tempDir, removeDir } from "./_temp.mjs";++const APP_PORT = Number(process.env.WIR_PORT ?? 3900);+const APP = `http://127.0.0.1:${APP_PORT}`;+const shots = path.resolve(process.argv[2] ?? fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-where-it-runs-")));+fs.mkdirSync(shots, { recursive: true });+const data = tempDir("fuobe-where-it-runs-data-");+const logFile = path.join(shots, "server.log");++const PASSWORD = "owner password for where it runs";+const ACCT_FAL = "wir-acct-key-id:wir-acct-secret-41c2";+const KINETIC = "ms-kinetic-headline";++const failures = [];+const check = (ok, what) => {+ console.log(`${ok ? "ok " : "FAIL"} ${what}`);+ if (!ok) failures.push(what);+};+const wait = (ms) => new Promise((r) => setTimeout(r, ms));++const fal = await startFakeFal(APP_PORT + 2);+fal.keys[ACCT_FAL] = "good";++const log = fs.openSync(logFile, "w");+const server = spawn(process.execPath, [path.join(root, "node_modules/next/dist/bin/next"), "dev", "-p", String(APP_PORT), "-H", "127.0.0.1"], {+ cwd: root,+ env: {+ ...process.env,+ NODE_ENV: "development",+ FUOBE_DATA_DIR: data,+ FUOBE_PASSWORD: PASSWORD,+ FUOBE_PUBLIC_SIGNUP: "1",+ FUOBE_DEV_FAL_URL: fal.url,+ COMFYUI_URL: "http://127.0.0.1:9",+ FUOBE_ACCOUNT_DISK_FREE_GB: "0",+ },+ stdio: ["ignore", log, log],+});++async function stopAll() {+ try {+ if (process.platform === "win32") execSync(`taskkill /pid ${server.pid} /T /F`, { stdio: "ignore" });+ else server.kill("SIGTERM");+ } catch {}+ await fal.close();+}++const api = async (route, { method = "GET", body, cookie } = {}) => {+ const res = await fetch(APP + route, { method, headers: { "Content-Type": "application/json", Origin: APP, ...(cookie && { cookie }) }, ...(body !== undefined && { body: JSON.stringify(body) }) });+ const text = await res.text();+ let json = null;+ try {+ json = JSON.parse(text);+ } catch {}+ return { status: res.status, text, json, headers: res.headers };+};+const cookieOf = (res) => /fuobe_session=[^;]+/.exec(res.headers.get("set-cookie") ?? "")?.[0];++/** The page's place chip, once the viewer is known (the chip waits for it). */+async function chipOf(page, scope = page, sel = "[data-run-place]") {+ const chip = scope.locator(sel).first();+ await chip.waitFor({ state: "attached", timeout: 60_000 }).catch(() => {});+ if (!(await chip.count())) return null;+ return { el: chip, where: await chip.getAttribute("data-run-place"), text: ((await chip.textContent()) ?? "").trim(), aria: (await chip.getAttribute("aria-label")) ?? "" };+}++const noSideScroll = (page) => page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1);++try {+ for (let i = 0; i < 240; i++) {+ try {+ const r = await fetch(`${APP}/login`);+ if (r.status < 500) break;+ } catch {}+ await wait(1000);+ }++ const owner = cookieOf(await api("/api/auth/login", { method: "POST", body: { password: PASSWORD } }));+ check(!!owner, "owner signs in");+ // A brand kit and a product, so Ads Studio's New ads has something to price.+ const brand = await api("/api/brands", { method: "POST", cookie: owner, body: { name: "Maison Test", description: "A small perfume house in Paris." } });+ const brandId = brand.json?.id;+ if (brandId) await api("/api/products", { method: "POST", cookie: owner, body: { name: "Eau de Nuit", brandId, description: "A night perfume." } });+ check(!!brandId, `owner makes a brand kit for New ads (${brand.status})`);++ const keyed = cookieOf(await api("/api/auth/signup", { method: "POST", body: { email: "[email protected]", password: "account password one" } }));+ check(!!keyed, "an account signs up (it will add its key)");+ const put = await api("/api/account/keys/fal", { method: "PUT", cookie: keyed, body: { key: ACCT_FAL } });+ check(put.status === 200, `that account adds its own fal.ai key (${put.status})`);+ const bare = cookieOf(await api("/api/auth/signup", { method: "POST", body: { email: "[email protected]", password: "account password two" } }));+ check(!!bare, "an account signs up with no key and no GPU");++ const AUDIENCES = [+ ["owner", owner],+ ["account-with-key", keyed],+ ["account-without", bare],+ ["guest", null],+ ];+ const SURFACES = [+ ["marketing", "/marketing", "Marketing Studio"],+ ["click-to-ad", "/marketing/click-to-ad", "Click to Ad"],+ ["multiplier", "/ads/multiplier", "Ad Multiplier"],+ ...(brandId ? [["new-ads", `/ads/${brandId}?step=new`, "Ads Studio"]] : []),+ ];++ const browser = await launch();+ for (const [who, cookie] of AUDIENCES) {+ for (const [size, opts] of [+ ["1440", DESKTOP],+ ["390", PHONE],+ ]) {+ const ctx = await browser.newContext({ ...opts, baseURL: APP });+ if (cookie) {+ const [name, value] = cookie.split("=");+ await ctx.addCookies([{ name, value, url: APP }]);+ }+ const page = await ctx.newPage();+ for (const [id, route, tool] of SURFACES) {+ // Ads Studio's brand pages are the owner's: anyone else never reaches New ads.+ if (id === "new-ads" && who !== "owner") continue;+ await page.goto(route, { waitUntil: "load", timeout: 240_000 });+ await page.waitForTimeout(2500);+ const tag = `${who} ${size} ${tool}`;+ if (id === "click-to-ad") {+ // Before a product is picked: the end card to try, drawn in your browser, free, for everyone.+ const card = await chipOf(page, page.locator('section[aria-labelledby="c2a-end-card-try"]'));+ check(card?.where === "browser" && /Your browser/.test(card.text) && /Free/.test(card.text), `${tag}: the end card runs in your browser, free ("${card?.text}")`);+ if (who !== "owner") {+ // No products of its own and no composer: the page says it isn't available here.+ check(await page.getByText("Click to Ad isn't available here.").first().isVisible().catch(() => false), `${tag}: the page says it isn't available here`);+ check(!(await page.locator('[data-run-place]:not([data-run-place="browser"])').count()), `${tag}: no run place offered`);+ if (size === "390") check(await noSideScroll(page), `${tag}: no horizontal scroll at 390`);+ await page.screenshot({ path: path.join(shots, `${who}-${size}-${id}.png`) });+ continue;+ }+ await page.getByRole("button", { name: /Eau de Nuit/ }).first().click();+ await page.waitForTimeout(2500);+ }+ const chip = await chipOf(page, page, '[data-run-place]:not([data-run-place="browser"])');+ check(!!chip, `${tag}: the composer says where it runs`);+ if (!chip) continue;+ if (who === "owner") {+ check(chip.where === "gpu" || chip.where === "cloud", `${tag}: on your GPU or in the cloud (${chip.where}: "${chip.text}")`);+ check(chip.where !== "gpu" || /Your GPU/.test(chip.text), `${tag}: the GPU chip says Your GPU`);+ await chip.el.click();+ const panel = page.getByText(chip.where === "gpu" ? "Runs on your GPU" : "Runs in the cloud").first();+ check(await panel.isVisible({ timeout: 10_000 }).catch(() => false), `${tag}: the chip opens where it runs`);+ await page.screenshot({ path: path.join(shots, `${who}-${size}-${id}-panel.png`) });+ const sw = page.getByRole("radiogroup").or(page.locator('[role="dialog"] button, [data-radix-popper-content-wrapper] button').filter({ hasText: /Cloud|Open source/ }));+ check((await sw.count()) > 0, `${tag}: the engine switch is in the panel`);+ await page.keyboard.press("Escape");+ } else {+ check(chip.where === "unavailable" && /Not available here/.test(chip.text), `${tag}: told it isn't available here ("${chip.text}")`);+ check(!/free|\$/i.test(chip.text + chip.aria), `${tag}: no price and never "free"`);+ }+ if (size === "390") check(await noSideScroll(page), `${tag}: no horizontal scroll at 390`);+ await page.screenshot({ path: path.join(shots, `${who}-${size}-${id}.png`) });+ }++ // A Kinetic template: drawn in your browser, free, for everyone.+ await page.goto(`/marketing?template=${KINETIC}`, { waitUntil: "load", timeout: 240_000 });+ const panel = page.locator(`[data-kinetic-template="${KINETIC}"]`);+ await panel.waitFor({ timeout: 120_000 }).catch(() => {});+ const k = await chipOf(page, panel);+ check(k?.where === "browser" && /Your browser/.test(k.text) && /Free/.test(k.text), `${who} ${size} Kinetic: runs in your browser, free ("${k?.text}")`);+ if (k) {+ await k.el.click();+ check(await page.getByText("Runs in your browser").first().isVisible({ timeout: 10_000 }).catch(() => false), `${who} ${size} Kinetic: the chip says it plays instantly and free`);+ await page.screenshot({ path: path.join(shots, `${who}-${size}-kinetic.png`) });+ await page.keyboard.press("Escape");+ }+ if (size === "390") check(await noSideScroll(page), `${who} 390 Kinetic: no horizontal scroll`);++ // Apps with tools of their own: on your GPU, free; a guest signs up and an account connects its GPU first.+ const APPS = [["recolor", "/apps/app-tap-to-recolor", "Tap to Recolor"], ...(who === "owner" ? [["relight", "/apps/app-relight", "Relight"]] : [])];+ for (const [id, route, tool] of APPS) {+ const tag = `${who} ${size} ${tool}`;+ await page.goto(route, { waitUntil: "load", timeout: 240_000 });+ if (id === "recolor") await page.getByText("Try it on this photo").first().click({ timeout: 60_000 }).catch(() => {});+ const a = await chipOf(page);+ check(a?.where === "gpu" && /Your GPU/.test(a.text) && /Free/.test(a.text), `${tag}: runs on your GPU, free ("${a?.text}")`);+ if (!a) continue;+ await a.el.click();+ check(await page.getByText("Runs on your GPU").first().isVisible({ timeout: 10_000 }).catch(() => false), `${tag}: the chip opens where it runs`);+ const next = { owner: null, guest: "Sign up free", "account-with-key": "Connect your GPU", "account-without": "Connect your GPU" }[who];+ if (next) check(await page.getByRole(next === "Sign up free" ? "link" : "button", { name: next }).first().isVisible().catch(() => false), `${tag}: says what to do first ("${next}")`);+ await page.screenshot({ path: path.join(shots, `${who}-${size}-${id}.png`) });+ await page.keyboard.press("Escape");+ if (size === "390") check(await noSideScroll(page), `${tag}: no horizontal scroll at 390`);+ }+ await ctx.close();+ }+ }+ await browser.close();+} catch (e) {+ console.error(e);+ failures.push(String(e?.message ?? e));+} finally {+ await stopAll();+ removeDir(data);+}++console.log(`\n${failures.length ? `${failures.length} FAILED` : "all passed"} · screenshots in ${shots}`);+process.exit(failures.length ? 1 : 0);diff --git a/tests/run-place.test.ts b/tests/run-place.test.tsnew file mode 100644index 00000000..a1ee94e7--- /dev/null+++ b/tests/run-place.test.ts@@ -0,0 +1,181 @@+import { describe, expect, it } from "vitest";+import { IN_BROWSER, mainModel, placePrice, runPlace, type RunPlaceInput } from "@/lib/run-place";++/** 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)}`;+const at = (o: Partial<RunPlaceInput> & Pick<RunPlaceInput, "audience" | "engine">) => runPlace({ format: fmt, ...o });+const AUDIENCES = ["owner", "account", "guest"] as const;++describe("the price's words", () => {+ it("says free on the open engine, even before the run is priced", () => {+ expect(placePrice({ open: true }, fmt)).toBe("Free");+ expect(placePrice({ open: true, costUsd: 0 }, fmt)).toBe("Free");+ });+ it("prices the cloud, says when no price is published, and nothing while pricing", () => {+ expect(placePrice({ open: false, costUsd: 0.04 }, fmt)).toBe("≈ $0.04");+ expect(placePrice({ open: false, costUsd: null }, fmt)).toBe("Price unknown");+ expect(placePrice({ open: false }, fmt)).toBe("");+ });+ it("says placeholder results are free stand-ins on either engine", () => {+ expect(placePrice({ open: false, demo: true, costUsd: 0.4 }, fmt)).toBe("Placeholder · free");+ expect(placePrice({ open: true, demo: true }, fmt)).toBe("Placeholder · free");+ });+});++describe("the owner", () => {+ it("runs open models on its own GPU, free", () => {+ const p = at({ audience: "owner", engine: "open", models: ["Qwen Image 2.1", "Qwen Image 2.1"], costUsd: 0 });+ expect(p).toMatchObject({ where: "gpu", label: "Your GPU", price: "Free", title: "Runs on your GPU", send: "Free · your GPU" });+ expect(p.tip).toBe("Runs on your own GPU with Qwen Image 2.1. Free.");+ expect(p.needs).toBeUndefined();+ });+ it("runs paid models in the cloud, named by the main model, billed to its key", () => {+ const p = at({ audience: "owner", engine: "cloud", models: ["GPT-5 mini", "Nano Banana Pro"], model: "Nano Banana Pro", costUsd: 0.15 });+ expect(p).toMatchObject({ where: "cloud", label: "Nano Banana Pro", price: "≈ $0.15", send: "≈ $0.15 · cloud" });+ expect(p.tip).toBe("Runs in the cloud with GPT-5 mini and Nano Banana Pro. Estimated cost, billed by the provider to your key.");+ });+ it("names the cloud before the run is priced, and the first model when no main one is given", () => {+ expect(at({ audience: "owner", engine: "cloud" })).toMatchObject({ label: "Cloud", price: "", send: "cloud" });+ expect(at({ audience: "owner", engine: "cloud", models: ["Kling 2.5"] }).label).toBe("Kling 2.5");+ });+ it("says placeholder results are free stand-ins", () => {+ const p = at({ audience: "owner", engine: "cloud", models: ["Nano Banana Pro"], costUsd: 0.15, demo: true });+ expect(p).toMatchObject({ price: "Placeholder · free", send: "Placeholder · free" });+ expect(p.tip).toMatch(/Placeholder results are on/);+ });+ it("runs a tool that is the owner's alone", () => {+ expect(at({ audience: "owner", engine: "open", ownerOnly: "Marketing Studio" }).where).toBe("gpu");+ expect(at({ audience: "owner", engine: "cloud", ownerOnly: "Marketing Studio", costUsd: 0.04 }).price).toBe("≈ $0.04");+ });+});++describe("an account", () => {+ it("with its own GPU: free on it", () => {+ const p = at({ audience: "account", engine: "open", gpu: true });+ expect(p).toMatchObject({ where: "gpu", price: "Free", send: "Free · your GPU" });+ expect(p.needs).toBeUndefined();+ });+ it("without one: still free, and connects its GPU first", () => {+ const p = at({ audience: "account", engine: "open", gpu: false });+ expect(p).toMatchObject({ where: "gpu", price: "Free", needs: "gpu", send: "Free · connect your GPU first" });+ expect(p.tip).toMatch(/Connect your GPU to run it\.$/);+ });+ it("with a key: the cloud's price, billed to its own provider account", () => {+ const p = at({ audience: "account", engine: "cloud", models: ["Nano Banana Pro"], costUsd: 0.15, payer: "fal" });+ expect(p).toMatchObject({ where: "cloud", price: "≈ $0.15", send: "≈ $0.15 · cloud" });+ expect(p.tip).toBe("Runs in the cloud with Nano Banana Pro. Estimated cost, billed to your fal.ai account.");+ expect(p.needs).toBeUndefined();+ });+ it("without a key: adds one first, never billed to the studio", () => {+ const p = at({ audience: "account", engine: "cloud", models: ["Nano Banana Pro"], costUsd: 0.15, payer: null });+ expect(p).toMatchObject({ needs: "key", send: "≈ $0.15 · add your key" });+ expect(p.tip).toMatch(/your own fal\.ai or Replicate account: add your key in Settings → Your keys\.$/);+ });+});++describe("a guest", () => {+ it("is told to sign up before a run on its GPU, never a bare free", () => {+ const p = at({ audience: "guest", engine: "open" });+ expect(p).toMatchObject({ where: "gpu", needs: "signup", send: "Free · your GPU, after sign-up" });+ expect(p.tip).toMatch(/Create a free account and connect your GPU to run it\.$/);+ });+ it("is told a cloud run is billed to its own key, after sign-up", () => {+ const p = at({ audience: "guest", engine: "cloud", models: ["Nano Banana Pro"], costUsd: 0.15 });+ expect(p).toMatchObject({ where: "cloud", needs: "signup", send: "≈ $0.15 · cloud, after sign-up" });+ expect(p.tip).toMatch(/your own fal\.ai or Replicate account: create a free account and add your key to run it\.$/);+ });+});++describe("hosted runs (this studio's GPUs)", () => {+ it("an account with no GPU runs open models there, at the quoted price", () => {+ const p = at({ audience: "account", engine: "open", hosted: true, gpu: false, models: ["Tap to Recolor"], pool: { text: "$0.02" } });+ expect(p).toMatchObject({ where: "pool", label: "This studio's GPUs", price: "$0.02", title: "Runs on this studio's GPUs", send: "$0.02 · this studio's GPUs" });+ expect(p.tip).toBe("Runs on this studio's GPUs with Tap to Recolor.");+ expect(p.needs).toBeUndefined();+ });+ it("says the service's own words, free when it quotes no price, and nothing while pricing", () => {+ expect(at({ audience: "account", engine: "open", hosted: true, pool: { text: "", sub: "Included in your plan" } })).toMatchObject({ price: "Free", tip: "Included in your plan" });+ expect(at({ audience: "account", engine: "open", hosted: true })).toMatchObject({ where: "pool", price: "", send: "this studio's GPUs" });+ });+ it("an account with its own GPU still runs there, free; the owner always on its own", () => {+ expect(at({ audience: "account", engine: "open", hosted: true, gpu: true }).where).toBe("gpu");+ expect(at({ audience: "owner", engine: "open", hosted: true }).where).toBe("gpu");+ });+ it("a guest signs up first", () => {+ const p = at({ audience: "guest", engine: "open", hosted: true });+ expect(p).toMatchObject({ where: "pool", needs: "signup", send: "this studio's GPUs, after sign-up" });+ expect(p.tip).toMatch(/Create a free account to run it.$/);+ });+ it("leaves the cloud and the owner's tools as they are", () => {+ expect(at({ audience: "account", engine: "cloud", hosted: true, payer: "fal", costUsd: 0.1 }).where).toBe("cloud");+ expect(at({ audience: "account", engine: "open", hosted: true, ownerOnly: "Ads Studio" }).where).toBe("unavailable");+ });+});++describe("a tool that runs for the owner only (the Marketing suite)", () => {+ for (const audience of ["account", "guest"] as const)+ for (const engine of ["open", "cloud"] as const)+ it(`tells ${audience === "account" ? "an account" : "a guest"} on ${engine} it isn't available here, with no price`, () => {+ const p = at({ audience, engine, ownerOnly: "Click to Ad", costUsd: 0, gpu: true, payer: "fal" });+ expect(p).toMatchObject({ where: "unavailable", label: "Not available here", price: "", send: "" });+ expect(p.tip).toBe("Click to Ad isn't available here. Try the Image, Video or Audio studio.");+ expect(p.needs).toBeUndefined();+ });+});++describe("a Kinetic template", () => {+ it("is the shared in-browser place", () => {+ expect(IN_BROWSER).toMatchObject({ where: "browser", label: "Your browser", price: "Free" });+ });+ it("runs in the browser, instant and free, for everyone (owner-only tools included)", () => {+ for (const audience of AUDIENCES) {+ const p = at({ audience, engine: "browser", ownerOnly: "Marketing Studio" });+ expect(p).toMatchObject({ where: "browser", label: "Your browser", price: "Free", title: "Runs in your browser", send: "Free · in your browser" });+ expect(p.tip).toMatch(/instantly and free/);+ expect(p.needs).toBeUndefined();+ }+ });+});++describe("no audience is told a run is free when it isn't", () => {+ it("a priced cloud run never reads free", () => {+ for (const audience of AUDIENCES) {+ const p = at({ audience, engine: "cloud", models: ["Kling 2.5"], costUsd: 0.7, payer: "fal" });+ expect(p.price).toBe("≈ $0.70");+ expect(p.send).not.toMatch(/free/i);+ }+ });+ it("the place's words hold no internal terms", () => {+ for (const audience of AUDIENCES)+ for (const engine of ["open", "cloud", "browser"] as const)+ for (const ownerOnly of [undefined, "Ad Multiplier"]) {+ for (const hosted of [false, true]) {+ const p = at({ audience, engine, ownerOnly, hosted, models: ["Kling 2.5"], costUsd: 0.7 });+ expect(`${p.label} ${p.price} ${p.title} ${p.tip} ${p.send}`).not.toMatch(/self-host|comfy|demo mode|pool|tenant|engine mode|hosted/i);+ }+ const p = at({ audience, engine, ownerOnly, models: ["Kling 2.5"], costUsd: 0.7 });+ expect(`${p.label} ${p.price} ${p.title} ${p.tip} ${p.send}`).not.toMatch(/self-host|comfy|demo mode|pool|tenant|engine mode/i);+ }+ });+});++describe("the main model of a pipeline", () => {+ it("is its costliest step, the first on a tie", () => {+ expect(+ mainModel([+ { modelName: "GPT-5 mini", costUsd: 0.001 },+ { modelName: "Kling 2.5", costUsd: 0.7 },+ { modelName: "ElevenLabs", costUsd: 0.05 },+ ]),+ ).toBe("Kling 2.5");+ expect(+ mainModel([+ { modelName: "Qwen Image 2.1", costUsd: 0 },+ { modelName: "Wan 2.2", costUsd: 0 },+ ]),+ ).toBe("Qwen Image 2.1");+ expect(mainModel([{ modelName: "Join", costUsd: null }, { modelName: "Seedance", costUsd: 0.2 }])).toBe("Seedance");+ expect(mainModel([])).toBeUndefined();+ expect(mainModel(undefined)).toBeUndefined();+ });+});