The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Runs on this install's GPUs: a price before every key run, waits that hold, and a way on from every label
Adarsh1b313821c942
diff --git a/docs/billing-hook.md b/docs/billing-hook.mdindex 6a1954f3..2bf04d17 100644--- a/docs/billing-hook.md+++ b/docs/billing-hook.md@@ -85,7 +85,7 @@ as it takes (the run never fails for a wait). Present, it wins over the reserveanswer says, and with none `FUOBE_POOL_WAIT_MIN`. `limits.offerAfterS` is the wait (in seconds, as the price checkestimates it) after which the line before Run offers an account its own GPU, or a key that runs the item's cloudversion at its price, for that one run. Absent: 1200. A wait with no end known (every GPU that could run it is away)-counts as past it.+counts as past it. 0 turns the offer off for waits: it shows only at the daily cap and while runs there are paused.`limits.held` says runs wait instead of being refused. Present (0 or more), a press past `limits.activeRuns`,`limits.waiting` or an hourly limit is taken: the run is made, its tile says "In line", and it enters the line when@@ -102,7 +102,10 @@ the run is expected to wait before it enters the line at all (behind the accountgiven); a service adds it to the hold's life.While the service doesn't answer, a run that would go to this install's GPUs because the service's last answer put them-first (`prefer: "pool"`) waits for the service; it is never moved to the account's own GPU for that.+first (`prefer: "pool"`) waits for the service; it is never moved to the account's own GPU for that. Fuobe keeps the+service's last policy answer in its database while hosted runs are on, so after a restart, or an outage longer than+it keeps an answer in memory, a press is still taken and waits for the service in line under that answer (when it says+runs wait: `limits.held`). With no answer ever kept, or one without `limits.held`, the press is refused as before.`queue.nextOpenAt` is when the first GPU that could run the run is due back (the start of its hours, or the end of apause on its PC that has one), when every such GPU is away and one says; otherwise null.diff --git a/docs/public-signup.md b/docs/public-signup.mdindex a3e0025c..c41702ca 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -670,7 +670,14 @@ With it on:(or key) and **OK**. Both keep a pick, so the note shows once for the account, on any device.- A connected GPU runs what this install's GPUs don't take with the first press ("Free · your GPU"). A key runs such anitem only when the key is the account's pick; otherwise the press shows "Run with your fal.ai key · ≈ $0.04" (one run,- its price first) and Connect your GPU. A key is never billed by a press that showed "Free".+ its price first) and Connect your GPU. A key is never billed by a press that showed "Free": with the key as the pick,+ the price chip says the key's price first ("≈ $0.04 · your key"), and every key offer on a failed run's tile carries+ its price (one with no price known is not shown).+- A run that failed on the account's own GPU or key offers **Run on …** once, only when this install's GPUs take it+ (on a key: the item's open version), and the account's pick stays. When its key turned the last run down (out of+ credit, not accepted), the composer says so before the next press, with the same **Run on …**.+- A tool open to the owner only (Marketing Studio, Ads Studio, Ad Multiplier, Click to Ad) reads "Coming soon" to+ accounts, with a press to the studio that makes it now ("Make it in the Image studio").- Visitors read this install's GPUs by one place name: "Runs on our GPUs", "Made on: Our GPUs", "Run on Our GPUs".The billing service's policy sets it (`placeName`); without one, Settings → Workers → Name for your GPUs, else`FUOBE_PLACE_NAME`, else "Our GPUs". It is never sent while hosted runs are off.@@ -734,7 +741,7 @@ With it on:"starts in about 3 h" when the first is due back at a known time). An account whose runs go to the studio's GPUs isnever moved to its own GPU for that, nor while the billing service is quiet; only what those GPUs can't run at allgoes there. After a long wait (the policy's `limits.offerAfterS`, 20 minutes by default, or a wait with no end- known) an account with its own GPU, or a key that runs the item's cloud version, is offered it for that one run+ known; 0 turns this offer off) an account with its own GPU, or a key that runs the item's cloud version, is offered it for that one run("Run it now on your GPU", "Run it now with your fal.ai key · ≈ $0.04"), and its pick of where runs go stays.- How long a run may wait before a GPU first takes it: the billing service's `limits.giveUpS` when its policy says(0: as long as it takes), else what its reserve answer says, else `FUOBE_POOL_WAIT_MIN` minutes (30 by default).diff --git a/src/app/api/admin/workers/route.ts b/src/app/api/admin/workers/route.tsindex 9cf3f80b..f4b8ff36 100644--- a/src/app/api/admin/workers/route.ts+++ b/src/app/api/admin/workers/route.ts@@ -1,6 +1,7 @@import { connection } from "next/server";import { adminAccess, audit } from "@/server/admin-tokens";import { addWorker, lanesCatalog, listWorkers } from "@/server/computer/pool";+import { hostedRunsOn } from "@/server/hosted-switch";import { heldView } from "@/server/pool-holds";const NO_STORE = { "Cache-Control": "no-store" };@@ -12,12 +13,13 @@ const DENIED = "Only the studio's owner manages workers";* `{ name, pool? }` adds one: paused, with no hours and no lanes; its token is in this answer only. A worker's token* receives accounts' queued jobs and their files, so making one needs workers:tokens, not just workers:write. `held`:* the runs made but waiting to enter the line (hosted runs, pool-holds.ts), by why, and the oldest: counts only.+ * `hosted`: hosted runs are on (only then is the name visitors read for these GPUs asked for).*/export async function GET(request: Request) {await connection();const access = adminAccess(request, "workers:read", DENIED);if (access instanceof Response) return access;- return Response.json({ workers: listWorkers(), lanes: lanesCatalog(), held: heldView() }, { headers: NO_STORE });+ return Response.json({ workers: listWorkers(), lanes: lanesCatalog(), held: heldView(), ...(hostedRunsOn() && { hosted: true }) }, { headers: NO_STORE });}export async function POST(request: Request) {diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.tsindex d5339584..e0ddc1de 100644--- a/src/app/api/generations/route.ts+++ b/src/app/api/generations/route.ts@@ -362,7 +362,10 @@ export async function POST(request: Request) {return { ...run, held: shape?.reason };},);- if (r.ok && !r.value.held) r.value.start();+ if (r.ok) {+ if (r.value.held) r.value.settle();+ else r.value.start();+ }return r;});if (!admitted.ok && "prior" in admitted) {diff --git a/src/components/ads/multiplier.tsx b/src/components/ads/multiplier.tsxindex 3a2f6bb2..4f80e742 100644--- a/src/components/ads/multiplier.tsx+++ b/src/components/ads/multiplier.tsx@@ -278,7 +278,7 @@ export function AdMultiplier({ models, examples }: { models: Record<string, Mode// 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) ?? model?.name, costUsd: priced?.costUsd, demo: priced?.demo, ownerOnly: "Ad Multiplier" });+ const place = useRunPlace({ engine, models: priced?.steps.map((s) => s.modelName), model: mainModel(priced?.steps) ?? model?.name, costUsd: priced?.costUsd, demo: priced?.demo, ownerOnly: "Ad Multiplier", ownerOnlyStudio: "video" });const runLabel = versions > 1 ? `Generate ${versions} versions` : "Generate";const mention = (n: number) => {diff --git a/src/components/billing-card.tsx b/src/components/billing-card.tsxindex 355f3ca7..83fe5f05 100644--- a/src/components/billing-card.tsx+++ b/src/components/billing-card.tsx@@ -6,6 +6,7 @@ import Link from "next/link";import { useEffect, useState } from "react";import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { useStatus } from "@/lib/api";import { BILLING_EVENT, refreshPriceChecks, safeLink, useInterest, type BillingRefusalDetail } from "@/lib/hosted";/**@@ -36,10 +37,15 @@ export function BillingCard() {const changed = r?.code === "price-changed";const [sending, setSending] = useState(false);const runAgain = changed ? r?.runAgain : undefined;- const sendAgain = async () => {- if (!runAgain) return;+ // Hosted runs: the way to the account's own GPU says what it does. Connected: the same run, sent there now; else the+ // way to connect one. (Off hosted runs: as it always was.)+ const viewer = useStatus().data?.viewer;+ const hosted = !!viewer?.hosted && viewer.kind === "account";+ const runOwn = hosted && viewer.gpu.connected ? r?.runOwn : undefined;+ const sendAgain = async (send = runAgain) => {+ if (!send) return;setSending(true);- const started = await runAgain().finally(() => setSending(false));+ const started = await send().finally(() => setSending(false));if (started) {setOpen(false);void qc.invalidateQueries({ queryKey: ["generations"] });@@ -63,11 +69,17 @@ export function BillingCard() {{r?.offer && <p className="text-[13px] text-muted-foreground">{r.offer.text}</p>}</DialogHeader><DialogFooter className="gap-2 sm:justify-between">- <Button asChild variant="ghost" size="sm" onClick={() => setOpen(false)}>- <Link href="/connect">- <Cpu /> Use your own GPU (free)- </Link>- </Button>+ {runOwn ? (+ <Button variant="ghost" size="sm" disabled={sending} onClick={() => void sendAgain(runOwn)}>+ <Cpu /> Run on your GPU+ </Button>+ ) : (+ <Button asChild variant="ghost" size="sm" onClick={() => setOpen(false)}>+ <Link href="/connect">+ <Cpu /> {hosted ? "Connect your GPU" : "Use your own GPU (free)"}+ </Link>+ </Button>+ )}<div className="flex gap-2">{r?.offer && (<Button size="sm" variant="secondary" disabled={interest.isPending} onClick={() => interest.mutate(r.offer!.key, { onSuccess: () => setOpen(false) })}>diff --git a/src/components/marketing/click-to-ad.tsx b/src/components/marketing/click-to-ad.tsxindex 9f3d4719..c89444d0 100644--- a/src/components/marketing/click-to-ad.tsx+++ b/src/components/marketing/click-to-ad.tsx@@ -286,7 +286,7 @@ export function ClickToAd({ models, starters = [] }: { models: Record<string, Moconst priced = est.data && !est.data.blocker ? est.data : undefined;// Before the run is priced (no product yet, or a key to add), the chip names the clip's model, never a bare "Cloud".const clipModel = models[withPresenter ? UGC_MODELS[engine].talk : UGC_MODELS[engine].clip]?.name;- const place = useRunPlace({ engine, models: priced?.steps.map((s) => s.modelName), model: mainModel(priced?.steps) ?? clipModel, costUsd: priced?.costUsd, demo: priced?.demo, ownerOnly: "Click to Ad" });+ const place = useRunPlace({ engine, models: priced?.steps.map((s) => s.modelName), model: mainModel(priced?.steps) ?? clipModel, costUsd: priced?.costUsd, demo: priced?.demo, ownerOnly: "Click to Ad", ownerOnlyStudio: "video" });const writeScript = async () => {if (!productId) return;diff --git a/src/components/marketing/marketing-studio.tsx b/src/components/marketing/marketing-studio.tsxindex 17d84e0f..fcc00bac 100644--- a/src/components/marketing/marketing-studio.tsx+++ b/src/components/marketing/marketing-studio.tsx@@ -2,7 +2,7 @@import { useQueryClient } from "@tanstack/react-query";import { ArrowUp, ChevronDown, Globe, Image as ImageIcon, LayoutTemplate, Loader2, SlidersHorizontal, Type, Video, X } from "lucide-react";-import { useSearchParams } from "next/navigation";+import { useRouter, useSearchParams } from "next/navigation";import { Suspense, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";import { toast } from "sonner";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";@@ -10,7 +10,7 @@ import { 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 { mainModel, ownerOnlyWay } from "@/lib/run-place";import { BrandChip } from "@/components/brand/brand-dialog";import { inputCls } from "@/components/brand/fields";import { withoutOwnGpu } from "@/lib/catalog/engines";@@ -18,7 +18,7 @@ import { Switch } from "@/components/ui/switch";import { DRAWN_WORDS_HINT, DRAWN_WORDS_LABEL, FORMATS, formatModels, isCodeTemplate, looksLikeWebsite, pickable, MAX_PROMPT, openingAspect, TEMPLATE_INDEX, visibleTemplate, 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 { useIsOwner, useLikelyVisitor, useModelAccess } from "@/lib/api";+import { useIsOwner, useLikelyVisitor, useModelAccess, usePlaceName } from "@/lib/api";import { keepOffered, offered } from "@/lib/model-access";import type { StarterCardData } from "@/lib/starters/types";import { cn } from "@/lib/utils";@@ -337,6 +337,7 @@ export function MarketingStudio({ models, starters = [] }: { models: Record<stri// (useIsOwner), so a visitor never sees them and then gone.const visitor = useLikelyVisitor();const isOwner = useIsOwner();+ const router = useRouter();const set = (p: Partial<Draft>) => setDraft((d) => ({ ...d, ...p }));const f = FORMATS[draft.format];const found = draft.templateId ? TEMPLATE_INDEX.get(draft.templateId) : undefined;@@ -389,8 +390,13 @@ export function MarketingStudio({ models, starters = [] }: { models: Record<stri);const est = useEstimate<RunEstimate>("/api/marketing/estimate", draft.avatar?.uploading || draft.voiceSample?.uploading ? null : body);const badSite = !!f.oneOf?.includes("website") && !!draft.website.trim() && !looksLikeWebsite(draft.website);+ // While hosted runs are on, a visitor's Generate opens the studio that makes it now, on this studio's GPUs.+ const site = usePlaceName();+ const way = visitor && site ? ownerOnlyWay("image") : null;const blocker = visitor- ? "Marketing Studio isn't available here"+ ? way+ ? `${way.label} · runs on ${site!.text}`+ : "Marketing Studio isn't available here": draft.product === null && f.product === "required"? "Attach a product to generate": badSite@@ -426,7 +432,10 @@ export function MarketingStudio({ models, starters = [] }: { models: Record<stri});const generate = async () => {- if (visitor) return;+ if (visitor) {+ if (way) router.push(way.href);+ return;+ }if (blocker) {setEngaged(true);toast(blocker, { id: "marketing-blocker" });diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsxindex 905f8d63..f6db85c4 100644--- a/src/components/studio/composer.tsx+++ b/src/components/studio/composer.tsx@@ -20,7 +20,7 @@ import { locksByDefault } from "@/lib/catalog/palettes";import { DEFAULT_LOOK, lookCard } from "@/lib/catalog/soul-cards";import { formatsOf } from "@/lib/av/formats";import { poolRunState, quoteBody, useHostedQuote, useSettled, type RunOn } from "@/lib/hosted";-import { composerOnPool, composerPlace, placeRows, type RunOnPick } from "@/lib/run-place";+import { composerOnPool, composerPlace, keyOnlyChip, placeRows, type RunOnPick } from "@/lib/run-place";import { useSetRunOn } from "@/lib/run-on";import { RunOnChip } from "./run-on";import { PlaceIntro } from "./place-intro";@@ -36,7 +36,8 @@ import { ExactOrbitControls } from "@/components/exact-orbit-controls";import { useFlyAround } from "@/components/fly-around-run";import { exactDefaults, takesExact, type ExactOrbit } from "@/lib/exact-orbit";import { placeOf } from "@/lib/place-name";-import { askToSignUp, CONNECT_GPU_EVENT, engineForNextPage, enhance, useClipFacts, useCreateGeneration, useElements, useEngine, useHydrated, useIsOwner, useLikelyVisitor, useStatus } from "@/lib/api";+import { askToSignUp, CONNECT_GPU_EVENT, engineForNextPage, enhance, useClipFacts, useCreateGeneration, useElements, useEngine, useHydrated, useIsOwner, useLikelyVisitor, useNewestRun, useStatus } from "@/lib/api";+import { keyTurnedDown, keyTurnedDownWords, siteRunOf, siteRunRequest } from "@/lib/site-run";import { usePagePlace } from "@/components/gpu/use-page-place";import { applyMentions, elementsNote, type StudioElement } from "@/lib/catalog/elements";import { applySketch, stripMotionPaths } from "@/lib/catalog/sketch";@@ -651,9 +652,12 @@ export function Composer({ docked }: { docked: boolean }) {// check last said this run goes (poolPrice, below).const [lockOnPool, setLockOnPool] = useState(false);const signature = useSignature(!!config.signature, draft.signature, lockOnPool);+ // Hosted runs: "Run without LoRAs" pressed (a run refused there only for its LoRAs): the next run goes without them.+ const [lorasOff, setLorasOff] = useState(false);+ const offLoras = <R extends object>(r: R): R => (lorasOff ? { ...r, lorasOff: true as const } : r);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)));+ const signed = signature.apply(offLoras(buildRequest(config.feature, d, studioOp, config.promptSuffix, config.multiRef?.kind, framesCtx, targetFor(d.modelId))));// Planned with the signature's sentences in the prompt (as the server runs it); sent with them apart.const raw = signed.worded;const m = catalog.getModel(raw.modelId) ?? model;@@ -844,8 +848,9 @@ export function Composer({ docked }: { docked: boolean }) {// it spends the person's own credit).// Hosted runs: the key that runs this item's cloud version (a row of the Run on list, "Run with your fal.ai key"), and// its price there, so a key is offered with its price and a press that showed "Free" never bills it.+ // (Not for an exact orbit: it runs as a fly-around, at its own price.)const keyTwin =- viewerInfo?.hosted && viewerInfo.kind === "account" && viewerInfo.paidAllowed !== false && model ? cloudVersion(preset, model, viewerInfo.keys ?? [], has, catalog.getModel) : null;+ viewerInfo?.hosted && viewerInfo.kind === "account" && viewerInfo.paidAllowed !== false && model && !exact ? cloudVersion(preset, model, viewerInfo.keys ?? [], has, catalog.getModel) : null;const keyPrice = (() => {const m = keyTwin ? catalog.getModel(keyTwin.modelId) : undefined;if (!m) return null;@@ -895,13 +900,14 @@ export function Composer({ docked }: { docked: boolean }) {// or a key that runs this item's cloud version (at its price, never without one), may run this run there now, once.// Its pick stays as it was, and the run is taken in line all the same when it doesn't. While the day's GPU time is used// up, or runs there are paused, an account with nothing of its own gets the quiet way to connect its own GPU.+ // ("Now" on its GPU only while it answers.)const waitOffer =viewerInfo?.kind === "account" && poolState && !poolState.refused && poolState.long- ? viewerInfo.gpu.connected+ ? viewerInfo.gpu.connected && viewerInfo.gpu.online? { label: "Run it now on your GPU", run: () => submitRef.current(undefined, undefined, "own") }: keyTwin && keyPrice? { label: `Run it now with your ${CLOUD_KEY[keyTwin.provider].label} key · ${keyPrice}`, run: () => submitRef.current(undefined, withKeyAction(keyTwin.provider, keyTwin.modelId, keyTwin.op, keyPrice)) }- : poolState.held === "today" || poolState.held === "service"+ : !viewerInfo.gpu.connected && (poolState.held === "today" || poolState.held === "service")? { label: "Or connect your own GPU", run: () => void pressSetup({ need: "gpu" }) }: undefined: undefined;@@ -968,9 +974,9 @@ export function Composer({ docked }: { docked: boolean }) {setRecent((r) => pushRecent(r, draft.modelId));// The server resolves @mentions and drawings itself; only pin the operation when there are none.// No "Queued" toast: the new card (and the "1 generating ↑" pill when it's off-screen) says it.- const sent = signature.apply(- buildRequest(config.feature, songDraft(draft, model, config.slots), resolvesOnServer ? studioOp : op, config.promptSuffix, config.multiRef?.kind, framesCtx, targetFor(draft.modelId)),- );+ const built = buildRequest(config.feature, songDraft(draft, model, config.slots), resolvesOnServer ? studioOp : op, config.promptSuffix, config.multiRef?.kind, framesCtx, targetFor(draft.modelId));+ // (Without LoRAs only where they were the reason: never on the account's own GPU or key.)+ const sent = signature.apply(withKey || once === "own" ? built : offLoras(built));// Hosted runs: where it should go, and the price shown (the server checks both; a higher price comes back to confirm).// A run on the account's key names neither: the key is where it goes.const placeNow = once ?? runPlace;@@ -997,6 +1003,7 @@ export function Composer({ docked }: { docked: boolean }) {// line says the run is on its way (hosted runs: its tile shows "In line" too).onSuccess: () => {dropGpuRetry();+ setLorasOff(false);if (signedUp && viewerInfo?.hosted) setPriceNote(PENDING_WORDS.made);},// Stopped by the GPU pre-flight, or refused with its own card: the guided fix or the card is open already, so no error toast on top.@@ -1141,7 +1148,21 @@ export function Composer({ docked }: { docked: boolean }) {? placeRows(viewerInfo, { key: { provider: viewerInfo.runKey ?? payer, price: cost ? `≈ ${formatCost(cost)}` : null }, cloud: true }): null;const ownGpuHere = hostedHere && !!viewerInfo?.gpu.connected && siteMissed && !runOnRows;- const runOnText = runOnRows?.on === "gpu" || ownGpuHere ? "Free · your GPU" : runOnRows?.on === "key" ? `${costText} · your key` : costText;+ // Refused there only for its LoRAs: the same run without them runs there (the price check asks again, then Generate).+ const withoutLoras = poolState?.refused && poolState.withoutLoras && !lorasOff ? { label: "Run without LoRAs", run: () => setLorasOff(true) } : undefined;+ // An item that runs on an own setup only, for an account whose runs go to its key (and no GPU): Generate runs it on the+ // key's cloud version, so the chip says the key's price first.+ const keyChip = keyOnlyChip({ ownSetup: !!poolSetup, key: keyTwin ? { provider: keyTwin.provider, price: keyPrice } : null, gpu: !!viewerInfo?.gpu.connected, picked: runOnPicked, rows: !!runOnRows });+ const ownKeyHere = !!keyChip;+ const keyTip = keyChip?.tip ?? "";+ const runOnText = runOnRows?.on === "gpu" || ownGpuHere ? "Free · your GPU" : keyChip ? keyChip.text : runOnRows?.on === "key" ? `${costText} · your key` : costText;+ // What Generate's tooltip says it costs.+ const pressCost = ownKeyHere ? runOnText : costText;+ // Hosted runs, runs going to the account's key: its key turned the last run down (out of credit, not accepted). Said+ // before the next press, with that run once on {Place} when it takes its open version.+ const newestRun = useNewestRun();+ const turnedDown = viewerInfo?.hosted && viewerInfo.kind === "account" && engine === "cloud" && newestRun ? keyTurnedDown([newestRun]) : null;+ const siteAgain = turnedDown ? siteRunOf(turnedDown.run, true, viewerInfo?.pool) : null;const runOnTip =runOnRows?.on === "gpu"? `Runs on your own GPU${viewerInfo?.gpu.online ? "" : " · not answering right now"}`@@ -1909,10 +1930,14 @@ export function Composer({ docked }: { docked: boolean }) {{!runOnRows && costText && (<Tooltip><TooltipTrigger asChild>- <span className={cn("shrink-0 text-[12px] font-medium text-muted-foreground tabular-nums", poolRefused && "min-w-0 shrink truncate max-sm:hidden")} data-pool-refused={poolRefused || undefined}>- <span className="sm:hidden">{exactPrice ? fly.compactPrice : poolPrice ? costText : keyOnly && cost == null ? ownSetupShort(keyOnly) : costLabel({ demo, cost: cost ?? freeHere, compact: true, unknown: loraPriceUnknown, gpu: gpuRun }, formatCost)}</span>+ <span+ className={cn("shrink-0 text-[12px] font-medium text-muted-foreground tabular-nums", poolRefused && !ownKeyHere && "min-w-0 shrink truncate max-sm:hidden")}+ data-pool-refused={(poolRefused && !ownKeyHere) || undefined}+ data-key-price={ownKeyHere || undefined}+ >+ <span className="sm:hidden">{exactPrice ? fly.compactPrice : ownKeyHere ? runOnText : poolPrice ? costText : keyOnly && cost == null ? ownSetupShort(keyOnly) : costLabel({ demo, cost: cost ?? freeHere, compact: true, unknown: loraPriceUnknown, gpu: gpuRun }, formatCost)}</span><span className="hidden sm:inline">- {ownGpuHere ? runOnText : costText}+ {ownGpuHere || ownKeyHere ? runOnText : costText}{payerText}</span></span>@@ -1920,6 +1945,8 @@ export function Composer({ docked }: { docked: boolean }) {<TooltipContent className="max-w-72">{ownGpuHere? "This one runs on your own GPU."+ : ownKeyHere+ ? keyTip: poolPrice? poolState?.refused? (poolState.sub ?? poolState.text)@@ -1946,7 +1973,7 @@ export function Composer({ docked }: { docked: boolean }) {size="icon"onClick={submit}disabled={create.isPending || signature.lock.isPending || (poolRefused && !poolSetup)}- aria-label={blocker ? `Generate — ${blocker.message}` : poolRefused && poolState ? `Generate — ${poolState.text}` : "Generate"}+ aria-label={blocker ? `Generate — ${blocker.message}` : ownKeyHere ? `Generate — ${runOnText}` : poolRefused && poolState ? `Generate — ${poolState.text}` : "Generate"}aria-busy={create.isPending || signature.lock.isPending || undefined}// Blocked, it stays the brand colour (paler, the arrow still 3:1 or more): pressing it still says what's missing and points at it.className={cn("size-10 shrink-0 rounded-full", blocker && "bg-primary/70 hover:bg-primary/80")}@@ -1966,7 +1993,7 @@ export function Composer({ docked }: { docked: boolean }) {{blocker?.message ?? (<span className="flex items-center gap-1.5">Generate <Kbd>↵</Kbd>- {costText && <span className="text-muted-foreground tabular-nums">· {costText}</span>}+ {pressCost && <span className="text-muted-foreground tabular-nums">· {pressCost}</span>}</span>)}</TooltipContent>@@ -1992,7 +2019,23 @@ export function Composer({ docked }: { docked: boolean }) {</p>)}{/* Folded (docked, not focused), the composer stays one line: the wait shows again once it opens. */}- {!blocker && !gpuSetup && poolState && (poolState.refused || !collapsed) && <PoolNote state={poolState} offer={waitOffer} />}+ {!blocker && !gpuSetup && !ownKeyHere && poolState && (poolState.refused || !collapsed) && <PoolNote state={poolState} offer={waitOffer} alt={withoutLoras} />}+ {!blocker && turnedDown && (+ <p data-key-turned-down className="flex flex-wrap items-center gap-x-2 px-2 text-[12px] text-muted-foreground">+ <span>{keyTurnedDownWords(turnedDown.provider)}</span>+ {siteAgain && (+ <button+ type="button"+ onMouseDown={(e) => e.preventDefault()}+ disabled={create.isPending}+ onClick={() => create.mutate(siteRunRequest(turnedDown.run, siteAgain), { onError: (e) => toastError(e) })}+ className="inline-flex min-h-6 items-center font-medium text-brand-text underline-offset-2 hover:underline"+ >+ Run on {sitePlace.label}+ </button>+ )}+ </p>+ )}{!blocker && priceNote && !poolRefused && (<p data-price-note className="px-2 text-[12px] font-medium text-foreground">{priceNote}diff --git a/src/components/studio/feed.tsx b/src/components/studio/feed.tsxindex dd03a046..6636c485 100644--- a/src/components/studio/feed.tsx+++ b/src/components/studio/feed.tsx@@ -23,7 +23,8 @@ import { TroubleActions, TroubleDetails } from "@/components/gpu/trouble";import { useCreateGeneration, useGenerationActions, useMakingPoolRuns, usePlaceName, useStatus } from "@/lib/api";import { knownPlace } from "@/lib/place-name";import { runOnSiteAction } from "@/lib/diagnose";-import { offersRunOnSite, retryRequest } from "@/lib/run-place";+import { retryRequest } from "@/lib/run-place";+import { shownTroubleActions, siteRunOf, siteRunRequest } from "@/lib/site-run";import { placeholdersOn } from "@/lib/demo-mode";import { useSoulFinish } from "./soul-finish";import { elapsed, formatCost, leftLabel, notePace, ratioValue, timeAgo, timeLeft } from "@/lib/format";@@ -179,9 +180,12 @@ const FILE_TROUBLE: readonly string[] = Object.values(FILE_TROUBLE_WORDS);export function FailedTile({ g, ratio, onRetry, onReuse }: { g: Generation; ratio: number; onRetry: () => void; onReuse?: () => void }) {const create = useCreateGeneration();const trouble = g.status === "failed" ? g.trouble : undefined;- // Hosted runs: a run that failed on the person's own GPU can run once on this studio's GPUs instead.+ // Hosted runs: a run that failed on the person's own GPU or key can run once on this studio's GPUs instead, when they+ // take it (on its key: its open version).const site = usePlaceName();- const onSite = !!trouble && offersRunOnSite(g, !!site);+ const pool = useStatus().data?.viewer?.pool;+ const siteRun = trouble ? siteRunOf(g, !!site, pool) : null;+ const actions = trouble ? shownTroubleActions(trouble.actions, !!site) : [];// A run on this studio's GPUs that couldn't finish: one plain sentence (the server's), nothing technical.const poolFailed = g.place === "pool" && g.status === "failed";const reuseFirst = poolFailed && !!onReuse && FILE_TROUBLE.includes(g.error ?? "");@@ -202,12 +206,12 @@ export function FailedTile({ g, ratio, onRetry, onReuse }: { g: Generation; rati{trouble && (<TroubleActionsclassName="mt-2"- actions={onSite && site ? [runOnSiteAction(site.label), ...trouble.actions] : trouble.actions}+ actions={siteRun && site ? [runOnSiteAction(site.label), ...actions] : actions}skip={["retry"]}max={3}handlers={{onRunWithKey: (a) => create.mutate(onCloudKey(g.request, a), { onError: (e) => toastError(e) }),- onRunOnSite: () => create.mutate({ ...g.request, place: "pool" } as Generation["request"], { onError: (e) => toastError(e) }),+ onRunOnSite: () => siteRun && create.mutate(siteRunRequest(g, siteRun), { onError: (e) => toastError(e) }),}}/>)}diff --git a/src/components/studio/place-intro.tsx b/src/components/studio/place-intro.tsxindex 1e3531b4..ffcacabb 100644--- a/src/components/studio/place-intro.tsx+++ b/src/components/studio/place-intro.tsx@@ -14,7 +14,10 @@ import { cn } from "@/lib/utils";* account, on any device. `onKeep`: what the page does besides (the composer moves its engine to Cloud for a key).*/-function useIntro(run: string): {+function useIntro(+ run: string,+ chip?: string,+): {intro: Intro | null;keep: (runOn: RunOnPick) => void;busy: boolean;@@ -22,7 +25,7 @@ function useIntro(run: string): {const hydrated = useHydrated();const v = useStatus().data?.viewer;const setRunOn = useSetRunOn();- const intro = hydrated ? placeIntro(v, run) : null;+ const intro = hydrated ? placeIntro(v, run, chip) : null;return {intro,keep: (runOn) =>@@ -74,10 +77,10 @@ export function PlaceIntro({ run, onKeep, className }: { run: string; onKeep?: (/*** A tool page's note (its place chip has no line above its Run): the same words and buttons, once per page, as a note- * that stays until one is pressed.+ * that stays until one is pressed. `chip`: the place chip's words, which the note points at.*/-export function PlaceIntroNote({ run }: { run: string }) {- const { intro, keep } = useIntro(run);+export function PlaceIntroNote({ run, chip }: { run: string; chip?: string }) {+ const { intro, keep } = useIntro(run, chip);const lead = intro?.lead;useEffect(() => {if (!intro) return;diff --git a/src/components/studio/pool-note.tsx b/src/components/studio/pool-note.tsxindex 8ae3d800..b9913936 100644--- a/src/components/studio/pool-note.tsx+++ b/src/components/studio/pool-note.tsx@@ -11,9 +11,20 @@ type PoolState = NonNullable<ReturnType<typeof poolRunState>>;* ("Ready in about 2 min", "Starts when a GPU is free", "Ready in seconds", "Starts after your other runs", "Lots of* runs today · starts in about 7 h"), with `offer` after a long wait (the account's own GPU or key for this run, once:* "Run it now on your GPU"); or, when the price check refused it, the words (the- * toolbar's price slot has no room for them on a phone), with the link or offer the answer carries.+ * toolbar's price slot has no room for them on a phone), with the link or offer the answer carries, and `alt`: the same+ * run another way that does run there ("Run without LoRAs").*/-export function PoolNote({ state, offer, className }: { state: PoolState; offer?: { label: string; run: () => void }; className?: string }) {+export function PoolNote({+ state,+ offer,+ alt,+ className,+}: {+ state: PoolState;+ offer?: { label: string; run: () => void };+ alt?: { label: string; run: () => void };+ className?: string;+}) {const interest = useInterest();const href = safeLink(state.action?.url);if (!state.refused) {@@ -37,7 +48,7 @@ export function PoolNote({ state, offer, className }: { state: PoolState; offer?</p>);}- const more = !!(href || state.offer || state.sub);+ const more = !!(href || state.offer || state.sub || alt);return (<p data-pool-note="refused" className={cn("flex flex-wrap items-center gap-x-2 px-2 text-[12px] text-muted-foreground", !more && "sm:hidden", className)}><span className="sm:hidden">{state.text}</span>@@ -58,6 +69,17 @@ export function PoolNote({ state, offer, className }: { state: PoolState; offer?{state.offer.label}</button>)}+ {alt && (+ <button+ type="button"+ data-pool-alt+ onMouseDown={(e) => e.preventDefault()}+ onClick={alt.run}+ className="font-medium text-brand-text underline-offset-2 hover:underline"+ >+ {alt.label}+ </button>+ )}</p>);}diff --git a/src/components/studio/run-place-chip.tsx b/src/components/studio/run-place-chip.tsxindex ff74279e..8478b6f4 100644--- a/src/components/studio/run-place-chip.tsx+++ b/src/components/studio/run-place-chip.tsx@@ -134,7 +134,7 @@ export function RunPlaceChip({if (!place) return null;const Icon = ICONS[place.where];// Once, for an account whose runs moved to this studio's GPUs when hosted runs went on (a tool page starts runs too).- const intro = openRun ? <PlaceIntroNote run={runLabel} /> : null;+ const intro = openRun ? <PlaceIntroNote run={runLabel} chip={place.label} /> : null;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;@@ -196,6 +196,11 @@ export function RunPlaceChip({<span className="font-mono tabular-nums">{place.price}</span></p>)}+ {place.way && (+ <Button asChild size="sm" className="w-full">+ <Link href={place.way.href}>{place.way.label}</Link>+ </Button>+ )}{place.needs === "signup" && (<Button asChild size="sm" className="w-full"><Link href={signInHref("signup", pathname)}>Sign up free</Link>diff --git a/src/components/workers-admin.tsx b/src/components/workers-admin.tsxindex d423724d..0551187f 100644--- a/src/components/workers-admin.tsx+++ b/src/components/workers-admin.tsx@@ -270,7 +270,7 @@ function WorkerCard({ w, lanes, onToken }: { w: WorkerView; lanes: Lane[]; onTokexport function useWorkers(enabled: boolean) {return useQuery({queryKey: ["admin", "workers"],- queryFn: () => call<{ workers: WorkerView[]; lanes: Lane[]; held?: HeldCounts }>("GET", "/api/admin/workers"),+ queryFn: () => call<{ workers: WorkerView[]; lanes: Lane[]; held?: HeldCounts; hosted?: boolean }>("GET", "/api/admin/workers"),enabled,refetchInterval: 10_000,});@@ -317,7 +317,8 @@ export function WorkersAdmin() {Run this studio's ComfyUI jobs on the workers</label></div>- <PlaceNameField saved={where.data?.find((s) => s.name === "hostedPlaceName")} />+ {/* The name visitors read for these GPUs: asked for only while hosted runs are on. */}+ {q.data?.hosted && <PlaceNameField saved={where.data?.find((s) => s.name === "hostedPlaceName")} />}{token && <TokenOnce token={token} onDone={() => setToken(null)} />}<formclassName="flex flex-wrap items-center gap-2"diff --git a/src/lib/api.ts b/src/lib/api.tsindex b9524d9a..8b6eace2 100644--- a/src/lib/api.ts+++ b/src/lib/api.ts@@ -547,6 +547,24 @@ export function useMakingPoolRuns(): { at: number; request: GenerationRequest }[return pending.filter((p): p is { at: number; request: GenerationRequest } => goesToPool(p.request));}+/**+ * The newest run any list on this page has loaded (the feed's own, read from what it already fetched: nothing more is+ * asked). Null until one is loaded. (The composer's line before the next press, when the person's key turned it down.)+ */+export function useNewestRun(): Generation | null {+ const qc = useQueryClient();+ const subscribe = useCallback((go: () => void) => qc.getQueryCache().subscribe(go), [qc]);+ const read = useCallback((): Generation | null => {+ let newest: Generation | null = null;+ for (const [, data] of qc.getQueriesData<Generation[]>({ queryKey: ["generations"] })) {+ if (!Array.isArray(data)) continue;+ for (const g of data) if (g && typeof g.createdAt === "number" && (!newest || g.createdAt > newest.createdAt)) newest = g;+ }+ return newest;+ }, [qc]);+ return useSyncExternalStore(subscribe, read, () => null);+}+/** A new id for one press of Run: every send of that press carries it, so the studio makes its run once. */export function newPressId(): string {const c = globalThis.crypto;@@ -1623,21 +1641,34 @@ export function refusalCard(kind: RefusalCard["kind"], at: { pathname: string; s* card. Never on the sign-in page (refusalCard). Installed once. A refused upload's card says so ("add your own* files"), not "run this".*/-/** Send a run again on this studio's GPUs (the toast a run that named no place gets when its own GPU didn't answer). */-async function runOnPool(sent: string): Promise<void> {+/**+ * Send a studio's run again at a place named for it: this studio's GPUs (the toast a run that named no place gets when+ * its own GPU didn't answer), or the account's own GPU (the billing card's "Run on your GPU"). True when it started.+ */+async function runAt(sent: string, place: "pool" | "own"): Promise<boolean> {let body: Record<string, unknown>;try {body = JSON.parse(sent) as Record<string, unknown>;} catch {- return;+ return false;}try {- const res = await window.fetch("/api/generations", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...body, place: "pool" }) });- if (res.ok) window.dispatchEvent(new Event(RUNS_CHANGED_EVENT));- else await json(res).catch((e: unknown) => void (refusalShown(e) || toast.error((e as Error).message)));+ const res = await window.fetch("/api/generations", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...body, place }) });+ if (res.ok) {+ window.dispatchEvent(new Event(RUNS_CHANGED_EVENT));+ return true;+ }+ await json(res).catch((e: unknown) => void (refusalShown(e) || toast.error((e as Error).message)));} catch {toast.error("That didn't start. Try again.");}+ return false;+}++/** A refused run sent again at a place named for it (a studio's run names it in its body, a tool's in a header). */+function againAt(input: RequestInfo | URL, init: RequestInit | undefined, place: "pool" | "own"): () => Promise<boolean> {+ const sent = init?.body;+ return requestPath(input) === "/api/generations" && typeof sent === "string" ? () => runAt(sent, place) : () => sendRunAgain(input, init, { [RUN_PLACE_HEADER]: place });}/**@@ -1718,7 +1749,9 @@ export function watchGuestRefusals(): void {const q = b.quote;const again =billing === "price-changed" && method === "POST" && q && resendable(input, init) ? () => sendRunAgain(input, init, { [RUN_SHOWN_HEADER]: shownHeader(q) }) : undefined;- window.dispatchEvent(new CustomEvent<BillingRefusalDetail>(BILLING_EVENT, { detail: { ...b, code: billing, ...(again && { runAgain: again }) } }));+ // Hosted runs: the same run on the account's own GPU, for the card's "Run on your GPU".+ const own = method === "POST" && resendable(input, init) ? againAt(input, init, "own") : undefined;+ window.dispatchEvent(new CustomEvent<BillingRefusalDetail>(BILLING_EVENT, { detail: { ...b, code: billing, ...(again && { runAgain: again }), ...(own && { runOwn: own }) } }));}).catch(() => {});}@@ -1726,9 +1759,9 @@ export function watchGuestRefusals(): void {// by itself.if (res.status === 409 && res.headers.get(PLACE_ASK_HEADER) === "1" && method === "POST" && resendable(input, init)) {markRefusalShown(res);- const sent = init?.body;// The studios' runs carry the place in their body; a tool's run in a header (every tool reads it).- const again = requestPath(input) === "/api/generations" && typeof sent === "string" ? () => void runOnPool(sent) : () => void sendRunAgain(input, init, { [RUN_PLACE_HEADER]: "pool" });+ const onPool = againAt(input, init, "pool");+ const again = () => void onPool();res.clone().json()diff --git a/src/lib/catalog/elements.ts b/src/lib/catalog/elements.tsindex 325bdf22..1f35ff57 100644--- a/src/lib/catalog/elements.ts+++ b/src/lib/catalog/elements.ts@@ -166,7 +166,9 @@ function elementPlan(req: GenerationRequest, model: ModelDef, mentioned: StudioE* prompt that tells the model which image is which. Leaves the request alone when nothing* is mentioned.*/-export function applyMentions(req: GenerationRequest, model: ModelDef, elements: StudioElement[]): MentionResolution {+export function applyMentions(asked: GenerationRequest, model: ModelDef, elements: StudioElement[]): MentionResolution {+ // "Run without LoRAs": none of the request's own either.+ const req = asked.lorasOff && asked.loras ? { ...asked, loras: undefined } : asked;// Shots (multi-shot) can mention elements too.const shots = req.params?.shots;// Voices are picked in the voice menu, not mentioned in visual prompts.@@ -191,7 +193,8 @@ export function applyMentions(req: GenerationRequest, model: ModelDef, elements:// LoRAs win over references for the model they were trained on.const loras: LoraRef[] = [...(req.loras ?? [])];const viaLora = new Set<string>();- for (const el of mentioned) {+ // (Asked without LoRAs: every element goes in as its photos.)+ for (const el of req.lorasOff ? [] : mentioned) {// A trained LoRA of this model's family, on the engine it runs on (Fuobe Soul ID). An older Soul ID kept only by// a reference id runs nowhere: the element is retrained on its photos.const l = identityFor(el.loras, model);diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.tsindex 6a1301eb..b3eaeb2f 100644--- a/src/lib/catalog/types.ts+++ b/src/lib/catalog/types.ts@@ -1238,6 +1238,8 @@ export interface GenerationRequest {mix?: { presetId: string; strength: number };/** LoRAs added by @element mentions (trained identities, server-side), or a recipe's LoRAs sent by the evaluation harness. */loras?: LoraRef[];+ /** "Run without LoRAs" (hosted runs): an @element with a trained LoRA goes in as its photos instead. */+ lorasOff?: true;/*** The engine a model that runs on both (a Fuobe Original, ModelDef.engines) runs on: the composer's switch.* Unset: the install's engine mode, else the first one connected (your GPU before the cloud).diff --git a/src/lib/hosted.ts b/src/lib/hosted.tsindex d53daf9c..8e2506ef 100644--- a/src/lib/hosted.ts+++ b/src/lib/hosted.ts@@ -39,6 +39,8 @@ export interface HostedQuote {* your GPU, Add your key, or a guest's sign-up) instead of staying off.*/ownSetup?: OwnSetup;+ /** Refused only for its LoRAs (an element's trained LoRA): the same run without them runs there ("Run without LoRAs"). */+ withoutLoras?: true;}/** The billing service's words for an account's balance (the top bar's chip and the account menu). */@@ -62,6 +64,8 @@ export interface BillingRefusalDetail {quote?: HostedQuote;/** A changed price: the same run sent again at the new price (true when it started). */runAgain?: () => Promise<boolean>;+ /** The same run sent again on the account's own GPU (true when it started). */+ runOwn?: () => Promise<boolean>;}/** Fired for every refusal marked x-fuobe-billing (watchGuestRefusals): the billing card opens. */@@ -190,10 +194,20 @@ export function poolRunState(check: HostedCheck | null | undefined): {action?: BillingAction;offer?: BillingOffer;setup?: OwnSetup;+ withoutLoras?: true;} | null {const q = check?.quote;if (!q) return null;- if (!q.allowed) return { refused: true, text: q.text, ...(q.sub && { sub: q.sub }), ...(q.action && { action: q.action }), ...(q.offer && { offer: q.offer }), ...(q.ownSetup && { setup: q.ownSetup }) };+ if (!q.allowed)+ return {+ refused: true,+ text: q.text,+ ...(q.sub && { sub: q.sub }),+ ...(q.action && { action: q.action }),+ ...(q.offer && { offer: q.offer }),+ ...(q.ownSetup && { setup: q.ownSetup }),+ ...(q.withoutLoras && { withoutLoras: true as const }),+ };const line = check?.line;const wait = line ? waitWords(line) : null;// A run pressed now would wait to enter the line: the line under the toolbar says why, as a sentence of its own.diff --git a/src/lib/place-intro.ts b/src/lib/place-intro.tsindex cf1338ff..6f3e5110 100644--- a/src/lib/place-intro.ts+++ b/src/lib/place-intro.ts@@ -16,6 +16,8 @@ export interface PlaceIntroViewer {ranOwn?: boolean;gpu: { connected: boolean };keys?: CloudProvider[];+ /** The policy's card words ("Try free"): runs there cost this account nothing, so the note may say "free". */+ cardText?: string;}export interface PlaceIntro {@@ -26,14 +28,19 @@ export interface PlaceIntro {keep: { label: string; runOn: "gpu" | "key"; key?: CloudProvider };}-/** The note for this viewer, or null. `run`: the page's own button ("Generate", "Render", "Run"). */-export function placeIntro(v: PlaceIntroViewer | undefined | null, run: string): PlaceIntro | null {+/**+ * The note for this viewer, or null. `run`: the page's own button ("Generate", "Render", "Run"), beside the composer's+ * price chip. `chip`: a tool page's place chip instead (its words, such as "Our GPUs"), which opens the same list.+ */+export function placeIntro(v: PlaceIntroViewer | undefined | null, run: string, chip?: string): PlaceIntro | null {if (!v?.hosted || v.kind !== "account" || !v.ranOwn || v.runOn) return null;const place = placeOf(v.placeName);+ // "Free" only while runs there cost this account nothing (the policy's card words say so).+ const free = !!v.cardText?.trim();if (v.gpu.connected) {return {- lead: `Runs now go to ${place.text}, free.`,- rest: `Your GPU is one tap away: Free ▾, next to ${run}.`,+ lead: free ? `Runs now go to ${place.text}, free.` : `Runs now go to ${place.text}.`,+ rest: chip ? `Your GPU is one tap away: tap ${chip} to pick it.` : `Your GPU is one tap away: ${free ? "Free ▾" : "the price"}, next to ${run}.`,keep: { label: "Keep my GPU as the default", runOn: "gpu" },};}@@ -41,7 +48,7 @@ export function placeIntro(v: PlaceIntroViewer | undefined | null, run: string):const key = keys.includes("fal") ? "fal" : keys[0];if (!key) return null;return {- lead: `Open models now run free on ${place.text}.`,+ lead: free ? `Open models now run free on ${place.text}.` : `Open models now run on ${place.text}.`,rest: `Your ${CLOUD_KEY[key].label} key still runs the cloud models: pick Cloud in the model list.`,keep: { label: "Keep my key as the default", runOn: "key", key },};diff --git a/src/lib/run-on.ts b/src/lib/run-on.tsindex de887ddb..8ba5dc01 100644--- a/src/lib/run-on.ts+++ b/src/lib/run-on.ts@@ -2,7 +2,7 @@import { useMutation, useQueryClient, type QueryClient } from "@tanstack/react-query";import { toast } from "sonner";-import type { StatusInfo } from "./api";+import { useEngine, type StatusInfo } from "./api";import { refreshPriceChecks } from "./hosted";import type { Place } from "./place-name";import type { RunOnPick } from "./run-place";@@ -38,6 +38,12 @@ export function noteRunOn(qc: QueryClient, runOn: RunOnPick | null, runKey?: Clo});}+/**+ * The engine the studios move to when the account's pick is kept: Cloud for its key, Open source when it moves away+ * from its key, none otherwise (the person's own switch stays).+ */+export const keyEngine = (was: RunOnPick | null | undefined, now: RunOnPick | null): "cloud" | "open" | null => (now === "key" ? "cloud" : was === "key" ? "open" : null);+/** Keep the account's pick (PUT /api/account/run-on). Throws the server's words when it can't. */export async function putRunOn(runOn: RunOnPick, key?: CloudProvider): Promise<{ runOn: RunOnPick | null; runKey?: CloudProvider }> {const res = await fetch(RUN_ON_PATH, {@@ -60,10 +66,21 @@ export async function putRunOn(runOn: RunOnPick, key?: CloudProvider): Promise<{*/export function useSetRunOn() {const qc = useQueryClient();+ const [, setEngine] = useEngine();return useMutation({mutationFn: ({ runOn, key }: { runOn: RunOnPick; key?: CloudProvider }) => putRunOn(runOn, key),- onMutate: ({ runOn, key }) => noteRunOn(qc, runOn, key),- onSuccess: (r) => noteRunOn(qc, r.runOn, r.runKey),+ onMutate: ({ runOn, key }) => {+ const was = qc.getQueryData<StatusInfo>(["status"])?.viewer?.runOn;+ noteRunOn(qc, runOn, key);+ return { was };+ },+ onSuccess: (r, _asked, ctx) => {+ noteRunOn(qc, r.runOn, r.runKey);+ // The studios follow a pick made anywhere (Settings, a tool page's note): a key runs on Cloud, and a pick away+ // from the key back on Open source.+ const next = keyEngine(ctx?.was, r.runOn);+ if (next) setEngine(next);+ },onError: (e) => toast((e as Error).message, { id: "run-on" }),onSettled: () => {void qc.invalidateQueries({ queryKey: ["status"] });diff --git a/src/lib/run-place.ts b/src/lib/run-place.tsindex 024a0672..5fe8726b 100644--- a/src/lib/run-place.ts+++ b/src/lib/run-place.ts@@ -31,6 +31,8 @@ export interface RunPlaceInput {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;+ /** The studio that makes what such a tool makes now (hosted runs on: the way on from its chip). Default: Image. */+ ownerOnlyStudio?: "image" | "video";/** 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. */@@ -65,6 +67,8 @@ export interface RunPlace {tip: string;/** After "Generate · " on the send button's tooltip: the price and the place, "Free · your GPU", "≈ $0.04 · cloud". */send: string;+ /** A tool open to the owner only, while hosted runs are on: the studio that makes it now (a button in the chip's panel). */+ way?: { label: string; href: string };/** What this viewer does before the run can start: create an account, connect a GPU, or add a key. */needs?: "signup" | "gpu" | "key";/** The run can't start now (this studio's GPUs refused it before Run): the send button is off, and these words say why. */@@ -89,6 +93,11 @@ const uniq = (names: readonly string[] | undefined) => [...new Set((names ?? [])const OWNER_ONLY_HOSTED: Omit<RunPlace, "tip"> = { where: "unavailable", label: "Coming soon", price: "", title: "Coming soon", send: "" };export const ownerOnlyTip = (tool: string): string => `${tool} isn't open to accounts yet. Try the Image, Video or Audio studio.`;+/** The way on from such a tool: the studio that makes it now, on this studio's GPUs ("Make it in the Image studio"). */+export function ownerOnlyWay(studio: "image" | "video" = "image"): { label: string; href: string } {+ return studio === "video" ? { label: "Make it in the Video studio", href: "/video" } : { label: "Make it in the Image studio", href: "/image" };+}+/** 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";@@ -113,7 +122,7 @@ export function runPlace(input: RunPlaceInput): RunPlace {}if (input.ownerOnly && audience !== "owner") {// Hosted runs on: said as what is coming, with the way on now (no visitor's own GPU or key runs it yet, so no setup).- if (input.hosted) return { ...OWNER_ONLY_HOSTED, tip: ownerOnlyTip(input.ownerOnly) };+ if (input.hosted) return { ...OWNER_ONLY_HOSTED, tip: ownerOnlyTip(input.ownerOnly), way: ownerOnlyWay(input.ownerOnlyStudio) };return {where: "unavailable",label: "Not available here",@@ -294,12 +303,6 @@ export function retryRequest<R extends object>(g: { request: R; place?: "pool" }return hosted ? { ...g.request, place: g.place === "pool" ? "pool" : "own" } : g.request;}-/**- * "Run on Our GPUs" on a run that failed on the person's own GPU (hosted runs): an open run that ran there. One-off: it- * is sent again here, named, and the account's pick stays as it was.- */-export const offersRunOnSite = (g: { place?: "pool"; engine: string; status: string }, hosted: boolean): boolean => hosted && g.place !== "pool" && g.engine === "open" && g.status === "failed";-/** One row of the Run on list: a place, the line under it, and whether this item's runs go there now. */export interface RunOnRow {id: RunOnPick;@@ -335,6 +338,16 @@ export interface RunOnViewer {/** The footer under the list: a pick holds for later runs too. */export const RUN_ON_FOOTER = "Your next runs go here too.";+/**+ * An item this studio's GPUs can't run, for an account with no GPU whose runs go to its key (hosted runs): Generate runs+ * it on the key's cloud version, so the price chip says the key's price first, and its tooltip who bills it. Null in any+ * other case, and with no price known (a key is never billed by a press that showed none: Run then opens the choice).+ */+export function keyOnlyChip(o: { ownSetup: boolean; key: { provider: CloudProvider; price: string | null } | null; gpu: boolean; picked: RunOnPick | null | undefined; rows: boolean }): { text: string; tip: string } | null {+ if (!o.ownSetup || !o.key?.price || o.gpu || o.picked !== "key" || o.rows) return null;+ return { text: `${o.key.price} · your key`, tip: `Runs with your ${CLOUD_KEY[o.key.provider].label} key · billed to ${billedTo(o.key.provider)}` };+}+/** The words of a key's row: its price first when known, and who bills it. */export const keyRowSub = (p: CloudProvider, price?: string | null): string => (price ? `${price} · billed to ${billedTo(p)}` : `Billed to ${billedTo(p)}`);diff --git a/src/lib/site-run.ts b/src/lib/site-run.tsnew file mode 100644index 00000000..2ff1358a--- /dev/null+++ b/src/lib/site-run.ts@@ -0,0 +1,66 @@+import { getModel, getPreset } from "@/lib/catalog";+import { dualEngine } from "@/lib/catalog/engines";+import { presetRoutes } from "@/lib/catalog/preset-recipe-routes";+import type { Generation } from "@/lib/catalog/types";+import type { TroubleAction } from "./diagnose";+import { CLOUD_KEY, isCloudProvider, type CloudProvider } from "./your-keys";+import { modelOwnSetup, poolRunsModel, poolRunsPreset, type PoolRules } from "./pool-rules";++type FailedRun = Pick<Generation, "place" | "engine" | "status" | "modelId" | "op" | "presetId" | "kind" | "trouble">;++/**+ * "Run on {Place}" on a run that failed on the person's own GPU or key (hosted runs): the open version this studio's GPUs+ * would run, once, named there; the account's pick stays as it was. A run on its own GPU: the same model. A run on its+ * key: the item's open version (a Fuobe Original on Open source, an app's open route). Null when they don't take it (a+ * model or app their rules keep off, one that runs on an own setup only), or there is no open version.+ */+export function siteRunOf(g: FailedRun, hosted: boolean, rules: PoolRules | undefined): { modelId: string; op?: string; engine?: "open" } | null {+ if (!hosted || g.place === "pool" || g.status !== "failed" || !g.trouble) return null;+ if (g.presetId && !poolRunsPreset(rules, g.presetId)) return null;+ const takes = (id: string): boolean => {+ const m = getModel(id);+ if (!m) return false;+ const open = { id: m.id, kind: m.kind, engine: "open" };+ return poolRunsModel(rules, open) && !modelOwnSetup(rules, open);+ };+ if (g.engine === "open") return takes(g.modelId) ? { modelId: g.modelId } : null;+ // On its key: the item's open version.+ const preset = g.presetId ? getPreset(g.presetId) : undefined;+ if (preset) {+ const route = presetRoutes(preset as Parameters<typeof presetRoutes>[0], "open", (id) => !!getModel(id))[0];+ return route && takes(route.modelId) ? { modelId: route.modelId, ...(route.op && { op: route.op }), engine: "open" } : null;+ }+ const m = getModel(g.modelId);+ return m && dualEngine(m) && takes(m.id) ? { modelId: m.id, engine: "open" } : null;+}++/**+ * A failed run's buttons as its tile shows them: while hosted runs are on, a key is never offered without its price (a+ * run whose offer was kept before prices were added to it says none: the offer goes).+ */+export const shownTroubleActions = (actions: TroubleAction[], hosted: boolean): TroubleAction[] =>+ hosted ? actions.filter((a) => a.kind !== "run-with-key" || / · /.test(a.label)) : actions;++const KEY_REFUSED = new Set(["key-balance", "key-rejected", "key-permission"]);++type KeyRun = Pick<Generation, "id" | "createdAt" | "engine" | "place" | "provider" | "status" | "trouble">;++/**+ * The account's last run, when its key turned it down (out of credit, not accepted, not allowed): the run, and the+ * provider whose key it was. Null when the newest run is anything else, so the line before the next press goes once a+ * run gets through.+ */+export function keyTurnedDown<G extends KeyRun>(runs: readonly G[]): { run: G; provider: CloudProvider } | null {+ let last: G | undefined;+ for (const g of runs) if (!last || g.createdAt > last.createdAt) last = g;+ if (!last || last.status !== "failed" || last.engine !== "cloud" || last.place === "pool" || !last.trouble || !KEY_REFUSED.has(last.trouble.cause)) return null;+ return isCloudProvider(last.provider) ? { run: last, provider: last.provider } : null;+}++/** The line before the next press on the key that turned the last run down. */+export const keyTurnedDownWords = (provider: CloudProvider): string => `Your ${CLOUD_KEY[provider].label} key was turned down last time.`;++/** The run sent once on {Place}: the failed run's request on the open version siteRunOf names, the place named. */+export function siteRunRequest(g: Pick<Generation, "request">, run: NonNullable<ReturnType<typeof siteRunOf>>): Generation["request"] {+ return { ...g.request, modelId: run.modelId, ...(run.op && { op: run.op }), ...(run.engine && { engine: run.engine }), place: "pool" } as Generation["request"];+}diff --git a/src/server/account-tool-run.ts b/src/server/account-tool-run.tsindex 1a863544..5248fe88 100644--- a/src/server/account-tool-run.ts+++ b/src/server/account-tool-run.ts@@ -14,7 +14,7 @@ import { accountInputProblem } from "./account-inputs";import { checkAccountLoras } from "./account-loras";import { requestViewer, type Account } from "./auth";import { accountRun, AccountRunError, asAccount, asVisitor, outputKind, previewChained, type AccountRunRefusal } from "./generations";-import type { Quote } from "./billing";+import { holdsOn, type Quote } from "./billing";import { queueRelease } from "./billing-outbox";import { gateGeneration, GPU_SETUP_HEADER } from "./gpu/gate";import { gpuTargetFor } from "./gpu/target";@@ -582,7 +582,14 @@ async function startOnPool<T>(}const kind = outputKind(pool.main.planned.op, pool.main.planned.model);const mod = await moderateRun(account, checkedRequest(steps, files), null, "pool", { kind, place: "pool" });- if (!mod.ok) return back(refuse(mod.refusal.status, mod.refusal.body.error, mod.refusal.body, mod.refusal.headers));+ // While runs here wait for the services (the policy says so), one the moderation service didn't answer for is taken,+ // and checked before it enters the line (as a studio's run is).+ let unchecked = false;+ if (!mod.ok) {+ if (!pool.light && holdsOn(pool.policy) && mod.refusal.body.code === "paused") unchecked = true;+ else return back(refuse(mod.refusal.status, mod.refusal.body.error, mod.refusal.body, mod.refusal.headers));+ }+ const checkOutputs = mod.ok && mod.checkOutputs;// The press of Run, kept from here (run-requests.ts): another server process may have started or answered it meanwhile.const claim = await claimToolPress();if (claim && "answer" in claim) return back(fromAnswer(claim.answer));@@ -590,11 +597,11 @@ async function startOnPool<T>(// Why the run waits for the billing service, when it does, and what its reserve then sends.let wait: ReserveWait | undefined;let facts: ReserveFacts | undefined;- if (pool.light) stamp = { place: "pool", light: true, ...(mod.checkOutputs && { checkOutputs: true }), ...policyWait(pool.policy) };+ if (pool.light) stamp = { place: "pool", light: true, ...(checkOutputs && { checkOutputs: true }), ...policyWait(pool.policy) };else {// One hold per try of a press of Run: every send of the try asks for it by the same request id.const limit = plan && "hold" in plan ? { reason: plan.hold, ...(plan.startAt !== undefined && { startAt: plan.startAt }) } : undefined;- const held = await reservePool(account, pool.main.req, pool.main.planned, run.shown ?? null, mod.checkOutputs, pool.steps, claim?.press ?? null, pool.policy, { heldMs: heldGuessMs(limit) });+ const held = await reservePool(account, pool.main.req, pool.main.planned, run.shown ?? null, checkOutputs, pool.steps, claim?.press ?? null, pool.policy, { heldMs: heldGuessMs(limit) });if (!held.ok) return back(refuse(held.refusal.status, held.refusal.body.error, held.refusal.body, held.refusal.headers));stamp = held.stamp;wait = held.wait;@@ -648,6 +655,7 @@ async function startOnPool<T>(* hold goes back by itself only when no row was made.*/const undo = () => {+ made.cap.settle();for (const g of ids) void cancelGeneration(g);if (!ids.length) release();};@@ -678,8 +686,10 @@ async function startOnPool<T>(}// Past a limit it can wait out, or while the billing service doesn't answer: its tiles show "In line" now, and it// enters the line when its reason clears (pool-holds.ts), nothing sent until then.- const shape = pool.light ? null : holdShape({ limit: made.admit.hold, wait });- if (shape) holdRun({ accountId: id, rows: made.cap.rows, pressedAt, ...shape, ...(facts && { facts }) });- else made.cap.start();+ const shape = pool.light ? null : holdShape({ limit: made.admit.hold, wait, unchecked });+ if (shape) {+ holdRun({ accountId: id, rows: made.cap.rows, pressedAt, ...shape, ...(facts && { facts }) });+ made.cap.settle();+ } else made.cap.start();return { ok: true, value };}diff --git a/src/server/billing.ts b/src/server/billing.tsindex 365530af..e7c51776 100644--- a/src/server/billing.ts+++ b/src/server/billing.ts@@ -1,6 +1,8 @@import "server-only";import type { Account } from "./auth";+import { db } from "./db";import { HookDown, hookCall, hookTarget, type HookTarget } from "./hook-client";+import { hostedRunsOn } from "./hosted-switch";/*** The billing hook (docs/billing-hook.md): an install can connect an external billing service at FUOBE_BILLING_URL.@@ -321,6 +323,7 @@ export async function policy(accountId: string | null): Promise<Policy | null> {const p = await call<Policy>("GET", accountId ? `/v1/policy?account=${encodeURIComponent(accountId)}` : "/v1/policy", undefined, BILLING_TIMEOUTS.policy);const ttlMs = Math.max(0, Math.min(3600, Number(p.ttlS) || 0)) * 1000;keep({ at: Date.now(), ttlMs, policy: p, goodAt: Date.now(), ...(p.prefer && { prefer: p.prefer }) });+ savePolicy(key, p);return p;} catch (e) {logDown("policy", e);@@ -344,8 +347,48 @@ export function lastPrefer(accountId: string | null): Policy["prefer"] {if (!billingConfigured()) return OPEN_POLICY.prefer;const cache = globalThis.__fuobeBillingPolicies;const own = cache?.get(accountId ?? "");- // (Its own last answer, when the service ever answered for it; else a guest's.)- return own?.goodAt !== undefined ? own.prefer : cache?.get("")?.prefer;+ // (Its own last answer, when the service ever answered for it here; else the one kept across restarts; else a guest's.)+ if (own?.goodAt !== undefined) return own.prefer;+ const kept = savedPolicy(accountId ?? "");+ return kept ? kept.prefer : cache?.get("")?.prefer;+}++/** Keep the service's answer across restarts (hosted runs on only): the key's own, and an account's as the last any got. */+function savePolicy(key: string, p: Policy): void {+ if (!hostedRunsOn()) return;+ try {+ const put = db().prepare("INSERT INTO billing_policies (key, policy_json, at) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET policy_json = excluded.policy_json, at = excluded.at");+ const json = JSON.stringify(p);+ const now = Date.now();+ put.run(key, json, now);+ if (key) put.run("*", json, now);+ } catch (e) {+ console.warn(`[fuobe] Couldn't keep the billing policy: ${(e as Error).message}`);+ }+}++/** The answer kept for this key across restarts, or null. */+function savedPolicy(key: string): Policy | null {+ if (!hostedRunsOn()) return null;+ try {+ const r = db().prepare("SELECT policy_json FROM billing_policies WHERE key = ?").get(key) as { policy_json: string } | undefined;+ return r ? (JSON.parse(r.policy_json) as Policy) : null;+ } catch {+ return null;+ }+}++/**+ * While the billing service doesn't answer and nothing recent is kept in memory (a restart, an outage past+ * POLICY_KEEP_MS, an account it never answered for here): its last answer kept across restarts, the account's own, else+ * the last any account got (a guest's for a guest). Only one under which runs wait instead of being refused (holdsOn):+ * a run pressed now is taken and waits for the service in line, and is reserved and checked when it answers. Null+ * otherwise (the press is refused as before). No service: OPEN_POLICY.+ */+export function keptPolicy(accountId: string | null): Policy | null {+ if (!billingConfigured()) return OPEN_POLICY;+ const p = accountId ? (savedPolicy(accountId) ?? savedPolicy("*")) : savedPolicy("");+ return p && holdsOn(p) ? p : null;}/** After how long a wait the line before Run offers an account its own GPU or key for that run, when the policy says none (s). */@@ -374,10 +417,14 @@ export function heldCap(p: Pick<Policy, "limits"> | null | undefined): number {return holdsOn(p) ? Math.floor(p!.limits.held!) : 0;}-/** After how long a wait the line before Run offers an account its own GPU or key, as the policy says (s). */+/**+ * After how long a wait the line before Run offers an account its own GPU or key, as the policy says (s). 0 turns the+ * offer off for waits (Infinity): it shows only at the daily cap and while runs there are paused.+ */export function policyOfferAfterS(p: Pick<Policy, "limits"> | null | undefined): number {const s = p?.limits?.offerAfterS;- return typeof s === "number" && Number.isFinite(s) && s >= 0 ? s : POOL_OFFER_AFTER_S;+ if (s === 0) return Infinity;+ return typeof s === "number" && Number.isFinite(s) && s > 0 ? s : POOL_OFFER_AFTER_S;}/**diff --git a/src/server/computer/finish.ts b/src/server/computer/finish.tsindex 3f9e8208..99e70dba 100644--- a/src/server/computer/finish.ts+++ b/src/server/computer/finish.ts@@ -61,10 +61,14 @@ export function finishTask(generationId: string, kind: FinishKind, step = 0): Tareturn rows.find((t) => ticketOf(t)?.kind === kind && (json<{ step?: number }>(t.extra_json, {}).step ?? 0) === step) ?? null;}-/** The wait the run was stamped with (the billing service's limit), else this install's (FUOBE_POOL_WAIT_MIN). */-function runWaitMs(generationId: string): number {+/**+ * The wait the run was stamped with (the billing service's limit; 0: as long as it takes, so none), else this+ * install's (FUOBE_POOL_WAIT_MIN). Undefined: no limit.+ */+function runWaitMs(generationId: string): number | undefined {const r = db().prepare("SELECT json_extract(request_json, '$.waitMs') AS w FROM generations WHERE id = ?").get(generationId) as { w: unknown } | undefined;- const w = Number(r?.w);+ const w = r?.w === null || r?.w === undefined ? NaN : Number(r.w);+ if (w === 0) return undefined;return Number.isFinite(w) && w > 0 ? w : poolWaitMs();}@@ -72,7 +76,7 @@ function runWaitMs(generationId: string): number {* Queue a finishing job for an account's run: its files staged as the account's (a picture with what it carries besides* its pixels blanked, as for a run's job), its ticket checked as the worker will check it, in the run's class and at the* run's place in line. It waits for a worker's CPU slot as long as the run was allowed to wait in line (its stamped wait,- * else this install's): a job no CPU slot took by then fails, and the run ends without what it would have made (a 3D+ * else this install's; stamped 0: as long as it takes): a job no CPU slot took by then fails, and the run ends without what it would have made (a 3D* model keeps its raw GLB; a camera path's step says one plain sentence). Once a CPU slot took it, it waits in its place* after any recovery, as every job does. Once a run (and step): while a job of this kind for it is in line, running or* done, its id comes back and nothing new is queued, in one locked step even while another app process (a deploy's@@ -116,6 +120,7 @@ export function queueFinish(o: {// job of its own yet, and keeps the place of the steps of its run before it.const run = runPlaceOf(o.generationId);const now = Date.now();+ const wait = runWaitMs(o.generationId);const t = createTask({principal,generationId: o.generationId,@@ -131,7 +136,7 @@ export function queueFinish(o: {rankAt: run?.rankAt ?? now,lane: "small",needs: { workflowId: `finish-${o.kind}`, files: [], packs: [], minVramBytes: 0 },- notAfter: now + runWaitMs(o.generationId),+ ...(wait !== undefined && { notAfter: now + wait }),slot: "cpu",},});diff --git a/src/server/db.ts b/src/server/db.tsindex 831a1030..8a81b046 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -1198,6 +1198,8 @@ function open(): Database.Database {db.exec(RUN_ON_TABLES);// Runs on this install's GPUs waiting to enter the line (pool-holds.ts): empty unless hosted runs are on.db.exec(POOL_HOLD_TABLES);+ // The billing service's last policy answer (billing.ts keptPolicy): empty unless hosted runs are on.+ db.exec(KEPT_POLICY_TABLES);// Its list reads this small summary, never every board's pages (a table made before it had the column gets it).if (!(db.prepare("PRAGMA table_info(account_canvases)").all() as { name: string }[]).some((c) => c.name === "summary_json")) {addColumn(db, "ALTER TABLE account_canvases ADD COLUMN summary_json TEXT");@@ -1271,6 +1273,16 @@ const POOL_HOLD_TABLES = `CREATE TABLE IF NOT EXISTS pool_holds (CREATE INDEX IF NOT EXISTS pool_holds_account ON pool_holds(account_id, pressed_at);CREATE INDEX IF NOT EXISTS pool_holds_run ON pool_holds(run_id);`;+/**+ * The billing service's last policy answer, kept across restarts (billing.ts keptPolicy): by account id, '' for a+ * guest's, '*' for the last any account got. Written only while hosted runs are on. Not a numbered migration.+ */+const KEPT_POLICY_TABLES = `CREATE TABLE IF NOT EXISTS billing_policies (+ key TEXT PRIMARY KEY,+ policy_json TEXT NOT NULL,+ at INTEGER NOT NULL+ );`;+/*** The runs let in whose rows are still being made (a tool's start that awaits before it makes them), counted until they* exist (pool-limits.ts openAdmission).diff --git a/src/server/generations.ts b/src/server/generations.tsindex 11225b4e..900fcfa8 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -19,6 +19,7 @@ import { sideMultipleProblem, upscaleTier } from "@/lib/av/upscale";import { chainedWaitMessage, framesWait, keyframeChain } from "@/lib/catalog/keyframes";import { clipFpsProblem, clipSizeProblem, clipTotalProblem, clipWindowProblem, elementClipProblem, insertRangeProblem, portraitShapeProblem, sourceFrames, voiceWindowProblem } from "@/lib/catalog/clip-windows";import { avatarSeconds, clipEditSeconds, estimateCost, inferOperation, movedAppRequest, planGeneration, presetRoute, routeLoras, routesFor, sourceLengthProblem, withoutTriggers } from "@/lib/catalog/plan";+import { formatCost } from "@/lib/format";import { framedLength, keepMatte, sizeValue } from "@/lib/catalog/payload";import { fitLoras, loraName, lorasFit } from "@/lib/catalog/loras";import { dualEngine, onEngine, pickEngine } from "@/lib/catalog/engines";@@ -126,7 +127,7 @@ import { engineMode, getSetting, withCandidates, withoutCandidates } from "./setimport { blockedForAccounts, discardBody, fetchRemoteToFile, RemoteFetchError } from "./remote-fetch";import { accountSend } from "./account-send";import { stamped, stampOf, withoutStamp, withRunStamp, type RunStamp } from "./run-stamp";-import { anyHeld, dropHold, holdRun, NOT_HELD } from "./pool-holds";+import { anyHeld, dropGone, dropHold, HELD, holdRun, NOT_HELD } from "./pool-holds";import { ACTIVE_STATES, FILE_TROUBLE_WORDS, POOL_WORDS, RELAY_WORDS } from "@/lib/relay";import { heldLine, placeInLine, poolOnWorkers, poolRunsProvider, poolWaitMs, runOnPool } from "./hosted";import { hostedRunsOn } from "./hosted-switch";@@ -1311,6 +1312,9 @@ export function createGenerations(sent: GenerationRequest, opts: CreateOptions =created.push(notes.length ? { ...toGeneration(row), notes } : toGeneration(row));const capture = captureStore().getStore();capture?.ids.push(id);+ // A later step made inside a capture waits for the capture's start too: one whose earlier steps finished in an+ // earlier run (a film's shots after its board) is otherwise sent before its run is kept or made to wait.+ if (capture && waits) parked().set(id, Date.now() + PARK_MS);if (!waits) {const start = () => void submit(id, route, providerId, plan, req, i);if (capture) {@@ -1343,19 +1347,43 @@ const captureStore = () => (globalThis.__fuobeRunCapture ??= new AsyncLocalStora* it (null: a later step, sent once its earlier steps are done), for a run that waits to enter the line instead* (pool-holds.ts): its rows are sent later from what is stored (sendHeld). (An awaiting `fn` adds rows as it goes.)*/-export function captureRun<T>(fn: () => T): { value: T; ids: string[]; readonly rows: { id: string; job: number | null }[]; start: () => void } {+export function captureRun<T>(fn: () => T): { value: T; ids: string[]; readonly rows: { id: string; job: number | null }[]; start: () => void; settle: () => void } {const cap: RunCapture = { ids: [], submits: [], jobs: new Map() };const value = captureStore().run(cap, fn);+ const settle = () => cap.ids.forEach((id) => parked().delete(id));return {value,ids: cap.ids,get rows() {return cap.ids.map((id) => ({ id, job: cap.jobs.get(id) ?? null }));},- start: () => cap.submits.splice(0).forEach((s) => s()),+ start: () => {+ settle();+ cap.submits.splice(0).forEach((s) => s());+ },+ settle,};}+declare global {+ var __fuobeParkedSteps: Map<string, number> | undefined;+}+/**+ * Later steps made inside a capture that is not started or settled yet (captureRun), with when they stop waiting for it+ * at the latest (a caller that never settles leaves nothing parked for long). advanceDependents leaves them alone.+ */+const parked = (): Map<string, number> => (globalThis.__fuobeParkedSteps ??= new Map<string, number>());+const PARK_MS = 10 * 60_000;++/** Is this later step still waiting for its capture (captureRun) to start or settle? */+function isParked(id: string, now = Date.now()): boolean {+ const until = parked().get(id);+ if (until === undefined) return false;+ if (until > now) return true;+ parked().delete(id);+ return false;+}+/** One row a run would make: its model, operation, provider, kind and app, and the earlier steps it waits for. */export interface PlannedStep {id: string;@@ -1378,7 +1406,9 @@ export function plannedSteps(fn: () => unknown): PlannedStep[] {let steps: PlannedStep[] = [];try {d.transaction(() => {- steps = stepsOf(captureRun(fn).ids);+ const run = captureRun(fn);+ run.settle();+ steps = stepsOf(run.ids);throw ROLLED_BACK;})();} catch (e) {@@ -1603,7 +1633,8 @@ const SENT_ELSEWHERE = (table: string) =>* failed, was canceled or is gone (so they fail now, not after the others finish). A per-frame render keeps* hundreds of steps waiting for its lanes, and a plain "oldest 50 waiting" would hold every chain started after* it until its backlog drained. The steps this process is handing to a provider right now are still "queued":- * the limit makes room for them. A step another app process is handing over is left to it.+ * the limit makes room for them. A step another app process is handing over is left to it, and so is a step of a run+ * that waits to enter the line (pool-holds.ts): it moves once its run is released.*/const READY_DEPENDENTS = `SELECT g.* FROM generations gWHERE g.status = 'queued' AND g.external_id IS NULL AND g.depends_on IS NOT NULL@@ -1611,7 +1642,7 @@ const READY_DEPENDENTS = `SELECT g.* FROM generations gNOT EXISTS (SELECT 1 FROM ${DEP_IDS} JOIN generations dep ON dep.id = d.value WHERE dep.status IN ('queued', 'running'))OR EXISTS (SELECT 1 FROM ${DEP_IDS} LEFT JOIN generations dep ON dep.id = d.value WHERE dep.id IS NULL OR dep.status IN ('failed', 'canceled')))- AND NOT ${SENT_ELSEWHERE("g")}+ AND NOT ${SENT_ELSEWHERE("g")} AND ${NOT_HELD("g")}ORDER BY g.created_at ASC LIMIT @limit`;/** The error a waiting step gets when an input failed (framesProgress tells these from a step's own failure). */@@ -1681,11 +1712,11 @@ export const COMFY_WAIT = { ms: 60_000 };async function advanceDependents(): Promise<void> {const rows = db().prepare(READY_DEPENDENTS)- .all({ limit: 50 + submitting().size, me: runnerToken(), quiet: Date.now() - QUIET_MS }) as Row[];+ .all({ limit: 50 + submitting().size + parked().size, me: runnerToken(), quiet: Date.now() - QUIET_MS }) as Row[];// A forced look at ComfyUI, at most one a sweep, for the steps that found it not answering.let lookedAgain: Promise<boolean> | undefined;for (const r of rows) {- if (submitting().has(r.id)) continue;+ if (submitting().has(r.id) || isParked(r.id)) continue;// A step queued before its model was retired runs on what replaced it (and its row says so).const moved = currentRequest(JSON.parse(r.request_json) as GenerationRequest);const stored = moved.request;@@ -2216,18 +2247,36 @@ export function cloudTwin(req: Pick<GenerationRequest, "presetId" | "modelId">,return null;}-/** A GPU trouble's buttons, with "Run with your … key" when one of the account's keys runs this tool's cloud version. */-function withKeyOffer(actions: TroubleAction[], account: string, req: Pick<GenerationRequest, "presetId" | "modelId">): TroubleAction[] {+/**+ * A GPU trouble's buttons, with "Run with your … key" when one of the account's keys runs this tool's cloud version.+ * While hosted runs are on, only with its price (a key is never billed by a press that showed none).+ */+function withKeyOffer(actions: TroubleAction[], account: string, req: Pick<GenerationRequest, "presetId" | "modelId" | "params" | "op">): TroubleAction[] {if (actions.some((a) => a.kind === "run-with-key")) return actions;const twin = cloudTwin(req, account);- return twin ? [...actions, withKeyAction(twin.provider, twin.modelId, twin.op)] : actions;+ if (!twin) return actions;+ if (!hostedRunsOn()) return [...actions, withKeyAction(twin.provider, twin.modelId, twin.op)];+ const price = keyRunPrice(twin, req);+ return price ? [...actions, withKeyAction(twin.provider, twin.modelId, twin.op, price)] : actions;+}++/** A run's price on its cloud version (one run, at the request's settings), as a key offer says it ("≈ $0.04"), or null. */+function keyRunPrice(twin: { modelId: string; op?: string }, req: Pick<GenerationRequest, "params" | "op">): string | null {+ const m = getModel(twin.modelId);+ if (!m) return null;+ try {+ const usd = estimateCost(dualEngine(m) ? onEngine(m, "cloud") : m, req.params ?? {}, 1, (twin.op ?? req.op) as Operation | undefined, false);+ return usd != null && usd > 0 ? `≈ ${formatCost(usd)}` : null;+ } catch {+ return null;+ }}/*** What an account's run ran into, as diagnose.ts reads it: its own GPU's words (comfyui.ts troubleError), or its key's* provider's status and words. Undefined for anything else (a request's own problem, already in plain words).*/-function accountTrouble(e: unknown, account: string, providerId: string, stage: KeyStage, req?: Pick<GenerationRequest, "presetId" | "modelId">): Diagnosis | undefined {+function accountTrouble(e: unknown, account: string, providerId: string, stage: KeyStage, req?: Pick<GenerationRequest, "presetId" | "modelId" | "params" | "op">): Diagnosis | undefined {const own = (e as { trouble?: Diagnosis } | null)?.trouble;if (own) return providerId === "comfyui" && req && own.cause.startsWith("gpu-") ? { ...own, actions: withKeyOffer(own.actions, account, req) } : own;if (!isCloudProvider(providerId)) return undefined;@@ -2825,6 +2874,19 @@ function sweepInterrupted(): void {}}+/**+ * Hosted runs were switched off while runs waited to enter the line: nothing will release them, so they end as a run cut+ * off before it started does (the sweep's words), and their holds go. What the billing service set aside for them goes+ * back (each ended row's report closes its hold; a run whose reserve was never answered is released by its request id).+ */+function endHeldRuns(): void {+ const rows = db()+ .prepare(`SELECT g.id FROM generations g WHERE g.status = 'queued' AND g.external_id IS NULL AND ${HELD("g")}`)+ .all() as { id: string }[];+ for (const r of rows) updateLive(r.id, { status: "failed", error: "This run stopped before it started. Press Retry.", completed_at: Date.now(), message: null });+ dropGone();+}+/*** A run on this install's GPUs cut off between its row and its GPU task: it waits to enter the line again, at its* press-time place (its row's time), as the job it was in its run (its seed's offset). Its rows counted against the@@ -2953,6 +3015,12 @@ async function tick(): Promise<void> {} catch (e) {console.warn(`[generations] runs waiting to enter the line: ${(e as Error).message}`);}+ } else if (anyHeld()) {+ try {+ endHeldRuns();+ } catch (e) {+ console.warn(`[generations] runs waiting to enter the line: ${(e as Error).message}`);+ }}// The owner's jobs first, then the accounts' in turn. An account's ComfyUI may be slow to answer: its polls run on// their own, so they never hold up the owner's (pollGuarded never polls one row twice at once).diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.tsindex 4502846f..6852311c 100644--- a/src/server/hosted-run.ts+++ b/src/server/hosted-run.ts@@ -16,6 +16,7 @@ import {forgetBalance,FREE_QUOTE,holdsOn,+ keptPolicy,lastPrefer,lastQuote,policy as billingPolicy,@@ -421,7 +422,7 @@ export function poolGate(// needs): a run that would wait for nothing, so it runs on the visitor's own GPU instead.if (!poolTakes(planned.route.endpoint)) return { ok: false, reason: "ownSetup", setup: gpu };if (poolCardRefuses(planned.model.id)) return { ok: false, reason: "rtxCard", setup: gpu };- if (req.loras?.length) return { ok: false, reason: "loras", setup: gpu };+ if (req.loras?.length && !req.lorasOff) return { ok: false, reason: "loras", setup: gpu };if (p) {const inputs = inputCounts(req);const takes = poolUploads(p);@@ -559,8 +560,12 @@ export async function decidePlace(account: Account, asked: GenerationRequest, wiif (p === undefined) p = await billingPolicy(account.id);// The billing service doesn't answer: a run whose own GPU goes first goes there as before; one that goes to this// install's GPUs (the service's last answer put them first, or the account picked them) is never moved to its own GPU- // for that: it waits for the service.- if (!p) return ownFallback && !poolFirst(p, picked, account.id) ? OWN : { kind: "refuse", refusal: billingRefusal("paused", BILLING_WAIT.run) };+ // for that: it waits for the service, in line, under the service's last answer kept here (billing.ts keptPolicy).+ if (!p) {+ if (ownFallback && !poolFirst(p, picked, account.id)) return OWN;+ p = keptPolicy(account.id);+ if (!p) return { kind: "refuse", refusal: billingRefusal("paused", BILLING_WAIT.run) };+ }// Closed to this account: its own GPU (or today's "Connect your GPU"); asked for by name, said so.if (!p.hosted) return wish === "pool" ? notOffered(hostedWords(placeFor(p)).notHosted) : OWN;// Planned, checked and priced for the outputs it would make there (the policy's cap per run).@@ -848,7 +853,9 @@ function poolLine(facts: Pick<QueueFacts, "ahead" | "etaS" | "nextOpenAt">, o: {const afterMs = policyOfferAfterS(o.p) * 1000;if (o.waits) {const back = facts.nextOpenAt && facts.nextOpenAt > now ? facts.nextOpenAt : undefined;- return { place, etaSeconds: null, unknown: true, ...(back && { returnAt: back }), ...((!back || back - now > afterMs) && { long: true }) };+ // An unknown wait is long, unless the offer is off for waits (offerAfterS 0).+ const long = back ? back - now > afterMs : Number.isFinite(afterMs);+ return { place, etaSeconds: null, unknown: true, ...(back && { returnAt: back }), ...(long && { long: true as const }) };}const eta = o.q?.etaS ?? facts.etaS ?? null;return { place, etaSeconds: eta, ...(eta !== null && eta * 1000 > afterMs && { long: true }) };@@ -870,10 +877,13 @@ const notOfferedQuote = (text: string, setup?: OwnSetup, sub?: string): Quote &/*** A gate's refusal as the price check's quote: its label (gateText), the sentence under it (`sub`: the tooltip), and the- * own setup Run opens. A run past the outputs a run here makes has no setup: the person picks fewer.+ * own setup Run opens. A run past the outputs a run here makes has no setup: the person picks fewer. One refused only for+ * its LoRAs (an element's trained LoRA) says so (`withoutLoras`): the page offers the same run without them.*/-const gateQuote = (gate: GateRefusal, guest: boolean, place: Place): Quote & { ownSetup?: OwnSetup } =>- notOfferedQuote(gateText(gate, guest, place), gate.reason === "outputs" ? undefined : (gate.setup ?? needsGpu()), gateDetail(gate, place));+const gateQuote = (gate: GateRefusal, guest: boolean, place: Place): Quote & { ownSetup?: OwnSetup; withoutLoras?: true } => ({+ ...notOfferedQuote(gateText(gate, guest, place), gate.reason === "outputs" ? undefined : (gate.setup ?? needsGpu()), gateDetail(gate, place)),+ ...(gate.reason === "loras" && { withoutLoras: true as const }),+});/*** A price check on this install's GPUs (hosted runs on): the plan there, the billing service's quote (no service: free,@@ -898,7 +908,8 @@ export async function poolQuote(const picked = pickedPlace(account, wish);if (picked === "own") return null;// A guest is priced under the billing service's policy for guests (none set: as an account would be, once signed up).- const p = await billingPolicy(account?.id ?? null);+ // A quiet service: its last answer kept here, so Run stays on and a press waits for it in line (billing.ts keptPolicy).+ const p = (await billingPolicy(account?.id ?? null)) ?? keptPolicy(account?.id ?? null);// Priced for the outputs it would make: the studio's cap per run, and the policy's when lower (as the run is).const { req } = poolRequest(asked, p);let planned: Planned;@@ -1037,7 +1048,11 @@ export async function decideToolPlace(account: Account, steps: ToolRunStep[], wi}if (p === undefined) p = await billingPolicy(account.id);// As decidePlace: a run that goes to this install's GPUs waits for a quiet service, never moved to its own GPU for it.- if (!p) return ownFallback && !poolFirst(p, picked, account.id) ? OWN : { kind: "refuse", refusal: billingRefusal("paused", BILLING_WAIT.run) };+ if (!p) {+ if (ownFallback && !poolFirst(p, picked, account.id)) return OWN;+ p = keptPolicy(account.id);+ if (!p) return { kind: "refuse", refusal: billingRefusal("paused", BILLING_WAIT.run) };+ }if (!p.hosted) return wish === "pool" ? notOffered(hostedWords(placeFor(p)).notHosted) : OWN;// What these GPUs can't take (a label) goes to its own GPU; what they take is taken, even while every GPU that could// run it is away or being updated: it waits in line until one is free.@@ -1065,7 +1080,7 @@ export async function toolPoolQuote(if (!hostedRunsOn() || wish === "own" || !poolReady() || !steps.length) return null;const picked = pickedPlace(account, wish);if (picked === "own") return null;- const p = await billingPolicy(account?.id ?? null);+ const p = (await billingPolicy(account?.id ?? null)) ?? keptPolicy(account?.id ?? null);const hasGpu = !!account && !!accountGpu(account.id);if (account && hasGpu && wish !== "pool" && !poolFirst(p, picked, account.id) && (await ownGpuOnline(account.id))) return null;if (p && !p.hosted) return null;diff --git a/src/server/hosted.ts b/src/server/hosted.tsindex f2bf01bf..4eee338c 100644--- a/src/server/hosted.ts+++ b/src/server/hosted.ts@@ -218,7 +218,7 @@ export function hostedGuestWords() {export function outputsWords(cap: number, guest: boolean, place: Place): string {const most = cap === 1 ? "one at a time" : `up to ${cap} at a time`;const pick = cap === 1 ? "Pick one" : `Pick ${cap} or fewer`;- return guest ? `Makes ${most}. ${pick}.` : `Makes ${most} on ${place.text}. ${pick}, or connect your own GPU in Settings.`;+ return guest ? `Makes ${most}. ${pick}.` : `Makes ${most} on ${place.text}. ${pick}, or run it on your own GPU.`;}/** Are these words outputsWords (a run past the outputs a run here makes: the person picks fewer), not a label? */@@ -355,17 +355,30 @@ function ownServerPlace(pressedAt: number): LinePlace {}/**- * About when a run held behind the account's runs going would be ready: when the first of them still in line is due- * done, plus a new run's wait now. Null when that isn't known (none of them waits in line with an estimate).+ * About when a run held behind the account's runs going would be ready: when the first of them is due done (one in line:+ * its wait; one working: its time left, from its GPU task's estimate, else a typical run's), plus a new run's wait now.+ * Null when that isn't known (none of them has an estimate).*/-function mineEta(accountId: string, workflow: string | null): number | null {+function mineEta(accountId: string, workflow: string | null, now = Date.now()): number | null {const going = db()- .prepare(`SELECT g.id FROM generations g WHERE ${POOL_ROWS} AND json_extract(g.request_json, '$.account') = ? AND ${NOT_HELD("g")}`)- .all(accountId) as { id: string }[];+ .prepare(+ `SELECT g.id, r.started_at FROM generations g LEFT JOIN generation_runs r ON r.id = g.id+ WHERE ${POOL_ROWS} AND json_extract(g.request_json, '$.account') = ? AND ${NOT_HELD("g")}`,+ )+ .all(accountId) as { id: string; started_at: number | null }[];let first: number | null = null;+ let typical: number | null | undefined;for (const g of going) {- const q = placeInLine(g.id);- if (q?.etaSeconds != null) first = first === null ? q.etaSeconds : Math.min(first, q.etaSeconds);+ let eta: number | null = null;+ if (g.started_at !== null) {+ const task = db().prepare("SELECT est_ms, started_at FROM relay_tasks WHERE generation_id = ? AND state = 'running' ORDER BY created_at DESC LIMIT 1").get(g.id) as+ | { est_ms: number | null; started_at: number | null }+ | undefined;+ const est = task?.est_ms ?? (typical === undefined ? (typical = typicalRunMs()) : typical);+ const since = task?.started_at ?? g.started_at;+ if (est !== null && est > 0) eta = Math.max(5, Math.round((est - (now - since)) / 1000));+ } else eta = placeInLine(g.id)?.etaSeconds ?? null;+ if (eta !== null) first = first === null ? eta : Math.min(first, eta);}if (first === null) return null;const own = queueFacts(accountId, workflow).etaS;diff --git a/src/server/pool-holds.ts b/src/server/pool-holds.tsindex a8e7a417..0fcb7b66 100644--- a/src/server/pool-holds.ts+++ b/src/server/pool-holds.ts@@ -181,14 +181,16 @@ export const endRunLease = (runId: string): void => endLease("pool_holds", runId/*** The run enters the line now: its holds go, in one step that only this app process's lease may take, and only for the* rows that still wait (one cancelled meanwhile is left out). Returns its rows to send (job index set) and the rank they- * enter at, or null when it isn't this process's to release any more.+ * enter at, or null when it isn't this process's to release any more. `room`: asked in the same locked step, so two app+ * processes releasing an account's runs at once never pass its room among its runs going (false: it waits).*/-export function takeRun(runId: string, now = Date.now()): { send: { id: string; job: number }[]; rankAt: number | undefined } | null {+export function takeRun(runId: string, now = Date.now(), room?: () => boolean): { send: { id: string; job: number }[]; rankAt: number | undefined } | null {const d = db();return d.transaction(() => {const rows = d.prepare(`SELECT * FROM pool_holds WHERE run_id = ? AND ${MINE_NOW}`).all(runId, leaseToken(), now) as HoldRow[];if (!rows.length) return null;+ if (room && !room()) return null;d.prepare("DELETE FROM pool_holds WHERE run_id = ?").run(runId);const live = d.prepare("SELECT 1 FROM generations WHERE id = ? AND status = 'queued' AND external_id IS NULL");const send = rows.filter((r) => r.job !== null && live.get(r.generation_id)).map((r) => ({ id: r.generation_id, job: r.job! }));diff --git a/src/server/pool-release.ts b/src/server/pool-release.tsindex 453eb042..f71b0526 100644--- a/src/server/pool-release.ts+++ b/src/server/pool-release.ts@@ -1,7 +1,7 @@import "server-only";import type { GenerationRequest } from "@/lib/catalog/types";import { accountById } from "./auth";-import { accountFacts, billingConfigured, forgetBalance, policy as billingPolicy, policyGiveUpMs, reserve, serviceAnsweredAt } from "./billing";+import { accountFacts, billingConfigured, forgetBalance, keptPolicy, policy as billingPolicy, policyGiveUpMs, reserve, serviceAnsweredAt, type Policy } from "./billing";import { db } from "./db";import { failWaiting, previewGeneration, restampRows, sendHeld } from "./generations";import { queueFacts, runOnPool } from "./hosted";@@ -75,15 +75,15 @@ function sayServiceWait(heads: HoldRow[], now: number): void {}/**- * How many more of an account's runs may enter the line now (pool-limits.ts lineRoom: held runs don't count). Null when- * its policy isn't known (the service is quiet and nothing is kept): its runs wait.+ * The account's policy for its room among its runs going (pool-limits.ts lineRoom: held runs don't count), read once a+ * turn. Null when it isn't known (the service is quiet and nothing is kept, here or across restarts): its runs wait, as+ * they are.*/-async function roomFor(accountId: string, kept: Map<string, number | null>): Promise<number | null> {+async function policyFor(accountId: string, kept: Map<string, Policy | null>): Promise<Policy | null> {if (kept.has(accountId)) return kept.get(accountId)!;- const p = await billingPolicy(accountId);- const left = p ? lineRoom(p, poolRunCounts(accountId)) : null;- kept.set(accountId, left);- return left;+ const p = (await billingPolicy(accountId)) ?? keptPolicy(accountId);+ kept.set(accountId, p);+ return p;}/** Ask again later: one more try, and the next one after a growing wait (`paused`: the service said runs are paused). */@@ -179,20 +179,27 @@ export async function releaseHeldRuns(now = Date.now()): Promise<number> {const heads = heldRunHeads();if (!heads.length) return 0;sayServiceWait(heads, now);- const room = new Map<string, number | null>();+ const policies = new Map<string, Policy | null>();+ // Accounts whose earlier press couldn't enter this turn (no room, or another app process is releasing it): their later+ // presses wait too, so they enter in the order they were made.+ const blocked = new Set<string>();let released = 0;let serviceCalls = 0;let serviceDown = false;for (const h of heads) {// Not before its time.if (h.start_at !== null && h.start_at > now) continue;+ if (!h.counted && blocked.has(h.account_id)) continue;const needsService = !h.reserved || !h.checked;if (needsService) {if (serviceDown || serviceCalls >= SERVICE_TRIES_PER_TURN) continue;const due = h.next_at === null || h.next_at <= now || (h.tried_at !== null && serviceAnsweredAt() > h.tried_at);if (!due) continue;}- if (!leaseRun(h.run_id, now)) continue;+ if (!leaseRun(h.run_id, now)) {+ blocked.add(h.account_id);+ continue;+ }try {if (needsService) {serviceCalls++;@@ -200,18 +207,29 @@ export async function releaseHeldRuns(now = Date.now()): Promise<number> {if (step === "down") serviceDown = true;if (step !== "ready") continue;}+ let p: Policy | null = null;if (!h.counted) {- const left = await roomFor(h.account_id, room);- if (left === null || left <= 0) {+ p = await policyFor(h.account_id, policies);+ // No policy to count by: it waits as it is, its tile unchanged.+ if (!p) {+ blocked.add(h.account_id);+ continue;+ }+ if (lineRoom(p, poolRunCounts(h.account_id)) <= 0) {// Its own reason cleared, but the account's runs going fill its room: it waits behind them, as its tile says.if (h.reason !== "mine") setRunHold(h.run_id, { reason: "mine", start_at: null, paused: 0 });+ blocked.add(h.account_id);continue;}}- const taken = takeRun(h.run_id);- if (!taken) continue;+ const limits = p;+ // The room is counted again in the step that takes the run (another app process may have released one meanwhile).+ const taken = takeRun(h.run_id, Date.now(), limits ? () => lineRoom(limits, poolRunCounts(h.account_id)) > 0 : undefined);+ if (!taken) {+ if (!h.counted) blocked.add(h.account_id);+ continue;+ }for (const s of taken.send) sendHeld(s.id, s.job, taken.rankAt);- if (!h.counted) room.set(h.account_id, (room.get(h.account_id) ?? 1) - 1);released++;} finally {endRunLease(h.run_id);diff --git a/src/server/request-schema.ts b/src/server/request-schema.tsindex a427ccda..255b356a 100644--- a/src/server/request-schema.ts+++ b/src/server/request-schema.ts@@ -127,6 +127,8 @@ export const GenerationRequestSchema = z.object({// A Fuobe Original runs on both engines: the one to run on (the composer's switch). Unset: the engine mode, else// the first connected.engine: z.enum(["open", "cloud"]).optional(),+ // "Run without LoRAs": an @element with a trained LoRA goes in as its photos instead.+ lorasOff: z.literal(true).optional(),// A recipe's LoRAs (the evaluation harness, scripts/eval): added after the preset's own. On ComfyUI `file` must// already be in models/loras (ComfyUI checks the name against its list); a cloud LoRA endpoint takes `url`.loras: zdiff --git a/src/server/tool-runs.ts b/src/server/tool-runs.tsindex 3f6d1faf..8891c8c0 100644--- a/src/server/tool-runs.ts+++ b/src/server/tool-runs.ts@@ -30,6 +30,7 @@ export function dryRunSteps(start: () => unknown): ToolStep[] {try {d.transaction(() => {const made = captureRun(start);+ made.settle();if (made.value && typeof (made.value as { then?: unknown }).then === "function") throw new Error("A run that waits before it starts can't be planned here.");const q = d.prepare("SELECT request_json, depends_on FROM generations WHERE id = ?");steps = made.ids.flatMap((id) => {diff --git a/tests/cpu-slot.test.ts b/tests/cpu-slot.test.tsindex 25d112c8..a2193bc4 100644--- a/tests/cpu-slot.test.ts+++ b/tests/cpu-slot.test.ts@@ -649,6 +649,18 @@ describe("finishing jobs and their run", () => {finish.stopWorkerFinish(gid);});+ it("a run stamped to wait as long as it takes (0): its finishing job has no wait limit either", async () => {+ const { saveFile } = await import("@/server/storage");+ const gid = generation(accountId, "image-to-3d");+ db().prepare("UPDATE generations SET request_json = ? WHERE id = ?").run(JSON.stringify({ account: accountId, place: "pool", waitMs: 0 }), gid);+ const raw = saveFile({ data: Buffer.from("glTF raw model"), contentType: "model/gltf-binary", name: "model.glb", source: "generation", generationId: gid, accountId });+ const outputs = [{ url: raw.url, kind: "model3d" as const, contentType: "model/gltf-binary", assetId: raw.id }];+ finish.startWorkerModelFinish(gid, outputs, { op: "image-to-3d", provider: "comfyui", account: accountId, done: () => {} });+ const t = finish.finishTask(gid, "model3d")!;+ expect(t.not_after).toBeNull();+ finish.stopWorkerFinish(gid);+ });+it("count only a CPU slot heard from lately, on a worker built for this studio's catalog", () => {const w = addWorker();beat(w, { cpuSlot: { finishes: ["model3d"] }, catalogVersion: "e".repeat(64) });diff --git a/tests/elements.test.ts b/tests/elements.test.tsindex 380eda57..af2fc39e 100644--- a/tests/elements.test.ts+++ b/tests/elements.test.ts@@ -72,6 +72,15 @@ describe("applyMentions", () => {expect(planGeneration(request, getModel, getPreset).loras.map((l) => l.file)).toEqual(["maya.safetensors"]);});+ it("asked without LoRAs (Run without LoRAs): a trained element goes in as its photos, and the request carries none", () => {+ const m = getModel("oss-z-image-turbo")!;+ const trained = el({ loras: [{ engine: "open", modelId: m.id, file: "maya.safetensors", trigger: "mya woman" }] });+ const { request } = applyMentions({ feature: "image", modelId: m.id, prompt: "@Maya on a beach", lorasOff: true }, m, [trained]);+ expect(request.loras).toBeUndefined();+ const own = applyMentions({ feature: "image", modelId: m.id, prompt: "a beach", lorasOff: true, loras: [{ file: "x.safetensors" }] }, m, [trained]).request;+ expect(own.loras).toBeUndefined();+ });+it("leaves requests without mentions untouched", () => {const nb = getModel("nano-banana-pro")!;const req = { feature: "image", modelId: nb.id, prompt: "email [email protected]" };diff --git a/tests/golden/self-host/composer.html b/tests/golden/self-host/composer.htmlnew file mode 100644index 00000000..525cfd81--- /dev/null+++ b/tests/golden/self-host/composer.html@@ -0,0 +1,735 @@+<div class="group/composer w-full rounded-[20px] border bg-background p-2.5 shadow-soft transition-[border-color,box-shadow] focus-within:border-primary focus-within:ring-4 focus-within:ring-brand-faint sm:rounded-composer">+<div class="relative">+<div aria-hidden="true" class="w-full px-2.5 py-1.5 text-left text-base leading-relaxed whitespace-pre-wrap break-words pointer-events-none absolute inset-0 overflow-hidden text-foreground"></div>+<textarea rows="1" placeholder="Describe an image… try “a koi pond at night, neon rain”" aria-label="Prompt" spellCheck="true" class="w-full px-2.5 py-1.5 text-left text-base leading-relaxed whitespace-pre-wrap break-words scrollbar-none relative field-sizing-content resize-none bg-transparent text-transparent caret-foreground outline-none placeholder:text-subtle-foreground selection:bg-brand-faint selection:text-transparent max-h-52 min-h-12">+</textarea>+</div>+<div class="flex items-center gap-2">+<div data-composer-toolbar="true" class="scrollbar-none -my-1 flex min-w-0 flex-1 items-center gap-1.5 overflow-x-auto py-1 sm:flex-wrap sm:overflow-x-visible">+<button type="button" aria-label="Add media" class="grid size-8 shrink-0 place-items-center rounded-full bg-secondary text-secondary-foreground transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/50" data-state="closed" data-slot="popover-trigger" aria-haspopup="dialog" aria-expanded="false">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-plus size-4" aria-hidden="true">+<path d="M5 12h14">+</path>+<path d="M12 5v14">+</path>+</svg>+</button>+<span class="flex min-w-0 shrink-0 max-sm:order-2 max-sm:min-w-[4.5rem] max-sm:shrink max-sm:[&>button]:min-w-0 max-sm:[&>button]:shrink max-sm:[&>button>svg:first-child]:hidden">+<button data-slot="popover-trigger" data-variant="secondary" data-size="sm" class="group/button inline-flex items-center justify-center border border-transparent bg-clip-padding whitespace-nowrap transition-[color,background-color,border-color,box-shadow,scale] duration-(--motion-base) ease-(--ease-standard) outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:duration-(--motion-fast) active:not-aria-[haspopup]:scale-(--motion-press-card) disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5 h-8 shrink-0 gap-1.5 rounded-full px-3 text-[13px] font-medium" aria-label="Model: Ideogram 4. Change model" type="button" aria-haspopup="dialog" aria-expanded="false" data-state="closed">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-cpu size-3.5" aria-hidden="true">+<path d="M12 20v2">+</path>+<path d="M12 2v2">+</path>+<path d="M17 20v2">+</path>+<path d="M17 2v2">+</path>+<path d="M2 12h2">+</path>+<path d="M2 17h2">+</path>+<path d="M2 7h2">+</path>+<path d="M20 12h2">+</path>+<path d="M20 17h2">+</path>+<path d="M20 7h2">+</path>+<path d="M7 20v2">+</path>+<path d="M7 2v2">+</path>+<rect x="4" y="4" width="16" height="16" rx="2">+</rect>+<rect x="8" y="8" width="8" height="8" rx="1">+</rect>+</svg>+<span class="max-w-40 truncate max-sm:hidden sm:max-w-44">Ideogram 4</span>+<span class="max-w-40 truncate sm:hidden">Ideogram 4</span>+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-down size-3.5 opacity-60" aria-hidden="true">+<path d="m6 9 6 6 6-6">+</path>+</svg>+</button>+</span>+<button type="button" class="grid size-8 shrink-0 place-items-center rounded-full bg-secondary text-secondary-foreground transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/50 max-sm:order-3" aria-label="Add an element" data-state="closed" data-slot="tooltip-trigger">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-at-sign size-3.5" aria-hidden="true">+<circle cx="12" cy="12" r="4">+</circle>+<path d="M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8">+</path>+</svg>+</button>+<span class="contents max-sm:hidden">+<button type="button" aria-pressed="false" data-state="closed" data-slot="tooltip-trigger" class="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring/50 bg-secondary text-secondary-foreground hover:bg-accent">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-layout-dashboard size-3.5" aria-hidden="true">+<rect width="7" height="9" x="3" y="3" rx="1">+</rect>+<rect width="7" height="5" x="14" y="3" rx="1">+</rect>+<rect width="7" height="9" x="14" y="12" rx="1">+</rect>+<rect width="7" height="5" x="3" y="16" rx="1">+</rect>+</svg>Layout</button>+</span>+<button type="button" aria-label="Settings: 1:1, 1.5K, ×1" aria-haspopup="dialog" aria-expanded="false" data-state="closed" data-slot="popover-trigger" class="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring/50 bg-secondary text-secondary-foreground hover:bg-accent relative tabular-nums max-sm:w-8 max-sm:justify-center max-sm:px-0 max-sm:order-1">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-sliders-horizontal size-3.5" aria-hidden="true">+<path d="M10 5H3">+</path>+<path d="M12 19H3">+</path>+<path d="M14 3v4">+</path>+<path d="M16 17v4">+</path>+<path d="M21 12h-9">+</path>+<path d="M21 19h-5">+</path>+<path d="M21 5h-7">+</path>+<path d="M8 10v4">+</path>+<path d="M8 12H3">+</path>+</svg>+<span class="max-sm:hidden">1:1 · 1.5K · ×1</span>+</button>+<span class="contents max-sm:hidden">+<span aria-hidden="true" class="h-8 w-40 shrink-0 animate-pulse rounded-full bg-secondary">+</span>+<button type="button" aria-haspopup="dialog" aria-expanded="false" data-state="closed" data-slot="popover-trigger" class="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring/50 bg-secondary text-secondary-foreground hover:bg-accent">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-settings-2 size-3.5" aria-hidden="true">+<path d="M14 17H5">+</path>+<path d="M19 7h-9">+</path>+<circle cx="17" cy="17" r="3">+</circle>+<circle cx="7" cy="7" r="3">+</circle>+</svg>Options</button>+</span>+</div>+<span class="shrink-0 text-[12px] font-medium text-muted-foreground tabular-nums" data-state="closed" data-slot="tooltip-trigger">+<span class="sm:hidden">Free · GPU</span>+<span class="hidden sm:inline">Free · your GPU</span>+</span>+<button data-slot="tooltip-trigger" data-variant="default" data-size="icon" class="group/button inline-flex items-center justify-center border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-[color,background-color,border-color,box-shadow,scale] duration-(--motion-base) ease-(--ease-standard) outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:duration-(--motion-fast) disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 text-primary-foreground active:not-aria-[haspopup]:scale-(--motion-press) size-10 shrink-0 rounded-full bg-primary/70 hover:bg-primary/80" aria-label="Generate — Write a prompt first" data-state="closed">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-arrow-up size-4" aria-hidden="true">+<path d="m5 12 7-7 7 7">+</path>+<path d="M12 19V5">+</path>+</svg>+</button>+</div>+<div aria-live="polite">+</div>+</div>++<div class="group/composer w-full rounded-[20px] border bg-background p-2.5 shadow-soft transition-[border-color,box-shadow] focus-within:border-primary focus-within:ring-4 focus-within:ring-brand-faint sm:rounded-composer">+<div class="relative">+<div aria-hidden="true" class="w-full px-2.5 py-1.5 text-left text-base leading-relaxed whitespace-pre-wrap break-words pointer-events-none absolute inset-0 overflow-hidden text-foreground"></div>+<textarea rows="1" placeholder="Describe an image… try “a koi pond at night, neon rain”" aria-label="Prompt" spellCheck="true" class="w-full px-2.5 py-1.5 text-left text-base leading-relaxed whitespace-pre-wrap break-words scrollbar-none relative field-sizing-content resize-none bg-transparent text-transparent caret-foreground outline-none placeholder:text-subtle-foreground selection:bg-brand-faint selection:text-transparent max-h-52 min-h-12">+</textarea>+</div>+<div class="flex items-center gap-2">+<div data-composer-toolbar="true" class="scrollbar-none -my-1 flex min-w-0 flex-1 items-center gap-1.5 overflow-x-auto py-1 sm:flex-wrap sm:overflow-x-visible">+<button type="button" aria-label="Add media" class="grid size-8 shrink-0 place-items-center rounded-full bg-secondary text-secondary-foreground transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/50" data-state="closed" data-slot="popover-trigger" aria-haspopup="dialog" aria-expanded="false">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-plus size-4" aria-hidden="true">+<path d="M5 12h14">+</path>+<path d="M12 5v14">+</path>+</svg>+</button>+<span class="flex min-w-0 shrink-0 max-sm:order-2 max-sm:min-w-[4.5rem] max-sm:shrink max-sm:[&>button]:min-w-0 max-sm:[&>button]:shrink max-sm:[&>button>svg:first-child]:hidden">+<button data-slot="popover-trigger" data-variant="secondary" data-size="sm" class="group/button inline-flex items-center justify-center border border-transparent bg-clip-padding whitespace-nowrap transition-[color,background-color,border-color,box-shadow,scale] duration-(--motion-base) ease-(--ease-standard) outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:duration-(--motion-fast) active:not-aria-[haspopup]:scale-(--motion-press-card) disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5 h-8 shrink-0 gap-1.5 rounded-full px-3 text-[13px] font-medium" aria-label="Model: Ideogram 4. Change model" type="button" aria-haspopup="dialog" aria-expanded="false" data-state="closed">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-cpu size-3.5" aria-hidden="true">+<path d="M12 20v2">+</path>+<path d="M12 2v2">+</path>+<path d="M17 20v2">+</path>+<path d="M17 2v2">+</path>+<path d="M2 12h2">+</path>+<path d="M2 17h2">+</path>+<path d="M2 7h2">+</path>+<path d="M20 12h2">+</path>+<path d="M20 17h2">+</path>+<path d="M20 7h2">+</path>+<path d="M7 20v2">+</path>+<path d="M7 2v2">+</path>+<rect x="4" y="4" width="16" height="16" rx="2">+</rect>+<rect x="8" y="8" width="8" height="8" rx="1">+</rect>+</svg>+<span class="max-w-40 truncate max-sm:hidden sm:max-w-44">Ideogram 4</span>+<span class="max-w-40 truncate sm:hidden">Ideogram 4</span>+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-down size-3.5 opacity-60" aria-hidden="true">+<path d="m6 9 6 6 6-6">+</path>+</svg>+</button>+</span>+<button type="button" class="grid size-8 shrink-0 place-items-center rounded-full bg-secondary text-secondary-foreground transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/50 max-sm:order-3" aria-label="Add an element" data-state="closed" data-slot="tooltip-trigger">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-at-sign size-3.5" aria-hidden="true">+<circle cx="12" cy="12" r="4">+</circle>+<path d="M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8">+</path>+</svg>+</button>+<span class="contents max-sm:hidden">+<button type="button" aria-pressed="false" data-state="closed" data-slot="tooltip-trigger" class="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring/50 bg-secondary text-secondary-foreground hover:bg-accent">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-layout-dashboard size-3.5" aria-hidden="true">+<rect width="7" height="9" x="3" y="3" rx="1">+</rect>+<rect width="7" height="5" x="14" y="3" rx="1">+</rect>+<rect width="7" height="9" x="14" y="12" rx="1">+</rect>+<rect width="7" height="5" x="3" y="16" rx="1">+</rect>+</svg>Layout</button>+</span>+<button type="button" aria-label="Settings: 1:1, 1.5K, ×1" aria-haspopup="dialog" aria-expanded="false" data-state="closed" data-slot="popover-trigger" class="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring/50 bg-secondary text-secondary-foreground hover:bg-accent relative tabular-nums max-sm:w-8 max-sm:justify-center max-sm:px-0 max-sm:order-1">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-sliders-horizontal size-3.5" aria-hidden="true">+<path d="M10 5H3">+</path>+<path d="M12 19H3">+</path>+<path d="M14 3v4">+</path>+<path d="M16 17v4">+</path>+<path d="M21 12h-9">+</path>+<path d="M21 19h-5">+</path>+<path d="M21 5h-7">+</path>+<path d="M8 10v4">+</path>+<path d="M8 12H3">+</path>+</svg>+<span class="max-sm:hidden">1:1 · 1.5K · ×1</span>+</button>+<span class="contents max-sm:hidden">+<span aria-hidden="true" class="h-8 w-40 shrink-0 animate-pulse rounded-full bg-secondary">+</span>+<button type="button" aria-haspopup="dialog" aria-expanded="false" data-state="closed" data-slot="popover-trigger" class="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring/50 bg-secondary text-secondary-foreground hover:bg-accent">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-settings-2 size-3.5" aria-hidden="true">+<path d="M14 17H5">+</path>+<path d="M19 7h-9">+</path>+<circle cx="17" cy="17" r="3">+</circle>+<circle cx="7" cy="7" r="3">+</circle>+</svg>Options</button>+</span>+</div>+<span class="shrink-0 text-[12px] font-medium text-muted-foreground tabular-nums" data-state="closed" data-slot="tooltip-trigger">+<span class="sm:hidden">Free · GPU</span>+<span class="hidden sm:inline">Free · your GPU</span>+</span>+<button data-slot="tooltip-trigger" data-variant="default" data-size="icon" class="group/button inline-flex items-center justify-center border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-[color,background-color,border-color,box-shadow,scale] duration-(--motion-base) ease-(--ease-standard) outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:duration-(--motion-fast) disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 text-primary-foreground active:not-aria-[haspopup]:scale-(--motion-press) size-10 shrink-0 rounded-full bg-primary/70 hover:bg-primary/80" aria-label="Generate — Write a prompt first" data-state="closed">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-arrow-up size-4" aria-hidden="true">+<path d="m5 12 7-7 7 7">+</path>+<path d="M12 19V5">+</path>+</svg>+</button>+</div>+<div aria-live="polite">+</div>+</div>++<div class="group/composer w-full rounded-[20px] border bg-background p-2.5 shadow-soft transition-[border-color,box-shadow] focus-within:border-primary focus-within:ring-4 focus-within:ring-brand-faint sm:rounded-composer">+<div class="relative">+<div aria-hidden="true" class="w-full px-2.5 py-1.5 text-left text-base leading-relaxed whitespace-pre-wrap break-words pointer-events-none absolute inset-0 overflow-hidden text-foreground"></div>+<textarea rows="1" placeholder="Describe an image… try “a koi pond at night, neon rain”" aria-label="Prompt" spellCheck="true" class="w-full px-2.5 py-1.5 text-left text-base leading-relaxed whitespace-pre-wrap break-words scrollbar-none relative field-sizing-content resize-none bg-transparent text-transparent caret-foreground outline-none placeholder:text-subtle-foreground selection:bg-brand-faint selection:text-transparent max-h-52 min-h-12">+</textarea>+</div>+<div class="flex items-center gap-2">+<div data-composer-toolbar="true" class="scrollbar-none -my-1 flex min-w-0 flex-1 items-center gap-1.5 overflow-x-auto py-1 sm:flex-wrap sm:overflow-x-visible">+<button type="button" aria-label="Add media" class="grid size-8 shrink-0 place-items-center rounded-full bg-secondary text-secondary-foreground transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/50" data-state="closed" data-slot="popover-trigger" aria-haspopup="dialog" aria-expanded="false">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-plus size-4" aria-hidden="true">+<path d="M5 12h14">+</path>+<path d="M12 5v14">+</path>+</svg>+</button>+<span class="flex min-w-0 shrink-0 max-sm:order-2 max-sm:min-w-[4.5rem] max-sm:shrink max-sm:[&>button]:min-w-0 max-sm:[&>button]:shrink max-sm:[&>button>svg:first-child]:hidden">+<button data-slot="popover-trigger" data-variant="secondary" data-size="sm" class="group/button inline-flex items-center justify-center border border-transparent bg-clip-padding whitespace-nowrap transition-[color,background-color,border-color,box-shadow,scale] duration-(--motion-base) ease-(--ease-standard) outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:duration-(--motion-fast) active:not-aria-[haspopup]:scale-(--motion-press-card) disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5 h-8 shrink-0 gap-1.5 rounded-full px-3 text-[13px] font-medium" aria-label="Model: Nano Banana Pro. Change model" type="button" aria-haspopup="dialog" aria-expanded="false" data-state="closed">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-cloud size-3.5" aria-hidden="true">+<path d="M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z">+</path>+</svg>+<span class="max-w-40 truncate max-sm:hidden sm:max-w-44">Nano Banana Pro</span>+<span class="max-w-40 truncate sm:hidden">Nano Banana Pro</span>+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-down size-3.5 opacity-60" aria-hidden="true">+<path d="m6 9 6 6 6-6">+</path>+</svg>+</button>+</span>+<button type="button" class="grid size-8 shrink-0 place-items-center rounded-full bg-secondary text-secondary-foreground transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/50 max-sm:order-3" aria-label="Add an element" data-state="closed" data-slot="tooltip-trigger">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-at-sign size-3.5" aria-hidden="true">+<circle cx="12" cy="12" r="4">+</circle>+<path d="M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8">+</path>+</svg>+</button>+<span class="contents max-sm:hidden">+<button type="button" aria-pressed="false" data-state="closed" data-slot="tooltip-trigger" class="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring/50 bg-secondary text-secondary-foreground hover:bg-accent">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-layout-dashboard size-3.5" aria-hidden="true">+<rect width="7" height="9" x="3" y="3" rx="1">+</rect>+<rect width="7" height="5" x="14" y="3" rx="1">+</rect>+<rect width="7" height="9" x="14" y="12" rx="1">+</rect>+<rect width="7" height="5" x="3" y="16" rx="1">+</rect>+</svg>Layout</button>+</span>+<button type="button" aria-label="Settings: 1:1, 1K, ×1" aria-haspopup="dialog" aria-expanded="false" data-state="closed" data-slot="popover-trigger" class="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring/50 bg-secondary text-secondary-foreground hover:bg-accent relative tabular-nums max-sm:w-8 max-sm:justify-center max-sm:px-0 max-sm:order-1">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-sliders-horizontal size-3.5" aria-hidden="true">+<path d="M10 5H3">+</path>+<path d="M12 19H3">+</path>+<path d="M14 3v4">+</path>+<path d="M16 17v4">+</path>+<path d="M21 12h-9">+</path>+<path d="M21 19h-5">+</path>+<path d="M21 5h-7">+</path>+<path d="M8 10v4">+</path>+<path d="M8 12H3">+</path>+</svg>+<span class="max-sm:hidden">1:1 · 1K · ×1</span>+</button>+<span class="contents max-sm:hidden">+<span aria-hidden="true" class="h-8 w-40 shrink-0 animate-pulse rounded-full bg-secondary">+</span>+</span>+</div>+<button data-slot="tooltip-trigger" data-variant="default" data-size="icon" class="group/button inline-flex items-center justify-center border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-[color,background-color,border-color,box-shadow,scale] duration-(--motion-base) ease-(--ease-standard) outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:duration-(--motion-fast) disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 text-primary-foreground active:not-aria-[haspopup]:scale-(--motion-press) size-10 shrink-0 rounded-full bg-primary/70 hover:bg-primary/80" aria-label="Generate — Write a prompt first" data-state="closed">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-arrow-up size-4" aria-hidden="true">+<path d="m5 12 7-7 7 7">+</path>+<path d="M12 19V5">+</path>+</svg>+</button>+</div>+<div aria-live="polite">+</div>+</div>++<div class="group/composer w-full rounded-[20px] border bg-background p-2.5 shadow-soft transition-[border-color,box-shadow] focus-within:border-primary focus-within:ring-4 focus-within:ring-brand-faint sm:rounded-composer">+<div class="relative">+<div aria-hidden="true" class="w-full px-2.5 py-1.5 text-left text-base leading-relaxed whitespace-pre-wrap break-words pointer-events-none absolute inset-0 overflow-hidden text-foreground"></div>+<textarea rows="1" placeholder="Describe a shot… e.g. “slow dolly-in on a rainy street, neon reflections”" aria-label="Prompt" spellCheck="true" class="w-full px-2.5 py-1.5 text-left text-base leading-relaxed whitespace-pre-wrap break-words scrollbar-none relative field-sizing-content resize-none bg-transparent text-transparent caret-foreground outline-none placeholder:text-subtle-foreground selection:bg-brand-faint selection:text-transparent max-h-52 min-h-12">+</textarea>+</div>+<div class="flex items-center gap-2">+<div data-composer-toolbar="true" class="scrollbar-none -my-1 flex min-w-0 flex-1 items-center gap-1.5 overflow-x-auto py-1 sm:flex-wrap sm:overflow-x-visible">+<button type="button" aria-label="Add media" class="grid size-8 shrink-0 place-items-center rounded-full bg-secondary text-secondary-foreground transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/50" data-state="closed" data-slot="popover-trigger" aria-haspopup="dialog" aria-expanded="false">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-plus size-4" aria-hidden="true">+<path d="M5 12h14">+</path>+<path d="M12 5v14">+</path>+</svg>+</button>+<button type="button" aria-pressed="false" title="Images, clips and a voice or music clip the shot follows" class="inline-flex h-8 shrink-0 items-center rounded-full px-3 text-[13px] font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring/50 bg-secondary text-secondary-foreground hover:bg-accent gap-1.5">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-library size-3.5" aria-hidden="true">+<path d="m16 6 4 14">+</path>+<path d="M12 6v14">+</path>+<path d="M8 8v12">+</path>+<path d="M4 4v16">+</path>+</svg>+<span class="max-sm:sr-only">References</span>+</button>+<span class="flex min-w-0 shrink-0 max-sm:order-2 max-sm:min-w-[4.5rem] max-sm:shrink max-sm:[&>button]:min-w-0 max-sm:[&>button]:shrink max-sm:[&>button>svg:first-child]:hidden">+<button data-slot="popover-trigger" data-variant="secondary" data-size="sm" class="group/button inline-flex items-center justify-center border border-transparent bg-clip-padding whitespace-nowrap transition-[color,background-color,border-color,box-shadow,scale] duration-(--motion-base) ease-(--ease-standard) outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:duration-(--motion-fast) active:not-aria-[haspopup]:scale-(--motion-press-card) disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5 h-8 shrink-0 gap-1.5 rounded-full px-3 text-[13px] font-medium" aria-label="Model: MiniMax H3. Change model" type="button" aria-haspopup="dialog" aria-expanded="false" data-state="closed">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-cpu size-3.5" aria-hidden="true">+<path d="M12 20v2">+</path>+<path d="M12 2v2">+</path>+<path d="M17 20v2">+</path>+<path d="M17 2v2">+</path>+<path d="M2 12h2">+</path>+<path d="M2 17h2">+</path>+<path d="M2 7h2">+</path>+<path d="M20 12h2">+</path>+<path d="M20 17h2">+</path>+<path d="M20 7h2">+</path>+<path d="M7 20v2">+</path>+<path d="M7 2v2">+</path>+<rect x="4" y="4" width="16" height="16" rx="2">+</rect>+<rect x="8" y="8" width="8" height="8" rx="1">+</rect>+</svg>+<span class="max-w-40 truncate max-sm:hidden sm:max-w-44">MiniMax H3</span>+<span class="max-w-40 truncate sm:hidden">MiniMax H3</span>+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-down size-3.5 opacity-60" aria-hidden="true">+<path d="m6 9 6 6 6-6">+</path>+</svg>+</button>+</span>+<button type="button" class="grid size-8 shrink-0 place-items-center rounded-full bg-secondary text-secondary-foreground transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/50 max-sm:order-3" aria-label="Add an element" data-state="closed" data-slot="tooltip-trigger">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-at-sign size-3.5" aria-hidden="true">+<circle cx="12" cy="12" r="4">+</circle>+<path d="M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8">+</path>+</svg>+</button>+<span class="contents max-sm:hidden">+<button type="button" aria-pressed="false" data-state="closed" data-slot="tooltip-trigger" class="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring/50 bg-secondary text-secondary-foreground hover:bg-accent">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-gallery-horizontal-end size-3.5" aria-hidden="true">+<path d="M2 7v10">+</path>+<path d="M6 5v14">+</path>+<rect width="12" height="18" x="10" y="3" rx="2">+</rect>+</svg>Frames</button>+</span>+<button type="button" aria-label="Settings: Auto, 768p, 5s, ×1" aria-haspopup="dialog" aria-expanded="false" data-state="closed" data-slot="popover-trigger" class="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring/50 bg-secondary text-secondary-foreground hover:bg-accent relative tabular-nums max-sm:w-8 max-sm:justify-center max-sm:px-0 max-sm:order-1">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-sliders-horizontal size-3.5" aria-hidden="true">+<path d="M10 5H3">+</path>+<path d="M12 19H3">+</path>+<path d="M14 3v4">+</path>+<path d="M16 17v4">+</path>+<path d="M21 12h-9">+</path>+<path d="M21 19h-5">+</path>+<path d="M21 5h-7">+</path>+<path d="M8 10v4">+</path>+<path d="M8 12H3">+</path>+</svg>+<span class="max-sm:hidden">Auto · 768p · 5s · ×1</span>+</button>+<span class="contents max-sm:hidden">+<span aria-hidden="true" class="h-8 w-32 shrink-0 animate-pulse rounded-full bg-secondary">+</span>+<button type="button" aria-haspopup="dialog" aria-expanded="false" data-state="closed" data-slot="popover-trigger" class="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring/50 bg-secondary text-secondary-foreground hover:bg-accent">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-clapperboard size-3.5" aria-hidden="true">+<path d="m12.296 3.464 3.02 3.956">+</path>+<path d="M20.2 6 3 11l-.9-2.4c-.3-1.1.3-2.2 1.3-2.5l13.5-4c1.1-.3 2.2.3 2.5 1.3z">+</path>+<path d="M3 11h18v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z">+</path>+<path d="m6.18 5.276 3.1 3.899">+</path>+</svg>Director</button>+</span>+</div>+<span class="shrink-0 text-[12px] font-medium text-muted-foreground tabular-nums" data-state="closed" data-slot="tooltip-trigger">+<span class="sm:hidden">Free · GPU</span>+<span class="hidden sm:inline">Free · your GPU</span>+</span>+<button data-slot="tooltip-trigger" data-variant="default" data-size="icon" class="group/button inline-flex items-center justify-center border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-[color,background-color,border-color,box-shadow,scale] duration-(--motion-base) ease-(--ease-standard) outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:duration-(--motion-fast) disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 text-primary-foreground active:not-aria-[haspopup]:scale-(--motion-press) size-10 shrink-0 rounded-full bg-primary/70 hover:bg-primary/80" aria-label="Generate — Write a prompt first" data-state="closed">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-arrow-up size-4" aria-hidden="true">+<path d="m5 12 7-7 7 7">+</path>+<path d="M12 19V5">+</path>+</svg>+</button>+</div>+<div aria-live="polite">+</div>+</div>++<div class="group/composer w-full rounded-[20px] border bg-background p-2.5 shadow-soft transition-[border-color,box-shadow] focus-within:border-primary focus-within:ring-4 focus-within:ring-brand-faint sm:rounded-composer">+<div class="relative">+<div aria-hidden="true" class="w-full px-2.5 py-1.5 text-left text-base leading-relaxed whitespace-pre-wrap break-words pointer-events-none absolute inset-0 overflow-hidden text-foreground"></div>+<textarea rows="1" placeholder="Describe a shot… e.g. “slow dolly-in on a rainy street, neon reflections”" aria-label="Prompt" spellCheck="true" class="w-full px-2.5 py-1.5 text-left text-base leading-relaxed whitespace-pre-wrap break-words scrollbar-none relative field-sizing-content resize-none bg-transparent text-transparent caret-foreground outline-none placeholder:text-subtle-foreground selection:bg-brand-faint selection:text-transparent max-h-52 min-h-12">+</textarea>+</div>+<div class="flex items-center gap-2">+<div data-composer-toolbar="true" class="scrollbar-none -my-1 flex min-w-0 flex-1 items-center gap-1.5 overflow-x-auto py-1 sm:flex-wrap sm:overflow-x-visible">+<button type="button" aria-label="Add media" class="grid size-8 shrink-0 place-items-center rounded-full bg-secondary text-secondary-foreground transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/50" data-state="closed" data-slot="popover-trigger" aria-haspopup="dialog" aria-expanded="false">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-plus size-4" aria-hidden="true">+<path d="M5 12h14">+</path>+<path d="M12 5v14">+</path>+</svg>+</button>+<button type="button" aria-pressed="false" title="Images, clips and a voice or music clip the shot follows" class="inline-flex h-8 shrink-0 items-center rounded-full px-3 text-[13px] font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring/50 bg-secondary text-secondary-foreground hover:bg-accent gap-1.5">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-library size-3.5" aria-hidden="true">+<path d="m16 6 4 14">+</path>+<path d="M12 6v14">+</path>+<path d="M8 8v12">+</path>+<path d="M4 4v16">+</path>+</svg>+<span class="max-sm:sr-only">References</span>+</button>+<span class="flex min-w-0 shrink-0 max-sm:order-2 max-sm:min-w-[4.5rem] max-sm:shrink max-sm:[&>button]:min-w-0 max-sm:[&>button]:shrink max-sm:[&>button>svg:first-child]:hidden">+<button data-slot="popover-trigger" data-variant="secondary" data-size="sm" class="group/button inline-flex items-center justify-center border border-transparent bg-clip-padding whitespace-nowrap transition-[color,background-color,border-color,box-shadow,scale] duration-(--motion-base) ease-(--ease-standard) outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:duration-(--motion-fast) active:not-aria-[haspopup]:scale-(--motion-press-card) disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5 h-8 shrink-0 gap-1.5 rounded-full px-3 text-[13px] font-medium" aria-label="Model: MiniMax H3. Change model" type="button" aria-haspopup="dialog" aria-expanded="false" data-state="closed">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-cpu size-3.5" aria-hidden="true">+<path d="M12 20v2">+</path>+<path d="M12 2v2">+</path>+<path d="M17 20v2">+</path>+<path d="M17 2v2">+</path>+<path d="M2 12h2">+</path>+<path d="M2 17h2">+</path>+<path d="M2 7h2">+</path>+<path d="M20 12h2">+</path>+<path d="M20 17h2">+</path>+<path d="M20 7h2">+</path>+<path d="M7 20v2">+</path>+<path d="M7 2v2">+</path>+<rect x="4" y="4" width="16" height="16" rx="2">+</rect>+<rect x="8" y="8" width="8" height="8" rx="1">+</rect>+</svg>+<span class="max-w-40 truncate max-sm:hidden sm:max-w-44">MiniMax H3</span>+<span class="max-w-40 truncate sm:hidden">MiniMax H3</span>+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-down size-3.5 opacity-60" aria-hidden="true">+<path d="m6 9 6 6 6-6">+</path>+</svg>+</button>+</span>+<button type="button" class="grid size-8 shrink-0 place-items-center rounded-full bg-secondary text-secondary-foreground transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/50 max-sm:order-3" aria-label="Add an element" data-state="closed" data-slot="tooltip-trigger">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-at-sign size-3.5" aria-hidden="true">+<circle cx="12" cy="12" r="4">+</circle>+<path d="M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8">+</path>+</svg>+</button>+<span class="contents max-sm:hidden">+<button type="button" aria-pressed="false" data-state="closed" data-slot="tooltip-trigger" class="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring/50 bg-secondary text-secondary-foreground hover:bg-accent">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-gallery-horizontal-end size-3.5" aria-hidden="true">+<path d="M2 7v10">+</path>+<path d="M6 5v14">+</path>+<rect width="12" height="18" x="10" y="3" rx="2">+</rect>+</svg>Frames</button>+</span>+<button type="button" aria-label="Settings: Auto, 768p, 5s, ×1" aria-haspopup="dialog" aria-expanded="false" data-state="closed" data-slot="popover-trigger" class="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring/50 bg-secondary text-secondary-foreground hover:bg-accent relative tabular-nums max-sm:w-8 max-sm:justify-center max-sm:px-0 max-sm:order-1">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-sliders-horizontal size-3.5" aria-hidden="true">+<path d="M10 5H3">+</path>+<path d="M12 19H3">+</path>+<path d="M14 3v4">+</path>+<path d="M16 17v4">+</path>+<path d="M21 12h-9">+</path>+<path d="M21 19h-5">+</path>+<path d="M21 5h-7">+</path>+<path d="M8 10v4">+</path>+<path d="M8 12H3">+</path>+</svg>+<span class="max-sm:hidden">Auto · 768p · 5s · ×1</span>+</button>+<span class="contents max-sm:hidden">+<span aria-hidden="true" class="h-8 w-32 shrink-0 animate-pulse rounded-full bg-secondary">+</span>+<button type="button" aria-haspopup="dialog" aria-expanded="false" data-state="closed" data-slot="popover-trigger" class="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring/50 bg-secondary text-secondary-foreground hover:bg-accent">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-clapperboard size-3.5" aria-hidden="true">+<path d="m12.296 3.464 3.02 3.956">+</path>+<path d="M20.2 6 3 11l-.9-2.4c-.3-1.1.3-2.2 1.3-2.5l13.5-4c1.1-.3 2.2.3 2.5 1.3z">+</path>+<path d="M3 11h18v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z">+</path>+<path d="m6.18 5.276 3.1 3.899">+</path>+</svg>Director</button>+</span>+</div>+<span class="shrink-0 text-[12px] font-medium text-muted-foreground tabular-nums" data-state="closed" data-slot="tooltip-trigger">+<span class="sm:hidden">Free · GPU</span>+<span class="hidden sm:inline">Free · your GPU</span>+</span>+<button data-slot="tooltip-trigger" data-variant="default" data-size="icon" class="group/button inline-flex items-center justify-center border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-[color,background-color,border-color,box-shadow,scale] duration-(--motion-base) ease-(--ease-standard) outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:duration-(--motion-fast) disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 text-primary-foreground active:not-aria-[haspopup]:scale-(--motion-press) size-10 shrink-0 rounded-full bg-primary/70 hover:bg-primary/80" aria-label="Generate — Write a prompt first" data-state="closed">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-arrow-up size-4" aria-hidden="true">+<path d="m5 12 7-7 7 7">+</path>+<path d="M12 19V5">+</path>+</svg>+</button>+</div>+<div aria-live="polite">+</div>+</div>++<div class="group/composer w-full rounded-[20px] border bg-background p-2.5 shadow-soft transition-[border-color,box-shadow] focus-within:border-primary focus-within:ring-4 focus-within:ring-brand-faint sm:rounded-composer">+<div class="relative">+<div aria-hidden="true" class="w-full px-2.5 py-1.5 text-left text-base leading-relaxed whitespace-pre-wrap break-words pointer-events-none absolute inset-0 overflow-hidden text-foreground"></div>+<textarea rows="1" placeholder="Describe a shot… e.g. “slow dolly-in on a rainy street, neon reflections”" aria-label="Prompt" spellCheck="true" class="w-full px-2.5 py-1.5 text-left text-base leading-relaxed whitespace-pre-wrap break-words scrollbar-none relative field-sizing-content resize-none bg-transparent text-transparent caret-foreground outline-none placeholder:text-subtle-foreground selection:bg-brand-faint selection:text-transparent max-h-52 min-h-12">+</textarea>+</div>+<div class="flex items-center gap-2">+<div data-composer-toolbar="true" class="scrollbar-none -my-1 flex min-w-0 flex-1 items-center gap-1.5 overflow-x-auto py-1 sm:flex-wrap sm:overflow-x-visible">+<button type="button" aria-label="Add media" class="grid size-8 shrink-0 place-items-center rounded-full bg-secondary text-secondary-foreground transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/50" data-state="closed" data-slot="popover-trigger" aria-haspopup="dialog" aria-expanded="false">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-plus size-4" aria-hidden="true">+<path d="M5 12h14">+</path>+<path d="M12 5v14">+</path>+</svg>+</button>+<span class="flex min-w-0 shrink-0 max-sm:order-2 max-sm:min-w-[4.5rem] max-sm:shrink max-sm:[&>button]:min-w-0 max-sm:[&>button]:shrink max-sm:[&>button>svg:first-child]:hidden">+<button data-slot="popover-trigger" data-variant="secondary" data-size="sm" class="group/button inline-flex items-center justify-center border border-transparent bg-clip-padding whitespace-nowrap transition-[color,background-color,border-color,box-shadow,scale] duration-(--motion-base) ease-(--ease-standard) outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:duration-(--motion-fast) active:not-aria-[haspopup]:scale-(--motion-press-card) disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5 h-8 shrink-0 gap-1.5 rounded-full px-3 text-[13px] font-medium" aria-label="Model: MiniMax H3. Change model" type="button" aria-haspopup="dialog" aria-expanded="false" data-state="closed">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-cloud size-3.5" aria-hidden="true">+<path d="M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z">+</path>+</svg>+<span class="max-w-40 truncate max-sm:hidden sm:max-w-44">MiniMax H3</span>+<span class="max-w-40 truncate sm:hidden">MiniMax H3</span>+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-down size-3.5 opacity-60" aria-hidden="true">+<path d="m6 9 6 6 6-6">+</path>+</svg>+</button>+</span>+<button type="button" class="grid size-8 shrink-0 place-items-center rounded-full bg-secondary text-secondary-foreground transition-colors outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/50 max-sm:order-3" aria-label="Add an element" data-state="closed" data-slot="tooltip-trigger">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-at-sign size-3.5" aria-hidden="true">+<circle cx="12" cy="12" r="4">+</circle>+<path d="M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8">+</path>+</svg>+</button>+<span class="contents max-sm:hidden">+<button type="button" aria-pressed="false" data-state="closed" data-slot="tooltip-trigger" class="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring/50 bg-secondary text-secondary-foreground hover:bg-accent">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-gallery-horizontal-end size-3.5" aria-hidden="true">+<path d="M2 7v10">+</path>+<path d="M6 5v14">+</path>+<rect width="12" height="18" x="10" y="3" rx="2">+</rect>+</svg>Frames</button>+</span>+<button type="button" aria-label="Settings: 16:9, 768P, 5s, ×1" aria-haspopup="dialog" aria-expanded="false" data-state="closed" data-slot="popover-trigger" class="inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium whitespace-nowrap transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring/50 bg-secondary text-secondary-foreground hover:bg-accent relative tabular-nums max-sm:w-8 max-sm:justify-center max-sm:px-0 max-sm:order-1">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-sliders-horizontal size-3.5" aria-hidden="true">+<path d="M10 5H3">+</path>+<path d="M12 19H3">+</path>+<path d="M14 3v4">+</path>+<path d="M16 17v4">+</path>+<path d="M21 12h-9">+</path>+<path d="M21 19h-5">+</path>+<path d="M21 5h-7">+</path>+<path d="M8 10v4">+</path>+<path d="M8 12H3">+</path>+</svg>+<span class="max-sm:hidden">16:9 · 768P · 5s · ×1</span>+</button>+<span class="contents max-sm:hidden">+<span aria-hidden="true" class="h-8 w-32 shrink-0 animate-pulse rounded-full bg-secondary">+</span>+</span>+</div>+<button data-slot="tooltip-trigger" data-variant="default" data-size="icon" class="group/button inline-flex items-center justify-center border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-[color,background-color,border-color,box-shadow,scale] duration-(--motion-base) ease-(--ease-standard) outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:duration-(--motion-fast) disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 text-primary-foreground active:not-aria-[haspopup]:scale-(--motion-press) size-10 shrink-0 rounded-full bg-primary/70 hover:bg-primary/80" aria-label="Generate — Write a prompt first" data-state="closed">+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-arrow-up size-4" aria-hidden="true">+<path d="m5 12 7-7 7 7">+</path>+<path d="M12 19V5">+</path>+</svg>+</button>+</div>+<div aria-live="polite">+</div>+</div>\ No newline at end of filediff --git a/tests/hosted-surface-labels.test.ts b/tests/hosted-surface-labels.test.tsindex 33bf1c6a..63ba6046 100644--- a/tests/hosted-surface-labels.test.ts+++ b/tests/hosted-surface-labels.test.ts@@ -77,6 +77,10 @@ describe("the surfaces that don't run here yet", () => {expect(hosted).toMatchObject({ where: "unavailable", label: "Coming soon", title: "Coming soon", price: "", send: "", tip: "Ad Multiplier isn't open to accounts yet. Try the Image, Video or Audio studio." });const off = runPlace({ audience: "guest", engine: "cloud", ownerOnly: "Ad Multiplier", format: String });expect(off).toMatchObject({ label: "Not available here", tip: "Ad Multiplier isn't available here. Try the Image, Video or Audio studio." });+ // A press that leads on: the studio that makes it now (the Image studio unless the tool names another).+ expect(hosted.way).toEqual({ label: "Make it in the Image studio", href: "/image" });+ expect(runPlace({ audience: "account", engine: "cloud", hosted: true, ownerOnly: "Ad Multiplier", ownerOnlyStudio: "video", format: String }).way).toEqual({ label: "Make it in the Video studio", href: "/video" });+ expect(off.way).toBeUndefined();// The owner runs it as always.expect(runPlace({ audience: "owner", engine: "cloud", hosted: true, ownerOnly: "Ad Multiplier", format: String }).where).toBe("cloud");});diff --git a/tests/hosted-words.test.ts b/tests/hosted-words.test.tsindex 094a41db..d206636d 100644--- a/tests/hosted-words.test.ts+++ b/tests/hosted-words.test.ts@@ -167,7 +167,7 @@ describe("the words for runs on this install's GPUs", () => {it("say the place by its name, as a label and inside a sentence, with no verb that agrees with it", () => {expect(hostedWords(NAMED).notHosted).toBe("Your account can't run on Studio North GPUs right now. Your own GPU or key still works.");expect(hostedWords(DEFAULT).notHosted).toBe("Your account can't run on our GPUs right now. Your own GPU or key still works.");- expect(outputsWords(3, false, NAMED)).toBe("Makes up to 3 at a time on Studio North GPUs. Pick 3 or fewer, or connect your own GPU in Settings.");+ expect(outputsWords(3, false, NAMED)).toBe("Makes up to 3 at a time on Studio North GPUs. Pick 3 or fewer, or run it on your own GPU.");expect(outputsWords(1, true, NAMED)).toBe("Makes one at a time. Pick one.");expect(runPlace({ audience: "account", engine: "open", hosted: true, pool: { text: "" }, place: NAMED, format: String })).toMatchObject({ label: "Studio North GPUs", title: "Runs on Studio North GPUs" });const agrees = new RegExp(`(Studio North GPUs|our GPUs|Our GPUs)\\s+(is|are|was|were|make|makes|run|runs|has|have)\\b`);diff --git a/tests/place-intro.test.ts b/tests/place-intro.test.tsindex e58d5ba4..e6c57698 100644--- a/tests/place-intro.test.ts+++ b/tests/place-intro.test.ts@@ -17,7 +17,7 @@ const { PlaceIntro } = await import("@/components/studio/place-intro");const gpu = { connected: true };const none = { connected: false };-const base = { kind: "account" as const, hosted: true, ranOwn: true, placeName: "Studio North GPUs" };+const base = { kind: "account" as const, hosted: true, ranOwn: true, placeName: "Studio North GPUs", cardText: "Try free" };describe("who gets the note", () => {it("an account with its GPU that ran there first, and no pick yet", () => {@@ -45,6 +45,14 @@ describe("who gets the note", () => {it("the default name reads inside the sentence", () => {expect(placeIntro({ ...base, placeName: undefined, gpu }, "Run")?.lead).toBe("Runs now go to our GPUs, free.");});+ it("says free only while runs there cost the account nothing (the policy's card words)", () => {+ const paid = { ...base, cardText: undefined };+ expect(placeIntro({ ...paid, gpu }, "Generate")).toMatchObject({ lead: "Runs now go to Studio North GPUs.", rest: "Your GPU is one tap away: the price, next to Generate." });+ expect(placeIntro({ ...paid, gpu: none, keys: ["fal"] }, "Run")?.lead).toBe("Open models now run on Studio North GPUs.");+ });+ it("a tool page's note points at its place chip, as it reads", () => {+ expect(placeIntro({ ...base, gpu }, "Run", "Studio North GPUs")?.rest).toBe("Your GPU is one tap away: tap Studio North GPUs to pick it.");+ });});describe("the note above Generate", () => {diff --git a/tests/pool-holds.test.ts b/tests/pool-holds.test.tsindex 5288a2c2..a403022c 100644--- a/tests/pool-holds.test.ts+++ b/tests/pool-holds.test.ts@@ -380,11 +380,16 @@ describe("service blips (H3)", () => {expect(taskOf(id)).toBeUndefined();const requestId = heldOf(id)!.request_id;expect(requestId).toBeTruthy();- // Back: it reserves under its press's request id (one hold for the press) and enters the line.+ // Back, a while after the press: it reserves under its press's request id (one hold for the press) and enters the+ // line at its press-time place, never at the time it was let in.+ await new Promise((r) => setTimeout(r, 40));+ const backAt = Date.now();fake.down = false;const t = await until(() => taskOf(id));expect(t).toBeTruthy();+ expect(t!.created_at).toBeGreaterThanOrEqual(backAt);expect(t!.rank_at).toBeLessThanOrEqual(before);+ expect(t!.rank_at).toBeLessThan(backAt);const made = [...fake.holds.values()].filter((h) => h.requestId === requestId);expect(made.length).toBe(1);const g = db().prepare("SELECT json_extract(request_json, '$.hold') AS hold FROM generations WHERE id = ?").get(id) as { hold: string | null };@@ -623,3 +628,78 @@ describe("hold shapes", () => {expect(holds.startReason(2 * 86_400_000 + 60_000)).toBe("hour");});});++describe("review fixes: holds that stay held, a cold service, and hosted runs switched off", () => {+ it("a held run whose row waits on an earlier result stays unsent until it is released", async () => {+ const a = account();+ const [one, two] = [await press(a.cookie), await press(a.cookie)];+ const third = await press(a.cookie);+ expect(third.body.held).toEqual({ reason: "mine" });+ const id = idOf(third);+ // An earlier result it waits on, already done (a film's shots after its board).+ const done = `done-${++n}`;+ db()+ .prepare(+ `INSERT INTO generations (id, batch_id, feature, preset_id, model_id, engine, provider, op, kind, status, progress, message, prompt, request_json, outputs_json, cost_usd, favorite, created_at, updated_at)+ SELECT ?, NULL, feature, preset_id, model_id, engine, provider, op, kind, 'succeeded', NULL, NULL, prompt, request_json, '[]', NULL, 0, created_at, updated_at FROM generations WHERE id = ?`,+ )+ .run(done, idOf(one));+ db().prepare("UPDATE generations SET depends_on = ? WHERE id = ?").run(JSON.stringify([done]), id);+ for (let i = 0; i < 5; i++) await tick();+ expect(taskOf(id)).toBeUndefined();+ expect(getGeneration(id)!.status).toBe("queued");+ expect(heldOf(id)).toBeTruthy();+ // Room opens: it enters the line then.+ await stop([idOf(one), idOf(two)]);+ expect(await until(() => taskOf(id))).toBeTruthy();+ });++ it("the step that takes a run counts the account's room again: no room, it stays held", async () => {+ const a = account();+ await press(a.cookie);+ await press(a.cookie);+ const third = await press(a.cookie);+ const run = heldOf(idOf(third))!.run_id;+ expect(holds.leaseRun(run)).toBe(true);+ try {+ expect(holds.takeRun(run, Date.now(), () => false)).toBeNull();+ expect(heldOf(idOf(third))).toBeTruthy();+ } finally {+ holds.endRunLease(run);+ }+ });++ it("A3 cold: after a restart while the service is down, a press is held for it (its last answer kept), and Run stays on", async () => {+ const a = account();+ // The service answered once; then the app restarts (nothing in memory) and the service stops.+ expect((await check(a.cookie)).status).toBe(200);+ billing.resetBillingCache();+ fake.down = "error";+ const quiet = await check(a.cookie);+ expect(quiet.body.quote?.allowed, JSON.stringify(quiet.body)).not.toBe(false);+ const r = await press(a.cookie);+ expect(r.status, JSON.stringify(r.body)).toBe(201);+ expect(r.body.held).toEqual({ reason: "service" });+ fake.down = false;+ expect(await until(() => taskOf(idOf(r)))).toBeTruthy();+ });++ it("hosted runs switched off while runs wait: they end in today's words and their holds go", async () => {+ const a = account();+ await press(a.cookie);+ await press(a.cookie);+ const third = await press(a.cookie);+ const id = idOf(third);+ expect(heldOf(id)).toBeTruthy();+ delete process.env.FUOBE_HOSTED_RUNS;+ try {+ await tick();+ const g = db().prepare("SELECT status, error FROM generations WHERE id = ?").get(id);+ expect(g).toEqual({ status: "failed", error: "This run stopped before it started. Press Retry." });+ expect(heldOf(id)).toBeUndefined();+ expect(holds.anyHeld()).toBe(false);+ } finally {+ process.env.FUOBE_HOSTED_RUNS = "1";+ }+ });+});diff --git a/tests/pool-limits.test.ts b/tests/pool-limits.test.tsindex b0a5af96..fd00f763 100644--- a/tests/pool-limits.test.ts+++ b/tests/pool-limits.test.ts@@ -536,7 +536,8 @@ describe("where a run goes", () => {expect((await hostedRun.decidePlace(acct, req, undefined)).kind).toBe("pool");expect((await hostedRun.poolQuote(acct, req, undefined))?.line).toMatchObject({ unknown: true });beatWith(worker, catalogVersion());- // The service goes quiet for longer than its last answer stands: the run waits for it, never sent to the own GPU.+ // The service goes quiet for longer than its last answer stands: never sent to the own GPU. Under a policy without+ // runs that wait (`held`) it is refused as before; with them it is held for the service (pool-holds.test.ts, A3 cold).fake.down = "error";try {const kept = globalThis.__fuobeBillingPolicies!.get(a.id)!;@@ -714,6 +715,43 @@ describe("where a run goes", () => {delete process.env.FUOBE_BILLING_URL;expect((await visitorStatus(null)).viewer.hosted).toBe(true);});+ it("a run refused there only for its LoRAs says so, and runs there without them", async () => {+ withBilling({ prefer: "pool", limits: { activeRuns: 0, waiting: 0, runsPerHour: 0 } });+ const a = account();+ const LORA = { loras: [{ file: "x.safetensors", url: "https://huggingface.co/x/x.safetensors" }] };+ type Check = { place?: string; quote?: { allowed: boolean; withoutLoras?: true } };+ const refused = (await preview({ ...IMAGE, ...LORA, place: "pool" }, a.cookie)).body as Check;+ expect(refused.quote).toMatchObject({ allowed: false, withoutLoras: true });+ const without = (await preview({ ...IMAGE, ...LORA, place: "pool", lorasOff: true }, a.cookie)).body as Check;+ expect(without.quote).toMatchObject({ allowed: true });+ expect(without.quote?.withoutLoras).toBeUndefined();+ });++ it("offer_after_s 0 turns the wait offer off: an unknown wait is not long, and a known one never is", async () => {+ expect(billing.policyOfferAfterS({ limits: { offerAfterS: 0 } } as never)).toBe(Infinity);+ expect(billing.policyOfferAfterS({ limits: { offerAfterS: 1200 } } as never)).toBe(1200);+ expect(billing.policyOfferAfterS({ limits: {} } as never)).toBe(billing.POOL_OFFER_AFTER_S);+ withBilling({ prefer: "pool", limits: { activeRuns: 0, waiting: 0, runsPerHour: 0, offerAfterS: 0 } });+ const a = account({ gpu: "online" });+ const req = { ...IMAGE, account: a.id } as never;+ pool.patchWorker(worker.id, { paused: true });+ try {+ const away = await hostedRun.poolQuote(auth.accountById(a.id)!, req, undefined);+ expect(away?.line).toMatchObject({ unknown: true });+ expect(away?.line.long).toBeUndefined();+ } finally {+ pool.patchWorker(worker.id, { paused: false });+ beatWith(worker, catalogVersion());+ }+ withBilling({ prefer: "pool", limits: { activeRuns: 0, waiting: 0, runsPerHour: 0, offerAfterS: 1200 } });+ pool.patchWorker(worker.id, { paused: true });+ try {+ expect((await hostedRun.poolQuote(auth.accountById(a.id)!, req, undefined))?.line.long).toBe(true);+ } finally {+ pool.patchWorker(worker.id, { paused: false });+ beatWith(worker, catalogVersion());+ }+ });});describe("a run's price facts", () => {diff --git a/tests/run-place.test.ts b/tests/run-place.test.tsindex 1ce4a1b7..e1a38ddc 100644--- a/tests/run-place.test.ts+++ b/tests/run-place.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vitest";import { placeOf } from "@/lib/place-name";import { quoteBody } from "@/lib/hosted";-import { checkedPool, composerOnPool, composerPlace, IN_BROWSER, mainModel, offersRunOnSite, openCheckPlace, placePrice, placeRows, refusedBeforeRun, retryRequest, runPlace, toolPoolPrice, withPoolRefusal, type RunPlaceInput } from "@/lib/run-place";+import { checkedPool, composerOnPool, composerPlace, IN_BROWSER, keyOnlyChip, mainModel, openCheckPlace, placePrice, placeRows, refusedBeforeRun, retryRequest, runPlace, toolPoolPrice, withPoolRefusal, type RunPlaceInput } from "@/lib/run-place";import { RUN_SHOWN_HEADER, shownHeader } from "@/lib/guest-access";/** Where a run happens and what it costs, for each audience and engine (the composers' place chip and send button). */@@ -253,13 +253,6 @@ describe("Retry and Run on <the place> on a run's tile", () => {expect(retryRequest({ request, place: "pool" }, false)).toBe(request);expect(retryRequest({ request }, false)).toBe(request);});- it("Run on <the place>: an open run that failed on the person's own GPU, while hosted runs are on", () => {- expect(offersRunOnSite({ engine: "open", status: "failed" }, true)).toBe(true);- expect(offersRunOnSite({ engine: "open", status: "failed", place: "pool" }, true)).toBe(false);- expect(offersRunOnSite({ engine: "cloud", status: "failed" }, true)).toBe(false);- expect(offersRunOnSite({ engine: "open", status: "canceled" }, true)).toBe(false);- expect(offersRunOnSite({ engine: "open", status: "failed" }, false)).toBe(false);- });});describe("the Run on list", () => {@@ -435,3 +428,20 @@ describe("Run on a tool page (Character Sheet, AI Influencer) after its price ch}});});++describe("an item only an own setup runs, for an account whose runs go to its key", () => {+ const key = { provider: "fal" as const, price: "≈ $0.04" };+ const base = { ownSetup: true, key, gpu: false, picked: "key" as const, rows: false };+ it("the chip says the key's price first, and who bills it", () => {+ expect(keyOnlyChip(base)).toEqual({ text: "≈ $0.04 · your key", tip: "Runs with your fal.ai key · billed to your fal.ai account" });+ });+ it("never without a price, with a GPU, with another pick, with the Run on list, or for an item the GPUs take", () => {+ expect(keyOnlyChip({ ...base, key: { ...key, price: null } })).toBeNull();+ expect(keyOnlyChip({ ...base, key: null })).toBeNull();+ expect(keyOnlyChip({ ...base, gpu: true })).toBeNull();+ expect(keyOnlyChip({ ...base, picked: "site" })).toBeNull();+ expect(keyOnlyChip({ ...base, picked: null })).toBeNull();+ expect(keyOnlyChip({ ...base, rows: true })).toBeNull();+ expect(keyOnlyChip({ ...base, ownSetup: false })).toBeNull();+ });+});diff --git a/tests/self-host-unchanged.test.ts b/tests/self-host-unchanged.test.tsindex e20d9ea3..2cedbf02 100644--- a/tests/self-host-unchanged.test.ts+++ b/tests/self-host-unchanged.test.ts@@ -1,5 +1,5 @@import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { createElement, type ReactNode } from "react";+import { createElement, type ComponentProps, type ReactNode } from "react";import { renderToStaticMarkup } from "react-dom/server";import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import type { StatusInfo, ViewerInfo } from "@/lib/api";@@ -23,6 +23,7 @@ const state = vi.hoisted(() => ({hydrated: true,viewer: undefined as ViewerInfo | undefined,status: undefined as StatusInfo | undefined,+ engine: undefined as "open" | "cloud" | undefined,}));vi.mock("next/navigation", () => ({@@ -30,13 +31,18 @@ vi.mock("next/navigation", () => ({usePathname: () => "/image",useSearchParams: () => new URLSearchParams(),}));-vi.mock("@/lib/api", async (load) => ({- ...(await load<typeof import("@/lib/api")>()),+vi.mock("@/lib/api", async (load) => {+ const real = await load<typeof import("@/lib/api")>();+ return {+ ...real,+ // The engine switched to, for the composer's snapshot (else the browser's own, as before).+ useEngine: () => (state.engine ? ([state.engine, () => {}, "both"] as const) : real.useEngine()),useHydrated: () => state.hydrated,useViewer: () => ({ data: state.viewer }),useStatus: () => ({ data: state.status }),useEngineMode: () => "both",-}));+ };+});const { PendingTile, FailedTile, Feed } = await import("@/components/studio/feed");const { StatusCover } = await import("@/components/library/asset-card");@@ -48,7 +54,7 @@ const { TooltipProvider } = await import("@/components/ui/tooltip");const { runPlace } = await import("@/lib/run-place");const { accountEngine } = await import("@/lib/your-keys");const { againWhere } = await import("@/lib/demo-mode");-const { ACCOUNT_MESSAGES } = await import("@/server/account-files");+const { ACCOUNT_LIMITS, ACCOUNT_MESSAGES } = await import("@/server/account-files");const auth = await import("@/server/auth");const { visitorStatus } = await import("@/server/account-gpu");@@ -114,6 +120,7 @@ beforeEach(() => {state.hydrated = true;state.viewer = undefined;state.status = undefined;+ state.engine = undefined;});describe("a self-hosted install with hosted runs off", () => {@@ -295,4 +302,79 @@ describe("a self-hosted install with hosted runs off", () => {}expect((db().prepare("SELECT COUNT(*) AS n FROM pool_holds").get() as { n: number }).n).toBe(0);});++ it("the composer for an account, in the Image and Video studios, on each engine", async () => {+ const { Composer } = await import("@/components/studio/composer");+ const { StudioProvider } = await import("@/components/studio/studio-context");+ const { CatalogProvider } = await import("@/components/studio/catalog");+ const { initialDraft } = await import("@/components/studio/draft");+ const { studioCatalog } = await import("@/lib/studio-catalog");+ const { IMAGE_STUDIO, VIDEO_STUDIO } = await import("@/lib/studios");+ const catalog = await import("@/lib/catalog");+ state.viewer = accountViewer;+ const out: string[] = [];+ for (const config of [IMAGE_STUDIO, VIDEO_STUDIO])+ for (const [engine, status] of [+ ["open", statusOf({ gpu: { connected: true, mode: "link", online: true } })],+ ["open", statusOf()],+ ["cloud", statusOf({ keys: ["fal"] })],+ ] as const) {+ state.engine = engine;+ state.status = status;+ const initial = initialDraft(config, new URLSearchParams(), engine, catalog);+ const html = render(+ createElement(+ CatalogProvider,+ { catalog: studioCatalog(config), config } as ComponentProps<typeof CatalogProvider>,+ createElement(StudioProvider, { config, initial } as ComponentProps<typeof StudioProvider>, createElement(Composer, { docked: false })),+ ),+ );+ // (React's generated ids change with the render order, never with the words.)+ out.push(lines(html.replace(/ (id|for|aria-controls|aria-labelledby|aria-describedby)="[^"]*"/g, ' $1="_"')));+ }+ await expect(out.join("\n\n")).toMatchFileSnapshot(`${GOLDEN}/composer.html`);+ });++ it("a fifth run at once on the account's own place is turned down in today's words", async () => {+ vi.doMock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));+ const { db } = await import("@/server/db");+ const { saveAccountKey } = await import("@/server/account-keys");+ const route = await import("@/app/api/generations/route");+ const a = auth.createAccount("[email protected]", "long enough");+ saveAccountKey(a.id, "fal", "self-host-key");+ const cookie = `${auth.SESSION_COOKIE}=${auth.createSession(a.id).value}`;+ const now = Date.now();+ for (let i = 0; i < ACCOUNT_LIMITS.activeRuns; i++)+ db()+ .prepare(+ `INSERT INTO generations (id, batch_id, feature, preset_id, model_id, engine, provider, op, kind, status, progress, message, prompt, request_json, outputs_json, cost_usd, favorite, created_at, updated_at, external_id)+ VALUES (?, NULL, 'image', NULL, 'nano-banana-pro', 'cloud', 'fal', 'generate', 'image', 'running', NULL, 'Generating', 'a fox', ?, '[]', NULL, 0, ?, ?, ?)`,+ )+ .run(`self-host-fifth-${i}`, JSON.stringify({ feature: "image", modelId: "nano-banana-pro", prompt: "a fox", account: a.id }), now, now, `ext-${i}`);+ const text = JSON.stringify({ feature: "image", modelId: "nano-banana-pro", engine: "cloud", prompt: "a quiet harbour" });+ const res = await route.POST(+ new Request("http://localhost:3000/api/generations", { method: "POST", headers: { cookie, host: "localhost:3000", "content-type": "application/json", "content-length": String(text.length) }, body: text }),+ );+ expect(res.status).toBe(429);+ expect(((await res.json()) as { error: string }).error).toBe(ACCOUNT_MESSAGES.activeRuns);+ db().prepare("UPDATE generations SET status = 'canceled' WHERE id LIKE 'self-host-fifth-%'").run();+ });++ it("the ways on added for hosted runs are all behind the switch", async () => {+ const { siteRunOf, shownTroubleActions, keyTurnedDown } = await import("@/lib/site-run");+ const { placeIntro } = await import("@/lib/place-intro");+ const { withKeyAction } = await import("@/lib/diagnose");+ const trouble = { cause: "key-balance", words: "Your fal.ai key is out of credit.", actions: [], retryable: false } as unknown as Generation["trouble"];+ // "Run on {Place}" on a failed tile, and the line about a key that turned the last run down: never.+ expect(siteRunOf(gen({ status: "failed", trouble }), false, undefined)).toBeNull();+ // A failed tile's key offer: as it was, priced or not.+ const actions = [withKeyAction("fal", "nano-banana-pro")];+ expect(shownTroubleActions(actions, false)).toBe(actions);+ // The one-time note: never.+ expect(placeIntro({ kind: "account", ranOwn: true, gpu: { connected: true } }, "Generate")).toBeNull();+ // A tool for the owner only: no way on to another studio.+ expect(runPlace({ audience: "account", engine: "cloud", ownerOnly: "Ad Multiplier", ownerOnlyStudio: "video", format: String }).way).toBeUndefined();+ // (keyTurnedDown is read only while viewer.hosted, which a self-hoster's status never carries: above.)+ expect(typeof keyTurnedDown).toBe("function");+ });});diff --git a/tests/site-run.test.ts b/tests/site-run.test.tsnew file mode 100644index 00000000..3a2d31eb--- /dev/null+++ b/tests/site-run.test.ts@@ -0,0 +1,79 @@+import { describe, expect, it } from "vitest";+import type { Generation } from "@/lib/catalog/types";+import { withKeyAction, type TroubleAction } from "@/lib/diagnose";+import type { PoolRules } from "@/lib/pool-rules";+import { shownTroubleActions, siteRunOf } from "@/lib/site-run";++/** "Run on {Place}" on a failed run (hosted runs): offered only for what this studio's GPUs take, on its open version. */+const trouble = { cause: "gpu-offline", words: "Your GPU isn't answering.", actions: [], retryable: false } as unknown as Generation["trouble"];+const run = (o: Partial<Generation>) =>+ ({ status: "failed", engine: "open", kind: "image", modelId: "oss-z-image-turbo", op: "t2i", presetId: null, trouble, ...o }) as Parameters<typeof siteRunOf>[0];++describe("Run on the place, on a run that failed on the person's own GPU or key", () => {+ it("an open run on its own GPU: the same model, while hosted runs are on", () => {+ expect(siteRunOf(run({}), true, undefined)).toEqual({ modelId: "oss-z-image-turbo" });+ });++ it("never off hosted runs, on a run there already, a run that didn't fail, or one with no trouble of its own", () => {+ expect(siteRunOf(run({}), false, undefined)).toBeNull();+ expect(siteRunOf(run({ place: "pool" }), true, undefined)).toBeNull();+ expect(siteRunOf(run({ status: "canceled" }), true, undefined)).toBeNull();+ expect(siteRunOf(run({ trouble: undefined }), true, undefined)).toBeNull();+ });++ it("never for what they don't take: a model that runs on an own setup only, or one their rules keep off", () => {+ expect(siteRunOf(run({ kind: "video", modelId: "oss-h3-regenerate", op: "upscale-video" }), true, undefined)).toBeNull();+ const rules: PoolRules = { deny: ["oss-z-image-turbo"] } as PoolRules;+ expect(siteRunOf(run({}), true, rules)).toBeNull();+ const apps: PoolRules = { apps: { deny: ["app-face-swap"] } } as PoolRules;+ expect(siteRunOf(run({ engine: "cloud", modelId: "nano-banana-pro", op: "edit", presetId: "app-face-swap" }), true, apps)).toBeNull();+ });++ it("a run its key turned down: the item's open version (an app's open route, a Fuobe Original on Open source)", () => {+ expect(siteRunOf(run({ engine: "cloud", modelId: "nano-banana-pro", op: "edit", presetId: "app-face-swap" }), true, undefined)).toEqual({+ modelId: "oss-qwen-image-21-turbo",+ op: "edit",+ engine: "open",+ });+ expect(siteRunOf(run({ engine: "cloud", modelId: "fuobe-soul" }), true, undefined)).toEqual({ modelId: "fuobe-soul", engine: "open" });+ // A cloud model with no open version: nothing to offer.+ expect(siteRunOf(run({ engine: "cloud", modelId: "nano-banana-pro", op: "edit" }), true, undefined)).toBeNull();+ });+});++describe("a failed run's key offer", () => {+ const unpriced = withKeyAction("fal", "nano-banana-pro");+ const priced = withKeyAction("fal", "nano-banana-pro", undefined, "≈ $0.04");+ const add: TroubleAction = { kind: "add-credit", label: "Add credit on fal.ai", target: "https://fal.ai" } as TroubleAction;++ it("shows only with its price while hosted runs are on", () => {+ expect(shownTroubleActions([add, unpriced], true)).toEqual([add]);+ expect(shownTroubleActions([add, priced], true)).toEqual([add, priced]);+ });++ it("is unchanged with hosted runs off", () => {+ const actions = [add, unpriced];+ expect(shownTroubleActions(actions, false)).toBe(actions);+ });+});++describe("a pick made anywhere moves the studios' engine", () => {+ it("to Cloud for the key, back to Open source away from it, and leaves the switch alone otherwise", async () => {+ const { keyEngine } = await import("@/lib/run-on");+ expect(keyEngine("site", "key")).toBe("cloud");+ expect(keyEngine(null, "key")).toBe("cloud");+ expect(keyEngine("key", "site")).toBe("open");+ expect(keyEngine("key", "gpu")).toBe("open");+ expect(keyEngine("gpu", "site")).toBeNull();+ expect(keyEngine(undefined, "gpu")).toBeNull();+ });+});++describe("a run refused there only for its LoRAs", () => {+ it("carries the way on to the composer's line", async () => {+ const { poolRunState } = await import("@/lib/hosted");+ const quote = { allowed: false, amount: 0, priceVersion: "", text: "LoRAs run on your own GPU", code: "not-offered", ownSetup: { need: "gpu" as const }, withoutLoras: true as const };+ expect(poolRunState({ quote } as never)).toMatchObject({ refused: true, withoutLoras: true, setup: { need: "gpu" } });+ expect(poolRunState({ quote: { ...quote, withoutLoras: undefined } } as never)?.withoutLoras).toBeUndefined();+ });+});