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
Studios start on Open source while hosted runs are on, and the key button runs once
Adarshcbbaa77ea683
diff --git a/docs/public-signup.md b/docs/public-signup.mdindex bf79706e..2494035f 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -603,7 +603,8 @@ keep their words as before.the reason and its buttons above Generate. It reads the status the strip already has (every 30seconds), so the GPU is never asked more often. When one of the account's keys runs the tool'scloud version (a preset's cloud route, or a Fuobe Original on the cloud engine), **Run with your- fal.ai key** switches to Cloud and runs it there, billed to that key. A run started anyway waits.+ fal.ai key** switches to Cloud and runs it there, billed to that key (with hosted runs on, it runs+ that one run there and the switch stays where it was). A run started anyway waits.The account menu says why the GPU is offline: "pod stopped", "starting up", "needs a password".- **A run that waits.** A run whose GPU is off, starting up or out of reach waits and tries again byitself, with a growing wait (up to a minute between tries). Its tile says what it waits for@@ -654,6 +655,13 @@ With it on:- 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.+- The studios' engine switch starts on Open source, where open models run free on this install's GPUs. Each account+ keeps its own switch in the browser (a second account on the same browser keeps its own, under a hash of its email,+ never the address; a guest keeps one for the browser), and the owner keeps the browser's one switch. Saving a key+ doesn't move it: Cloud is one pick away, and the note after saving says so. **Run with your fal.ai key** runs that+ one run on the key, and a note's link to a tool's cloud version opens that page on Cloud for that visit: neither+ moves the switch. (With hosted runs off, the browser keeps one switch, starting on Cloud, and saving a key moves it+ there, as before.)- A model, mode or option that runs only on a person's own GPU or key keeps its label there ("Runs on your own GPU ·48 GB", `src/lib/own-setup.ts`), and Run opens that setup. So does a run that no worker can take (none holds itsfiles or may run its lane). Extra LoRAs added to a request stay on the account's own GPU.diff --git a/src/components/keys/your-keys.tsx b/src/components/keys/your-keys.tsxindex 9aed24ce..9a2343d9 100644--- a/src/components/keys/your-keys.tsx+++ b/src/components/keys/your-keys.tsx@@ -11,7 +11,8 @@ import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";import { ADD_KEY_EVENT, preferEngine, useHydrated, useStatus, useViewer } from "@/lib/api";import { settingProblem } from "@/lib/connections";-import { CLOUD_KEY, CLOUD_PROVIDERS, type CloudProvider, type KeyInfo, type YourKeys } from "@/lib/your-keys";+import { CLOUD_KEY, CLOUD_PROVIDERS, keySavedText, type CloudProvider, type KeyInfo, type YourKeys } from "@/lib/your-keys";+import { engineAfterKeySave } from "@/lib/engine-pref";import { cn } from "@/lib/utils";/**@@ -88,6 +89,7 @@ function KeyForm({ provider, replacing, onSaved, onCancel, autoFocus }: { providconst p = CLOUD_KEY[provider];const id = useId();const changed = useKeysChanged();+ const hosted = !!useStatus().data?.viewer?.hosted;const [key, setKey] = useState("");const [busy, setBusy] = useState(false);const [error, setError] = useState<string | null>(null);@@ -101,13 +103,15 @@ function KeyForm({ provider, replacing, onSaved, onCancel, autoFocus }: { providconst r = await call<KeyInfo & { detail?: string; note?: string }>(`/api/account/keys/${provider}`, "PUT", { key, ...(stopRuns && { stopRuns: true }) });setKey("");setGoing(null);- // The person just asked for paid models: the studios start on Cloud.- preferEngine("cloud");+ // The person just asked for paid models: the studios start on Cloud (while hosted runs are on, they stay where they+ // were: open models run free there, and Cloud is one pick away).+ const engine = engineAfterKeySave(hosted);+ if (engine) preferEngine(engine);changed();const who = provider === "replicate" && r.detail?.startsWith("Signed in as ") ? ` (${r.detail.replace("Signed in as ", "signed in as ")})` : "";// A key that works on a provider account with nothing on it yet: saved, and the next step said.if (r.note) toast.warning(r.note, { duration: 10_000 });- else toast.success(`Your ${p.label} key works${who}. Paid models on ${p.label} are ready.`);+ else toast.success(keySavedText(p.label, who, hosted));onSaved(r);} catch (e) {const k = e as KeyError;diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsxindex 28ff24d0..fccf8f90 100644--- a/src/components/studio/composer.tsx+++ b/src/components/studio/composer.tsx@@ -33,7 +33,7 @@ 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, 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, useStatus } from "@/lib/api";import { usePagePlace } from "@/components/gpu/use-page-place";import { applyMentions, elementsNote, type StudioElement } from "@/lib/catalog/elements";import { applySketch, stripMotionPaths } from "@/lib/catalog/sketch";@@ -100,7 +100,8 @@ import { H3_TIER_PARAM, h3TierNote } from "@/lib/gpu/h3-tier";import { formatCost } from "@/lib/format";import { toastError } from "@/lib/refusals";import { addKeyLabel, billedTo, CLOUD_KEY, needsKey, paidThrough, startingModel } from "@/lib/your-keys";-import { gpuBeforeRun } from "@/lib/before-run";+import { gpuBeforeRun, onCloudKey } from "@/lib/before-run";+import type { TroubleAction } from "@/lib/diagnose";import { TroubleActions, TroubleDetails } from "@/components/gpu/trouble";import { cn } from "@/lib/utils";import { h3ReferenceProblem, openReferenceMode } from "@/lib/h3-references";@@ -835,8 +836,10 @@ export function Composer({ docked }: { docked: boolean }) {// waits for the GPU. One of the account's keys that runs this tool's cloud version is offered too (an explicit click:// it spends the person's own credit).const gpuDown = gpuBeforeRun({ viewer: status?.viewer, model, engine, onPool: hostedHere && runOn === "pool", preset, has, getModel: catalog.getModel });+ // "Run with your fal.ai key". While hosted runs are on: this run, once, on the tool's cloud version and that key; the+ // engine switch stays where it was, so the next run goes where runs go (the person picks Cloud themselves to stay+ // there). Otherwise (as always): the switch moves to Cloud, and once it has moved the tool to its cloud model, it runs.const [cloudRun, setCloudRun] = useState(false);- // "Run with your fal.ai key": once the switch to Cloud has moved the tool to its cloud model, it runs (once).useEffect(() => {if (!cloudRun) return;const late = setTimeout(() => setCloudRun(false), 4000);@@ -846,9 +849,16 @@ export function Composer({ docked }: { docked: boolean }) {}return () => clearTimeout(late);}, [cloudRun, engine, model]);+ const onRunWithKey = viewerInfo?.hosted+ ? (a: TroubleAction) => submitRef.current(undefined, a)+ : () => {+ setEngine("cloud");+ setCloudRun(true);+ };- // `skip` is true only from the guided fix's "Run anyway" (a click handler passes its event here).- const submit = (skip?: unknown) => {+ // `skip` is true only from the guided fix's "Run anyway" (a click handler passes its event here). `withKey`: this run+ // only, on the cloud version that action names and the account's key (hosted runs on; see onRunWithKey).+ const submit = (skip?: unknown, withKey?: TroubleAction) => {const skipGpu = skip === true;if (exact) {// An exact orbit: the still filmed along the orbit's numbers (Fly around), priced in its panel.@@ -856,14 +866,14 @@ export function Composer({ docked }: { docked: boolean }) {if (stop) return void toast(stop, { id: "composer-blocker" });if (fly.run.isPending) return;toast.dismiss("composer-blocker");- pressSetup(owner ? null : "fly-around:exact-orbit", () => fly.run.mutate({ engine, image: exactImage, orbit: exact, prompt: draft.prompt.trim() || undefined, feature: config.feature }));+ pressSetup(owner ? null : "fly-around:exact-orbit", () => fly.run.mutate({ engine: withKey ? "cloud" : engine, image: exactImage, orbit: exact, prompt: draft.prompt.trim() || undefined, feature: config.feature }));return;}if (keyToAdd && model && !create.isPending) return openAddKey(keyToAdd, model.id);- if (!blocker && gpuSetup && !skipGpu && !create.isPending) return openGpuFix();+ if (!blocker && gpuSetup && !skipGpu && !withKey && !create.isPending) return openGpuFix();// It runs on the visitor's own setup: Run opens it (Connect your GPU, Add your key, a guest's sign-up), and nothing// is sent. An account that has it (its own GPU, or the key that runs it) is moved there, to run with the next press.- if (!blocker && poolSetup) {+ if (!blocker && poolSetup && !withKey) {if (pressSetup(poolSetup)) {setRunOn("own");toast(movedToOwnText(!!viewerInfo?.gpu.connected), { id: "composer-blocker" });@@ -871,7 +881,7 @@ export function Composer({ docked }: { docked: boolean }) {return;}// Refused by the price check (Run is off; Enter in the prompt lands here too): its words, and nothing is sent.- if (!blocker && poolRefused && poolState) return void toast(poolState.text, { id: "composer-blocker" });+ if (!blocker && poolRefused && poolState && !withKey) return void toast(poolState.text, { id: "composer-blocker" });if (blocker || create.isPending || signature.lock.isPending) {if (blocker) {// One blocker toast at a time (pressing Generate again replaces it), gone once a run starts.@@ -899,18 +909,24 @@ export function Composer({ docked }: { docked: boolean }) {buildRequest(config.feature, songDraft(draft, model, config.slots), resolvesOnServer ? studioOp : op, config.promptSuffix, config.multiRef?.kind, framesCtx, targetFor(draft.modelId)),);// Hosted runs: where it should go, and the price shown (the server checks both; a higher price comes back to confirm).- const hosted = viewerInfo?.hosted ? { ...(runPlace && { place: runPlace }), ...(poolPrice && hostedQuote && { shown: { amount: hostedQuote.amount, priceVersion: hostedQuote.priceVersion } }) } : {};+ // A run on the account's key names neither: the key is where it goes.+ const hosted = viewerInfo?.hosted && !withKey ? { ...(runPlace && { place: runPlace }), ...(poolPrice && hostedQuote && { shown: { amount: hostedQuote.amount, priceVersion: hostedQuote.priceVersion } }) } : {};// Open palette lock: the images are recoloured to the palette by a chained step (POST /api/palettes/lock).// (An account's lock runs on this studio's GPUs only: sent there by name.)- if (sent.lock) return signature.lock.mutate({ request: sent.request, colors: sent.lock.colors, ...hosted, ...(poolPrice && { place: "pool" as const }) }, { onError: (e) => toastError(e) });+ if (sent.lock) {+ const request = withKey ? onCloudKey(sent.request, withKey) : sent.request;+ return signature.lock.mutate({ request, colors: sent.lock.colors, ...hosted, ...(poolPrice && !withKey && { place: "pool" as const }) }, { onError: (e) => toastError(e) });+ }// If the server's pre-flight stops it (409 gpu-setup), the guided fix that opens can try again, or run it anyway.- setGpuRetry(- () => submitRef.current(),- () => submitRef.current(true),- model?.kind,- );+ if (!withKey)+ setGpuRetry(+ () => submitRef.current(),+ () => submitRef.current(true),+ model?.kind,+ );const withVoiceFirst = cleanFirst ? { ...sent.request, params: { ...sent.request.params, extra: { ...sent.request.params?.extra, [VOICE_FIRST_PARAM]: true } } } : sent.request;- const body = { ...withVoiceFirst, ...hosted, ...(skipGpu && { gpuCheck: "skip" }) } as typeof sent.request;+ const onKey = withKey ? onCloudKey(withVoiceFirst, withKey) : withVoiceFirst;+ const body = { ...onKey, ...hosted, ...(skipGpu && { gpuCheck: "skip" }) } as typeof sent.request;create.mutate(body, {// Accepted: nothing to try again (a card opened later never starts this run a second time).onSuccess: () => dropGpuRetry(),@@ -1878,16 +1894,7 @@ export function Composer({ docked }: { docked: boolean }) {<span className="font-medium text-foreground">{gpuDown.words}</span> A run you start now waits for it.</p><TroubleDetails details={gpuDown.details} />- <TroubleActions- actions={gpuDown.actions}- skip={["retry"]}- handlers={{- onRunWithKey: () => {- setEngine("cloud");- setCloudRun(true);- },- }}- />+ <TroubleActions actions={gpuDown.actions} skip={["retry"]} handlers={{ onRunWithKey }} /></div>)}{outcome && (@@ -1913,7 +1920,12 @@ export function Composer({ docked }: { docked: boolean }) {</p>{alternative && alternativeHref && engineMode !== "open" && (<p>- <Link href={alternativeHref} onClick={() => setEngine("cloud")} className="font-medium text-brand-text underline-offset-2 hover:underline">+ <Link+ href={alternativeHref}+ // While hosted runs are on, it opens there on Cloud for that page only: the switch the studios start on stays.+ onClick={() => (viewerInfo?.hosted ? engineForNextPage("cloud") : setEngine("cloud"))}+ className="font-medium text-brand-text underline-offset-2 hover:underline"+ >{alternative.label}</Link></p>diff --git a/src/components/studio/studio-page.tsx b/src/components/studio/studio-page.tsxindex cfbc454d..cccde269 100644--- a/src/components/studio/studio-page.tsx+++ b/src/components/studio/studio-page.tsx@@ -12,7 +12,7 @@ import { PhoneNavButton } from "@/components/nav/phone-nav-button";import { HeaderPill } from "@/components/gpu/readiness-chip";import { badgeFor, openGpuSetup, useGpuBadges } from "@/hooks/use-gpu";import type { Generation } from "@/lib/catalog/types";-import { GUEST_PROMPT_EVENT, useEngine, useGenerations, useHydrated, useIsGuest, useLikelyVisitor } from "@/lib/api";+import { GUEST_PROMPT_EVENT, leavePageEngine, setPageEngine, takeNextPageEngine, useEngine, useGenerations, useHydrated, useIsGuest, useLikelyVisitor } from "@/lib/api";import { claimStartToken, followEngineDefault, handoffKey, mergeHandoff, promptShown, relatedHref, START_PARAM, withoutStart, withPreset } from "@/lib/composer";import { presetGpuKey } from "@/lib/catalog/preset-recipe-routes";import { editableLayout, EDIT_LAYOUT_PARAM, readEditLayoutParam } from "@/lib/output-actions";@@ -877,12 +877,17 @@ function StudioDraft({ config, header, tabs, initialRefs, initialPrompt, examplereturn d;};// A model named in the URL (?model=, from ⌘K or a hand-off) brings its engine along, as Reuse- // does: left on the other engine, the composer would swap it for that engine's default.+ // does: left on the other engine, the composer would swap it for that engine's default. A link that asked for this+ // page only (engineForNextPage) leaves the person's own switch where it was.const adopt = (key: string) => {const id = new URLSearchParams(key).get("model");const m = id ? catalog.getModel(id) : undefined;- if (m && m.engine !== engine) setEngine(m.engine);+ if (!m || m.engine === engine) return;+ if (takeNextPageEngine(m.engine)) setPageEngine(m.engine);+ else setEngine(m.engine);};+ // An engine for this page only ends when the page is left.+ useEffect(() => leavePageEngine, []);// The composer swaps an untouched default for the engine's own when the engine is read after hydration: a// hand-off still applies over that swap.const follow = (base: Draft, current: Draft) => followEngineDefault(base, current, config.defaultModels, engine, config.uncaptioned);diff --git a/src/lib/api.ts b/src/lib/api.tsindex bfe18072..aa2a23a8 100644--- a/src/lib/api.ts+++ b/src/lib/api.ts@@ -38,6 +38,7 @@ import { ADD_KEY_HEADER, isCloudProvider, type CloudProvider } from "./your-keysimport type { Diagnosis } from "./diagnose";import { BILLING_EVENT, BILLING_HEADER, refreshPriceChecks, type BillingAction, type BillingRefusalDetail, type HostedBalance } from "./hosted";import { knownPlace, notePlaceName, placeOf, type Place } from "./place-name";+import { ENGINE_KEY, ENGINE_SLOT_KEY, engineSlot, SHARED_SLOT, slotToCache, storedEngine, type EngineSlot, type SlotFacts } from "./engine-pref";/** What the status strip says of a GPU that didn't answer (src/server/account-gpu.ts VisitorTrouble). */export type GpuTroubleView = Pick<Diagnosis, "cause" | "words" | "actions" | "retryable" | "details">;@@ -966,6 +967,11 @@ export interface StatusInfo {prefer?: "pool";/** The name visitors read for this install's GPUs ("Runs on Our GPUs", src/lib/place-name.ts). Only with `hosted`. */placeName?: string;+ /**+ * Where the account's runs go, as it picked (only with `hosted`, only to that account; none: the install's GPUs).+ * "key" starts its engine switch on Cloud (src/lib/engine-pref.ts).+ */+ runOn?: "site" | "gpu" | "key";/** The words a preset card shows when its run would go to this studio's GPUs ("Try free"), from the server. None: no words. */cardText?: string;/** What this studio's GPUs keep off, for a viewer with no GPU of its own: its pickers leave it out (src/lib/pool-rules.ts). */@@ -1086,19 +1092,66 @@ export async function writeLyrics(idea: string, o: { seconds?: number; max?: num// ---------------------------------------------------------------------------// Engine preference (Cloud vs Open source), shared across tabs via localStorage.// Settings → Engine mode can lock the install to one engine; then the toggle is disabled.+// While hosted runs are on, each account keeps its own, starting on Open source (src/lib/engine-pref.ts).-const ENGINE_KEY = "fuobe.engine";const MODE_KEY = "fuobe.engineMode";const listeners = new Set<() => void>();-function readEngine(): Engine {+function browserStorage(): Storage | null {try {- return localStorage.getItem(ENGINE_KEY) === "open" ? "open" : "cloud";+ return typeof localStorage === "undefined" ? null : localStorage;} catch {- return "cloud";+ return null;}}+/**+ * An engine for one page only, never remembered: while hosted runs are on, a note's "… in the cloud" link opens its tool+ * on Cloud for that page, and the person's own switch stays where it was. It holds on that page (its path) only, ends+ * when the studio page is left, and gives way to the person's own pick.+ */+let pageEngine: { engine: Engine; path: string } | null = null;+/** Asked by a link for the page it opens (engineForNextPage), until that page's hand-off takes it. */+let nextPageEngine: { engine: Engine; until: number } | null = null;++const herePath = (): string => (typeof location === "undefined" ? "" : location.pathname);++/** The next studio page this tab opens takes `e` for that page only, when the model it is handed runs on `e`. */+export function engineForNextPage(e: Engine): void {+ nextPageEngine = { engine: e, until: Date.now() + 15_000 };+}++/** A hand-off's model on engine `e`: true when a link asked for `e` on this page only (and that ask is used up). */+export function takeNextPageEngine(e: Engine): boolean {+ const ask = nextPageEngine;+ if (ask && Date.now() > ask.until) nextPageEngine = null;+ if (!ask || ask !== nextPageEngine || ask.engine !== e) return false;+ nextPageEngine = null;+ return true;+}++/** The page open now runs on `e`, for this page only. */+export function setPageEngine(e: Engine): void {+ pageEngine = { engine: e, path: herePath() };+ listeners.forEach((l) => l());+}++/**+ * A studio page closed: an engine for a page that is no longer open ends. (The next page may already be open when this+ * runs, with an engine of its own: that one stays.)+ */+export function leavePageEngine(): void {+ if (!pageEngine || pageEngine.path === herePath()) return;+ pageEngine = null;+ listeners.forEach((l) => l());+}++/** The engine a page reads in `slot`: this page's own, else the kept one (the browser's one switch by default). */+export function readEngine(slot: EngineSlot = SHARED_SLOT): Engine {+ const here = pageEngine && pageEngine.path === herePath() ? pageEngine.engine : null;+ return here ?? storedEngine(browserStorage(), slot);+}+function readCachedMode(): EngineMode {try {const m = localStorage.getItem(MODE_KEY);@@ -1150,8 +1203,47 @@ export function useModelAccess(): AccessSummary | undefined {return hydrated ? access : undefined;}+/**+ * Where this viewer's engine switch is kept (src/lib/engine-pref.ts): the browser's one switch, or while hosted runs+ * are on the account's own (a guest's). Remembers it for the next page, so that page opens on it before the status+ * answers.+ */+function useEngineSlot(): EngineSlot {+ const status = useStatus();+ const me = useViewer().data;+ const v = status.data?.viewer;+ const known = status.data !== undefined;+ const hosted = !!v?.hosted;+ const kind = v?.kind;+ const runOn = v?.runOn;+ const email = me?.account?.email;+ const cached = useSyncExternalStore(noopSubscribe, readCachedSlot, () => null);+ const facts: SlotFacts = { known, viewer: kind ? { kind, hosted, runOn } : undefined, email, cached };+ const slot = engineSlot(facts);+ const remember = slotToCache(facts, slot);+ useEffect(() => {+ if (remember === undefined || remember === readCachedSlot()) return;+ try {+ if (remember) localStorage.setItem(ENGINE_SLOT_KEY, remember);+ else localStorage.removeItem(ENGINE_SLOT_KEY);+ } catch {}+ }, [remember]);+ // One object per key and start, so the snapshot reader below changes only when the slot does.+ return useMemo(() => ({ key: slot.key, start: slot.start }), [slot.key, slot.start]);+}++function readCachedSlot(): string | null {+ try {+ return browserStorage()?.getItem(ENGINE_SLOT_KEY) ?? null;+ } catch {+ return null;+ }+}+export function useEngine(): [Engine, (e: Engine) => void, EngineMode] {const mode = useEngineMode();+ const slot = useEngineSlot();+ const read = useCallback(() => readEngine(slot), [slot]);const engine = useSyncExternalStore((cb) => {listeners.add(cb);@@ -1161,18 +1253,22 @@ export function useEngine(): [Engine, (e: Engine) => void, EngineMode] {window.removeEventListener("storage", cb);};},- readEngine,+ read,() => "cloud" as Engine,);const set = useCallback((e: Engine) => {if (mode !== "both") return;- try {- localStorage.setItem(ENGINE_KEY, e);- } catch {}+ // The person's own pick: remembered in their slot (an engine for this page only gives way to it).+ pageEngine = null;+ if (slot.key) {+ try {+ localStorage.setItem(slot.key, e);+ } catch {}+ } else pageEngine = { engine: e, path: herePath() };listeners.forEach((l) => l());},- [mode],+ [mode, slot],);return [mode === "both" ? engine : mode, set, mode];}@@ -1188,7 +1284,10 @@ export function useOpenEngine(): boolean {return hydrated && make3dOffered(status);}-/** Remember the engine the studios start on, before the mode allows it (an account that just added its own key: Cloud). */+/**+ * Remember the engine the studios start on, before the mode allows it (an account that just added its own key: Cloud).+ * The browser's one switch: never called while hosted runs are on, where each account keeps its own (useEngine).+ */export function preferEngine(e: Engine): void {try {localStorage.setItem(ENGINE_KEY, e);diff --git a/src/lib/before-run.ts b/src/lib/before-run.tsindex 6cd27e7f..6932cd5a 100644--- a/src/lib/before-run.ts+++ b/src/lib/before-run.ts@@ -2,12 +2,13 @@* The check before Run (public sign-up): an account whose own GPU at a web address didn't answer its last status check* (the status strip's, every 30 s; nothing here asks the GPU) sees what is wrong and its fixes above Generate, instead* of starting a run that can only wait. When one of its keys runs the tool's cloud version, "Run with your fal.ai key"- * is offered too: an explicit click, because it spends the person's own credit. Pure, for the composer and its tests.+ * is offered too: an explicit click, for that run only (the engine switch stays where it was), because it spends the+ * person's own credit. Pure, for the composer and its tests.*/import { dualEngine } from "./catalog/engines";import type { Engine, GenerationRequest } from "./catalog/types";import { withKeyAction, type Diagnosis, type TroubleAction } from "./diagnose";-import { cloudVersionKey, type CloudProvider } from "./your-keys";+import { cloudVersion, type CloudProvider } from "./your-keys";type Routed = { id: string; engine: string; engines?: Engine[]; routes: { provider: string }[] };@@ -39,7 +40,7 @@ export function gpuBeforeRun(o: {engine: Engine;/** The run goes to this studio's GPUs (hosted runs), not the account's own. */onPool?: boolean;- preset?: Parameters<typeof cloudVersionKey>[0];+ preset?: Parameters<typeof cloudVersion>[0];has: (id: string) => boolean;getModel: (id: string) => Routed | undefined;}): BeforeRun | null {@@ -49,7 +50,8 @@ export function gpuBeforeRun(o: {const toOwnGpu = dualEngine(model) ? o.engine === "open" : model.engine === "open";const gpu = viewer.gpu;if (!toOwnGpu || !gpu.connected || gpu.mode !== "link" || gpu.online !== false) return null;- const key = viewer.paidAllowed !== false ? cloudVersionKey(o.preset, model, viewer.keys ?? [], o.has, o.getModel) : null;+ // The cloud version itself (its model and operation there), so one click runs it, once.+ const twin = viewer.paidAllowed !== false ? cloudVersion(o.preset, model, viewer.keys ?? [], o.has, o.getModel) : null;const base: TroubleAction[] = gpu.trouble?.actions ?? [{ kind: "check-gpu", label: "Check my GPU" },{ kind: "gpu-settings", label: "Open Settings → Your GPU", target: "/settings#your-gpu" },@@ -57,7 +59,7 @@ export function gpuBeforeRun(o: {return {words: gpu.trouble?.words ?? GPU_OFF_WORDS,...(gpu.trouble?.details && { details: gpu.trouble.details }),- actions: [...base.filter((a) => a.kind !== "retry" && a.kind !== "run-with-key"), ...(key ? [withKeyAction(key)] : [])],+ actions: [...base.filter((a) => a.kind !== "retry" && a.kind !== "run-with-key"), ...(twin ? [withKeyAction(twin.provider, twin.modelId, twin.op)] : [])],};}diff --git a/src/lib/engine-pref.ts b/src/lib/engine-pref.tsnew file mode 100644index 00000000..34f46b54--- /dev/null+++ b/src/lib/engine-pref.ts@@ -0,0 +1,88 @@+/**+ * Where this browser keeps the studios' engine switch (Cloud / Open source), and what a studio starts on. Pure, for+ * src/lib/api.ts (useEngine) and its tests.+ *+ * Hosted runs off (every self-hosted install by default), and the owner: one switch for the browser, `fuobe.engine`,+ * starting on Cloud, as always. While runs can go to the install's own GPUs (`viewer.hosted`), open models run free+ * there, so the switch starts on Open source: each account keeps its own (a second account on the same browser keeps+ * its own too), starting on Cloud only when the account picked its key as the place for its runs (`runOn` "key"). A+ * guest keeps one for the browser. Saving a key never moves it.+ */+import type { Engine } from "./catalog/types";++/** The browser's one switch: hosted runs off, and the owner. */+export const ENGINE_KEY = "fuobe.engine";+/** The switch this browser used last while hosted runs were on, so a page opens on it before the status answers. */+export const ENGINE_SLOT_KEY = "fuobe.engineSlot";+/** An account's own switch while hosted runs are on: this, then a short tag of the account. */+export const ACCOUNT_ENGINE_PREFIX = "fuobe.engine.a.";+/** A guest's switch while hosted runs are on. */+export const GUEST_ENGINE_KEY = "fuobe.engine.guest";++export interface EngineSlot {+ /** The storage key, or null when there is none yet (an account whose email hasn't answered): the pick then lasts for the page. */+ key: string | null;+ /** What the switch starts on while nothing is kept there. */+ start: Engine;+}++/** The browser's one switch, starting on Cloud. */+export const SHARED_SLOT: EngineSlot = { key: ENGINE_KEY, start: "cloud" };++/**+ * A short tag for an account in a storage key: a hash of its email (FNV-1a), so no address is written to the browser's+ * storage. Two accounts sharing a tag would only share a switch.+ */+export function accountTag(email: string): string {+ let h = 0x811c9dc5;+ for (const ch of email.trim().toLowerCase()) {+ h ^= ch.codePointAt(0)!;+ h = Math.imul(h, 0x01000193) >>> 0;+ }+ return h.toString(36);+}++/** What the slot needs to know: the status's viewer and who is signed in. */+export interface SlotFacts {+ /** The status has answered (until then the browser's last slot is used). */+ known: boolean;+ viewer?: { kind: "guest" | "account"; hosted?: boolean; runOn?: string };+ /** The signed-in account's email (GET /api/auth/me), when it has answered. */+ email?: string | null;+ /** ENGINE_SLOT_KEY as stored. */+ cached?: string | null;+}++const isAccountKey = (k: string | null | undefined): k is string => !!k && k.startsWith(ACCOUNT_ENGINE_PREFIX) && k.length > ACCOUNT_ENGINE_PREFIX.length;+const isHostedKey = (k: string | null | undefined): k is string => k === GUEST_ENGINE_KEY || isAccountKey(k);++/** Where this viewer's switch is kept, and what it starts on. */+export function engineSlot(f: SlotFacts): EngineSlot {+ if (!f.known) return isHostedKey(f.cached) ? { key: f.cached, start: "open" } : SHARED_SLOT;+ const v = f.viewer;+ if (!v?.hosted) return SHARED_SLOT;+ if (v.kind !== "account") return { key: GUEST_ENGINE_KEY, start: "open" };+ const start: Engine = v.runOn === "key" ? "cloud" : "open";+ if (f.email) return { key: `${ACCOUNT_ENGINE_PREFIX}${accountTag(f.email)}`, start };+ return { key: isAccountKey(f.cached) ? f.cached : null, start };+}++/** The slot to remember for the next page (while hosted runs are on), null to forget it, undefined before the status answers. */+export const slotToCache = (f: SlotFacts, slot: EngineSlot): string | null | undefined => (!f.known ? undefined : f.viewer?.hosted && isHostedKey(slot.key) ? slot.key : null);++/**+ * What a saved key does to the switch the studios start on: Cloud (the person just asked for paid models), except while+ * hosted runs are on, where it stays (open models run free on the install's GPUs; Cloud is one pick away).+ */+export const engineAfterKeySave = (hosted: boolean): Engine | null => (hosted ? null : "cloud");++/** The engine kept in `slot`, or what it starts on. */+export function storedEngine(storage: Pick<Storage, "getItem"> | null | undefined, slot: EngineSlot): Engine {+ if (!slot.key || !storage) return slot.start;+ try {+ const v = storage.getItem(slot.key);+ return v === "open" || v === "cloud" ? v : slot.start;+ } catch {+ return slot.start;+ }+}diff --git a/src/lib/your-keys.ts b/src/lib/your-keys.tsindex 2e0226a8..84c57c49 100644--- a/src/lib/your-keys.ts+++ b/src/lib/your-keys.ts@@ -100,12 +100,26 @@ export function cloudVersionKey(has: (id: string) => boolean,getModel: (id: string) => Routed | undefined,): CloudProvider | null {+ return cloudVersion(preset, model, keys, has, getModel)?.provider ?? null;+}++/**+ * The tool's cloud version that one of the account's keys runs: the key, the model, and (another model) its operation+ * there. What "Run with your fal.ai key" runs, once, before Run or on a run that couldn't reach the GPU.+ */+export function cloudVersion(+ preset: Parameters<typeof presetRoutes>[0] | undefined,+ model: (Routed & { id: string }) | undefined,+ keys: readonly CloudProvider[],+ has: (id: string) => boolean,+ getModel: (id: string) => Routed | undefined,+): { provider: CloudProvider; modelId: string; op?: string } | null {if (!keys.length) return null;- const ids = preset ? presetRoutes(preset, "cloud", has).map((r) => r.modelId) : model && dualEngine(model as Parameters<typeof dualEngine>[0]) ? [model.id] : [];- for (const id of ids) {+ const routes: { modelId: string; op?: string }[] = preset ? presetRoutes(preset, "cloud", has) : model && dualEngine(model as Parameters<typeof dualEngine>[0]) ? [{ modelId: model.id }] : [];+ for (const { modelId: id, op } of routes) {const m = getModel(id);const p = m && CLOUD_PROVIDERS.find((k) => keys.includes(k) && m.routes.some((r) => r.provider === k));- if (p) return p;+ if (p) return { provider: p, modelId: id, ...(op && id !== model?.id && { op }) };}return null;}@@ -116,6 +130,13 @@ export const addKeyLabel = (p: CloudProvider) => `Add your ${CLOUD_KEY[p].label}/** "your fal.ai account": who pays for an account's paid run. */export const billedTo = (p: CloudProvider) => `your ${CLOUD_KEY[p].label} account`;+/**+ * The note after a key is saved. While hosted runs are on the studios stay on Open source (free there), so it says where+ * the paid models are. `who`: " (signed in as …)" or "".+ */+export const keySavedText = (label: string, who: string, hosted: boolean) =>+ `Your ${label} key works${who}. Paid models on ${label} are ready${hosted ? ": pick Cloud in the model list to use them." : "."}`;+/** "fal.ai and Replicate" */const names = (ps: readonly CloudProvider[]) => ps.map((p) => CLOUD_KEY[p].label).join(" and ");diff --git a/tests/e2e/byo-keys.mjs b/tests/e2e/byo-keys.mjsindex 04a3d468..081f750a 100644--- a/tests/e2e/byo-keys.mjs+++ b/tests/e2e/byo-keys.mjs@@ -6,11 +6,13 @@// node tests/e2e/byo-keys.mjs [screenshots folder]//// BYO_PORT moves all three (app, fal.ai, Replicate on the next two ports) when 3390–3392 are taken.+// BYO_HOSTED=1 runs it with hosted runs on (FUOBE_HOSTED_RUNS, free, no billing service).//// Checks: the owner's runs send the owner's key; an account without a key can't run a paid model; an account adds a-// bad key (refused) and a good one; its paid run sends only its key; removing the key with a run going asks first and-// stops the run with that key; no key shows in any answer, page or server log. Screenshots: Settings → Your keys and-// the model picker, on a phone and a desktop.+// bad key (refused) and a good one; saving it moves the studios to Cloud (hosted: leaves them on Open source, where+// open models run free); its paid run sends only its key; removing the key with a run going asks first and stops the+// run with that key; no key shows in any answer, page or server log. Screenshots: Settings → Your keys and the model+// picker, on a phone and a desktop.import { spawn, execSync } from "node:child_process";import fs from "node:fs";import os from "node:os";@@ -20,6 +22,7 @@ import { startFakeFal, startFakeReplicate } from "../helpers/fake-cloud.ts";import { tempDir, removeDir } from "./_temp.mjs";const APP_PORT = Number(process.env.BYO_PORT ?? 3390);+const HOSTED = process.env.BYO_HOSTED === "1";const APP = `http://127.0.0.1:${APP_PORT}`;const shots = path.resolve(process.argv[2] ?? fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-byo-shots-")));fs.mkdirSync(shots, { recursive: true });@@ -59,6 +62,7 @@ const server = spawn(process.execPath, [path.join(root, "node_modules/next/dist/FUOBE_DEV_REPLICATE_URL: rep.url,COMFYUI_URL: "http://127.0.0.1:9",FUOBE_ACCOUNT_DISK_FREE_GB: "0",+ ...(HOSTED ? { FUOBE_HOSTED_RUNS: "1", FUOBE_HOSTED_FREE: "1" } : { FUOBE_HOSTED_RUNS: "", FUOBE_HOSTED_FREE: "" }),},stdio: ["ignore", log, log],});@@ -138,7 +142,7 @@ try {// The Image studio: the switch is locked on open source, pointing at Your keys.await page.goto("/image", { waitUntil: "load", timeout: 180_000 });await page.waitForTimeout(2500);- const lockedSwitch = page.getByRole("link", { name: /Open source only/ }).first();+ const lockedSwitch = page.getByRole("link", { name: /^Open source\b/ }).first();check((await lockedSwitch.getAttribute("href").catch(() => null)) === "/settings#your-keys", "the engine switch is locked on open source, linking to Your keys");// Settings → Your keys: a bad key, then a good one.@@ -155,6 +159,9 @@ try {await page.getByRole("button", { name: "Check and save" }).first().click();await page.getByText("Key ending in").waitFor({ timeout: 30_000 });check((await page.content()).includes("9f3a"), "a good key is saved and shown by its last 4 characters");+ const shared = await page.evaluate(() => localStorage.getItem("fuobe.engine"));+ if (HOSTED) check(shared !== "cloud", `saving a key leaves the studios where they were (${shared})`);+ else check(shared === "cloud", `saving a key moves the studios to Cloud (${shared})`);await shootKeys(page, "your-keys-saved-desktop.png");readable.push(await page.content());@@ -163,6 +170,8 @@ try {await page.waitForTimeout(2500);const radio = page.getByRole("radiogroup", { name: "Engine" }).first();check(await radio.isVisible().catch(() => false), "with a key, the engine switch switches");+ const startsOn = await radio.getByRole("radio", { checked: true }).first().getAttribute("aria-label").catch(() => null);+ check(HOSTED ? /Open/.test(startsOn ?? "") : /Cloud/.test(startsOn ?? ""), `the studio starts on ${HOSTED ? "Open source" : "Cloud"} (${startsOn})`);await page.getByRole("radio", { name: "Cloud" }).first().click().catch(() => {});// The price shows once there is something to run.await page.locator("textarea").first().fill("a quiet harbour at dawn");diff --git a/tests/engine-mode.test.ts b/tests/engine-mode.test.tsindex 417ba84c..e400576a 100644--- a/tests/engine-mode.test.ts+++ b/tests/engine-mode.test.ts@@ -1,4 +1,5 @@-import { beforeAll, describe, expect, it } from "vitest";+import { readFileSync } from "node:fs";+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";import { tempDir } from "./helpers/temp-dir";// Isolated database for this file (must be set before the server modules load).@@ -8,7 +9,12 @@ process.env.COMFYUI_URL = "http://127.0.0.1:9"; // nothing listens here → openconst { setSetting, getSetting, validateSetting } = await import("@/server/settings");const { chooseRoute, createGenerations, previewGeneration } = await import("@/server/generations");-const { getModel } = await import("@/lib/catalog");+const { getModel, getPreset } = await import("@/lib/catalog");+const pref = await import("@/lib/engine-pref");+const api = await import("@/lib/api");+const { gpuBeforeRun, onCloudKey } = await import("@/lib/before-run");+const { withKeyAction } = await import("@/lib/diagnose");+const { keySavedText } = await import("@/lib/your-keys");beforeAll(() => setSetting("demoMode", "auto"));@@ -69,3 +75,145 @@ describe("routes that take fewer images or can't batch", () => {setSetting("replicateToken", "");});});++/** A browser's storage, for the engine switch's slots. */+function memoryStorage(seed: Record<string, string> = {}) {+ const m = new Map(Object.entries(seed));+ return {+ getItem: (k: string) => m.get(k) ?? null,+ setItem: (k: string, v: string) => void m.set(k, String(v)),+ removeItem: (k: string) => void m.delete(k),+ clear: () => m.clear(),+ key: (i: number) => [...m.keys()][i] ?? null,+ get length() {+ return m.size;+ },+ map: m,+ };+}++describe("the engine switch a studio starts on", () => {+ const known = (viewer: { kind: "guest" | "account"; hosted?: boolean; runOn?: string } | undefined, email?: string | null) => ({ known: true, viewer, email });+ afterEach(() => vi.unstubAllGlobals());++ it("hosted runs off: the browser's one switch, starting on Cloud, as always (the owner too)", () => {+ for (const facts of [known(undefined), known({ kind: "account" }, "[email protected]"), known({ kind: "guest" }), { known: false }]) {+ expect(pref.engineSlot(facts)).toEqual({ key: "fuobe.engine", start: "cloud" });+ expect(pref.slotToCache(facts, pref.engineSlot(facts))).toBe(facts.known ? null : undefined);+ }+ vi.stubGlobal("localStorage", memoryStorage());+ expect(api.readEngine()).toBe("cloud");+ localStorage.setItem("fuobe.engine", "open");+ expect(api.readEngine()).toBe("open");+ localStorage.setItem("fuobe.engine", "something else");+ expect(api.readEngine()).toBe("cloud");+ });++ it("hosted: an account starts on Open source, kept for that account; a second account on the browser keeps its own", () => {+ const ana = pref.engineSlot(known({ kind: "account", hosted: true }, "[email protected]"));+ const bo = pref.engineSlot(known({ kind: "account", hosted: true }, "[email protected]"));+ expect(ana.start).toBe("open");+ expect(ana.key).toMatch(/^fuobe\.engine\.a\.[0-9a-z]+$/);+ expect(ana.key).not.toContain("ana");+ expect(bo.key).not.toBe(ana.key);+ // Same account, whatever the case or spaces of its email.+ expect(pref.engineSlot(known({ kind: "account", hosted: true }, " [email protected] ")).key).toBe(ana.key);+ const storage = memoryStorage({ "fuobe.engine": "cloud" });+ vi.stubGlobal("localStorage", storage);+ // The browser's old switch on Cloud doesn't carry over: open models run free on the install's GPUs.+ expect(api.readEngine(ana)).toBe("open");+ storage.setItem(ana.key!, "cloud");+ expect(api.readEngine(ana)).toBe("cloud");+ expect(api.readEngine(bo)).toBe("open");+ expect(api.readEngine()).toBe("cloud");+ });++ it("hosted: an account whose remembered place is its key starts on Cloud", () => {+ expect(pref.engineSlot(known({ kind: "account", hosted: true, runOn: "key" }, "[email protected]")).start).toBe("cloud");+ for (const runOn of ["site", "gpu", undefined]) expect(pref.engineSlot(known({ kind: "account", hosted: true, runOn }, "[email protected]")).start).toBe("open");+ });++ it("hosted: a guest starts on Open source; a page opens on the last slot before the status answers", () => {+ const guest = pref.engineSlot(known({ kind: "guest", hosted: true }));+ expect(guest).toEqual({ key: "fuobe.engine.guest", start: "open" });+ const ana = pref.engineSlot(known({ kind: "account", hosted: true }, "[email protected]"));+ expect(pref.slotToCache(known({ kind: "account", hosted: true }, "[email protected]"), ana)).toBe(ana.key);+ expect(pref.engineSlot({ known: false, cached: ana.key })).toEqual({ key: ana.key, start: "open" });+ expect(pref.engineSlot({ known: false, cached: "fuobe.engine.guest" })).toEqual(guest);+ // Anything else stored there is not a slot.+ expect(pref.engineSlot({ known: false, cached: "fuobe.engine" })).toEqual(pref.SHARED_SLOT);+ expect(pref.engineSlot({ known: false, cached: "fuobe.engine.a." })).toEqual(pref.SHARED_SLOT);+ // The account's email not answered yet: the last account slot, or none.+ expect(pref.engineSlot({ known: true, viewer: { kind: "account", hosted: true }, cached: ana.key })).toEqual({ key: ana.key, start: "open" });+ expect(pref.engineSlot({ known: true, viewer: { kind: "account", hosted: true }, cached: "fuobe.engine.guest" })).toEqual({ key: null, start: "open" });+ // Hosted runs switched off again: forgotten.+ expect(pref.slotToCache(known({ kind: "account" }, "[email protected]"), pref.SHARED_SLOT)).toBeNull();+ });++ it("saving a key moves the switch to Cloud only while hosted runs are off", () => {+ expect(pref.engineAfterKeySave(false)).toBe("cloud");+ expect(pref.engineAfterKeySave(true)).toBeNull();+ expect(keySavedText("fal.ai", "", false)).toBe("Your fal.ai key works. Paid models on fal.ai are ready.");+ expect(keySavedText("Replicate", " (signed in as ana)", false)).toBe("Your Replicate key works (signed in as ana). Paid models on Replicate are ready.");+ expect(keySavedText("fal.ai", "", true)).toBe("Your fal.ai key works. Paid models on fal.ai are ready: pick Cloud in the model list to use them.");+ // Settings → Your keys asks this, and writes the browser's one switch only with its answer.+ const keys = readFileSync("src/components/keys/your-keys.tsx", "utf8");+ expect(keys).toMatch(/const engine = engineAfterKeySave\(hosted\);\s+if \(engine\) preferEngine\(engine\);/);+ expect(keys.match(/preferEngine\(/g)).toHaveLength(1);+ });++ it("hosted: the key rescue runs once on the cloud version and leaves the switch where it was", () => {+ const storage = memoryStorage();+ vi.stubGlobal("localStorage", storage);+ const ana = pref.engineSlot(known({ kind: "account", hosted: true }, "[email protected]"));+ const gpu = { connected: true, mode: "link" as const, online: false };+ const viewer = { kind: "account" as const, gpu, keys: ["fal" as const], paidAllowed: true, hosted: true };+ const h3 = getModel("oss-minimax-h3")!;+ const fpv = getPreset("motion-fpv-drone")!;+ const down = gpuBeforeRun({ viewer, model: h3, engine: "open", preset: fpv, has: (id) => !!getModel(id), getModel })!;+ const rescue = down.actions.find((a) => a.kind === "run-with-key")!;+ expect(rescue).toEqual(withKeyAction("fal", "minimax-h3", "i2v"));+ const request = { feature: "video", modelId: h3.id, engine: "open" as const, prompt: "a fast pass over the cliffs", params: { extra: { graph: 1 } } };+ expect(onCloudKey(request as never, rescue)).toEqual({ feature: "video", modelId: "minimax-h3", engine: "cloud", op: "i2v", prompt: "a fast pass over the cliffs", params: {} });+ // Nothing was written: the next run starts on the switch as it was.+ expect(storage.map.size).toBe(0);+ expect(api.readEngine(ana)).toBe("open");+ // The composer: while hosted, the press sends this run on the key; the switch moves to Cloud only with hosted runs off.+ const composer = readFileSync("src/components/studio/composer.tsx", "utf8");+ expect(composer).toMatch(/const onRunWithKey = viewerInfo\?\.hosted\s+\? \(a: TroubleAction\) => submitRef\.current\(undefined, a\)\s+: \(\) => \{\s+setEngine\("cloud"\);\s+setCloudRun\(true\);/);+ expect(composer).toMatch(/const onKey = withKey \? onCloudKey\(withVoiceFirst, withKey\) : withVoiceFirst;/);+ expect(composer).toMatch(/onClick=\{\(\) => \(viewerInfo\?\.hosted \? engineForNextPage\("cloud"\) : setEngine\("cloud"\)\)\}/);+ });++ it("hosted: a link's page opens on Cloud for that page only", () => {+ const storage = memoryStorage();+ vi.stubGlobal("localStorage", storage);+ const here = { pathname: "/export" };+ vi.stubGlobal("location", here);+ const ana = pref.engineSlot(known({ kind: "account", hosted: true }, "[email protected]"));+ // Nothing asked: a hand-off's model moves the person's own switch, as always.+ expect(api.takeNextPageEngine("cloud")).toBe(false);+ api.engineForNextPage("cloud");+ expect(api.takeNextPageEngine("open")).toBe(false);+ here.pathname = "/upscale/hdr";+ expect(api.takeNextPageEngine("cloud")).toBe(true);+ expect(api.takeNextPageEngine("cloud")).toBe(false);+ api.setPageEngine("cloud");+ expect(api.readEngine(ana)).toBe("cloud");+ // The page that closed is the one left behind: nothing ends while this one is open.+ api.leavePageEngine();+ expect(api.readEngine(ana)).toBe("cloud");+ here.pathname = "/video";+ expect(api.readEngine(ana)).toBe("open");+ api.leavePageEngine();+ here.pathname = "/upscale/hdr";+ expect(api.readEngine(ana)).toBe("open");+ expect(storage.map.size).toBe(0);+ // An ask nobody took runs out.+ vi.useFakeTimers({ toFake: ["Date"] });+ api.engineForNextPage("cloud");+ vi.setSystemTime(Date.now() + 16_000);+ expect(api.takeNextPageEngine("cloud")).toBe(false);+ vi.useRealTimers();+ });+});diff --git a/tests/own-graceful-ui.test.ts b/tests/own-graceful-ui.test.tsindex 7812f152..dd17ce22 100644--- a/tests/own-graceful-ui.test.ts+++ b/tests/own-graceful-ui.test.ts@@ -41,7 +41,8 @@ describe("the check before Run", () => {it("offers the tool's cloud version on the account's own key, an explicit button", () => {const withFal = gpuBeforeRun({ viewer: account(offline, ["fal"]), model: h3, engine: "open", preset: fpv, has, getModel })!;- expect(withFal.actions.at(-1)).toEqual(withKeyAction("fal"));+ // The cloud version itself (its model and operation there), so one click runs it, once.+ expect(withFal.actions.at(-1)).toEqual(withKeyAction("fal", "minimax-h3", "i2v"));expect(withFal.actions.at(-1)?.label).toBe("Run with your fal.ai key");// FPV Drone's cloud versions are on fal.ai only: a Replicate token runs none of them.expect(gpuBeforeRun({ viewer: account(offline, ["replicate"]), model: h3, engine: "open", preset: fpv, has, getModel })!.actions.map((a) => a.kind)).not.toContain("run-with-key");diff --git a/tests/self-host-unchanged.test.ts b/tests/self-host-unchanged.test.tsindex 4f64bfee..442e550c 100644--- a/tests/self-host-unchanged.test.ts+++ b/tests/self-host-unchanged.test.ts@@ -221,4 +221,24 @@ describe("a self-hosted install with hosted runs off", () => {expect(JSON.stringify(s.viewer)).not.toMatch(/placeName|runOn|prefer|hosted|"pool"/);}});++ it("the engine switch: the browser's one switch, Cloud with nothing stored, and a saved key moves it to Cloud", async () => {+ const { engineSlot, engineAfterKeySave, SHARED_SLOT } = await import("@/lib/engine-pref");+ const { readEngine } = await import("@/lib/api");+ const a = auth.createAccount("[email protected]", "long enough");+ for (const s of [await visitorStatus(a), await visitorStatus(null)]) {+ expect(engineSlot({ known: true, viewer: s.viewer, email: "[email protected]" })).toEqual(SHARED_SLOT);+ }+ expect(engineSlot({ known: true })).toEqual(SHARED_SLOT);+ const stored = new Map<string, string>();+ vi.stubGlobal("localStorage", { getItem: (k: string) => stored.get(k) ?? null, setItem: (k: string, v: string) => void stored.set(k, v), removeItem: (k: string) => void stored.delete(k) });+ try {+ expect(readEngine()).toBe("cloud");+ stored.set("fuobe.engine", "open");+ expect(readEngine()).toBe("open");+ } finally {+ vi.unstubAllGlobals();+ }+ expect(engineAfterKeySave(false)).toBe("cloud");+ });});