Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

Engine switch: both sides for guests and accounts, with a Cloud panel

Adarshf23f30dcbfce
diff --git a/src/app/providers.tsx b/src/app/providers.tsx
index baaecd2d..56eb07c7 100644
--- a/src/app/providers.tsx
+++ b/src/app/providers.tsx
@@ -7,6 +7,7 @@ import dynamic from "next/dynamic";
import { GuestPrompt } from "@/components/guest-prompt";
import { DeleteForGoodHost } from "@/components/studio/delete-for-good";
import { AddKeyPrompt } from "@/components/keys/your-keys";
+import { CloudPanel } from "@/components/keys/cloud-panel";
import { toast } from "sonner";
import { AUTH_CHANNEL, takeNotice, type ViewerInfo } from "@/lib/api";
@@ -60,6 +61,7 @@ export function Providers({ children }: { children: React.ReactNode }) {
<GuestPrompt />
<DeleteForGoodHost />
<AddKeyPrompt />
+ <CloudPanel />
<BillingCard />
<GuidedFixHost />
<ComputerRunnerHost />
diff --git a/src/components/keys/cloud-panel.tsx b/src/components/keys/cloud-panel.tsx
new file mode 100644
index 00000000..db329774
--- /dev/null
+++ b/src/components/keys/cloud-panel.tsx
@@ -0,0 +1,78 @@
+"use client";
+
+import { Cloud, Cpu } from "lucide-react";
+import { useEffect, useState } from "react";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { VendorMark } from "@/components/studio/vendor-mark";
+import { askToSignUp, useStatus } from "@/lib/api";
+import { addProviderKeyLabel, CLOUD_PANEL_EVENT, CLOUD_PANEL_STAY_EVENT, CLOUD_SHOWCASE, cloudPanelWords, panelProviders, visitorEngine, type CloudPanelAsk } from "@/lib/engine-ux";
+import { openAddKey } from "./your-keys";
+
+/**
+ * "Cloud models": what a visitor without a key reads when it chooses Cloud (the engine switch, a Cloud model in a
+ * picker, the one-time hint). It names a few Cloud models and why, says they run on the visitor's own fal.ai or
+ * Replicate key and are billed there, and opens the add-key flow (a guest is asked to sign up first). The switch stays
+ * on Open source until a key is saved. Mounted once, in the app's providers.
+ */
+export function CloudPanel() {
+ const [ask, setAsk] = useState<CloudPanelAsk | null>(null);
+ const engine = visitorEngine(useStatus().data);
+ useEffect(() => {
+ const open = (e: Event) => setAsk((e as CustomEvent<CloudPanelAsk>).detail ?? {});
+ window.addEventListener(CLOUD_PANEL_EVENT, open);
+ return () => window.removeEventListener(CLOUD_PANEL_EVENT, open);
+ }, []);
+ const stay = () => {
+ setAsk(null);
+ window.dispatchEvent(new Event(CLOUD_PANEL_STAY_EVENT));
+ };
+ if (!engine) return null;
+ const words = cloudPanelWords(engine.place, ask?.modelName);
+ const add = (p: Parameters<typeof openAddKey>[0]) => {
+ const modelId = ask?.modelId;
+ setAsk(null);
+ if (engine.guest) return askToSignUp("run");
+ openAddKey(p, modelId);
+ };
+ const providers = panelProviders(ask?.served);
+ return (
+ <Dialog open={!!ask} onOpenChange={(o) => !o && stay()}>
+ <DialogContent data-cloud-panel="" className="gap-0 overflow-hidden p-0 sm:max-w-[420px]">
+ <DialogHeader className="gap-1.5 px-5 pt-5 pb-4 text-left">
+ <span aria-hidden className="mb-1.5 grid size-10 place-items-center rounded-xl bg-primary text-primary-foreground">
+ <Cloud className="size-5" />
+ </span>
+ <DialogTitle className="font-heading text-[20px] leading-tight font-normal">{words.title}</DialogTitle>
+ <DialogDescription className="text-[13px] leading-relaxed">{words.lead}</DialogDescription>
+ </DialogHeader>
+ <ul className="mx-5 divide-y rounded-xl border" aria-label="Some Cloud models">
+ {CLOUD_SHOWCASE.map((m) => (
+ <li key={m.id} className="flex items-start gap-3 px-3 py-2.5">
+ <VendorMark vendor={m.vendor} engine="cloud" />
+ <span className="min-w-0">
+ <span className="block text-[13px] leading-snug font-medium">{m.name}</span>
+ <span className="block text-[12px] leading-snug text-muted-foreground">{m.why}</span>
+ </span>
+ </li>
+ ))}
+ </ul>
+ <p className="mx-5 mt-2 text-[12px] text-muted-foreground">{words.more}</p>
+ <div className="mt-4 flex flex-col gap-2 border-t bg-muted/40 px-5 pt-4 pb-5">
+ <div className={providers.length > 1 ? "grid gap-2 sm:grid-cols-2" : "grid"}>
+ {providers.map((p, i) => (
+ <Button key={p} variant={i === 0 ? "default" : "secondary"} className="h-10 rounded-full" onClick={() => add(p)}>
+ {addProviderKeyLabel(p)}
+ </Button>
+ ))}
+ </div>
+ <Button variant="ghost" className="h-10 gap-1.5 rounded-full" onClick={stay}>
+ <Cpu className="size-4" aria-hidden />
+ {words.stay}
+ </Button>
+ <p className="text-center text-[12px] text-muted-foreground">{words.stayNote}</p>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/src/components/studio/engine-switch.tsx b/src/components/studio/engine-switch.tsx
index ffd6217f..34dc8fc3 100644
--- a/src/components/studio/engine-switch.tsx
+++ b/src/components/studio/engine-switch.tsx
@@ -2,10 +2,15 @@
import { Cloud, Cpu, Lock } from "lucide-react";
import Link from "next/link";
-import { openAddKey } from "@/components/keys/your-keys";
+import { useEffect, useRef, useState } from "react";
+import { Popover as PopoverPrimitive } from "radix-ui";
+import { KEY_ADDED_EVENT, openAddKey } from "@/components/keys/your-keys";
+import { Button } from "@/components/ui/button";
+import { Popover, PopoverAnchor, PopoverContent } from "@/components/ui/popover";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import type { Engine } from "@/lib/catalog/types";
import { useEngineMode, useHydrated, useStatus, useViewer } from "@/lib/api";
+import { CLOUD_KEYLESS_TIP, CLOUD_PANEL_STAY_EVENT, engineCaption, engineHintKey, engineHintText, openCloudPanel, visitorEngine, visitorEngineLabel, visitorPick, type VisitorEngine } from "@/lib/engine-ux";
import { placeOf, type Place } from "@/lib/place-name";
import { accountEngine } from "@/lib/your-keys";
import { cn } from "@/lib/utils";
@@ -33,6 +38,8 @@ export function engineTip(value: Engine, account: ReturnType<typeof accountEngin
* `wordless`: no "Add key" on a phone either, in a header that has no room for it (the lock and the label still say it).
* `selfHostedOnly`: a tool that runs on a self-hosted Fuobe only (its page says so to a guest or an account), where
* anyone but the owner gets a plain badge: no way to Your GPU or a key, which wouldn't run it.
+ * A guest or an account while open models run free on this install's GPUs gets both sides, always (VisitorSwitch);
+ * `hint`: a studio's own switch, where an account without a key reads a one-time hint about Cloud.
*/
export function EngineSwitch({
value,
@@ -41,6 +48,7 @@ export function EngineSwitch({
compact = size === "md",
wordless,
selfHostedOnly,
+ hint,
}: {
value: Engine;
onChange: (e: Engine) => void;
@@ -48,6 +56,7 @@ export function EngineSwitch({
compact?: boolean;
wordless?: boolean;
selfHostedOnly?: boolean;
+ hint?: boolean;
}) {
const mode = useEngineMode();
// Until hydrated, the server's switch (as useEngineMode): a viewer or status that lands mid-hydration must not change it.
@@ -61,6 +70,23 @@ export function EngineSwitch({
const locked = account && "locked" in account ? account.locked : null;
// Hosted runs: open models run free on this studio's GPUs, said with their place name (a guest's tip too).
const place = hydrated && status?.viewer?.hosted ? placeOf(status.viewer.placeName) : null;
+ // A guest or an account while hosted runs are on: both sides, always, with what each costs (the owner and a
+ // self-hosted install keep the switch below exactly as it was).
+ const visitor = hydrated && !owner && !selfHostedOnly ? visitorEngine(status) : null;
+ if (visitor)
+ return (
+ <VisitorSwitch
+ value={value}
+ onChange={onChange}
+ size={size}
+ compact={compact}
+ wordless={wordless}
+ visitor={visitor}
+ mode={mode}
+ account={account}
+ hintFor={hint && !visitor.guest && visitor.keyless ? viewer?.account?.email : undefined}
+ />
+ );
const idx = OPTIONS.findIndex((o) => o.value === value);
if (mode !== "both" || locked) {
// One engine and nothing to change: only the owner (Settings) or an account that can add a key gets a badge.
@@ -159,3 +185,202 @@ export function EngineSwitch({
</div>
);
}
+
+/** A visitor's sides: Open source first (free there), then Cloud (its own key). */
+const VISITOR_ORDER: Engine[] = ["open", "cloud"];
+
+/**
+ * A guest's or an account's switch while hosted runs are on: "Open source" with "Free · {place}" under it, and "Cloud"
+ * with "Your key" (and a lock while it has none). Without a key, Cloud opens the Cloud panel and the switch stays on
+ * Open source (a run there would fail); once a key is saved from that panel, the switch moves to Cloud by itself.
+ */
+function VisitorSwitch({
+ value,
+ onChange,
+ size,
+ compact,
+ wordless,
+ visitor,
+ mode,
+ account,
+ hintFor,
+}: {
+ value: Engine;
+ onChange: (e: Engine) => void;
+ size: "sm" | "md";
+ compact: boolean;
+ wordless?: boolean;
+ visitor: VisitorEngine;
+ mode: string;
+ account: ReturnType<typeof accountEngine>;
+ hintFor?: string;
+}) {
+ const { keyless, place } = visitor;
+ // The panel was opened from this switch: a key saved there (for no model in particular) moves it to Cloud.
+ const asked = useRef(false);
+ const moveToCloud = useRef(false);
+ useEffect(() => {
+ const added = (e: Event) => {
+ if (asked.current && !(e as CustomEvent<{ modelId?: string }>).detail?.modelId) moveToCloud.current = true;
+ asked.current = false;
+ };
+ const stayed = () => (asked.current = false);
+ window.addEventListener(KEY_ADDED_EVENT, added);
+ window.addEventListener(CLOUD_PANEL_STAY_EVENT, stayed);
+ return () => {
+ window.removeEventListener(KEY_ADDED_EVENT, added);
+ window.removeEventListener(CLOUD_PANEL_STAY_EVENT, stayed);
+ };
+ }, []);
+ // (The status answers with the key, the engine mode turns "both", and the switch can move.)
+ useEffect(() => {
+ if (!moveToCloud.current || mode !== "both") return;
+ moveToCloud.current = false;
+ onChange("cloud");
+ }, [mode, onChange]);
+ const showCloud = () => {
+ asked.current = true;
+ openCloudPanel();
+ };
+ const shown: Engine = keyless ? "open" : value;
+ const idx = VISITOR_ORDER.indexOf(shown);
+ // A phone keeps a short caption under each icon, unless the header has no room for words at all.
+ const phoneWords = compact && !wordless;
+ const control = (
+ <div
+ role="radiogroup"
+ aria-label="Engine"
+ data-engine-switch="visitor"
+ onKeyDown={radioKeys}
+ className={cn("relative inline-grid shrink-0 grid-cols-2 rounded-full bg-muted p-0.5", size === "sm" ? "h-9" : "h-9 sm:h-10")}
+ >
+ <span
+ aria-hidden
+ className="absolute inset-y-0.5 left-0.5 w-[calc(50%-2px)] rounded-full bg-background shadow-soft transition-transform duration-300 ease-move"
+ style={{ transform: `translateX(${idx * 100}%)` }}
+ />
+ {VISITOR_ORDER.map((side) => {
+ const o = OPTIONS.find((x) => x.value === side)!;
+ const on = shown === side;
+ const caption = side === "open" ? engineCaption.open(place) : engineCaption.cloud;
+ const short = side === "open" ? "Free" : "Key";
+ return (
+ <Tooltip key={side}>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ role="radio"
+ aria-checked={on}
+ tabIndex={radioTab(on)}
+ aria-label={visitorEngineLabel(side, visitor)}
+ onClick={() => {
+ const to = visitorPick(side, visitor);
+ if (to === "panel") showCloud();
+ else onChange(to);
+ }}
+ className={cn(
+ "relative z-10 flex min-w-0 flex-col justify-center gap-[3px] rounded-full leading-none transition-colors",
+ compact ? "items-center px-2.5 sm:items-start sm:px-4" : "items-start px-4",
+ on ? "text-foreground" : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ <span className="flex items-center gap-1.5 text-[13px] font-medium whitespace-nowrap">
+ <o.icon className="size-3.5" />
+ <span className={cn(compact && "hidden sm:inline")}>{o.label}</span>
+ </span>
+ <span
+ className={cn(
+ "flex max-w-[9.5rem] items-center gap-1 text-[10.5px] font-medium whitespace-nowrap",
+ side === "open" ? "text-success" : "text-muted-foreground",
+ compact && !phoneWords && "max-sm:hidden",
+ )}
+ >
+ {side === "cloud" && keyless && <Lock className="size-2.5 shrink-0" aria-hidden />}
+ {phoneWords && <span className="sm:hidden">{short}</span>}
+ <span className={cn("truncate", phoneWords && "max-sm:hidden")}>{caption}</span>
+ </span>
+ </button>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-72">
+ <span>
+ <span className="font-medium">{o.label}</span> · {side === "cloud" && keyless ? CLOUD_KEYLESS_TIP : engineTip(side, account, place)}
+ </span>
+ </TooltipContent>
+ </Tooltip>
+ );
+ })}
+ </div>
+ );
+ return hintFor ? (
+ <EngineHint email={hintFor} place={place} onSee={showCloud}>
+ {control}
+ </EngineHint>
+ ) : (
+ control
+ );
+}
+
+/**
+ * The one-time hint by a studio's switch, for an account without a key: open models are free there, and Cloud is one
+ * key away. Closed for good (in this browser, for this account) by either button, Esc, or a tap outside.
+ */
+function EngineHint({ email, place, onSee, children }: { email: string; place: Place; onSee: () => void; children: React.ReactNode }) {
+ const key = engineHintKey(email);
+ const [open, setOpen] = useState(false);
+ useEffect(() => {
+ let seen = true;
+ try {
+ seen = localStorage.getItem(key) === "1";
+ } catch {}
+ // A moment after the page settles, so it points at the switch where it ends up.
+ const t = seen ? undefined : setTimeout(() => setOpen(true), 600);
+ return () => clearTimeout(t);
+ }, [key]);
+ const close = () => {
+ setOpen(false);
+ try {
+ localStorage.setItem(key, "1");
+ } catch {}
+ };
+ const words = engineHintText(place);
+ return (
+ <Popover open={open} onOpenChange={(o) => !o && close()}>
+ <PopoverAnchor asChild>
+ <span className="inline-flex shrink-0" onClickCapture={() => open && close()}>
+ {children}
+ </span>
+ </PopoverAnchor>
+ <PopoverContent
+ role="note"
+ data-engine-hint=""
+ side="bottom"
+ align="end"
+ sideOffset={10}
+ collisionPadding={12}
+ onOpenAutoFocus={(e) => e.preventDefault()}
+ className="w-[min(18rem,calc(100vw-24px))] gap-3 rounded-xl p-3.5 shadow-strong"
+ >
+ <PopoverPrimitive.Arrow width={14} height={7} className="fill-popover" />
+ <p className="text-[13px] leading-snug">
+ <span className="font-medium">{words.lead}</span> <span className="text-muted-foreground">{words.rest}</span>
+ </p>
+ <div className="flex justify-end gap-1.5">
+ <Button
+ variant="secondary"
+ size="sm"
+ className="rounded-full"
+ onClick={() => {
+ close();
+ onSee();
+ }}
+ >
+ {words.see}
+ </Button>
+ <Button size="sm" className="rounded-full" onClick={close}>
+ {words.ok}
+ </Button>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/src/components/studio/hub-chrome.tsx b/src/components/studio/hub-chrome.tsx
index 4fe73cb7..7d576842 100644
--- a/src/components/studio/hub-chrome.tsx
+++ b/src/components/studio/hub-chrome.tsx
@@ -197,7 +197,7 @@ export const HUB_SKELETON_AFTER_MS = 60;
function HubEngine({ kind, mode }: { kind: HubKind; mode: string | undefined }) {
const [engine, setEngine] = useEngine();
const selfHostedOnly = !!HUB_MODES[kind].find((m) => m.id === mode)?.selfHostedOnly;
- return <EngineSwitch value={engine} onChange={setEngine} selfHostedOnly={selfHostedOnly} />;
+ return <EngineSwitch value={engine} onChange={setEngine} selfHostedOnly={selfHostedOnly} hint />;
}
/**
diff --git a/src/components/studio/model-picker.tsx b/src/components/studio/model-picker.tsx
index 1042fdfe..5353cc23 100644
--- a/src/components/studio/model-picker.tsx
+++ b/src/components/studio/model-picker.tsx
@@ -24,6 +24,7 @@ import { cn } from "@/lib/utils";
import { ownSetupLabel } from "@/lib/own-setup";
import { answerPickModel } from "@/lib/pick-model";
import { addKeyLabel, billedTo, CLOUD_KEY, CLOUD_PROVIDERS, needsKey, type CloudProvider } from "@/lib/your-keys";
+import { CLOUD_SECTION_LABEL, cloudModelAsk, openCloudPanel, visitorEngine } from "@/lib/engine-ux";
import { EngineSwitch } from "./engine-switch";
import { ResponsivePanel } from "./responsive-panel";
import { RECENT_MODELS, STARRED_MODELS, useStoredList } from "./stored-list";
@@ -295,18 +296,20 @@ export function ModelPicker(props: PickerProps) {
<PickerList
{...props}
onPicked={() => setOpen(false)}
- onNeedsKey={(m, p) => {
+ onNeedsKey={(m, p, served) => {
waiting.current = m.id;
setOpen(false);
- openAddKey(p, m.id);
+ // While open models run free here, the Cloud panel first: what Cloud is, then the key it needs.
+ if (cloudModelAsk(status) === "panel") openCloudPanel({ modelId: m.id, modelName: m.name, served });
+ else openAddKey(p, m.id);
}}
/>
</ResponsivePanel>
);
}
-/** The searchable list (mounted by the popover / sheet only while it shows). */
-function PickerList({
+/** The searchable list (mounted by the popover / sheet only while it shows; exported for tests). */
+export function PickerList({
models,
value,
onChange,
@@ -321,7 +324,7 @@ function PickerList({
ownSetup,
onPicked,
onNeedsKey,
-}: PickerProps & { onPicked: () => void; onNeedsKey?: (m: ModelDef, p: CloudProvider) => void }) {
+}: PickerProps & { onPicked: () => void; onNeedsKey?: (m: ModelDef, p: CloudProvider, served: CloudProvider[]) => void }) {
const [q, setQ] = useState("");
const status = useStatus().data;
const badges = useGpuBadges().data;
@@ -360,7 +363,9 @@ function PickerList({
() => (keyless && !engines.includes("cloud") ? (groupModels({ models, engine: "cloud", engines: ["cloud"], query: q, recent: [], starred: [], best: [] }).groups[0]?.models ?? []) : []),
[keyless, q, engines, models],
);
- const listed = paid.length ? [...groups, { id: "paid" as const, label: "Paid models · with your own key", models: paid }] : groups;
+ // While open models run free here, the section says which side it is: Cloud, on the visitor's own key.
+ const hostedVisitor = !!visitorEngine(status);
+ const listed = paid.length ? [...groups, { id: "paid" as const, label: hostedVisitor ? CLOUD_SECTION_LABEL : "Paid models · with your own key", models: paid }] : groups;
// The key a paid row needs: an account's (needsKey), or for a guest the providers that serve it.
const rowNeeds = (m: ModelDef): CloudProvider[] | null => {
if (!guest) return needsKey(m, status);
@@ -369,12 +374,13 @@ function PickerList({
return served.length ? served : null;
};
const pick = (m: ModelDef) => {
- if (guest && rowNeeds(m)) {
+ // A guest while open models run free here reads the Cloud panel first (its buttons ask to sign up).
+ if (guest && rowNeeds(m) && !(hostedVisitor && onNeedsKey)) {
onPicked();
return askToSignUp("run");
}
- const needs = needsKey(m, status);
- if (needs && onNeedsKey) return onNeedsKey(m, needs[0]);
+ const needs = guest ? rowNeeds(m) : needsKey(m, status);
+ if (needs && onNeedsKey) return onNeedsKey(m, needs[0], needs);
onChange(m);
onPicked();
};
diff --git a/src/components/studio/studio-page.tsx b/src/components/studio/studio-page.tsx
index dbf44a7e..8606c0fa 100644
--- a/src/components/studio/studio-page.tsx
+++ b/src/components/studio/studio-page.tsx
@@ -478,7 +478,7 @@ function StudioHeader({ title, header, tabs }: { title: string; header?: React.R
<div className="ml-auto flex shrink-0 items-center gap-2">
{header}
<StudioGpuPill />
- <EngineSwitch value={engine} onChange={setEngine} />
+ <EngineSwitch value={engine} onChange={setEngine} hint />
</div>
<PhoneNavButton />
</header>
diff --git a/src/lib/engine-ux.ts b/src/lib/engine-ux.ts
new file mode 100644
index 00000000..9426dbf1
--- /dev/null
+++ b/src/lib/engine-ux.ts
@@ -0,0 +1,112 @@
+import { placeOf, type Place } from "./place-name";
+import { CLOUD_KEY, CLOUD_PROVIDERS, type CloudProvider, type KeyStatus } from "./your-keys";
+
+/**
+ * How a visitor (a guest or an account) sees the two engines while open models run free on this install's GPUs: both
+ * sides always show, Open source first ("Free · {place}"), Cloud second ("Your key"). Cloud runs on the visitor's own
+ * fal.ai or Replicate key; without one, choosing Cloud opens a panel that says what Cloud models are and how to add a
+ * key, and the switch stays on Open source. The owner, and every visitor while hosted runs are off (a self-hosted
+ * install), keep the switch as it was (src/components/studio/engine-switch.tsx).
+ */
+
+export interface VisitorEngine {
+ /** Where open models run free. */
+ place: Place;
+ /** Signed out: acting (adding a key) asks to sign up first. */
+ guest: boolean;
+ /** No key of its own yet: Cloud opens the panel, never the switch. */
+ keyless: boolean;
+ /** The providers it has a key for. */
+ keys: CloudProvider[];
+}
+
+/** A guest's or an account's engines while hosted runs are on and paid models are allowed; null for everyone else. */
+export function visitorEngine(s: KeyStatus | undefined): VisitorEngine | null {
+ const v = s?.viewer;
+ if (!v || (v.kind !== "account" && v.kind !== "guest") || !v.hosted || v.paidAllowed === false) return null;
+ const keys = v.kind === "account" ? (v.keys ?? []) : [];
+ return { place: placeOf(v.placeName), guest: v.kind === "guest", keyless: !keys.length, keys };
+}
+
+/** What choosing a side does: Cloud without a key opens the Cloud panel and leaves the switch where it is. */
+export const visitorPick = (side: "open" | "cloud", e: VisitorEngine): "open" | "cloud" | "panel" => (side === "cloud" && e.keyless ? "panel" : side);
+
+/** What a picker does with a Cloud model the visitor has no key for: the Cloud panel while hosted runs are on, else "Add your key" as before. */
+export const cloudModelAsk = (s: KeyStatus | undefined): "panel" | "add-key" => (visitorEngine(s) ? "panel" : "add-key");
+
+/** The small line under each side's name. */
+export const engineCaption = {
+ open: (place: Place) => `Free · ${place.label}`,
+ cloud: "Your key",
+} as const;
+
+/** The Cloud side's tooltip while the visitor has no key. */
+export const CLOUD_KEYLESS_TIP = "Frontier paid models on your own fal.ai or Replicate key";
+
+/** A side's name for a screen reader, with its caption. */
+export function visitorEngineLabel(side: "open" | "cloud", e: VisitorEngine): string {
+ if (side === "open") return `Open source, free on ${e.place.text}`;
+ return e.keyless ? "Cloud, needs your own key" : "Cloud, on your own key";
+}
+
+/** A few Cloud models by name, each with why someone would pick it (checked against the model list in tests). */
+export const CLOUD_SHOWCASE: readonly { id: string; name: string; vendor: string; why: string }[] = [
+ { id: "nano-banana-pro", name: "Nano Banana Pro", vendor: "Google", why: "Clean text in pictures, and edits from several photos, up to 4K." },
+ { id: "gpt-image-2-5", name: "GPT Image 2.5 Flare", vendor: "OpenAI", why: "Exact layouts, and edits that follow long instructions." },
+ { id: "veo-3-1", name: "Veo 3.1", vendor: "Google", why: "Real-looking video with sound and speech." },
+ { id: "kling-4", name: "Kling 4.0", vendor: "Kuaishou", why: "Takes of 3 to 30 seconds, with several shots." },
+];
+
+/** The Cloud panel's words. `model`: the Cloud model it was opened for, if any. */
+export function cloudPanelWords(place: Place, model?: string) {
+ return {
+ title: model ? `${model} is a Cloud model` : "Cloud models",
+ lead: "Paid frontier models from Google, OpenAI, Kuaishou and more. They run on your own fal.ai or Replicate key, and that service bills you for each run.",
+ more: "Many more are in each studio's model list.",
+ stay: "Stay on Open source (free)",
+ stayNote: `Open source models run free on ${place.text}.`,
+ } as const;
+}
+
+/** "Add a fal.ai key" / "Add a Replicate key": the panel's buttons, which open the add-key flow. */
+export const addProviderKeyLabel = (p: CloudProvider) => `Add a ${CLOUD_KEY[p].label} key`;
+
+/** The providers a panel offers: the ones that serve its model (fal.ai first), else both. */
+export const panelProviders = (served?: readonly CloudProvider[] | null): CloudProvider[] =>
+ served?.length ? CLOUD_PROVIDERS.filter((p) => served.includes(p)) : [...CLOUD_PROVIDERS];
+
+/** The one-time hint for an account that has no key yet, the first time it opens a studio. */
+export const engineHintText = (place: Place) => ({
+ lead: `Free open-source models run on ${place.text}.`,
+ rest: "Want frontier models? Switch to Cloud with your own key.",
+ ok: "Got it",
+ see: "See Cloud models",
+});
+
+/** The picker's section of Cloud models for a visitor without a key. */
+export const CLOUD_SECTION_LABEL = "Cloud · your key";
+
+/** Where the browser remembers that an account closed the hint: one key per account (its email, hashed). */
+export function engineHintKey(email: string): string {
+ let h = 5381;
+ for (const c of email.trim().toLowerCase()) h = ((h * 33) ^ c.charCodeAt(0)) >>> 0;
+ return `fuobe:engine-hint:${h.toString(36)}`;
+}
+
+/** Event that opens the Cloud panel (mounted once, in the app's providers). */
+export const CLOUD_PANEL_EVENT = "fuobe:cloud-panel";
+
+/** Sent when the panel closes without a key ("Stay on Open source", Esc, the close button). */
+export const CLOUD_PANEL_STAY_EVENT = "fuobe:cloud-panel-stay";
+
+export interface CloudPanelAsk {
+ /** The Cloud model it opened for (picked once a key is saved), with its name and the providers that serve it. */
+ modelId?: string;
+ modelName?: string;
+ served?: CloudProvider[];
+}
+
+/** Open the Cloud panel. */
+export function openCloudPanel(ask: CloudPanelAsk = {}): void {
+ window.dispatchEvent(new CustomEvent<CloudPanelAsk>(CLOUD_PANEL_EVENT, { detail: ask }));
+}
diff --git a/tests/engine-ux.test.ts b/tests/engine-ux.test.ts
new file mode 100644
index 00000000..71e3683a
--- /dev/null
+++ b/tests/engine-ux.test.ts
@@ -0,0 +1,243 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { createElement, type ReactNode } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { StatusInfo, ViewerInfo } from "@/lib/api";
+
+/*
+ * The engine switch for a guest or an account while open models run free on this install's GPUs: both sides always
+ * show ("Open source" with "Free · {place}", then "Cloud" with "Your key"); Cloud without a key opens the Cloud panel
+ * and the switch stays on Open source; with a key it switches. The model picker lists Cloud models in their own
+ * section ("Cloud · your key"), and a one-time hint points at the switch. The owner's switch is the one it always was
+ * (a self-hosted install's: tests/self-host-unchanged.test.ts and its golden files).
+ */
+
+const state = vi.hoisted(() => ({
+ viewer: undefined as ViewerInfo | undefined,
+ status: undefined as StatusInfo | undefined,
+ mode: "both" as "both" | "open" | "cloud",
+}));
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ prefetch: () => {}, push: () => {}, replace: () => {}, back: () => {}, refresh: () => {} }),
+ usePathname: () => "/image",
+ useSearchParams: () => new URLSearchParams(),
+}));
+vi.mock("@/lib/api", async (load) => ({
+ ...(await load<typeof import("@/lib/api")>()),
+ useHydrated: () => true,
+ useViewer: () => ({ data: state.viewer }),
+ useStatus: () => ({ data: state.status }),
+ useEngineMode: () => state.mode,
+}));
+
+const { EngineSwitch } = await import("@/components/studio/engine-switch");
+const { PickerList } = await import("@/components/studio/model-picker");
+const { TooltipProvider } = await import("@/components/ui/tooltip");
+const { getModel } = await import("@/lib/catalog");
+const { CLOUD_MODELS } = await import("@/lib/catalog/cloud-models.generated");
+const ux = await import("@/lib/engine-ux");
+const { placeOf } = await import("@/lib/place-name");
+
+const PLACE = placeOf("Studio North GPUs");
+/** Words no visitor reads about runs on this install's GPUs (as tests/hosted-words.test.ts). */
+const FORBIDDEN = /studio's GPUs|\bworkers?\b|\blanes?\b|\btickets?\b|\bpool\b|\bhosted\b|\bqueue|\bcatalog|Press Retry|Try again later|isn't available here|Not available here|not checked|unverified|ComfyUI/i;
+
+const render = (node: ReactNode) => renderToStaticMarkup(createElement(QueryClientProvider, { client: new QueryClient() }, createElement(TooltipProvider, null, node)));
+const textOf = (html: string) => html.replace(/<[^>]+>/g, " ").replace(/&#x27;/g, "'").replace(/&amp;/g, "&").replace(/\s+/g, " ").trim();
+/** The radio buttons in order: their label and whether checked. */
+const radios = (html: string) => [...html.matchAll(/role="radio" aria-checked="(true|false)"[^>]*aria-label="([^"]+)"/g)].map((m) => ({ label: m[2], checked: m[1] === "true" }));
+
+const ownerViewer: ViewerInfo = { signedIn: true, owner: true, publicSignup: true };
+const accountViewer: ViewerInfo = { signedIn: true, owner: false, publicSignup: true, account: { email: "[email protected]" } };
+const guestViewer: ViewerInfo = { signedIn: false, owner: false, publicSignup: true };
+
+function hostedStatus(v: Partial<NonNullable<StatusInfo["viewer"]>> = {}, engineMode: "open" | "both" = "open"): StatusInfo {
+ return {
+ providers: { comfyui: { label: "Your GPU", configured: true } },
+ demoMode: "off",
+ engineMode,
+ cloudProvider: "auto",
+ onboarded: true,
+ viewer: { kind: "account", gpu: { connected: false }, keys: [], paidAllowed: true, hosted: true, placeName: PLACE.label, ...v },
+ } as StatusInfo;
+}
+const ownerStatus = { providers: { comfyui: { label: "ComfyUI", configured: true } }, demoMode: "off", engineMode: "both", cloudProvider: "auto", onboarded: true } as StatusInfo;
+
+const sw = (value: "open" | "cloud" = "open", more: Record<string, unknown> = {}) => render(createElement(EngineSwitch, { value, onChange: () => {}, ...more }));
+
+beforeEach(() => {
+ state.viewer = accountViewer;
+ state.status = hostedStatus();
+ state.mode = "open";
+});
+
+describe("an account with no key of its own", () => {
+ it("sees both sides, Open source first and free on the place, Cloud with its key and a lock", () => {
+ const html = sw();
+ expect(html).toContain('data-engine-switch="visitor"');
+ expect(radios(html)).toEqual([
+ { label: "Open source, free on Studio North GPUs", checked: true },
+ { label: "Cloud, needs your own key", checked: false },
+ ]);
+ const text = textOf(html);
+ // A phone reads an icon and a short word under it ("Free", "Key"); a wider screen the name and the full line.
+ expect(text).toContain("Open source Free Free · Studio North GPUs");
+ expect(text).toContain("Cloud Key Your key");
+ expect(html).toMatch(/class="sm:hidden">Free</);
+ expect(html).toMatch(/class="sm:hidden">Key</);
+ expect(html).toMatch(/aria-label="Cloud, needs your own key"[\s\S]*lucide-lock/);
+ expect(text).not.toMatch(FORBIDDEN);
+ });
+
+ it("choosing Cloud opens the Cloud panel and the switch stays on Open source", () => {
+ const e = ux.visitorEngine(state.status)!;
+ expect(ux.visitorPick("cloud", e)).toBe("panel");
+ expect(ux.visitorPick("open", e)).toBe("open");
+ // Whatever engine the page asks for, the switch shows Open source until a key exists.
+ expect(radios(sw("cloud"))[0]).toEqual({ label: "Open source, free on Studio North GPUs", checked: true });
+ });
+
+ it("a header with no room for words keeps the icons only on a phone, and the lock", () => {
+ const html = sw("open", { wordless: true });
+ expect(html).not.toMatch(/class="sm:hidden">Free</);
+ expect(html).toContain("lucide-lock");
+ });
+
+ it("a studio open source only (no Cloud at all): the switch as it was", () => {
+ state.status = hostedStatus({ paidAllowed: false });
+ expect(ux.visitorEngine(state.status)).toBeNull();
+ expect(sw()).not.toContain("data-engine-switch");
+ });
+});
+
+describe("an account with its own key", () => {
+ it("switches between both sides", () => {
+ state.status = hostedStatus({ keys: ["fal"] }, "both");
+ state.mode = "both";
+ const e = ux.visitorEngine(state.status)!;
+ expect(e.keyless).toBe(false);
+ expect(ux.visitorPick("cloud", e)).toBe("cloud");
+ expect(radios(sw("cloud"))).toEqual([
+ { label: "Open source, free on Studio North GPUs", checked: false },
+ { label: "Cloud, on your own key", checked: true },
+ ]);
+ expect(sw("cloud")).not.toContain("lucide-lock");
+ });
+});
+
+describe("a guest", () => {
+ it("sees the same two sides (acting asks to sign up)", () => {
+ state.viewer = guestViewer;
+ state.status = hostedStatus({ kind: "guest", keys: undefined });
+ const html = sw();
+ expect(radios(html).map((r) => r.label)).toEqual(["Open source, free on Studio North GPUs", "Cloud, needs your own key"]);
+ expect(ux.visitorEngine(state.status)).toMatchObject({ guest: true, keyless: true });
+ });
+});
+
+describe("the owner, and visitors while hosted runs are off", () => {
+ it("the owner keeps the switch as it was: Cloud first, no captions", () => {
+ state.viewer = ownerViewer;
+ state.status = ownerStatus;
+ state.mode = "both";
+ const html = sw();
+ expect(html).not.toContain("data-engine-switch");
+ expect(radios(html)).toEqual([
+ { label: "Cloud", checked: false },
+ { label: "Open source", checked: true },
+ ]);
+ expect(textOf(html)).not.toContain("Free");
+ expect(ux.visitorEngine(state.status)).toBeNull();
+ expect(ux.cloudModelAsk(state.status)).toBe("add-key");
+ });
+
+ it("an account while hosted runs are off: no visitor switch, the add-key flow as before", () => {
+ state.status = hostedStatus({ hosted: false, placeName: undefined });
+ expect(ux.visitorEngine(state.status)).toBeNull();
+ expect(sw()).not.toContain("data-engine-switch");
+ expect(ux.cloudModelAsk(state.status)).toBe("add-key");
+ });
+
+ it("a tool for a self-hosted Fuobe only keeps its plain badge", () => {
+ expect(sw("open", { selfHostedOnly: true })).not.toContain("data-engine-switch");
+ });
+});
+
+describe("the model picker", () => {
+ const open = getModel("oss-z-image-turbo")!;
+ const cloud = getModel("nano-banana-pro")!;
+ const list = () =>
+ render(createElement(PickerList, { models: [open, cloud], value: open, onChange: () => {}, engine: "open", onEngineChange: () => {}, onPicked: () => {}, onNeedsKey: () => {} }));
+
+ it("lists Cloud models under the open ones, labelled, each selectable with what it needs", () => {
+ const html = list();
+ const text = textOf(html);
+ expect(text).toContain(ux.CLOUD_SECTION_LABEL);
+ expect(text.indexOf(open.name)).toBeLessThan(text.indexOf(ux.CLOUD_SECTION_LABEL));
+ expect(text.indexOf(ux.CLOUD_SECTION_LABEL)).toBeLessThan(text.indexOf(cloud.name));
+ expect(html).toContain(`aria-label="${cloud.name} needs your fal.ai key"`);
+ expect(ux.cloudModelAsk(state.status)).toBe("panel");
+ });
+
+ it("for a guest too", () => {
+ state.viewer = guestViewer;
+ state.status = hostedStatus({ kind: "guest", keys: undefined });
+ expect(textOf(list())).toContain(ux.CLOUD_SECTION_LABEL);
+ });
+
+ it("keeps its old section name while hosted runs are off", () => {
+ state.status = hostedStatus({ hosted: false, placeName: undefined });
+ const text = textOf(list());
+ expect(text).toContain("Paid models · with your own key");
+ expect(text).not.toContain(ux.CLOUD_SECTION_LABEL);
+ });
+});
+
+describe("the words", () => {
+ it("the Cloud panel names real Cloud models, by their names and makers", () => {
+ expect(ux.CLOUD_SHOWCASE.length).toBeGreaterThanOrEqual(3);
+ expect(ux.CLOUD_SHOWCASE.length).toBeLessThanOrEqual(4);
+ for (const s of ux.CLOUD_SHOWCASE) {
+ const m = CLOUD_MODELS.find((x) => x.id === s.id);
+ expect(m, s.id).toBeDefined();
+ expect(m).toMatchObject({ name: s.name, vendor: s.vendor, engine: "cloud" });
+ expect(s.why.length, s.id).toBeLessThanOrEqual(70);
+ }
+ });
+
+ it("are plain, short, say the place by its name, and never name the machinery", () => {
+ for (const place of [PLACE, placeOf(null)]) {
+ const panel = ux.cloudPanelWords(place);
+ const hint = ux.engineHintText(place);
+ expect(panel.stay).toBe("Stay on Open source (free)");
+ expect(panel.lead).toContain("fal.ai or Replicate key");
+ expect(panel.lead).toMatch(/bills you/);
+ expect(ux.cloudPanelWords(place, "Veo 3.1").title).toBe("Veo 3.1 is a Cloud model");
+ expect(ux.addProviderKeyLabel("fal")).toBe("Add a fal.ai key");
+ expect(ux.addProviderKeyLabel("replicate")).toBe("Add a Replicate key");
+ expect(`${hint.lead} ${hint.rest}`).toBe(`Free open-source models run on ${place.text}. Want frontier models? Switch to Cloud with your own key.`);
+ expect(ux.engineCaption.open(place)).toBe(`Free · ${place.label}`);
+ const all = [...Object.values(panel), ...Object.values(hint), ux.engineCaption.open(place), ux.engineCaption.cloud, ux.CLOUD_KEYLESS_TIP, ux.CLOUD_SECTION_LABEL, ...ux.CLOUD_SHOWCASE.map((s) => s.why)];
+ for (const w of all) {
+ expect(w, w).not.toMatch(FORBIDDEN);
+ // Short sentences: none over 25 words.
+ for (const sentence of w.split(/(?<=\.)\s/)) expect(sentence.split(/\s+/).length, sentence).toBeLessThanOrEqual(25);
+ }
+ // The product names stay: the sides are "Open source" and "Cloud".
+ expect(all.join(" ")).not.toMatch(/\b(Paid side|Premium|Pro side|Open-weight)\b/);
+ }
+ });
+
+ it("a panel opened for a model offers only the keys that run it", () => {
+ expect(ux.panelProviders(["replicate"])).toEqual(["replicate"]);
+ expect(ux.panelProviders(["replicate", "fal"])).toEqual(["fal", "replicate"]);
+ expect(ux.panelProviders()).toEqual(["fal", "replicate"]);
+ });
+
+ it("the hint is remembered per account", () => {
+ expect(ux.engineHintKey("[email protected]")).toBe(ux.engineHintKey(" [email protected] "));
+ expect(ux.engineHintKey("[email protected]")).not.toBe(ux.engineHintKey("[email protected]"));
+ expect(ux.engineHintKey("[email protected]")).not.toContain("ana");
+ });
+});