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.

Your keys: Settings, the add-key dialog, the picker, the engine switch and prices

Adarsh9936444f4172
diff --git a/src/app/(studio)/settings/page.tsx b/src/app/(studio)/settings/page.tsx
index e9293779..4cfa611f 100644
--- a/src/app/(studio)/settings/page.tsx
+++ b/src/app/(studio)/settings/page.tsx
@@ -1,6 +1,7 @@
import type { Metadata } from "next";
import { AccountsAdmin } from "@/components/accounts-admin";
import { AccountGpuSection } from "@/components/gpu/account-gpu-section";
+import { AccountKeysSection } from "@/components/keys/your-keys";
import { OwnerSettings, SettingsIntro } from "@/components/owner-settings";
import { PageHeader, PageShell } from "@/components/page-shell";
import { SettingsForm } from "@/components/settings-form";
@@ -9,12 +10,14 @@ import { starterPriceLine } from "@/lib/starter-prices";
export const metadata: Metadata = { title: "Settings" };
export default function Page() {
+ const prices = starterPriceLine();
return (
<PageShell>
<PageHeader title="Settings" description={<SettingsIntro />} />
<AccountGpuSection />
+ <AccountKeysSection prices={prices} />
<OwnerSettings>
- <SettingsForm prices={starterPriceLine()} />
+ <SettingsForm prices={prices} />
</OwnerSettings>
<AccountsAdmin />
</PageShell>
diff --git a/src/app/providers.tsx b/src/app/providers.tsx
index 97afe4a6..2cc768d1 100644
--- a/src/app/providers.tsx
+++ b/src/app/providers.tsx
@@ -5,6 +5,7 @@ import { ThemeProvider } from "next-themes";
import { useEffect, useState } from "react";
import dynamic from "next/dynamic";
import { GuestPrompt } from "@/components/guest-prompt";
+import { AddKeyPrompt } from "@/components/keys/your-keys";
import { AUTH_CHANNEL } from "@/lib/api";
/** The GPU pre-flight's guided fix: loaded after the page, listening for "fuobe:gpu-setup". */
@@ -42,6 +43,7 @@ export function Providers({ children }: { children: React.ReactNode }) {
{children}
<Toaster position="top-center" gap={8} offset={29} />
<GuestPrompt />
+ <AddKeyPrompt />
<GuidedFixHost />
<ComputerRunnerHost />
</TooltipProvider>
diff --git a/src/components/accounts-admin.tsx b/src/components/accounts-admin.tsx
index a5b931e9..2310e648 100644
--- a/src/components/accounts-admin.tsx
+++ b/src/components/accounts-admin.tsx
@@ -19,6 +19,8 @@ export interface AccountRow {
lastLoginAt: number | null;
disabled: boolean;
gpu: boolean;
+ /** The providers it added its own key for (Your keys): never a key. */
+ keys?: ("fal" | "replicate")[];
/** Runs: all time, the last 24 hours and 7 days, going now, failed in the last 7 days. */
runs: number;
runsDay: number;
@@ -159,7 +161,8 @@ export function AccountsAdmin() {
{total} {total === 1 ? "person has" : "people have"} signed up (Settings → Security → Public sign-up).{" "}
</>
)}
- Accounts never see your library or use your keys and GPU. What they make stays out of your library: see it here.
+ Accounts never see your library or use your keys and GPU: they run on their own GPU or their own fal.ai or Replicate key. What they make stays out of your
+ library: see it here.
</p>
</div>
{!q.data ? (
@@ -205,6 +208,7 @@ export function AccountsAdmin() {
<th className="px-3 py-2 font-medium">Last run</th>
<th className="px-3 py-2 font-medium">Space</th>
<th className="px-3 py-2 font-medium">GPU</th>
+ <th className="px-3 py-2 font-medium">Keys</th>
<th className="px-3 py-2 font-medium max-2xl:hidden">Created</th>
<th className="px-3 py-2 font-medium max-2xl:hidden">Last login</th>
{/* The actions stay in view when the table is wider than its box (a long email, a phone); what's under them fades out. */}
@@ -233,6 +237,9 @@ export function AccountsAdmin() {
{storageSize(a.bytes)} of {storageSize(a.capBytes)}
</td>
<td className="px-3 py-2">{a.gpu ? "Connected" : "—"}</td>
+ <td className="px-3 py-2 whitespace-nowrap" title="Runs paid models on its own key. Fuobe never shows the key.">
+ {a.keys?.length ? a.keys.map((k) => (k === "fal" ? "fal.ai" : "Replicate")).join(", ") : "None"}
+ </td>
<td className="px-3 py-2 whitespace-nowrap max-2xl:hidden">{timeAgo(a.createdAt)}</td>
<td className="px-3 py-2 whitespace-nowrap max-2xl:hidden">{a.lastLoginAt ? timeAgo(a.lastLoginAt) : "—"}</td>
<td className="sticky right-0 bg-background px-2 py-1 text-right whitespace-nowrap before:pointer-events-none before:absolute before:inset-y-0 before:right-full before:w-4 before:bg-linear-to-l before:from-background">
diff --git a/src/components/guest-prompt.tsx b/src/components/guest-prompt.tsx
index dca0c830..9ba60e95 100644
--- a/src/components/guest-prompt.tsx
+++ b/src/components/guest-prompt.tsx
@@ -9,7 +9,8 @@ import type { FindReason } from "@/components/gpu/computer-runner";
import { takeGpuRetry } from "@/hooks/use-gpu";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
-import { CONNECT_GPU_EVENT, GUEST_PROMPT_EVENT, refusalCard, signInHref, watchGuestRefusals, type RefusalCard } from "@/lib/api";
+import { CONNECT_GPU_EVENT, GUEST_PROMPT_EVENT, refusalCard, signInHref, useStatus, watchGuestRefusals, type RefusalCard } from "@/lib/api";
+import { CLOUD_KEY } from "@/lib/your-keys";
/**
* The cards a public studio shows when something is refused (watchGuestRefusals): "Create a free
@@ -31,6 +32,7 @@ export function GuestPrompt() {
setOpen(false);
setRetry(null);
}, []);
+ const viewer = useStatus().data?.viewer;
useEffect(() => {
watchGuestRefusals();
const show = (kind: RefusalCard["kind"]) => {
@@ -70,6 +72,22 @@ export function GuestPrompt() {
</div>
<DialogTitle>{TITLES[reason ?? "run"]}</DialogTitle>
<DialogDescription>Fuobe runs this on the ComfyUI on your computer. It&apos;s free and private.</DialogDescription>
+ {/* Paid models run on the account's own key instead (Your keys), when the studio allows them. */}
+ {viewer?.kind === "account" && viewer.paidAllowed !== false && (
+ <p className="text-[13px] text-muted-foreground">
+ {viewer.keys?.length ? (
+ `Or switch to Cloud to use your ${viewer.keys.map((k) => CLOUD_KEY[k].label).join(" or ")} key.`
+ ) : (
+ <>
+ Or{" "}
+ <Link href="/settings#your-keys" onClick={close} className="text-brand-text underline underline-offset-4">
+ add your own fal.ai or Replicate key
+ </Link>{" "}
+ to use paid models.
+ </>
+ )}
+ </p>
+ )}
</DialogHeader>
<ConnectChoice
fromRun={!!retry}
diff --git a/src/components/keys/your-keys.tsx b/src/components/keys/your-keys.tsx
new file mode 100644
index 00000000..2bf5faba
--- /dev/null
+++ b/src/components/keys/your-keys.tsx
@@ -0,0 +1,365 @@
+"use client";
+
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { AlertTriangle, Check, ExternalLink, KeyRound, Loader2 } from "lucide-react";
+import Link from "next/link";
+import { useEffect, useId, useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { ADD_KEY_EVENT, preferEngine, useViewer } from "@/lib/api";
+import { settingProblem } from "@/lib/connections";
+import { CLOUD_KEY, CLOUD_PROVIDERS, OPEN_ONLY_MESSAGE, type CloudProvider, type KeyInfo, type YourKeys } from "@/lib/your-keys";
+import { cn } from "@/lib/utils";
+
+/**
+ * "Your keys" (public sign-up): an account's own fal.ai key and Replicate token, so it runs paid models billed to its
+ * own account with that provider, never to this studio. The server checks a key with the provider, stores it encrypted
+ * and only ever shows its last 4 characters (src/app/api/account/keys). Settings shows the section; "Add your key" opens
+ * from a dimmed model, a run the server refused (x-fuobe-add-key) or a link (openAddKey).
+ */
+
+/** After a key is saved from the dialog: { provider, modelId? }, so the picker can pick the model it was opened for. */
+export const KEY_ADDED_EVENT = "fuobe:key-added";
+
+/** Open "Add your key" for a provider (and the model it is for, picked once the key is saved). */
+export function openAddKey(provider: CloudProvider, modelId?: string): void {
+ window.dispatchEvent(new CustomEvent(ADD_KEY_EVENT, { detail: { provider, modelId } }));
+}
+
+class KeyError extends Error {
+ constructor(
+ message: string,
+ readonly status: number,
+ readonly body: { code?: string; count?: number },
+ ) {
+ super(message);
+ }
+}
+
+async function call<T>(url: string, method: string, body?: unknown): Promise<T> {
+ const res = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
+ const j = (await res.json().catch(() => ({}))) as T & { error?: string; code?: string; count?: number };
+ if (!res.ok) throw new KeyError(j.error ?? `Request failed (${res.status})`, res.status, j);
+ return j;
+}
+
+export function useYourKeys(enabled = true) {
+ return useQuery({ queryKey: ["account-keys"], queryFn: () => call<YourKeys>("/api/account/keys", "GET"), enabled });
+}
+
+/** What changes once a key is added or removed: the pickers, the engine switch, the prices. */
+function useKeysChanged() {
+ const qc = useQueryClient();
+ return () => {
+ void qc.invalidateQueries({ queryKey: ["account-keys"] });
+ void qc.invalidateQueries({ queryKey: ["status"] });
+ void qc.invalidateQueries({ queryKey: ["models"] });
+ };
+}
+
+const day = (t: number) => new Date(t).toLocaleDateString(undefined, { day: "numeric", month: "short" });
+
+/** "2 runs are using this key now…": stop them and go on, or keep the key. */
+function RunsGoing({ message, action, busy, onGo, onKeep }: { message: string; action: string; busy: boolean; onGo: () => void; onKeep: () => void }) {
+ return (
+ <div role="alert" className="grid gap-2 rounded-lg bg-highlight/20 p-3 text-[13px]">
+ <p>{message}</p>
+ <div className="flex flex-wrap gap-2">
+ <Button size="sm" variant="destructive" onClick={onGo} disabled={busy}>
+ {busy && <Loader2 className="animate-spin" />}
+ {action}
+ </Button>
+ <Button size="sm" variant="secondary" onClick={onKeep} disabled={busy}>
+ Keep it
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+/**
+ * The field that takes a key: "Get a key ↗", a gentle hint when it doesn't look like one (the provider has the last
+ * word), "Check and save". Replacing a key runs are going on asks first.
+ */
+function KeyForm({ provider, replacing, onSaved, onCancel, autoFocus }: { provider: CloudProvider; replacing?: boolean; onSaved: (info: KeyInfo) => void; onCancel?: () => void; autoFocus?: boolean }) {
+ const p = CLOUD_KEY[provider];
+ const id = useId();
+ const changed = useKeysChanged();
+ const [key, setKey] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [going, setGoing] = useState<string | null>(null);
+ const hint = settingProblem(p.setting, key);
+
+ const save = async (stopRuns = false) => {
+ setBusy(true);
+ setError(null);
+ try {
+ const r = await call<KeyInfo & { detail?: 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");
+ changed();
+ const who = provider === "replicate" && r.detail?.startsWith("Signed in as ") ? ` (${r.detail.replace("Signed in as ", "signed in as ")})` : "";
+ toast.success(`Your ${p.label} key works${who}. Paid models on ${p.label} are ready.`);
+ onSaved(r);
+ } catch (e) {
+ const k = e as KeyError;
+ if (k.body?.code === "runs-going") setGoing(k.message);
+ else setError(k.message);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <form
+ className="grid gap-2"
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (key.trim()) void save();
+ }}
+ >
+ <div className="flex items-baseline justify-between gap-3">
+ <Label htmlFor={id} className="text-[13px]">
+ {p.field}
+ </Label>
+ <a href={p.keysUrl} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-[12px] text-brand-text hover:underline">
+ {p.getKey} <ExternalLink className="size-3" />
+ </a>
+ </div>
+ <Input
+ id={id}
+ type="password"
+ autoComplete="off"
+ spellCheck={false}
+ placeholder={p.placeholder}
+ value={key}
+ readOnly={busy}
+ autoFocus={autoFocus}
+ aria-invalid={!!error}
+ aria-describedby={`${id}-help`}
+ onChange={(e) => {
+ setKey(e.target.value);
+ setError(null);
+ }}
+ />
+ <div id={`${id}-help`} className="grid gap-1 text-[12px]" aria-live="polite">
+ {hint && !error && <p className="text-muted-foreground">{hint}</p>}
+ {error && <p className="text-destructive">{error}</p>}
+ </div>
+ {going ? (
+ <RunsGoing message={going} action="Stop runs and replace" busy={busy} onGo={() => void save(true)} onKeep={() => setGoing(null)} />
+ ) : (
+ <div className="flex flex-wrap gap-2">
+ <Button type="submit" size="sm" disabled={busy || !key.trim()}>
+ {busy ? <Loader2 className="animate-spin" /> : <KeyRound />}
+ {busy ? "Checking…" : replacing ? "Check and replace" : "Check and save"}
+ </Button>
+ {onCancel && (
+ <Button type="button" size="sm" variant="ghost" onClick={onCancel} disabled={busy}>
+ Cancel
+ </Button>
+ )}
+ </div>
+ )}
+ </form>
+ );
+}
+
+/** One provider in Settings → Your keys: the field, or the saved key (its last 4 characters) with Replace and Remove. */
+function KeyCard({ provider, info }: { provider: CloudProvider; info: KeyInfo | null }) {
+ const p = CLOUD_KEY[provider];
+ const changed = useKeysChanged();
+ const [replacing, setReplacing] = useState(false);
+ const [confirm, setConfirm] = useState<null | { going?: string }>(null);
+ const [busy, setBusy] = useState(false);
+
+ const remove = async (stopRuns: boolean) => {
+ setBusy(true);
+ try {
+ await call(`/api/account/keys/${provider}`, "DELETE", stopRuns ? { stopRuns: true } : {});
+ setConfirm(null);
+ changed();
+ toast.success(`Your ${p.label} key is removed from this studio.`);
+ } catch (e) {
+ const k = e as KeyError;
+ if (k.body?.code === "runs-going") setConfirm({ going: k.message });
+ else toast.error(k.message);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <div className="grid gap-3 rounded-xl border p-4">
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0">
+ <h3 className="text-[14px] font-medium">{p.label}</h3>
+ <p className="text-[12px] text-muted-foreground">{p.blurb}</p>
+ </div>
+ {info?.readable && !info.rejectedAt && (
+ <span className="inline-flex shrink-0 items-center gap-1 rounded-full bg-emerald-500/10 px-2 py-0.5 text-[12px] font-medium text-emerald-700 dark:text-emerald-400">
+ <Check className="size-3" /> Ready
+ </span>
+ )}
+ </div>
+ {info && !replacing ? (
+ <>
+ <p className="text-[13px]">
+ {info.readable ? (
+ <>
+ <span className="font-medium">{provider === "replicate" ? "Token" : "Key"} ending in </span>
+ <code className="rounded bg-muted px-1 font-mono text-[12px]">{info.last4}</code>
+ <span className="text-muted-foreground"> · added {day(info.addedAt)}</span>
+ </>
+ ) : (
+ <span className="inline-flex items-start gap-1.5 text-destructive">
+ <AlertTriangle className="mt-0.5 size-3.5 shrink-0" /> This key can&apos;t be read on this studio any more. Add it again.
+ </span>
+ )}
+ </p>
+ {info.readable && info.rejectedAt && (
+ <p className="inline-flex items-start gap-1.5 text-[13px] text-destructive">
+ <AlertTriangle className="mt-0.5 size-3.5 shrink-0" />
+ {p.label} stopped accepting this key on {day(info.rejectedAt)}. Replace it, or remove it.
+ </p>
+ )}
+ {confirm ? (
+ confirm.going ? (
+ <RunsGoing message={confirm.going} action="Stop runs and remove" busy={busy} onGo={() => void remove(true)} onKeep={() => setConfirm(null)} />
+ ) : (
+ <div role="alert" className="grid gap-2 rounded-lg border p-3 text-[13px]">
+ <p>
+ Remove your {p.label} key? Paid models on {p.label} stop working for you until you add a key again.
+ </p>
+ <div className="flex flex-wrap gap-2">
+ <Button size="sm" variant="destructive" onClick={() => void remove(false)} disabled={busy}>
+ {busy && <Loader2 className="animate-spin" />}
+ Remove key
+ </Button>
+ <Button size="sm" variant="secondary" onClick={() => setConfirm(null)} disabled={busy}>
+ Keep it
+ </Button>
+ </div>
+ </div>
+ )
+ ) : (
+ <div className="flex flex-wrap gap-2">
+ <Button size="sm" variant="secondary" onClick={() => setReplacing(true)}>
+ {info.readable ? "Replace" : "Add again"}
+ </Button>
+ <Button size="sm" variant="ghost" onClick={() => setConfirm({})}>
+ Remove
+ </Button>
+ </div>
+ )}
+ </>
+ ) : (
+ <KeyForm provider={provider} replacing={!!info} onSaved={() => setReplacing(false)} onCancel={info ? () => setReplacing(false) : undefined} />
+ )}
+ </div>
+ );
+}
+
+/** Settings → Your keys, for accounts (below Your GPU). `prices`: what the studios' paid defaults cost (starterPriceLine). */
+export function AccountKeysSection({ prices }: { prices?: string }) {
+ const account = useViewer().data?.account;
+ const q = useYourKeys(!!account);
+ if (!account) return null;
+ return (
+ <section id="your-keys" aria-labelledby="your-keys-title" className="grid scroll-mt-28 grid-cols-[minmax(0,1fr)] gap-6 border-b py-8 md:scroll-mt-20 md:grid-cols-[260px_minmax(0,1fr)]">
+ <div className="min-w-0">
+ <h2 id="your-keys-title" className="text-[15px] font-semibold">
+ Your keys
+ </h2>
+ <p className="mt-1 text-[13px] text-muted-foreground">
+ Add your own fal.ai key or Replicate token to use paid models such as Nano Banana, Kling and Veo. Those runs are billed to your account with that provider, never
+ to this studio. Fuobe checks the key with the provider, stores it encrypted on this server and shows only its last 4 characters.
+ </p>
+ </div>
+ <div className="grid min-w-0 gap-4">
+ <ul className="grid gap-1.5 text-[13px] text-muted-foreground">
+ {prices && (
+ <li>
+ <span className="font-medium text-foreground">What it costs:</span> {prices}. The price next to Generate is an estimate; your provider&apos;s bill is the
+ final word.
+ </li>
+ )}
+ <li>Runs with your key send your prompt and the files you attach to that provider.</li>
+ <li>Account limits still apply: 4 runs at once, 60 an hour, up to 4 pictures a run, 3 GB of files.</li>
+ </ul>
+ {q.data && !q.data.paidAllowed && <p className="rounded-lg bg-muted px-3 py-2 text-[13px] text-muted-foreground">{OPEN_ONLY_MESSAGE}</p>}
+ {q.isError ? (
+ <p className="text-[13px] text-muted-foreground">{q.error.message}</p>
+ ) : !q.data ? (
+ <Loader2 className="size-5 animate-spin text-muted-foreground" />
+ ) : (
+ <div className="grid gap-3 lg:grid-cols-2">
+ {CLOUD_PROVIDERS.map((p) => (
+ <KeyCard key={p} provider={p} info={q.data.keys[p]} />
+ ))}
+ </div>
+ )}
+ </div>
+ </section>
+ );
+}
+
+/**
+ * "Add your fal.ai key": opens from a dimmed model in a picker, a paid run the server refused (403 add-key), or an
+ * "Add a key" link. Once the key is saved it closes, and the model it was opened for is picked (never run: the person
+ * sees the price first). Mounted once, in the app's providers.
+ */
+export function AddKeyPrompt() {
+ const [ask, setAsk] = useState<{ provider: CloudProvider; modelId?: string } | null>(null);
+ useEffect(() => {
+ const open = (e: Event) => {
+ const d = (e as CustomEvent<{ provider?: CloudProvider; modelId?: string }>).detail;
+ if (d?.provider === "fal" || d?.provider === "replicate") setAsk({ provider: d.provider, modelId: d.modelId });
+ };
+ window.addEventListener(ADD_KEY_EVENT, open);
+ return () => window.removeEventListener(ADD_KEY_EVENT, open);
+ }, []);
+ const p = ask ? CLOUD_KEY[ask.provider] : null;
+ return (
+ <Dialog open={!!ask} onOpenChange={(o) => !o && setAsk(null)}>
+ <DialogContent className="sm:max-w-md">
+ {ask && p && (
+ <>
+ <DialogHeader>
+ <div className="mb-1 grid size-10 place-items-center rounded-xl bg-primary text-primary-foreground">
+ <KeyRound className="size-5" />
+ </div>
+ <DialogTitle>Add your {p.label} key</DialogTitle>
+ <DialogDescription>
+ Runs on {p.label} are billed to your own {p.label} account. Fuobe checks the key with {p.label}, then stores it encrypted on this server.
+ </DialogDescription>
+ </DialogHeader>
+ <KeyForm
+ provider={ask.provider}
+ autoFocus
+ onSaved={() => {
+ window.dispatchEvent(new CustomEvent(KEY_ADDED_EVENT, { detail: ask }));
+ setAsk(null);
+ }}
+ />
+ <DialogFooter className="sm:justify-start">
+ <p className={cn("text-[12px] text-muted-foreground")}>
+ Change or remove it any time in{" "}
+ <Link href="/settings#your-keys" onClick={() => setAsk(null)} className="text-brand-text underline-offset-2 hover:underline">
+ Settings → Your keys
+ </Link>
+ .
+ </p>
+ </DialogFooter>
+ </>
+ )}
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsx
index 8e90ec7e..c6420b76 100644
--- a/src/components/studio/composer.tsx
+++ b/src/components/studio/composer.tsx
@@ -68,6 +68,7 @@ import {
} from "@/lib/composer";
import { formatCost } from "@/lib/format";
import { toastError } from "@/lib/refusals";
+import { addKeyLabel, billedTo, CLOUD_KEY, needsKey, paidThrough, startingModel } from "@/lib/your-keys";
import { cn } from "@/lib/utils";
import { badgeFor, badgeText, openGpuSetup, setGpuRetry, useGpuBadges } from "@/hooks/use-gpu";
import { AttachMenu } from "./attach-menu";
@@ -364,6 +365,16 @@ export function Composer({ docked }: { docked: boolean }) {
toast(`${offModel.name} is turned off in Settings → Models & licences, so this uses ${m.name}`, { id: "model-access" });
}, [offModel, fallback, lockedModel, catalog, setDraft]);
+ // An account (Your keys) starts on a paid model it can run: the studio's untouched default when it has that key, else
+ // the first of the list it can run. Quietly: nothing it picked changed (a model it picked is never swapped).
+ const keyStart =
+ model && model.id === config.defaultModels[engine] && needsKey(model, status) ? startingModel(model.id, models.filter((m) => m.engine === engine && catalog.offered(m.id, engine)), status) : undefined;
+ useEffect(() => {
+ const m = keyStart && model && keyStart !== model.id && !lockedModel ? catalog.getModel(keyStart) : undefined;
+ if (!m || !model) return;
+ setDraft((d) => (d.modelId !== model.id ? {} : { modelId: m.id, params: { ...m.defaults, numOutputs: d.params.numOutputs, enhancePrompt: d.params.enhancePrompt }, ...lookCleared(model, m) }));
+ }, [keyStart, model, lockedModel, catalog, setDraft]);
+
// A camera motion or effect runs on its Original on this engine (Fuobe DoP): picking one moves the composer there,
// with the move's own settings (Focus Change: 6 s, silent). Another video model can be picked after it; it takes
// the move's words. A move whose cloud route is a partner model's words leaves the person's model as it is.
@@ -633,6 +644,10 @@ export function Composer({ docked }: { docked: boolean }) {
const demo = !!(model && status && status.demoMode !== "off" && !model.routes.some((r) => status.providers[r.provider]?.configured));
// On the open engine every run is free on the GPU: said even before the run can be planned (no voice sample, no clip yet).
const costText = costLabel({ demo, cost: cost ?? (engine === "open" && model ? 0 : null), unknown: loraPriceUnknown }, formatCost);
+ // An account's paid run is billed to its own provider account (Your keys), or still needs that key.
+ const payer = paidThrough(model, status);
+ const missingKey = needsKey(model, status)?.[0];
+ const payerText = payer && cost ? ` · ${billedTo(payer)}` : missingKey ? ` · ${addKeyLabel(missingKey).toLowerCase()}` : "";
// Attachments: only when something is attached, a required slot is still empty, or none of a "one of these" group is filled (U8).
const kinds = [...attach.kinds];
@@ -1106,17 +1121,24 @@ export function Composer({ docked }: { docked: boolean }) {
<TooltipTrigger asChild>
<span className="shrink-0 text-[12px] font-medium text-muted-foreground tabular-nums">
<span className="sm:hidden">{costLabel({ demo, cost, compact: true, unknown: loraPriceUnknown }, formatCost)}</span>
- <span className="hidden sm:inline">{costText}</span>
+ <span className="hidden sm:inline">
+ {costText}
+ {payerText}
+ </span>
</span>
</TooltipTrigger>
- <TooltipContent>
+ <TooltipContent className="max-w-72">
{demo
? "Demo mode: no key connected for this model, so outputs are free placeholders"
: cost === 0
? "Runs on your own GPU"
- : cost === null
- ? "The provider publishes no price for this model with LoRAs yet: it bills your key at its own rate"
- : "Estimated cost, billed by the provider to your key"}
+ : missingKey
+ ? `Runs on ${CLOUD_KEY[missingKey].label}, billed to your own ${CLOUD_KEY[missingKey].label} account. Add your key in Settings → Your keys.`
+ : cost === null
+ ? "The provider publishes no price for this model with LoRAs yet: it bills your key at its own rate"
+ : payer
+ ? `Estimated cost, billed to ${billedTo(payer)}. ${CLOUD_KEY[payer].label}'s bill is the final word.`
+ : "Estimated cost, billed by the provider to your key"}
</TooltipContent>
</Tooltip>
)}
diff --git a/src/components/studio/engine-switch.tsx b/src/components/studio/engine-switch.tsx
index 324768db..64bcc2b8 100644
--- a/src/components/studio/engine-switch.tsx
+++ b/src/components/studio/engine-switch.tsx
@@ -4,7 +4,8 @@ import { Cloud, Cpu, Lock } from "lucide-react";
import Link from "next/link";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import type { Engine } from "@/lib/catalog/types";
-import { useEngineMode, useViewer } from "@/lib/api";
+import { useEngineMode, useStatus, useViewer } from "@/lib/api";
+import { accountEngine } from "@/lib/your-keys";
import { cn } from "@/lib/utils";
import { radioKeys, radioTab } from "./radio-keys";
@@ -32,10 +33,13 @@ export function EngineSwitch({
const mode = useEngineMode();
// Only the owner can change the engine mode (Settings): anyone else gets a plain badge, not a link to a page they can't use.
const owner = useViewer().data?.owner === true;
+ // An account (public sign-up): locked on open source until it adds its own key, and why; with one, who pays.
+ const account = accountEngine(useStatus().data);
+ const locked = account && "locked" in account ? account.locked : null;
const idx = OPTIONS.findIndex((o) => o.value === value);
- if (mode !== "both") {
- const o = OPTIONS.find((x) => x.value === mode)!;
- const text = mode === "open" ? "Open source only" : "Cloud only";
+ if (mode !== "both" || locked) {
+ const o = OPTIONS.find((x) => x.value === (locked ? "open" : mode))!;
+ const text = locked?.text ?? (mode === "open" ? "Open source only" : "Cloud only");
const cls = cn(
"inline-flex shrink-0 items-center gap-1.5 rounded-full bg-muted px-3 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition-colors",
size === "sm" ? "h-8" : "h-8 sm:h-9",
@@ -46,6 +50,20 @@ export function EngineSwitch({
<span className={cn(compact && "hidden sm:inline")}>{text}</span>
</>
);
+ // An account opens Your keys (or Your GPU) from here: the way to paid models is its own key.
+ if (locked) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Link href={locked.href} aria-label={`${text}. ${locked.tip}`} className={cn(cls, "hover:text-foreground")}>
+ {body}
+ <Lock className="size-3 opacity-60" />
+ </Link>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-72">{locked.tip}</TooltipContent>
+ </Tooltip>
+ );
+ }
return owner ? (
<Tooltip>
<TooltipTrigger asChild>
@@ -103,7 +121,7 @@ export function EngineSwitch({
<TooltipContent>
{/* One span: the tooltip lays its children out in a row. */}
<span>
- <span className="font-medium">{o.label}</span> · {o.tip}
+ <span className="font-medium">{o.label}</span> · {account && "tips" in account ? account.tips[o.value] : o.tip}
</span>
</TooltipContent>
</Tooltip>
diff --git a/src/components/studio/model-picker.tsx b/src/components/studio/model-picker.tsx
index 802e9045..813031e8 100644
--- a/src/components/studio/model-picker.tsx
+++ b/src/components/studio/model-picker.tsx
@@ -2,7 +2,8 @@
import { ChevronDown, Cloud, Cpu, SearchX, Server, Star } from "lucide-react";
import Link from "next/link";
-import { useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { KEY_ADDED_EVENT, openAddKey } from "@/components/keys/your-keys";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Command, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
@@ -16,6 +17,7 @@ import { useEngineMode, useStatus } from "@/lib/api";
import { groupModels, studioBest, toggleIn } from "@/lib/composer";
import { ISOLATED_NOTE, pickerPrice } from "@/lib/model-rows";
import { cn } from "@/lib/utils";
+import { addKeyLabel, billedTo, CLOUD_KEY, needsKey, type CloudProvider } from "@/lib/your-keys";
import { EngineSwitch } from "./engine-switch";
import { ResponsivePanel } from "./responsive-panel";
import { RECENT_MODELS, STARRED_MODELS, useStoredList } from "./stored-list";
@@ -80,6 +82,7 @@ function ModelRow({
onStar,
gpu,
gpuName,
+ needs,
}: {
m: ModelDef;
selected: boolean;
@@ -91,11 +94,13 @@ function ModelRow({
/** Its state on the viewer's GPU (the GPU pre-flight). */
gpu?: BadgeT | null;
gpuName?: string;
+ /** An account's paid model it has no key for yet: dimmed, "Add your fal.ai key" in place of the price. */
+ needs?: CloudProvider[] | null;
}) {
return (
<>
<VendorMark vendor={m.vendor} engine={m.engine} />
- <span className="min-w-0 flex-1">
+ <span className={cn("min-w-0 flex-1", needs && "opacity-60")}>
<span className="flex items-center gap-1.5">
<span className={cn("truncate text-[13px] font-medium", selected && "text-brand-text")}>
{m.name}
@@ -120,7 +125,11 @@ function ModelRow({
</span>
)}
</span>
- <span className="shrink-0 text-right text-[11px] text-muted-foreground tabular-nums">{pickerPrice(m, today)}</span>
+ {needs ? (
+ <span className="shrink-0 text-right text-[11px] font-medium text-brand-text">{addKeyLabel(needs[0])}</span>
+ ) : (
+ <span className="shrink-0 text-right text-[11px] text-muted-foreground tabular-nums">{pickerPrice(m, today)}</span>
+ )}
{/* Pointer only: inside an option it would be a nested control. Keyboard: Alt+S on the highlighted row (starKey). */}
<button
type="button"
@@ -162,7 +171,19 @@ interface PickerProps {
*/
export function ModelPicker(props: PickerProps) {
const [open, setOpen] = useState(false);
- const { value } = props;
+ const { value, models, onChange } = props;
+ // The model a dimmed row was chosen for: picked once its key is saved (by this picker only).
+ const waiting = useRef<string | null>(null);
+ useEffect(() => {
+ const added = (e: Event) => {
+ const id = (e as CustomEvent<{ modelId?: string }>).detail?.modelId;
+ const m = id && id === waiting.current ? models.find((x) => x.id === id) : undefined;
+ waiting.current = null;
+ if (m) onChange(m);
+ };
+ window.addEventListener(KEY_ADDED_EVENT, added);
+ return () => window.removeEventListener(KEY_ADDED_EVENT, added);
+ }, [models, onChange]);
return (
<ResponsivePanel
open={open}
@@ -178,13 +199,31 @@ export function ModelPicker(props: PickerProps) {
</Button>
}
>
- <PickerList {...props} onPicked={() => setOpen(false)} />
+ <PickerList
+ {...props}
+ onPicked={() => setOpen(false)}
+ onNeedsKey={(m, p) => {
+ waiting.current = m.id;
+ setOpen(false);
+ openAddKey(p, m.id);
+ }}
+ />
</ResponsivePanel>
);
}
/** The searchable list (mounted by the popover / sheet only while it shows). */
-function PickerList({ models, value, onChange, engine, onEngineChange, defaultModels, ops, onPicked }: PickerProps & { onPicked: () => void }) {
+function PickerList({
+ models,
+ value,
+ onChange,
+ engine,
+ onEngineChange,
+ defaultModels,
+ ops,
+ onPicked,
+ onNeedsKey,
+}: PickerProps & { onPicked: () => void; onNeedsKey?: (m: ModelDef, p: CloudProvider) => void }) {
const [q, setQ] = useState("");
const status = useStatus().data;
const badges = useGpuBadges().data;
@@ -203,7 +242,12 @@ function PickerList({ models, value, onChange, engine, onEngineChange, defaultMo
const otherEngine = engine === "cloud" ? "open" : "cloud";
const noneForEngine = !q && !models.some((m) => m.engine === engine);
+ // An account (public sign-up): paid models it has no key for are dimmed; choosing one asks for the key first.
+ const keys = status?.viewer?.kind === "account" ? (status.viewer.keys ?? []) : null;
+ const payer = keys?.length && engine === "cloud" ? keys : null;
const pick = (m: ModelDef) => {
+ const needs = needsKey(m, status);
+ if (needs && onNeedsKey) return onNeedsKey(m, needs[0]);
onChange(m);
onPicked();
};
@@ -218,7 +262,19 @@ function PickerList({ models, value, onChange, engine, onEngineChange, defaultMo
</div>
<div className="flex items-baseline gap-x-2 px-3 pb-1.5 leading-snug text-[11px] text-muted-foreground sm:px-3.5">
<span className="shrink-0 whitespace-nowrap tabular-nums">{q ? `${count} result${count === 1 ? "" : "s"}` : `${count} ${engine === "open" ? "open-source" : "cloud"} model${count === 1 ? "" : "s"}`}</span>
- {demo && (
+ {keys && engine === "cloud" && (
+ <>
+ <span aria-hidden>·</span>
+ <span className="min-w-0">
+ {payer ? `Paid models are billed to ${payer.length > 1 ? "your fal.ai and Replicate accounts" : billedTo(payer[0])}` : "Add a fal.ai or Replicate key to run paid models"}
+ {" · "}
+ <Link href="/settings#your-keys" className="text-brand-text underline underline-offset-2">
+ {payer ? "Your keys" : "Add a key"}
+ </Link>
+ </span>
+ </>
+ )}
+ {demo && !keys && (
<>
<span aria-hidden>·</span>
<span className="min-w-0">
@@ -242,6 +298,7 @@ function PickerList({ models, value, onChange, engine, onEngineChange, defaultMo
value={`${g.id}:${m.id}`}
onSelect={() => pick(m)}
data-checked={value?.id === m.id}
+ aria-label={needsKey(m, status) ? `${m.name} needs your ${CLOUD_KEY[needsKey(m, status)![0]].label} key` : undefined}
className={cn("gap-2.5 rounded-lg px-2 py-1.5 [&>svg:last-child]:hidden", value?.id === m.id && "bg-brand-faint data-selected:bg-brand-faint-hover")}
>
<ModelRow
@@ -253,6 +310,7 @@ function PickerList({ models, value, onChange, engine, onEngineChange, defaultMo
onStar={() => setStarred((s) => toggleIn(s, m.id))}
gpu={m.engine === "open" ? badgeFor(badges, { modelId: m.id }) : null}
gpuName={badges?.gpu}
+ needs={needsKey(m, status)}
/>
</CommandItem>
))}
diff --git a/src/lib/api.ts b/src/lib/api.ts
index 3ba970fb..fad00cd7 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -30,6 +30,7 @@ import { markRefusalShown, responseError } from "./refusals";
import { postFile } from "./upload";
import type { ShareCreated, ShareInfo, ShareListItem, SharePatch, ShareRequest } from "./share";
import type { AccessSummary } from "./model-access";
+import { ADD_KEY_HEADER, isCloudProvider, type CloudProvider } from "./your-keys";
export interface Asset {
id: string;
@@ -837,9 +838,15 @@ export interface StatusInfo {
access?: AccessSummary;
/**
* Public sign-up: a guest or an account is looking. Then everything else here is its own view
- * (its own GPU as ComfyUI, the open engine, no Demo mode), never the install's (src/server/account-gpu.ts).
+ * (its own GPU as ComfyUI, its own fal.ai and Replicate keys, no Demo mode), never the install's
+ * (src/server/account-gpu.ts). `keys`: the providers it has its own key for (src/lib/your-keys.ts).
*/
- viewer?: { kind: "guest" | "account"; gpu: { connected: boolean; mode?: "computer" | "link"; online?: boolean; comfy?: "down" | "no-setting"; device?: string; vramBytes?: number } };
+ viewer?: {
+ kind: "guest" | "account";
+ gpu: { connected: boolean; mode?: "computer" | "link"; online?: boolean; comfy?: "down" | "no-setting"; device?: string; vramBytes?: number };
+ keys?: CloudProvider[];
+ paidAllowed?: boolean;
+ };
}
/** A connection test's answer (POST /api/providers/test). */
@@ -999,6 +1006,14 @@ export function useEngine(): [Engine, (e: Engine) => void, EngineMode] {
return [mode === "both" ? engine : mode, set, mode];
}
+/** Remember the engine the studios start on, before the mode allows it (an account that just added its own key: Cloud). */
+export function preferEngine(e: Engine): void {
+ try {
+ localStorage.setItem(ENGINE_KEY, e);
+ } catch {}
+ listeners.forEach((l) => l());
+}
+
// ---------------------------------------------------------------------------
// Assist
@@ -1152,6 +1167,8 @@ export const CONNECT_GPU_EVENT = "fuobe:connect-gpu";
export const COMPUTER_KICK_EVENT = "fuobe:computer-kick";
/** The guided fix (src/components/gpu/guided-fix.tsx): { ref, plan? }. */
export const GPU_SETUP_EVENT = "fuobe:gpu-setup";
+/** "Add your key" (src/components/keys/your-keys.tsx): { provider, modelId? }. */
+export const ADD_KEY_EVENT = "fuobe:add-key";
/** A card GuestPrompt shows for a refusal: "Create a free account" (coming back to `here` after) or "Connect your GPU". */
export type RefusalCard = { kind: "guest"; here: string } | { kind: "gpu" };
@@ -1194,6 +1211,12 @@ export function watchGuestRefusals(): void {
if (res.status === 201 && (init?.method ?? "").toUpperCase() === "POST" && new URL(input instanceof Request ? input.url : String(input), window.location.href).pathname === "/api/generations") {
window.dispatchEvent(new Event(COMPUTER_KICK_EVENT));
}
+ // An account's paid run without its own key for that provider (x-fuobe-add-key: fal | replicate): "Add your key".
+ const addKey = res.status === 403 ? res.headers.get(ADD_KEY_HEADER) : null;
+ if (isCloudProvider(addKey) && refusalCard("gpu", window.location)) {
+ markRefusalShown(res);
+ window.dispatchEvent(new CustomEvent(ADD_KEY_EVENT, { detail: { provider: addKey } }));
+ }
// A run the GPU pre-flight stopped (something missing on the viewer's ComfyUI): the guided fix opens with its plan.
if (res.status === 409 && res.headers.get("x-fuobe-gpu-setup") === "1") {
res
diff --git a/src/lib/your-keys.ts b/src/lib/your-keys.ts
index 10fc47ec..23303e9c 100644
--- a/src/lib/your-keys.ts
+++ b/src/lib/your-keys.ts
@@ -52,3 +52,68 @@ export const keyRemovedMessage = (p: CloudProvider) => `Your ${CLOUD_KEY[p].labe
/** The owner (or anyone not signed in as an account) on /api/account/keys. */
export const NOT_ACCOUNT_KEYS = "Your keys are for accounts. The studio's own keys are in Settings → Paid API configuration.";
export const OPEN_ONLY_MESSAGE = "This studio runs open-source models only right now, so your keys aren't used.";
+
+// ---------------------------------------------------------------------------
+// What the studios say to an account about its keys (pure: tests/your-keys-ui.test.ts)
+
+/** The part of /api/status these read (StatusInfo in src/lib/api.ts). */
+export interface KeyStatus {
+ viewer?: { kind: "guest" | "account"; gpu?: { connected: boolean }; keys?: CloudProvider[]; paidAllowed?: boolean };
+}
+type Routed = { engine: string; routes: { provider: string }[] };
+
+const viewerKeys = (s: KeyStatus | undefined): CloudProvider[] | null => (s?.viewer?.kind === "account" ? (s.viewer.keys ?? []) : null);
+
+/**
+ * A paid model an account can't run yet: the providers that serve it (fal.ai first), any of whose keys would do. Null
+ * for the owner and guests, an open model, or a paid model the account has a key for.
+ */
+export function needsKey(m: Routed | undefined, s: KeyStatus | undefined): CloudProvider[] | null {
+ const keys = viewerKeys(s);
+ if (!m || !keys || m.engine === "open") return null;
+ const served = CLOUD_PROVIDERS.filter((p) => m.routes.some((r) => r.provider === p));
+ return served.length && !served.some((p) => keys.includes(p)) ? served : null;
+}
+
+/** The provider an account's run of a paid model is billed through: the first that serves it and has its key. */
+export function paidThrough(m: Routed | undefined, s: KeyStatus | undefined): CloudProvider | null {
+ const keys = viewerKeys(s);
+ if (!m || !keys || m.engine === "open") return null;
+ return CLOUD_PROVIDERS.find((p) => keys.includes(p) && m.routes.some((r) => r.provider === p)) ?? null;
+}
+
+/** "Add your fal.ai key": the words on a paid model an account can't run yet. */
+export const addKeyLabel = (p: CloudProvider) => `Add your ${CLOUD_KEY[p].label} key`;
+
+/** "your fal.ai account": who pays for an account's paid run. */
+export const billedTo = (p: CloudProvider) => `your ${CLOUD_KEY[p].label} account`;
+
+/** "fal.ai and Replicate" */
+const names = (ps: readonly CloudProvider[]) => ps.map((p) => CLOUD_KEY[p].label).join(" and ");
+
+/**
+ * The engine switch for an account: locked on open source (and why, and where to change that), or the words for its two
+ * sides. Null for the owner and guests (the switch follows Settings → Engine mode).
+ */
+export function accountEngine(s: KeyStatus | undefined): { locked: { text: string; tip: string; href: string } } | { tips: { cloud: string; open: string } } | null {
+ const v = s?.viewer;
+ if (v?.kind !== "account") return null;
+ if (v.paidAllowed === false) return { locked: { text: "Open source only", tip: "This studio runs open-source models only.", href: "/settings#your-gpu" } };
+ const keys = v.keys ?? [];
+ if (!keys.length) {
+ return { locked: { text: "Open source only", tip: "Your runs use your own GPU. Add a fal.ai or Replicate key in Settings → Your keys to use paid models.", href: "/settings#your-keys" } };
+ }
+ return {
+ tips: {
+ cloud: `Paid models, billed to your ${names(keys)} ${keys.length > 1 ? "accounts" : "account"}`,
+ open: v.gpu?.connected ? "Open models on your own GPU" : "Open models on your own GPU. Connect it first",
+ },
+ };
+}
+
+/** The first model of a list an account can run (the studio's default when it can): where a studio starts it. */
+export function startingModel<M extends Routed & { id: string }>(defaultId: string | undefined, models: readonly M[], s: KeyStatus | undefined): string | undefined {
+ const own = models.find((m) => m.id === defaultId);
+ if (!own || !needsKey(own, s)) return defaultId;
+ return models.find((m) => m.engine === own.engine && !needsKey(m, s))?.id ?? defaultId;
+}
diff --git a/tests/your-keys-ui.test.ts b/tests/your-keys-ui.test.ts
new file mode 100644
index 00000000..94b25dec
--- /dev/null
+++ b/tests/your-keys-ui.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it } from "vitest";
+import { getModel } from "@/lib/catalog";
+import { accountEngine, addKeyLabel, billedTo, needsKey, paidThrough, startingModel, type KeyStatus } from "@/lib/your-keys";
+
+/** Your keys in the studios: which paid models an account can run, who pays, and what the engine switch says. */
+const account = (keys: ("fal" | "replicate")[], o: { gpu?: boolean; paidAllowed?: boolean } = {}): KeyStatus => ({
+ viewer: { kind: "account", gpu: { connected: !!o.gpu }, keys, paidAllowed: o.paidAllowed ?? true },
+});
+const owner: KeyStatus = {};
+const guest: KeyStatus = { viewer: { kind: "guest", gpu: { connected: false } } };
+
+const nanoPro = getModel("nano-banana-pro")!; // fal.ai and Replicate
+const imagen = getModel("imagen-4")!; // Replicate only
+const nano2 = getModel("nano-banana-2")!; // fal.ai only
+const open = { id: "oss", engine: "open", routes: [{ provider: "comfyui" }] };
+
+describe("which paid models an account can run", () => {
+ it("dims a paid model none of whose providers it has a key for, and names them (fal.ai first)", () => {
+ expect(needsKey(nanoPro, account([]))).toEqual(["fal", "replicate"]);
+ expect(needsKey(nanoPro, account(["replicate"]))).toBeNull();
+ expect(needsKey(imagen, account(["fal"]))).toEqual(["replicate"]);
+ expect(needsKey(nano2, account(["replicate"]))).toEqual(["fal"]);
+ expect(needsKey(nano2, account(["fal"]))).toBeNull();
+ });
+
+ it("never dims open models, or anything for the owner or a guest", () => {
+ expect(needsKey(open, account([]))).toBeNull();
+ expect(needsKey(nanoPro, owner)).toBeNull();
+ expect(needsKey(nanoPro, guest)).toBeNull();
+ expect(needsKey(undefined, account([]))).toBeNull();
+ });
+
+ it("says who pays: the first provider that serves it and has the account's key", () => {
+ expect(paidThrough(nanoPro, account(["fal", "replicate"]))).toBe("fal");
+ expect(paidThrough(nanoPro, account(["replicate"]))).toBe("replicate");
+ expect(paidThrough(imagen, account(["fal"]))).toBeNull();
+ expect(paidThrough(nanoPro, owner)).toBeNull();
+ expect(paidThrough(open, account(["fal"]))).toBeNull();
+ expect(billedTo("fal")).toBe("your fal.ai account");
+ expect(addKeyLabel("replicate")).toBe("Add your Replicate key");
+ });
+
+ it("starts a studio on a model the account can run; the default when it can", () => {
+ const list = [nano2, nanoPro, imagen];
+ expect(startingModel("nano-banana-2", list, account(["fal"]))).toBe("nano-banana-2");
+ expect(startingModel("nano-banana-2", list, account(["replicate"]))).toBe("nano-banana-pro");
+ expect(startingModel("nano-banana-2", list, owner)).toBe("nano-banana-2");
+ // Nothing it can run: the default stays (Generate then asks for the key).
+ expect(startingModel("nano-banana-2", [nano2], account(["replicate"]))).toBe("nano-banana-2");
+ });
+});
+
+describe("the engine switch for an account", () => {
+ it("is locked on open source without a key, pointing at Your keys", () => {
+ expect(accountEngine(account([]))).toEqual({
+ locked: { text: "Open source only", tip: "Your runs use your own GPU. Add a fal.ai or Replicate key in Settings → Your keys to use paid models.", href: "/settings#your-keys" },
+ });
+ });
+
+ it("is locked when the studio runs open-source models only, saying so", () => {
+ expect(accountEngine(account(["fal"], { paidAllowed: false }))).toMatchObject({ locked: { tip: "This studio runs open-source models only." } });
+ });
+
+ it("switches with a key, saying who pays and where open models run", () => {
+ expect(accountEngine(account(["fal"]))).toEqual({ tips: { cloud: "Paid models, billed to your fal.ai account", open: "Open models on your own GPU. Connect it first" } });
+ expect(accountEngine(account(["fal", "replicate"], { gpu: true }))).toEqual({
+ tips: { cloud: "Paid models, billed to your fal.ai and Replicate accounts", open: "Open models on your own GPU" },
+ });
+ });
+
+ it("leaves the owner's and a guest's switch to Settings → Engine mode", () => {
+ expect(accountEngine(owner)).toBeNull();
+ expect(accountEngine(guest)).toBeNull();
+ });
+});