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
Settings: engine mode (open source only / paid APIs only / both) and API configuration
Claude569c8abb8942
diff --git a/README.md b/README.mdindex b58804a7..b0f0d4fa 100644--- a/README.md+++ b/README.md@@ -17,12 +17,20 @@ pnpm installpnpm dev # http://localhost:3000```-Open **Settings** and connect what you have:+Open **Settings** and pick an **Engine mode**:++| Engine mode | What the install offers | Needs |+|---|---|---|+| **Open source + paid APIs** (default) | A Cloud / Open source switch in every studio | A paid-API key and/or a ComfyUI server |+| **Open source only** | Only open-weight models on your ComfyUI; paid models are hidden and rejected by the server, and prompt enhancement never calls a paid API on its own | A ComfyUI server |+| **Paid APIs only** | Only hosted frontier models; open-source models are hidden and rejected | A fal.ai or Replicate key |++The mode can also be set with `FUOBE_ENGINE_MODE=both|open|cloud`. Then connect what you have:| You have | What to set | You get ||---|---|---|| A [fal.ai](https://fal.ai/dashboard/keys) key | `fal.ai API key` (or `FAL_KEY`) | Every cloud model and cloud app |-| A Replicate token | `Replicate API token` (or `REPLICATE_API_TOKEN`) | Fallback route for models Replicate hosts |+| A Replicate token | `Replicate API token` (or `REPLICATE_API_TOKEN`) | Fallback route for models Replicate hosts; **Preferred provider** (or `FUOBE_CLOUD_PROVIDER`: `auto`, `fal` or `replicate`) picks which one goes first || A GPU running ComfyUI | `ComfyUI server URL` (or `COMFYUI_URL`, default `http://127.0.0.1:8188`) | Every open-source model, app, motion and effect || An Anthropic key or Ollama | `Prompt enhancement` | The **Enhance** toggle rewrites prompts with Claude or a local LLM (offline rewriter otherwise) |diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 9f9dd7a7..a2593814 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -9,8 +9,11 @@ Composer (React) ──POST /api/generations──▶ planGeneration() src/│ → prompt (preset template, LoRA trigger)│ → params, LoRAs, number of jobs▼+ engine mode check Settings → Engine mode (both / open / cloud)+ │ rejects models of a disabled enginechooseRoute() src/server/generations.ts- │ first configured provider for that operation,+ │ first configured provider for that operation+ │ (Settings → Preferred provider sets fal/Replicate order),│ else the demo provider (Settings → Demo mode)▼SQLite row (queued) ─ submit() in the background:@@ -56,7 +59,7 @@ All adapters implement `prepareFile`, `submit`, `poll`, `cancel`, `test`.## Storage (`src/server/db.ts`, `storage.ts`, `settings.ts`)-SQLite (WAL) with tables `generations`, `assets`, `settings`, `characters`. Files live in `data/files/{uploads,outputs}/<date>/<id>.<ext>` and are served by `/api/files/...` with HTTP range support for video. `FUOBE_DATA_DIR` moves everything.+SQLite (WAL) with tables `generations`, `assets`, `settings`, `characters`. Settings (`src/server/settings.ts`) are typed, validated against allowed values, overridable by environment variables, and secrets are masked before reaching the browser. `engineMode` is enforced server-side; the client reads it from `/api/status` (`useEngineMode`) to lock the engine switch and filter what it shows. Files live in `data/files/{uploads,outputs}/<date>/<id>.<ext>` and are served by `/api/files/...` with HTTP range support for video. `FUOBE_DATA_DIR` moves everything.## UI (`src/components/`, `src/app/(studio)/`)diff --git a/docs/STATUS.md b/docs/STATUS.mdindex 06cc9808..94528f2d 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -16,7 +16,7 @@ _Last updated: 2026-10-16. The research behind this is in [`docs/research/`](res| check | result ||---|---|| `pnpm typecheck`, `pnpm lint` | clean |-| `pnpm test` (Vitest, 28 tests) | pass — payload mapping, durations/enums, response parsing, operation inference, prompt composition, batching, input validation, cost estimates, ComfyUI bindings, LoRA injection on Wan 2.2 experts, size/frame math, error hints, catalog integrity (every preset → existing model with that operation, every ComfyUI route → a workflow in the manifest, icons exist, defaults valid) |+| `pnpm test` (Vitest, 32 tests) | pass — payload mapping, durations/enums, response parsing, operation inference, prompt composition, batching, input validation, cost estimates, ComfyUI bindings, LoRA injection on Wan 2.2 experts, size/frame math, error hints, catalog integrity (every preset → existing model with that operation, every ComfyUI route → a workflow in the manifest, icons exist, defaults valid) || `pnpm build` | passes (150 prerendered pages) || Demo mode, browser | ✅ image and video generations queue, show live progress, land in the feed, open in the viewer; no console errors (headless Chromium, desktop + 390px mobile, light + dark) || ComfyUI engine, live server | ✅ `pnpm test:e2e:comfyui` against ComfyUI 0.41 (CPU): upload → bindings → `/prompt` → websocket/`/history` → download → library, for an image and a video workflow |@@ -24,6 +24,8 @@ _Last updated: 2026-10-16. The research behind this is in [`docs/research/`](res| ComfyUI error UX | ✅ a LoRA motion preset with missing files fails fast with "Missing model X — put it in ComfyUI/models/<folder> (download: URL)" for every missing file || Cloud providers (fal / Replicate) | 🟢 adapters and 67 model routes built from fal's per-endpoint OpenAPI schemas (499/517 researched endpoints verified); **no live paid run yet** — needs a key || Prompt enhancement | 🟢 Claude (Anthropic SDK) and Ollama paths built; offline rewriter ✅ |+| Engine mode (Settings) | ✅ Open source only / Paid APIs only / Both: enforced by the server (unit-tested + verified via the API), UI locks the engine switch, filters pickers, galleries and the model list, and dims unused settings sections (browser-checked in all three modes) |+| Preferred cloud provider | ✅ auto / fal.ai first / Replicate first — unit-tested route ordering |## 2. Feature matrix vs Higgsfield@@ -75,6 +77,7 @@ _Last updated: 2026-10-16. The research behind this is in [`docs/research/`](res|---|---|---|| Assets library, favorites, search, reuse/remix, "animate this image" hand-offs, download | ✅ | Library page, tile actions (Animate, Edit, Upscale, Use as reference, Lipsync, Add sound), viewer with keyboard shortcuts || Live progress, cancel, retry, failure messages | ✅ | Shimmer status, percent, elapsed time, cancel; retries re-submit the same request |+| Engine choice (open source only, paid only, or both) | ✅ | Settings → Engine mode, or `FUOBE_ENGINE_MODE` || Credits / pricing | 🟡 | Bring-your-own-key: live cost estimate per run from provider prices; "Free" for open source; no billing || Accounts, teams, sharing, community feed, contests | ⬜ | Single-user, self-hosted today || Supercomputer / Assist agent, MCP, plugins | ⬜ | |diff --git a/src/app/(studio)/settings/page.tsx b/src/app/(studio)/settings/page.tsxindex 51fc4d9f..9239f9d9 100644--- a/src/app/(studio)/settings/page.tsx+++ b/src/app/(studio)/settings/page.tsx@@ -8,7 +8,7 @@ export const metadata: Metadata = { title: "Settings" };export default function Page() {return (<PageShell>- <PageHeader title="Settings" description="Connect cloud providers, point Fuobe at your ComfyUI server, and choose how prompts get enhanced. Keys stay on this server." />+ <PageHeader title="Settings" description="Choose open source, paid APIs or both, connect providers, point Fuobe at your ComfyUI server, and choose how prompts get enhanced. Keys stay on this server." /><SettingsForm /></PageShell>);diff --git a/src/app/api/settings/route.ts b/src/app/api/settings/route.tsindex 0fe34da8..bf5ff8f5 100644--- a/src/app/api/settings/route.ts+++ b/src/app/api/settings/route.ts@@ -1,5 +1,5 @@import { connection } from "next/server";-import { publicSettings, setSetting, SETTINGS, type SettingName } from "@/server/settings";+import { publicSettings, setSetting, SETTINGS, validateSetting, type SettingName } from "@/server/settings";export async function GET() {await connection();@@ -8,9 +8,12 @@ export async function GET() {export async function PUT(request: Request) {const body = (await request.json().catch(() => ({}))) as Record<string, unknown>;- for (const [name, value] of Object.entries(body)) {- if (!(name in SETTINGS) || typeof value !== "string") continue;- setSetting(name as SettingName, value.trim());+ const entries = Object.entries(body).filter(([name, value]) => name in SETTINGS && typeof value === "string") as [SettingName, string][];+ try {+ entries.forEach(([name, value]) => validateSetting(name, value.trim()));+ } catch (e) {+ return Response.json({ error: (e as Error).message }, { status: 400 });}+ for (const [name, value] of entries) setSetting(name, value.trim());return Response.json({ settings: publicSettings() });}diff --git a/src/app/api/status/route.ts b/src/app/api/status/route.tsindex 0eb1a5d6..c7a86605 100644--- a/src/app/api/status/route.ts+++ b/src/app/api/status/route.ts@@ -13,5 +13,10 @@ export async function GET() {{ label: p.label, configured: p.id === "comfyui" ? comfy : p.id === "mock" ? true : p.isConfigured() },]),);- return Response.json({ providers, demoMode: getSetting("demoMode") });+ return Response.json({+ providers,+ demoMode: getSetting("demoMode"),+ engineMode: getSetting("engineMode"),+ cloudProvider: getSetting("cloudProvider"),+ });}diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsxindex 69351ca7..23d508a3 100644--- a/src/components/app-sidebar.tsx+++ b/src/components/app-sidebar.tsx@@ -44,7 +44,7 @@ import {SidebarTrigger,} from "@/components/ui/sidebar";import { Kbd } from "@/components/ui/kbd";-import { useStatus } from "@/lib/api";+import { useEngineMode, useStatus } from "@/lib/api";import { cn } from "@/lib/utils";const NAV = [@@ -127,6 +127,8 @@ export function AppSidebar() {const status = useStatus().data;const cloud = status && (status.providers.fal?.configured || status.providers.replicate?.configured);const comfy = status?.providers.comfyui?.configured;+ const mode = useEngineMode();+ const ready = mode === "open" ? comfy : mode === "cloud" ? cloud : cloud || comfy;return (<Sidebar variant="inset" collapsible="icon">@@ -165,15 +167,22 @@ export function AppSidebar() {href="/settings"className="flex flex-col gap-1.5 rounded-md px-2 py-1.5 text-[12px] text-muted-foreground transition-colors hover:bg-accent group-data-[collapsible=icon]:hidden">- <span className="flex items-center gap-2">- <StatusDot ok={cloud} /> Cloud models- <span className="ml-auto">{cloud ? "connected" : "add key"}</span>- </span>- <span className="flex items-center gap-2">- <StatusDot ok={comfy} /> ComfyUI- <span className="ml-auto">{comfy ? "online" : "offline"}</span>- </span>- {status && !cloud && !comfy && status.demoMode !== "off" && (+ {mode !== "open" && (+ <span className="flex items-center gap-2">+ <StatusDot ok={cloud} /> Cloud models+ <span className="ml-auto">{cloud ? "connected" : "add key"}</span>+ </span>+ )}+ {mode !== "cloud" && (+ <span className="flex items-center gap-2">+ <StatusDot ok={comfy} /> ComfyUI+ <span className="ml-auto">{comfy ? "online" : "offline"}</span>+ </span>+ )}+ {mode !== "both" && (+ <span className="text-[11px] text-subtle-foreground">{mode === "open" ? "Open source only" : "Paid APIs only"}</span>+ )}+ {status && !ready && status.demoMode !== "off" && (<span className="mt-0.5 rounded-sm bg-highlight/25 px-1.5 py-0.5 text-[11px] text-highlight-foreground dark:text-highlight">Demo mode · placeholder outputs</span>diff --git a/src/components/home-view.tsx b/src/components/home-view.tsxindex b8eb6de6..3084340f 100644--- a/src/components/home-view.tsx+++ b/src/components/home-view.tsx@@ -46,10 +46,12 @@ export function HomeView() {const router = useRouter();const [mode, setMode] = useState(MODES[0]);const [prompt, setPrompt] = useState("");- const [engine, setEngine] = useEngine();+ const [engine, setEngine, engineMode] = useEngine();const recent = useGenerations({ limit: 6 });const status = useStatus().data;- const nothingConnected = status && !status.providers.fal?.configured && !status.providers.replicate?.configured && !status.providers.comfyui?.configured;+ const cloudReady = !!(status?.providers.fal?.configured || status?.providers.replicate?.configured);+ const comfyReady = !!status?.providers.comfyui?.configured;+ const nothingConnected = status && !(engineMode === "open" ? comfyReady : engineMode === "cloud" ? cloudReady : cloudReady || comfyReady);const go = () => router.push(`${mode.href}${prompt.trim() ? `?prompt=${encodeURIComponent(prompt.trim())}` : ""}`);@@ -57,7 +59,13 @@ export function HomeView() {<PageShell><div className="flex flex-col items-center pt-[8vh] text-center"><h1 className="font-heading text-display text-balance sm:text-[44px]">What will you create today?</h1>- <p className="mt-2 text-[15px] text-muted-foreground">Frontier cloud models or fully open-source workflows — same studio, your choice.</p>+ <p className="mt-2 text-[15px] text-muted-foreground">+ {engineMode === "open"+ ? "Fully open-source models running on your own ComfyUI."+ : engineMode === "cloud"+ ? "Frontier paid models through your own API keys."+ : "Frontier cloud models or fully open-source workflows — same studio, your choice."}+ </p><div className="mt-8 w-full max-w-[720px] rounded-[20px] border bg-background p-2.5 text-left shadow-soft transition focus-within:border-primary focus-within:ring-4 focus-within:ring-brand-faint sm:rounded-composer"><textareavalue={prompt}@@ -100,7 +108,7 @@ export function HomeView() {<p className="mt-4 text-[13px] text-muted-foreground">You’re in <span className="font-medium text-foreground">demo mode</span> — outputs are placeholders.{" "}<Link href="/settings" className="text-brand-text underline-offset-2 hover:underline">- Add a fal.ai key or connect ComfyUI+ {engineMode === "open" ? "Connect ComfyUI" : engineMode === "cloud" ? "Add a fal.ai or Replicate key" : "Add a fal.ai key or connect ComfyUI"}</Link>{" "}to generate for real.</p>diff --git a/src/components/models-table.tsx b/src/components/models-table.tsxindex 22706d4f..7c538c64 100644--- a/src/components/models-table.tsx+++ b/src/components/models-table.tsx@@ -7,10 +7,13 @@ import { ModelBadges } from "@/components/studio/model-picker";import { MODELS } from "@/lib/catalog";import { OPERATION_LABELS, type Engine, type MediaKind } from "@/lib/catalog/types";import { formatCost } from "@/lib/format";+import { useEngine } from "@/lib/api";import { cn } from "@/lib/utils";export function ModelsTable() {- const [engine, setEngine] = useState<Engine | "all">("all");+ const [engineChoice, setEngine] = useState<Engine | "all">("all");+ const [, , mode] = useEngine();+ const engine: Engine | "all" = mode === "both" ? engineChoice : mode;const [kind, setKind] = useState<MediaKind | "all">("all");const list = MODELS.filter((m) => (engine === "all" || m.engine === engine) && (kind === "all" || m.kind === kind));const chip = (active: boolean) =>@@ -18,7 +21,7 @@ export function ModelsTable() {return (<div className="space-y-4"><div className="flex flex-wrap gap-1">- {(["all", "cloud", "open"] as const).map((e) => (+ {(mode === "both" ? (["all", "cloud", "open"] as const) : [mode]).map((e) => (<button key={e} className={chip(engine === e)} onClick={() => setEngine(e)}>{e === "all" ? "All engines" : e === "cloud" ? "Cloud" : "Open source"}</button>diff --git a/src/components/preset-gallery.tsx b/src/components/preset-gallery.tsxindex 616fb720..705645cf 100644--- a/src/components/preset-gallery.tsx+++ b/src/components/preset-gallery.tsx@@ -51,8 +51,10 @@ export function PresetCard({ preset, href, compact }: { preset: Preset; href: stexport function PresetGallery({ presets, href }: { presets: Preset[]; /** "{id}" is replaced with the preset id. */ href: string }) {const [cat, setCat] = useState("All");const [q, setQ] = useState("");- const [engine] = useEngine();- const [onlyEngine, setOnlyEngine] = useState(false);+ const [engine, , mode] = useEngine();+ const [onlyEngineChoice, setOnlyEngine] = useState(false);+ // When the install is locked to one engine, only show presets that engine can run.+ const onlyEngine = mode !== "both" || onlyEngineChoice;const cats = useMemo(() => ["All", ...new Set(presets.map((p) => p.category))], [presets]);const list = presets.filter((p) =>@@ -77,15 +79,17 @@ export function PresetGallery({ presets, href }: { presets: Preset[]; /** "{id}"</button>))}</div>- <button- onClick={() => setOnlyEngine((v) => !v)}- className={cn(- "h-8 rounded-full border px-3 text-[13px] text-muted-foreground hover:bg-accent",- onlyEngine && "border-primary bg-brand-faint text-brand-text",- )}- >- Only {engine === "open" ? "open source" : "cloud"}- </button>+ {mode === "both" && (+ <button+ onClick={() => setOnlyEngine((v) => !v)}+ className={cn(+ "h-8 rounded-full border px-3 text-[13px] text-muted-foreground hover:bg-accent",+ onlyEngine && "border-primary bg-brand-faint text-brand-text",+ )}+ >+ Only {engine === "open" ? "open source" : "cloud"}+ </button>+ )}<div className="relative"><Search className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground" /><inputdiff --git a/src/components/settings-form.tsx b/src/components/settings-form.tsxindex 4a8488d4..c4ffeb61 100644--- a/src/components/settings-form.tsx+++ b/src/components/settings-form.tsx@@ -1,7 +1,7 @@"use client";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import { CheckCircle2, CircleAlert, ExternalLink, Loader2 } from "lucide-react";+import { CheckCircle2, CircleAlert, Cloud, Cpu, ExternalLink, Layers, Loader2 } from "lucide-react";import { useState } from "react";import { toast } from "sonner";import { Button } from "@/components/ui/button";@@ -25,18 +25,88 @@ function useSettings() {});}-function Section({ title, description, children }: { title: string; description: React.ReactNode; children: React.ReactNode }) {+function Section({+ id,+ title,+ description,+ inactive,+ children,+}: {+ id?: string;+ title: string;+ description: React.ReactNode;+ /** Shown when the current engine mode doesn't use this section. */+ inactive?: string;+ children: React.ReactNode;+}) {return (- <section className="grid gap-6 border-b py-8 first:pt-0 md:grid-cols-[260px_1fr]">+ <section id={id} className="grid scroll-mt-6 gap-6 border-b py-8 first:pt-0 md:grid-cols-[260px_1fr]"><div><h2 className="text-[15px] font-semibold">{title}</h2><p className="mt-1 text-[13px] leading-relaxed text-muted-foreground">{description}</p>+ {inactive && <p className="mt-2 inline-flex rounded-md bg-muted px-2 py-1 text-[12px] text-muted-foreground">{inactive}</p>}</div>- <div className="space-y-5">{children}</div>+ <div className={cn("space-y-5", inactive && "opacity-55")}>{children}</div></section>);}+const ENGINE_MODES = [+ {+ value: "both",+ title: "Open source + paid APIs",+ icon: Layers,+ body: "Every studio gets a Cloud / Open source switch. Use frontier paid models when you want them, your own GPU when you don't.",+ needs: "A fal.ai or Replicate key and/or a ComfyUI server",+ },+ {+ value: "open",+ title: "Open source only",+ icon: Cpu,+ body: "Only open-weight models on your ComfyUI server. Paid models are hidden and blocked on the server, and nothing is sent to paid APIs.",+ needs: "A ComfyUI server",+ },+ {+ value: "cloud",+ title: "Paid APIs only",+ icon: Cloud,+ body: "Only hosted frontier models (Nano Banana, Seedance, Kling, Veo…). No GPU needed; open-source models are hidden.",+ needs: "A fal.ai or Replicate key",+ },+] as const;++function EngineModePicker({ value, onChange }: { value: string; onChange: (v: string) => void }) {+ return (+ <div role="radiogroup" aria-label="Engine mode" className="grid gap-2 lg:grid-cols-3">+ {ENGINE_MODES.map((m) => {+ const active = value === m.value;+ return (+ <button+ key={m.value}+ role="radio"+ aria-checked={active}+ onClick={() => !active && onChange(m.value)}+ className={cn(+ "flex flex-col gap-2 rounded-xl border p-4 text-left transition-colors hover:bg-accent",+ active && "border-primary bg-brand-faint hover:bg-brand-faint",+ )}+ >+ <span className="flex items-center gap-2">+ <span className={cn("grid size-8 place-items-center rounded-lg bg-muted text-muted-foreground", active && "bg-primary text-primary-foreground")}>+ <m.icon className="size-4" />+ </span>+ <span className="text-[14px] font-medium">{m.title}</span>+ {active && <CheckCircle2 className="ml-auto size-4 text-brand-text" />}+ </span>+ <span className="text-[13px] leading-relaxed text-muted-foreground">{m.body}</span>+ <span className="text-[12px] text-subtle-foreground">Needs: {m.needs}</span>+ </button>+ );+ })}+ </div>+ );+}+function TestButton({ provider }: { provider: string }) {const [res, setRes] = useState<{ ok: boolean; detail: string } | null>(null);const m = useMutation({@@ -127,7 +197,8 @@ export function SettingsForm() {const save = useMutation({mutationFn: async (patch: Record<string, string>) =>(await fetch("/api/settings", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(patch) })).json(),- onSuccess: () => {+ onSuccess: (body: { error?: string }) => {+ if (body?.error) return toast.error(body.error);toast.success("Saved");void qc.invalidateQueries({ queryKey: ["settings"] });void qc.invalidateQueries({ queryKey: ["status"] });@@ -137,16 +208,28 @@ export function SettingsForm() {const set = (n: string) => (v: string) => save.mutate({ [n]: v });if (settings.isLoading) return <Loader2 className="size-5 animate-spin text-muted-foreground" />;+ const mode = get("engineMode")?.value || "both";return (<div><Section- title="Cloud models"+ id="engine"+ title="Engine mode"+ description="Choose what this install runs: fully open source, only paid APIs, or both side by side. The mode is enforced on the server, so a locked engine can't be used from the API either."+ >+ <EngineModePicker value={mode} onChange={set("engineMode")} />+ <p className="text-[12px] text-muted-foreground">Also settable with the <code className="font-mono">FUOBE_ENGINE_MODE</code> environment variable (both · open · cloud).</p>+ </Section>++ <Section+ id="cloud"+ title="Paid API configuration"description={<>- One fal.ai key unlocks Nano Banana Pro, Seedream, Kling, Veo 3.1, Sora 2, Seedance, Hailuo, Wan and more. Replicate is used as a fallback where it hosts the same model.+ One fal.ai key unlocks Nano Banana, Seedream, GPT Image, FLUX, Kling, Seedance, Veo 3.1, Wan, MiniMax, avatars and more. Replicate hosts a subset and is used as a fallback (or first, if you prefer it).</>}+ inactive={mode === "open" ? "Not used in Open source only mode" : undefined}><Fieldsetting={get("falKey")}@@ -160,13 +243,39 @@ export function SettingsForm() {}/><TestButton provider="fal" />- <Field setting={get("replicateToken")} label="Replicate API token" placeholder="r8_…" onSave={set("replicateToken")} />+ <Field+ setting={get("replicateToken")}+ label="Replicate API token"+ placeholder="r8_…"+ onSave={set("replicateToken")}+ hint={+ <a href="https://replicate.com/account/api-tokens" target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-brand-text hover:underline">+ Get a token <ExternalLink className="size-3" />+ </a>+ }+ /><TestButton provider="replicate" />+ <div className="space-y-1.5">+ <Label className="text-[13px]">Preferred provider</Label>+ <Select value={get("cloudProvider")?.value || "auto"} onValueChange={set("cloudProvider")}>+ <SelectTrigger className="w-72">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="auto">Automatic (fal.ai first, Replicate fallback)</SelectItem>+ <SelectItem value="fal">Prefer fal.ai</SelectItem>+ <SelectItem value="replicate">Prefer Replicate</SelectItem>+ </SelectContent>+ </Select>+ <p className="text-[12px] text-muted-foreground">Used when a model is available on both. Models only one provider hosts always use that one.</p>+ </div></Section><Section- title="Open source · ComfyUI"- description="Run every open-source workflow on your own GPU (or a rented one). Fuobe talks to ComfyUI's HTTP API and uploads inputs for you. See Workflows for the models each one needs."+ id="comfyui"+ title="Open-source engine · ComfyUI"+ description="Run every open-source workflow on your own GPU (or a rented one). Fuobe talks to ComfyUI's HTTP API and uploads inputs for you. See ComfyUI workflows for the models each one needs."+ inactive={mode === "cloud" ? "Not used in Paid APIs only mode" : undefined}><Field setting={get("comfyUrl")} label="ComfyUI server URL" placeholder="http://127.0.0.1:8188" onSave={set("comfyUrl")} /><Field setting={get("comfyToken")} label="Auth token (optional)" hint="Sent as a Bearer token, for ComfyUI behind a proxy." onSave={set("comfyToken")} />@@ -175,7 +284,7 @@ export function SettingsForm() {<Sectiontitle="Prompt enhancement"- description="The Enhance toggle rewrites short ideas into rich prompts. Use Claude, a local Ollama model (fully open source), or the built-in offline rewriter."+ description="The Enhance toggle rewrites short ideas into rich prompts. Use Claude, a local Ollama model (fully open source), or the built-in offline rewriter. In Open source only mode, Automatic skips Claude."><div className="space-y-1.5"><Label className="text-[13px]">Enhancer</Label>diff --git a/src/components/studio/engine-switch.tsx b/src/components/studio/engine-switch.tsxindex 54a9e886..cd0ccd72 100644--- a/src/components/studio/engine-switch.tsx+++ b/src/components/studio/engine-switch.tsx@@ -1,8 +1,10 @@"use client";-import { Cloud, Cpu } from "lucide-react";+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 } from "@/lib/api";import { cn } from "@/lib/utils";const OPTIONS: { value: Engine; label: string; icon: typeof Cloud; tip: string }[] = [@@ -20,7 +22,29 @@ export function EngineSwitch({onChange: (e: Engine) => void;size?: "sm" | "md";}) {+ const mode = useEngineMode();const idx = OPTIONS.findIndex((o) => o.value === value);+ if (mode !== "both") {+ const o = OPTIONS.find((x) => x.value === mode)!;+ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <Link+ href="/settings"+ className={cn(+ "inline-flex items-center gap-1.5 rounded-full bg-muted px-3 text-[13px] font-medium text-muted-foreground transition-colors hover:text-foreground",+ size === "sm" ? "h-8" : "h-9",+ )}+ >+ <o.icon className="size-3.5" />+ {mode === "open" ? "Open source only" : "Cloud only"}+ <Lock className="size-3 opacity-60" />+ </Link>+ </TooltipTrigger>+ <TooltipContent>Locked in Settings → Engine mode</TooltipContent>+ </Tooltip>+ );+ }return (<divrole="radiogroup"diff --git a/src/lib/api.ts b/src/lib/api.tsindex 5a760cdc..140f4d28 100644--- a/src/lib/api.ts+++ b/src/lib/api.ts@@ -1,7 +1,7 @@"use client";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import { useCallback, useSyncExternalStore } from "react";+import { useCallback, useEffect, useSyncExternalStore } from "react";import type { Engine, Generation, GenerationRequest, MediaKind } from "./catalog/types";export interface Asset {@@ -124,9 +124,13 @@ export function useAssets(source?: "upload" | "generation", kind?: MediaKind) {// ---------------------------------------------------------------------------// Provider status+export type EngineMode = "both" | "open" | "cloud";+export interface StatusInfo {providers: Record<string, { label: string; configured: boolean }>;demoMode: string;+ engineMode: EngineMode;+ cloudProvider: string;}export function useStatus() {@@ -152,8 +156,10 @@ export async function enhance(prompt: string, kind: MediaKind, op: string): Prom// ---------------------------------------------------------------------------// 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.const ENGINE_KEY = "fuobe.engine";+const MODE_KEY = "fuobe.engineMode";const listeners = new Set<() => void>();function readEngine(): Engine {@@ -164,7 +170,49 @@ function readEngine(): Engine {}}-export function useEngine(): [Engine, (e: Engine) => void] {+function readCachedMode(): EngineMode {+ try {+ const m = localStorage.getItem(MODE_KEY);+ return m === "open" || m === "cloud" ? m : "both";+ } catch {+ return "both";+ }+}++const noopSubscribe = () => () => {};++/** false while hydrating (matches the server HTML), true afterwards. */+export function useHydrated(): boolean {+ return useSyncExternalStore(noopSubscribe, () => true, () => false);+}++/** The install's engine mode (from the server, cached locally so pages don't flash). */+export function useEngineMode(): EngineMode {+ const hydrated = useHydrated();+ const status = useStatus().data;+ const cached = useSyncExternalStore(+ (cb) => {+ listeners.add(cb);+ return () => listeners.delete(cb);+ },+ readCachedMode,+ () => "both" as EngineMode,+ );+ const serverMode = status?.engineMode;+ useEffect(() => {+ if (!serverMode || serverMode === readCachedMode()) return;+ try {+ localStorage.setItem(MODE_KEY, serverMode);+ } catch {}+ listeners.forEach((l) => l());+ }, [serverMode]);+ // Suspense subtrees can hydrate after the status query resolved; render the server's view until hydrated.+ if (!hydrated) return "both";+ return serverMode ?? cached;+}++export function useEngine(): [Engine, (e: Engine) => void, EngineMode] {+ const mode = useEngineMode();const engine = useSyncExternalStore((cb) => {listeners.add(cb);@@ -177,11 +225,15 @@ export function useEngine(): [Engine, (e: Engine) => void] {readEngine,() => "cloud" as Engine,);- const set = useCallback((e: Engine) => {- try {- localStorage.setItem(ENGINE_KEY, e);- } catch {}- listeners.forEach((l) => l());- }, []);- return [engine, set];+ const set = useCallback(+ (e: Engine) => {+ if (mode !== "both") return;+ try {+ localStorage.setItem(ENGINE_KEY, e);+ } catch {}+ listeners.forEach((l) => l());+ },+ [mode],+ );+ return [mode === "both" ? engine : mode, set, mode];}diff --git a/src/server/enhance.ts b/src/server/enhance.tsindex 5f976511..069aa5b1 100644--- a/src/server/enhance.ts+++ b/src/server/enhance.ts@@ -1,7 +1,7 @@import "server-only";import Anthropic from "@anthropic-ai/sdk";import type { MediaKind, Operation } from "@/lib/catalog/types";-import { getSetting } from "./settings";+import { engineMode, getSetting } from "./settings";/*** "Enhance prompt": rewrite a short idea into a rich, model-friendly prompt.@@ -82,7 +82,8 @@ export function heuristicEnhance(prompt: string, kind: MediaKind, op: Operation)export async function enhancePrompt(prompt: string, kind: MediaKind, op: Operation): Promise<string> {const choice = getSetting("enhanceProvider");- const useClaude = choice === "anthropic" || (choice === "auto" && !!getSetting("anthropicKey"));+ // "Open source only" installs never call a paid API unless Claude was picked explicitly.+ const useClaude = choice === "anthropic" || (choice === "auto" && engineMode() !== "open" && !!getSetting("anthropicKey"));if (useClaude) return viaClaude(prompt, kind, op);if (choice === "ollama") return viaOllama(prompt, kind, op);if (choice === "auto") {diff --git a/src/server/generations.ts b/src/server/generations.tsindex 6082ecda..20a0f3da 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -17,7 +17,7 @@ import { db } from "./db";import { enhancePrompt } from "./enhance";import { provider } from "./providers";import type { RemoteOutput } from "./providers/types";-import { getSetting } from "./settings";+import { engineMode, getSetting } from "./settings";import { contentTypeFor, readRef, saveFile } from "./storage";interface Row {@@ -142,7 +142,10 @@ export function deleteGeneration(id: string): void {// Routing/** Pick the provider for a run: a configured real provider, else the demo provider (unless demo is off). */-export function chooseRoute(routes: ModelRoute[]): { route: ModelRoute; demo: boolean } {+export function chooseRoute(candidates: ModelRoute[]): { route: ModelRoute; demo: boolean } {+ // Honour the preferred cloud aggregator (Settings → API configuration) when a model is on several.+ const preferred = getSetting("cloudProvider");+ const routes = preferred === "auto" ? candidates : [...candidates].sort((a, b) => Number(b.provider === preferred) - Number(a.provider === preferred));const demo = getSetting("demoMode");if (demo === "on") return { route: routes[0], demo: true };const real = routes.find((r) => provider(r.provider).isConfigured());@@ -159,6 +162,14 @@ export function chooseRoute(routes: ModelRoute[]): { route: ModelRoute; demo: boexport function createGenerations(req: GenerationRequest): Generation[] {const plan = planGeneration(req, getModel, getPreset);+ const mode = engineMode();+ if (mode !== "both" && plan.model.engine !== mode) {+ throw new Error(+ mode === "open"+ ? `${plan.model.name} is a paid cloud model, but this install is set to open source only (Settings → Engine mode)`+ : `${plan.model.name} is an open-source model, but this install is set to paid cloud APIs only (Settings → Engine mode)`,+ );+ }const { route, demo } = chooseRoute(routesFor(plan.model, plan.op));const providerId: ProviderId = demo ? "mock" : route.provider;const batchId = plan.jobs > 1 ? nanoid(10) : null;diff --git a/src/server/settings.ts b/src/server/settings.tsindex 8c4499e7..d634e005 100644--- a/src/server/settings.ts+++ b/src/server/settings.ts@@ -11,9 +11,15 @@ export interface SettingDef {env?: string;secret?: boolean;default?: string;+ /** Allowed values (validated on save). */+ options?: readonly string[];}export const SETTINGS = {+ /** Which engines this install offers: open-source only, paid cloud APIs only, or both. */+ engineMode: { key: "engine.mode", env: "FUOBE_ENGINE_MODE", default: "both", options: ["both", "open", "cloud"] },+ /** Which aggregator to try first when a cloud model is on several. */+ cloudProvider: { key: "cloud.provider", env: "FUOBE_CLOUD_PROVIDER", default: "auto", options: ["auto", "fal", "replicate"] },falKey: { key: "fal.key", env: "FAL_KEY", secret: true },replicateToken: { key: "replicate.token", env: "REPLICATE_API_TOKEN", secret: true },openaiKey: { key: "openai.key", env: "OPENAI_API_KEY", secret: true },@@ -22,8 +28,8 @@ export const SETTINGS = {comfyUrl: { key: "comfyui.url", env: "COMFYUI_URL", default: "http://127.0.0.1:8188" },comfyToken: { key: "comfyui.token", env: "COMFYUI_TOKEN", secret: true },/** "auto" = demo outputs only when the chosen provider is not configured. */- demoMode: { key: "demo.mode", env: "FUOBE_DEMO_MODE", default: "auto" },- enhanceProvider: { key: "enhance.provider", env: "FUOBE_ENHANCE_PROVIDER", default: "auto" },+ demoMode: { key: "demo.mode", env: "FUOBE_DEMO_MODE", default: "auto", options: ["auto", "on", "off"] },+ enhanceProvider: { key: "enhance.provider", env: "FUOBE_ENHANCE_PROVIDER", default: "auto", options: ["auto", "anthropic", "ollama", "none"] },ollamaUrl: { key: "ollama.url", env: "OLLAMA_URL", default: "http://127.0.0.1:11434" },ollamaModel: { key: "ollama.model", env: "OLLAMA_MODEL", default: "qwen3:8b" },} satisfies Record<string, SettingDef>;@@ -33,12 +39,28 @@ export type SettingName = keyof typeof SETTINGS;export function getSetting(name: SettingName): string {const def: SettingDef = SETTINGS[name];const row = db().prepare("SELECT value FROM settings WHERE key = ?").get(def.key) as { value: string } | undefined;- if (row && row.value !== "") return row.value;- if (def.env && process.env[def.env]) return process.env[def.env]!;- return def.default ?? "";+ const value = row && row.value !== "" ? row.value : def.env && process.env[def.env] ? process.env[def.env]! : (def.default ?? "");+ // An invalid env/db value falls back to the default instead of breaking routing.+ if (def.options && !def.options.includes(value)) return def.default ?? "";+ return value;+}++export type EngineMode = "both" | "open" | "cloud";++export function engineMode(): EngineMode {+ return getSetting("engineMode") as EngineMode;+}++/** Throws a user-facing message if the setting value isn't allowed. */+export function validateSetting(name: SettingName, value: string): void {+ const def: SettingDef = SETTINGS[name];+ if (value !== "" && def.options && !def.options.includes(value)) {+ throw new Error(`${name} must be one of: ${def.options.join(", ")}`);+ }}export function setSetting(name: SettingName, value: string): void {+ validateSetting(name, value);const def = SETTINGS[name];if (value === "") {db().prepare("DELETE FROM settings WHERE key = ?").run(def.key);diff --git a/tests/engine-mode.test.ts b/tests/engine-mode.test.tsnew file mode 100644index 00000000..760e3f8a--- /dev/null+++ b/tests/engine-mode.test.ts@@ -0,0 +1,53 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++// Isolated database for this file (must be set before the server modules load).+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-test-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9"; // nothing listens here → open models fall back to demo++const { setSetting, getSetting, validateSetting } = await import("@/server/settings");+const { chooseRoute, createGenerations } = await import("@/server/generations");+const { getModel } = await import("@/lib/catalog");++beforeAll(() => setSetting("demoMode", "auto"));+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++describe("engine mode", () => {+ it("defaults to both and rejects invalid values", () => {+ expect(getSetting("engineMode")).toBe("both");+ expect(() => validateSetting("engineMode", "gpu")).toThrow(/both, open, cloud/);+ expect(() => setSetting("cloudProvider", "openai")).toThrow();+ });++ it("open-source-only blocks paid models on the server", () => {+ setSetting("engineMode", "open");+ expect(() => createGenerations({ feature: "image", modelId: "nano-banana-pro", prompt: "x" })).toThrow(/open source only/);+ const [g] = createGenerations({ feature: "image", modelId: "oss-z-image-turbo", prompt: "x" });+ expect(g.engine).toBe("open");+ });++ it("paid-only blocks open models", () => {+ setSetting("engineMode", "cloud");+ expect(() => createGenerations({ feature: "image", modelId: "oss-z-image-turbo", prompt: "x" })).toThrow(/paid cloud APIs only/);+ setSetting("engineMode", "both");+ });+});++describe("preferred cloud provider", () => {+ it("orders routes by the preferred aggregator when both are configured", () => {+ setSetting("falKey", "fal_test_key_123456");+ setSetting("replicateToken", "r8_test_token_123456");+ const routes = getModel("nano-banana-pro")!.routes.filter((r) => r.op === "t2i");+ expect(chooseRoute(routes).route.provider).toBe("fal");+ setSetting("cloudProvider", "replicate");+ expect(chooseRoute(routes).route.provider).toBe("replicate");+ setSetting("cloudProvider", "auto");+ setSetting("falKey", "");+ expect(chooseRoute(routes).route.provider).toBe("replicate");+ setSetting("replicateToken", "");+ expect(chooseRoute(routes)).toMatchObject({ demo: true });+ });+});