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.

Settings: Save & test checks what you typed, a status strip, and the setup guide

Claude7057ffb75657
diff --git a/src/app/(studio)/settings/page.tsx b/src/app/(studio)/settings/page.tsx
index 4a17b9f6..bf59a55f 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 { PageHeader, PageShell } from "@/components/page-shell";
import { SettingsForm } from "@/components/settings-form";
+import { starterPriceLine } from "@/lib/starter-prices";
export const metadata: Metadata = { title: "Settings" };
@@ -8,7 +9,7 @@ export default function Page() {
return (
<PageShell>
<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 />
+ <SettingsForm prices={starterPriceLine()} />
</PageShell>
);
}
diff --git a/src/app/api/providers/test/route.ts b/src/app/api/providers/test/route.ts
index 6b6fe4f6..2b9aca2d 100644
--- a/src/app/api/providers/test/route.ts
+++ b/src/app/api/providers/test/route.ts
@@ -1,9 +1,30 @@
+import { candidateValues, isTestProvider, settingProblem } from "@/lib/connections";
import { PROVIDERS } from "@/server/providers";
-import type { ProviderId } from "@/lib/catalog/types";
+import { validateSetting, withCandidates, type SettingName } from "@/server/settings";
+/**
+ * Test a provider's connection. With `value` (the provider's main setting) or `values` (by setting
+ * name), the test runs with those unsaved values instead of the saved ones, so Settings can check a
+ * key or an address before saving it. Nothing is stored here.
+ */
export async function POST(request: Request) {
- const { provider } = (await request.json().catch(() => ({}))) as { provider?: ProviderId };
- const adapter = provider ? PROVIDERS[provider] : undefined;
- if (!adapter?.test) return Response.json({ ok: false, detail: "Unknown provider" }, { status: 400 });
- return Response.json(await adapter.test());
+ const body = (await request.json().catch(() => ({}))) as { provider?: unknown; value?: unknown; values?: unknown };
+ const provider = body.provider;
+ const adapter = isTestProvider(provider) ? PROVIDERS[provider] : undefined;
+ if (!isTestProvider(provider) || !adapter?.test) return Response.json({ ok: false, detail: "Unknown provider" }, { status: 400 });
+ const values = candidateValues(provider, body.values, body.value) as Partial<Record<SettingName, string>>;
+ try {
+ for (const [name, v] of Object.entries(values)) validateSetting(name as SettingName, v);
+ } catch (e) {
+ return Response.json({ ok: false, detail: (e as Error).message }, { status: 400 });
+ }
+ const test = adapter.test.bind(adapter);
+ try {
+ const res = await withCandidates(values, test);
+ // A rejected key that doesn't look like one: say what it should look like.
+ const hint = !res.ok && Object.entries(values).map(([n, v]) => settingProblem(n, v ?? "")).find(Boolean);
+ return Response.json(hint && !res.detail.includes(hint) ? { ...res, detail: `${res.detail} — ${hint}` } : res);
+ } catch (e) {
+ return Response.json({ ok: false, detail: `Couldn't run the test: ${(e as Error).message}` });
+ }
}
diff --git a/src/app/api/status/route.ts b/src/app/api/status/route.ts
index c7a86605..690f4b47 100644
--- a/src/app/api/status/route.ts
+++ b/src/app/api/status/route.ts
@@ -3,7 +3,7 @@ import { PROVIDERS } from "@/server/providers";
import { probeComfy } from "@/server/providers/comfyui";
import { getSetting } from "@/server/settings";
-/** Which providers are usable right now — drives badges and the demo-mode banner. */
+/** Which providers are usable right now — drives badges, the demo-mode notice and Home's first-run guide. */
export async function GET() {
await connection();
const comfy = await probeComfy(true);
@@ -18,5 +18,6 @@ export async function GET() {
demoMode: getSetting("demoMode"),
engineMode: getSetting("engineMode"),
cloudProvider: getSetting("cloudProvider"),
+ onboarded: getSetting("onboarded") === "1",
});
}
diff --git a/src/components/connect-field.tsx b/src/components/connect-field.tsx
new file mode 100644
index 00000000..d0d82310
--- /dev/null
+++ b/src/components/connect-field.tsx
@@ -0,0 +1,198 @@
+"use client";
+
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { CheckCircle2, CircleAlert, Loader2, TriangleAlert } from "lucide-react";
+import { useId, useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { saveSettings, testConnection, useStatus, type ConnectionTest } from "@/lib/api";
+import { settingProblem, type TestProvider } from "@/lib/connections";
+import { cn } from "@/lib/utils";
+
+export interface PublicSetting {
+ name: string;
+ value: string;
+ secret: boolean;
+ fromEnv: boolean;
+ isSet: boolean;
+}
+
+/** Every setting as the browser may see it (secrets masked). */
+export function useSettings() {
+ return useQuery({
+ queryKey: ["settings"],
+ queryFn: async () => ((await (await fetch("/api/settings")).json()) as { settings: PublicSetting[] }).settings,
+ });
+}
+
+interface Result extends ConnectionTest {
+ /** The typed values that didn't connect and weren't saved ("Save anyway" saves them). */
+ unsaved?: Record<string, string>;
+ saved?: boolean;
+}
+
+/**
+ * A key or address field with one button that does what it says: "Save & test" tests the typed value
+ * first and saves it once it connects (a value that doesn't connect is offered "Save anyway"); with
+ * nothing typed it tests the saved one. Used by Settings and by Home's first-run guide.
+ */
+export function ConnectField({
+ name,
+ setting,
+ provider,
+ label,
+ hint,
+ placeholder,
+ id,
+ idleLabel = "Test",
+ onConnected,
+ className,
+}: {
+ name: string;
+ setting?: PublicSetting;
+ provider: TestProvider;
+ label: string;
+ hint?: React.ReactNode;
+ placeholder?: string;
+ /** Anchor for links to this field (/settings#fal). */
+ id?: string;
+ /** The button's words when nothing new was typed. */
+ idleLabel?: string;
+ /** After a green test (the first-run guide closes itself). */
+ onConnected?: (r: ConnectionTest) => void;
+ className?: string;
+}) {
+ const qc = useQueryClient();
+ const status = useStatus().data;
+ const inputId = useId();
+ const [draft, setDraft] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [result, setResult] = useState<Result | null>(null);
+ const secret = !!setting?.secret;
+ const saved = secret ? "" : (setting?.value ?? "");
+ const typed = draft !== null && draft.trim() !== saved.trim() ? draft.trim() : null;
+ const shown = draft ?? saved;
+ const problem = typed ? settingProblem(name, typed) : null;
+ const canTest = typed !== null || !!setting?.isSet || !!setting?.value;
+
+ const refresh = () => {
+ void qc.invalidateQueries({ queryKey: ["settings"] });
+ void qc.invalidateQueries({ queryKey: ["status"] });
+ };
+
+ const run = async () => {
+ if (busy || !canTest) return;
+ setBusy(true);
+ try {
+ const values = typed !== null ? { [name]: typed } : undefined;
+ const res = await testConnection(provider, values);
+ if (res.ok) {
+ // Connected: keep it, and the first-run guide has done its job.
+ const patch = { ...values, ...(status?.onboarded ? {} : { onboarded: "1" }) };
+ if (Object.keys(patch).length) await saveSettings(patch);
+ setDraft(null);
+ refresh();
+ onConnected?.(res);
+ }
+ setResult({ ...res, saved: res.ok && !!values, unsaved: !res.ok ? values : undefined });
+ } catch (e) {
+ setResult({ ok: false, detail: (e as Error).message });
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const saveAnyway = async (values: Record<string, string>) => {
+ try {
+ await saveSettings(values);
+ setDraft(null);
+ setResult((r) => r && { ...r, unsaved: undefined, saved: true });
+ refresh();
+ toast.success("Saved — it didn't connect yet");
+ } catch (e) {
+ toast.error((e as Error).message);
+ }
+ };
+
+ const clear = async () => {
+ try {
+ await saveSettings({ [name]: "" });
+ setDraft(null);
+ setResult(null);
+ refresh();
+ toast.success(`${label} cleared`);
+ } catch (e) {
+ toast.error((e as Error).message);
+ }
+ };
+
+ return (
+ <div id={id} className={cn("min-w-0 scroll-mt-28 space-y-1.5", className)}>
+ <Label htmlFor={inputId} className="text-[13px]">
+ {label}
+ </Label>
+ <div className="flex flex-wrap gap-2">
+ <Input
+ id={inputId}
+ aria-describedby={`${inputId}-hint ${inputId}-result`}
+ aria-invalid={!!problem || (result ? !result.ok : undefined)}
+ autoComplete="off"
+ spellCheck={false}
+ type={secret ? "password" : "text"}
+ value={shown}
+ placeholder={secret && setting?.isSet ? setting.value : placeholder}
+ onChange={(e) => {
+ setDraft(e.target.value);
+ setResult(null);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && !e.nativeEvent.isComposing) {
+ e.preventDefault();
+ void run();
+ }
+ }}
+ className="min-w-0 flex-1 basis-56 font-mono text-[13px]"
+ />
+ <div className="flex shrink-0 gap-2">
+ <Button size="sm" className="h-9" disabled={busy || !canTest} onClick={() => void run()} aria-label={`${typed !== null ? "Save and test" : idleLabel} ${label}`}>
+ {busy && <Loader2 className="animate-spin" />}
+ {typed !== null ? "Save & test" : idleLabel}
+ </Button>
+ {setting?.isSet && !setting.fromEnv && secret && typed === null && (
+ <Button size="sm" variant="ghost" className="h-9" aria-label={`Clear ${label}`} onClick={() => void clear()}>
+ Clear
+ </Button>
+ )}
+ </div>
+ </div>
+ {problem && (
+ <p className="flex items-start gap-1.5 text-[12px] text-foreground">
+ <TriangleAlert className="mt-0.5 size-3.5 shrink-0 text-warning" /> {problem}
+ </p>
+ )}
+ <div id={`${inputId}-result`} role="status" aria-live="polite" className="empty:hidden">
+ {result && (
+ <p className={cn("flex flex-wrap items-center gap-x-1.5 gap-y-1 text-[12px]", result.ok ? "text-success" : "text-destructive")}>
+ {result.ok ? <CheckCircle2 className="size-3.5 shrink-0" /> : <CircleAlert className="size-3.5 shrink-0" />}
+ <span className="min-w-0 break-words">
+ {result.ok ? `Connected${result.saved ? " and saved" : ""} · ${result.detail}` : result.saved ? `Saved, not connected yet · ${result.detail}` : result.detail}
+ </span>
+ {result.unsaved && (
+ <button type="button" onClick={() => void saveAnyway(result.unsaved!)} className="font-medium text-foreground underline underline-offset-2 hover:no-underline">
+ Save anyway
+ </button>
+ )}
+ </p>
+ )}
+ </div>
+ {hint !== undefined && (
+ <p id={`${inputId}-hint`} className="text-[12px] text-muted-foreground">
+ {setting?.fromEnv ? "Set from an environment variable; a value saved here wins. " : ""}
+ {hint}
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/get-started.tsx b/src/components/get-started.tsx
new file mode 100644
index 00000000..2dda10c6
--- /dev/null
+++ b/src/components/get-started.tsx
@@ -0,0 +1,198 @@
+"use client";
+
+import { useQueryClient } from "@tanstack/react-query";
+import { AudioLines, Bot, Clapperboard, Cloud, Copy, Cpu, ExternalLink, ImageIcon, Megaphone, Mic2, Sparkles, Video, Wand2, X } from "lucide-react";
+import Link from "next/link";
+import { useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { ConnectField, useSettings } from "@/components/connect-field";
+import { saveSettings, type StatusInfo } from "@/lib/api";
+import { copyWithToast } from "@/lib/clipboard";
+import { COMFY_INSTALL_COMMAND, COMFY_INSTALL_DOCS, FAL_KEYS_URL } from "@/lib/connections";
+import { cn } from "@/lib/utils";
+
+/** "What do you want to do?" — Liner's first-run question, as one tap to the right place. */
+const INTENTS = [
+ { label: "Make an image", href: "/image", icon: ImageIcon, mode: "image" },
+ { label: "Animate a photo", href: "/video", icon: Video, mode: "video" },
+ { label: "Edit a photo", href: "/edit", icon: Wand2, mode: "edit" },
+ { label: "Advertise a product", href: "/marketing", icon: Megaphone },
+ { label: "A talking avatar", href: "/lipsync", icon: Mic2 },
+ { label: "A faceless video", href: "/faceless", icon: Clapperboard },
+ { label: "Voice or music", href: "/audio", icon: AudioLines },
+ { label: "Plan it with Assist", href: "/assist", icon: Bot },
+] as const;
+
+export type IntentMode = "image" | "video" | "edit";
+
+function GuideCard({ icon: Icon, title, cost, children }: { icon: typeof Cloud; title: string; cost: string; children: React.ReactNode }) {
+ return (
+ <section aria-label={title} className="flex min-w-0 flex-col gap-3 rounded-xl border bg-background p-4 text-left">
+ <div className="flex items-center gap-2.5">
+ <span className="grid size-8 shrink-0 place-items-center rounded-lg bg-brand-faint text-brand-text">
+ <Icon className="size-4" />
+ </span>
+ <div className="min-w-0">
+ <h3 className="text-[14px] font-medium">{title}</h3>
+ <p className="text-[12px] text-muted-foreground">{cost}</p>
+ </div>
+ </div>
+ {children}
+ </section>
+ );
+}
+
+/**
+ * The first-run guide: three ways to make things for real (a paid API key, your own GPU, or the
+ * demo), each finished without leaving the page, then Liner's "What do you want to do?" chips.
+ * It shows while nothing is connected and it wasn't dismissed (showFirstRun); connecting something
+ * or "Hide" remembers that on the server, so it doesn't come back in another browser.
+ */
+export function GetStarted({
+ status,
+ prices,
+ onDemo,
+ onMode,
+ intents = true,
+ className,
+}: {
+ status: StatusInfo;
+ /** What a first image and clip cost on the paid route (starterPriceLine on the server). */
+ prices?: string;
+ /** "Just try it": after the guide is put away (Home focuses its composer). */
+ onDemo?: () => void;
+ /** An image / video / edit chip: Home switches its composer instead of leaving the page. */
+ onMode?: (mode: IntentMode) => void;
+ /** Show the "What do you want to do?" chips. */
+ intents?: boolean;
+ className?: string;
+}) {
+ const qc = useQueryClient();
+ const settings = useSettings().data;
+ const get = (n: string) => settings?.find((s) => s.name === n);
+ const [hiding, setHiding] = useState(false);
+ const mode = status.engineMode;
+
+ const hide = async () => {
+ setHiding(true);
+ try {
+ await saveSettings({ onboarded: "1" });
+ await qc.invalidateQueries({ queryKey: ["status"] });
+ return true;
+ } catch (e) {
+ toast.error((e as Error).message);
+ return false;
+ } finally {
+ setHiding(false);
+ }
+ };
+ const connected = (what: string) => (r: { detail: string }) => toast.success(`${what} connected`, { description: r.detail });
+
+ return (
+ <div className={cn("w-full animate-fade-up rounded-2xl border bg-muted/40 p-4 text-left sm:p-5", className)} aria-labelledby="get-started-title">
+ <div className="flex items-start gap-3">
+ <div className="min-w-0 flex-1">
+ <h2 id="get-started-title" className="font-heading text-[24px] leading-tight">
+ Get started
+ </h2>
+ <p className="mt-1 text-[13px] text-muted-foreground">Nothing is connected yet, so every run is a free demo with placeholder results. Connect a model to make the real thing:</p>
+ </div>
+ <Button variant="ghost" size="sm" className="-mt-1 -mr-2 shrink-0 text-muted-foreground" disabled={hiding} onClick={() => void hide()} aria-label="Hide the setup guide">
+ <X /> <span className="hidden sm:inline">Hide</span>
+ </Button>
+ </div>
+
+ <div className={cn("mt-4 grid gap-3", mode === "both" ? "lg:grid-cols-3" : "md:grid-cols-2")}>
+ {mode !== "open" && (
+ <GuideCard icon={Cloud} title="Use paid models" cost={prices ? `Pay per run with your own key: ${prices}` : "Pay per run with your own key"}>
+ <p className="text-[13px] leading-relaxed text-muted-foreground">Nano Banana, Seedance, Kling, Veo and many more through one fal.ai key. Replicate and Higgsfield keys work too (Settings).</p>
+ <ConnectField
+ name="falKey"
+ setting={get("falKey")}
+ provider="fal"
+ label="fal.ai API key"
+ placeholder="key_id:key_secret"
+ onConnected={connected("fal.ai")}
+ hint={
+ <a href={FAL_KEYS_URL} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-brand-text underline-offset-2 hover:underline">
+ Get a key at fal.ai <ExternalLink className="size-3" />
+ </a>
+ }
+ />
+ </GuideCard>
+ )}
+ {mode !== "cloud" && (
+ <GuideCard icon={Cpu} title="Use your GPU" cost="Free: open-source models run on your machine">
+ <p className="text-[13px] leading-relaxed text-muted-foreground">Point Fuobe at a running ComfyUI. Each workflow lists the model files it needs.</p>
+ <ConnectField
+ name="comfyUrl"
+ setting={get("comfyUrl")}
+ provider="comfyui"
+ label="ComfyUI address"
+ placeholder="http://127.0.0.1:8188"
+ idleLabel="Connect"
+ onConnected={connected("ComfyUI")}
+ hint={
+ <span className="flex flex-wrap items-center gap-x-3 gap-y-1">
+ <Link href="/workflows" className="text-brand-text underline-offset-2 hover:underline">
+ Models per workflow
+ </Link>
+ <a href={COMFY_INSTALL_DOCS} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-brand-text underline-offset-2 hover:underline">
+ Install ComfyUI <ExternalLink className="size-3" />
+ </a>
+ <button
+ type="button"
+ onClick={() => void copyWithToast(COMFY_INSTALL_COMMAND, "Install command copied")}
+ className="inline-flex max-w-full items-center gap-1 rounded-md bg-background px-1.5 py-0.5 font-mono text-[11px] text-foreground ring-1 ring-border hover:bg-accent"
+ aria-label={`Copy the install command: ${COMFY_INSTALL_COMMAND}`}
+ >
+ <span className="truncate">{COMFY_INSTALL_COMMAND}</span> <Copy className="size-3 shrink-0" />
+ </button>
+ </span>
+ }
+ />
+ </GuideCard>
+ )}
+ <GuideCard icon={Sparkles} title="Just try it" cost="Free: no keys, no GPU">
+ <p className="text-[13px] leading-relaxed text-muted-foreground">Click through every studio with clearly labelled placeholder results. You can connect a model later in Settings.</p>
+ <Button
+ variant="outline"
+ className="mt-auto w-full sm:w-fit"
+ disabled={hiding}
+ onClick={async () => {
+ if (await hide()) onDemo?.();
+ }}
+ >
+ Try the demo
+ </Button>
+ </GuideCard>
+ </div>
+
+ {intents && (
+ <div className="mt-5">
+ <h3 className="text-[13px] font-medium">What do you want to do?</h3>
+ <ul className="mt-2 flex flex-wrap gap-2">
+ {INTENTS.map((i) => {
+ const cls = "inline-flex h-8 items-center gap-1.5 rounded-full border bg-background px-3 text-[13px] text-muted-foreground transition-colors hover:bg-accent hover:text-foreground";
+ const pick = "mode" in i && onMode ? i.mode : null;
+ return (
+ <li key={i.label}>
+ {pick ? (
+ <button type="button" className={cls} onClick={() => onMode?.(pick)}>
+ <i.icon className="size-3.5" /> {i.label}
+ </button>
+ ) : (
+ <Link href={i.href} className={cls}>
+ <i.icon className="size-3.5" /> {i.label}
+ </Link>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/settings-form.tsx b/src/components/settings-form.tsx
index fc120e78..39c5742c 100644
--- a/src/components/settings-form.tsx
+++ b/src/components/settings-form.tsx
@@ -1,33 +1,22 @@
"use client";
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { CheckCircle2, CircleAlert, Cloud, Cpu, ExternalLink, Layers, Loader2 } from "lucide-react";
-import { useEffect, useId, useState } from "react";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { CheckCircle2, Cloud, Cpu, ExternalLink, Info, Layers, Link2 } from "lucide-react";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useEffect, useState, useSyncExternalStore } from "react";
import { toast } from "sonner";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
+import { ConnectField, useSettings } from "@/components/connect-field";
+import { GetStarted } from "@/components/get-started";
+import { useStatus, type StatusInfo } from "@/lib/api";
+import { connectionSummary, ENGINE_MODE_LABEL, FAL_KEYS_URL, showFirstRun } from "@/lib/connections";
import { cn } from "@/lib/utils";
import { NotificationSettings } from "@/components/notification-settings";
import { SecuritySettings } from "@/components/security-settings";
-interface PublicSetting {
- name: string;
- value: string;
- secret: boolean;
- fromEnv: boolean;
- isSet: boolean;
-}
-
-function useSettings() {
- return useQuery({
- queryKey: ["settings"],
- queryFn: async () => ((await (await fetch("/api/settings")).json()) as { settings: PublicSetting[] }).settings,
- });
-}
-
function Section({
id,
title,
@@ -35,7 +24,7 @@ function Section({
inactive,
children,
}: {
- id?: string;
+ id: string;
title: string;
description: React.ReactNode;
/** Shown when the current engine mode doesn't use this section. */
@@ -43,10 +32,13 @@ function Section({
children: React.ReactNode;
}) {
return (
- <section id={id} aria-labelledby={id ? `${id}-title` : undefined} className="grid scroll-mt-6 grid-cols-[minmax(0,1fr)] gap-6 border-b py-8 first:pt-0 md:grid-cols-[260px_minmax(0,1fr)]">
+ <section id={id} aria-labelledby={`${id}-title`} className="grid scroll-mt-28 grid-cols-[minmax(0,1fr)] gap-6 border-b py-8 last:border-b-0 md:scroll-mt-20 md:grid-cols-[260px_minmax(0,1fr)]">
<div className="min-w-0">
- <h2 id={id ? `${id}-title` : undefined} className="text-[15px] font-semibold">
+ <h2 id={`${id}-title`} className="group flex items-center gap-1.5 text-[15px] font-semibold">
{title}
+ <a href={`#${id}`} aria-label={`Link to ${title}`} className="text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 focus-visible:opacity-100">
+ <Link2 className="size-3.5" />
+ </a>
</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>}
@@ -104,7 +96,7 @@ function EngineModePicker({ value, onChange }: { value: string; onChange: (v: st
{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>
+ <span className="text-[12px] text-muted-foreground">Needs: {m.needs}</span>
</button>
);
})}
@@ -112,101 +104,103 @@ function EngineModePicker({ value, onChange }: { value: string; onChange: (v: st
);
}
-function TestButton({ provider }: { provider: string }) {
- const [res, setRes] = useState<{ ok: boolean; detail: string } | null>(null);
- const m = useMutation({
- mutationFn: async () =>
- (await (
- await fetch("/api/providers/test", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ provider }),
- })
- ).json()) as { ok: boolean; detail: string },
- onSuccess: setRes,
- });
- return (
- <div className="flex items-center gap-2">
- <Button variant="outline" size="sm" onClick={() => m.mutate()} disabled={m.isPending}>
- {m.isPending && <Loader2 className="animate-spin" />} Test connection
- </Button>
- {res && (
- <span className={cn("inline-flex items-center gap-1 text-[12px]", res.ok ? "text-success" : "text-destructive")}>
- {res.ok ? <CheckCircle2 className="size-3.5" /> : <CircleAlert className="size-3.5" />}
- {res.detail}
- </span>
- )}
- </div>
- );
-}
-
-function Field({
- setting,
+/**
+ * A select whose trigger stays short ("Automatic") at any width; what the picked option does is
+ * the line under it, so nothing is cut off.
+ */
+function ChoiceField({
+ id,
label,
- hint,
- placeholder,
- onSave,
+ value,
+ options,
+ onChange,
}: {
- setting?: PublicSetting;
+ id: string;
label: string;
- hint?: React.ReactNode;
- placeholder?: string;
- onSave: (v: string) => void;
+ value: string;
+ options: { value: string; label: string; hint: string }[];
+ onChange: (v: string) => void;
}) {
- const [v, setV] = useState("");
- const [editing, setEditing] = useState(false);
- const id = useId();
- const shown = editing ? v : setting?.secret ? "" : (setting?.value ?? "");
+ const picked = options.find((o) => o.value === value) ?? options[0];
return (
<div className="space-y-1.5">
<Label htmlFor={id} className="text-[13px]">
{label}
</Label>
- <div className="flex gap-2">
- <Input
- id={id}
- aria-describedby={`${id}-hint`}
- autoComplete="off"
- spellCheck={false}
- type={setting?.secret ? "password" : "text"}
- value={shown}
- placeholder={setting?.secret && setting.isSet ? setting.value : placeholder}
- onChange={(e) => {
- setEditing(true);
- setV(e.target.value);
- }}
- className="font-mono text-[13px]"
- />
- <Button
- size="sm"
- className="h-9 shrink-0"
- disabled={!editing}
- aria-label={`Save ${label}`}
- onClick={() => {
- onSave(v);
- setEditing(false);
- setV("");
- }}
- >
- Save
- </Button>
- {setting?.isSet && !setting.fromEnv && (
- <Button size="sm" variant="ghost" className="h-9 shrink-0" aria-label={`Clear ${label}`} onClick={() => onSave("")}>
- Clear
- </Button>
- )}
- </div>
+ <Select value={picked.value} onValueChange={onChange}>
+ <SelectTrigger id={id} aria-describedby={`${id}-hint`} className="w-full sm:w-auto sm:min-w-56">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {options.map((o) => (
+ <SelectItem key={o.value} value={o.value}>
+ {o.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
<p id={`${id}-hint`} className="text-[12px] text-muted-foreground">
- {setting?.fromEnv ? "Set from environment variable. " : ""}
- {hint}
+ {picked.hint}
</p>
</div>
);
}
-export function SettingsForm() {
+/**
+ * What's connected, at a glance and always in view: one chip per connection (green when it works,
+ * each a link to its field) and the engine mode. Also opens the setup guide again.
+ */
+function StatusStrip({ status, onGuide, guideOpen }: { status?: StatusInfo; onGuide: () => void; guideOpen: boolean }) {
+ return (
+ <div className="sticky top-12 z-10 -mx-4 border-b bg-background/90 px-4 py-2.5 backdrop-blur sm:-mx-8 sm:px-8 md:top-0">
+ <nav aria-label="Connections" className="scrollbar-none -my-1 flex items-center gap-1.5 overflow-x-auto py-1">
+ {status ? (
+ <>
+ {connectionSummary(status).map((c) => (
+ <a
+ key={c.id}
+ href={c.href}
+ className={cn(
+ "inline-flex h-7 shrink-0 items-center gap-1.5 rounded-full border bg-background px-2.5 text-[12px] whitespace-nowrap transition-colors hover:bg-accent",
+ c.unused && "opacity-60",
+ )}
+ >
+ <span aria-hidden className={cn("size-1.5 rounded-full", c.ok ? "bg-success" : "bg-muted-foreground/50")} />
+ <span className="font-medium">{c.label}</span>
+ <span className="text-muted-foreground">{c.unused ? "Not used" : c.text}</span>
+ </a>
+ ))}
+ <a href="#engine" className="inline-flex h-7 shrink-0 items-center gap-1.5 rounded-full bg-secondary px-2.5 text-[12px] whitespace-nowrap transition-colors hover:bg-accent">
+ <span className="text-muted-foreground">Engine</span>
+ <span className="font-medium">{ENGINE_MODE_LABEL[status.engineMode]}</span>
+ </a>
+ {!guideOpen && (
+ <button type="button" onClick={onGuide} className="inline-flex h-7 shrink-0 items-center gap-1 rounded-full px-2.5 text-[12px] font-medium whitespace-nowrap text-brand-text hover:bg-brand-faint">
+ Setup guide
+ </button>
+ )}
+ </>
+ ) : (
+ <Skeleton className="h-7 w-full max-w-xl rounded-full" />
+ )}
+ </nav>
+ </div>
+ );
+}
+
+function subscribeHash(cb: () => void) {
+ window.addEventListener("hashchange", cb);
+ return () => window.removeEventListener("hashchange", cb);
+}
+
+export function SettingsForm({ prices }: { prices?: string }) {
const qc = useQueryClient();
+ const router = useRouter();
const settings = useSettings();
+ const status = useStatus().data;
+ // The setup guide on request: the strip's "Setup guide", or a link to /settings#get-started (Home's demo line).
+ const [guide, setGuide] = useState<boolean | null>(null);
+ const askedByLink = useSyncExternalStore(subscribeHash, () => window.location.hash === "#get-started", () => false);
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(),
@@ -236,9 +230,24 @@ export function SettingsForm() {
</div>
);
const mode = get("engineMode")?.value || "both";
+ // The guide opens by itself on a first run, and on request ("Setup guide") after that.
+ const firstRun = showFirstRun(status);
+ const guideOpen = !!status && (firstRun || (guide ?? askedByLink));
return (
<div>
+ <StatusStrip status={status} guideOpen={guideOpen} onGuide={() => setGuide(true)} />
+ {guideOpen && status && (
+ <div id="get-started" className="scroll-mt-28 pt-6 md:scroll-mt-20">
+ <GetStarted status={status} prices={prices} intents={false} onDemo={() => router.push("/")} />
+ {!firstRun && (
+ <button type="button" onClick={() => setGuide(false)} className="mt-2 text-[12px] text-muted-foreground underline-offset-2 hover:underline">
+ Close the guide
+ </button>
+ )}
+ </div>
+ )}
+
<Section
id="engine"
title="Engine mode"
@@ -251,42 +260,42 @@ export function SettingsForm() {
<Section
id="cloud"
title="Paid API configuration"
- description={
- <>
- 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).
- </>
- }
+ description="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). Save & test checks a key before saving it."
inactive={mode === "open" ? "Not used in Open source only mode" : undefined}
>
- <Field
+ <ConnectField
+ id="fal"
+ name="falKey"
setting={get("falKey")}
+ provider="fal"
label="fal.ai API key"
- placeholder="fal_…"
- onSave={set("falKey")}
+ placeholder="key_id:key_secret"
hint={
- <a href="https://fal.ai/dashboard/keys" target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-brand-text hover:underline">
+ <a href={FAL_KEYS_URL} target="_blank" rel="noreferrer" className="inline-flex items-center gap-1 text-brand-text hover:underline">
Get a key <ExternalLink className="size-3" />
</a>
}
/>
- <TestButton provider="fal" />
- <Field
+ <ConnectField
+ id="replicate"
+ name="replicateToken"
setting={get("replicateToken")}
+ provider="replicate"
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" />
- <Field
+ <ConnectField
+ id="higgsfield"
+ name="higgsfieldKey"
setting={get("higgsfieldKey")}
+ provider="higgsfield"
label="Higgsfield API key"
placeholder="KEY_ID:KEY_SECRET"
- onSave={set("higgsfieldKey")}
hint={
<span>
Unlocks Higgsfield&apos;s own models — Soul 2.0, Soul Cinema, Soul ID, Genjutsu, Cinema Studio, Marketing &amp; Ads Studio — and is another route for Seedance, Kling, Wan and MiniMax.{" "}
@@ -296,68 +305,67 @@ export function SettingsForm() {
</span>
}
/>
- <TestButton provider="higgsfield" />
- <div className="space-y-1.5">
- <Label htmlFor="setting-cloud-provider" className="text-[13px]">
- Preferred provider
- </Label>
- <Select value={get("cloudProvider")?.value || "auto"} onValueChange={set("cloudProvider")}>
- <SelectTrigger id="setting-cloud-provider" className="w-full max-w-80">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="auto">Automatic (fal.ai, then Replicate, then Higgsfield)</SelectItem>
- <SelectItem value="fal">Prefer fal.ai</SelectItem>
- <SelectItem value="replicate">Prefer Replicate</SelectItem>
- <SelectItem value="higgsfield">Prefer Higgsfield</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>
+ <ChoiceField
+ id="setting-cloud-provider"
+ label="Preferred provider"
+ value={get("cloudProvider")?.value || "auto"}
+ onChange={set("cloudProvider")}
+ options={[
+ { value: "auto", label: "Automatic", hint: "Tries fal.ai, then Replicate, then Higgsfield when a model is on more than one. Models only one provider hosts always use that one." },
+ { value: "fal", label: "fal.ai first", hint: "fal.ai whenever it hosts the model. Models only one provider hosts always use that one." },
+ { value: "replicate", label: "Replicate first", hint: "Replicate whenever it hosts the model. Models only one provider hosts always use that one." },
+ { value: "higgsfield", label: "Higgsfield first", hint: "Higgsfield whenever it hosts the model. Models only one provider hosts always use that one." },
+ ]}
+ />
</Section>
<Section
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."
+ description={
+ <>
+ Run every open-source workflow on your own GPU (or a rented one). Fuobe talks to ComfyUI&apos;s HTTP API and uploads inputs for you. See{" "}
+ <Link href="/workflows" className="text-brand-text underline-offset-2 hover:underline">
+ ComfyUI workflows
+ </Link>{" "}
+ 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")} />
- <Field
+ <ConnectField name="comfyUrl" setting={get("comfyUrl")} provider="comfyui" label="ComfyUI server URL" placeholder="http://127.0.0.1:8188" hint="Where ComfyUI listens; a local install is http://127.0.0.1:8188." />
+ <ConnectField name="comfyToken" setting={get("comfyToken")} provider="comfyui" label="Auth token (optional)" hint="Sent as a Bearer token, for ComfyUI behind a proxy." />
+ <ConnectField
+ name="comfyIsolatedUrl"
setting={get("comfyIsolatedUrl")}
+ provider="comfyui"
label="Isolated worker URL (optional)"
placeholder="http://127.0.0.1:8189"
hint="A second ComfyUI for LatentSync 1.6 and ThinkSound, whose node packs can't share the main install. scripts/comfy/README.md shows how to start one."
- onSave={set("comfyIsolatedUrl")}
/>
- <TestButton provider="comfyui" />
</Section>
<Section
- title="Prompt enhancement"
+ id="text-ai"
+ title="Prompt enhancement · Claude or Ollama"
description="The Enhance toggle rewrites short ideas into rich prompts, and storyboards split stories into frames. Use Claude, a local Ollama model (fully open source), or the built-in offline rewriter. Claude also powers the Assist agent. In Open source only mode, Automatic skips Claude."
>
- <div className="space-y-1.5">
- <Label htmlFor="setting-enhancer" className="text-[13px]">
- Enhancer
- </Label>
- <Select value={get("enhanceProvider")?.value || "auto"} onValueChange={set("enhanceProvider")}>
- <SelectTrigger id="setting-enhancer" className="w-full max-w-72">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="auto">Automatic (Claude → Ollama → offline)</SelectItem>
- <SelectItem value="anthropic">Claude (Anthropic API)</SelectItem>
- <SelectItem value="ollama">Ollama (local, open source)</SelectItem>
- <SelectItem value="none">Offline rewriter</SelectItem>
- </SelectContent>
- </Select>
- </div>
- <Field setting={get("anthropicKey")} label="Anthropic API key" placeholder="sk-ant-…" onSave={set("anthropicKey")} />
+ <ChoiceField
+ id="setting-enhancer"
+ label="Enhancer"
+ value={get("enhanceProvider")?.value || "auto"}
+ onChange={set("enhanceProvider")}
+ options={[
+ { value: "auto", label: "Automatic", hint: "Claude when a key is set, then Ollama, then the offline rewriter." },
+ { value: "anthropic", label: "Claude", hint: "Claude through your Anthropic key (paid per use)." },
+ { value: "ollama", label: "Ollama", hint: "A local, open-source model through Ollama. Claude is never called." },
+ { value: "none", label: "Offline rewriter", hint: "Built-in rules, no LLM. Text steps (translate, write) are off." },
+ ]}
+ />
+ <ConnectField name="anthropicKey" setting={get("anthropicKey")} provider="llm" label="Anthropic API key" placeholder="sk-ant-…" hint="Test checks the key with a free model list call." />
<div className="grid gap-4 sm:grid-cols-2">
- <Field setting={get("ollamaUrl")} label="Ollama URL" onSave={set("ollamaUrl")} />
- <Field setting={get("ollamaModel")} label="Ollama model" onSave={set("ollamaModel")} />
+ <ConnectField name="ollamaUrl" setting={get("ollamaUrl")} provider="llm" label="Ollama URL" placeholder="http://127.0.0.1:11434" hint="Test checks Ollama answers and has the model." />
+ <ConnectField name="ollamaModel" setting={get("ollamaModel")} provider="llm" label="Ollama model" placeholder="qwen3:8b" hint="Pull it first: ollama pull qwen3:8b" />
</div>
</Section>
@@ -377,17 +385,24 @@ export function SettingsForm() {
<SecuritySettings />
</Section>
- <Section title="Demo mode" description="Lets you click through everything without keys or a GPU. Demo runs return clearly-labelled placeholder media and cost nothing.">
- <Select value={get("demoMode")?.value || "auto"} onValueChange={set("demoMode")}>
- <SelectTrigger aria-label="Demo mode" className="w-full max-w-80">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="auto">Automatic — demo only when a model isn’t connected</SelectItem>
- <SelectItem value="on">Always demo</SelectItem>
- <SelectItem value="off">Never — show an error instead</SelectItem>
- </SelectContent>
- </Select>
+ <Section id="demo" title="Demo mode" description="Lets you click through everything without keys or a GPU. Demo runs return clearly-labelled placeholder media and cost nothing.">
+ <ChoiceField
+ id="setting-demo"
+ label="Demo mode"
+ value={get("demoMode")?.value || "auto"}
+ onChange={set("demoMode")}
+ options={[
+ { value: "auto", label: "Automatic", hint: "A demo only when the model you picked isn't connected." },
+ { value: "on", label: "Always demo", hint: "Every run is a free placeholder, even with keys or ComfyUI connected." },
+ { value: "off", label: "Never", hint: "A model that isn't connected shows an error instead of a demo." },
+ ]}
+ />
+ </Section>
+
+ <Section id="about" title="About & licences" description="Fuobe's version, and the licence of every open model it can run — some are non-commercial or exclude some countries.">
+ <Link href="/settings/about" className="inline-flex items-center gap-2 rounded-xl border px-4 py-3 text-[13px] font-medium transition-colors hover:bg-accent">
+ <Info className="size-4 text-muted-foreground" /> Open About & licences
+ </Link>
</Section>
</div>
);
diff --git a/src/lib/api.ts b/src/lib/api.ts
index b2042884..200def4c 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -4,6 +4,7 @@ import { keepPreviousData, useInfiniteQuery, useMutation, useQuery, useQueryClie
import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from "react";
import { toast } from "sonner";
import type { AssistThread, AssistThreadSummary, AssistThreadView } from "./assist";
+import type { TestProvider } from "./connections";
import type { ElementKind, StudioElement } from "./catalog/elements";
import type { Engine, Generation, GenerationRequest, MediaKind, ReviewStatus } from "./catalog/types";
import {
@@ -772,6 +773,26 @@ export interface StatusInfo {
demoMode: string;
engineMode: EngineMode;
cloudProvider: string;
+ /** The first-run guide was dismissed, or something tested green. */
+ onboarded?: boolean;
+}
+
+/** A connection test's answer (POST /api/providers/test). */
+export interface ConnectionTest {
+ ok: boolean;
+ detail: string;
+}
+
+/** Test a provider, with unsaved values (by setting name) in place of the saved ones when given. */
+export async function testConnection(provider: TestProvider, values?: Record<string, string>): Promise<ConnectionTest> {
+ const res = await fetch("/api/providers/test", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ provider, values }) });
+ const body = (await res.json().catch(() => null)) as ConnectionTest | null;
+ return body && typeof body.ok === "boolean" ? body : { ok: false, detail: `The test didn't answer (${res.status})` };
+}
+
+/** Save settings by name (PUT /api/settings); throws the server's message when a value isn't allowed. */
+export async function saveSettings(patch: Record<string, string>): Promise<void> {
+ await json(await fetch("/api/settings", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(patch) }));
}
export function useStatus() {
diff --git a/src/lib/connections.ts b/src/lib/connections.ts
new file mode 100644
index 00000000..ca0bb3dd
--- /dev/null
+++ b/src/lib/connections.ts
@@ -0,0 +1,145 @@
+/**
+ * Connecting Fuobe to models, as pure logic shared by Settings, Home's first-run guide and the
+ * connection test route: which settings each provider's test reads, what a well-formed key or
+ * address looks like, when to offer the first-run guide, and each connection's one-line status.
+ */
+
+export type TestProvider = "fal" | "replicate" | "higgsfield" | "comfyui" | "llm";
+
+/** The settings each provider's connection test reads; an unsaved value for one of them can be tested before it's saved. */
+export const PROVIDER_SETTINGS = {
+ fal: ["falKey"],
+ replicate: ["replicateToken"],
+ higgsfield: ["higgsfieldKey"],
+ comfyui: ["comfyUrl", "comfyToken", "comfyIsolatedUrl"],
+ llm: ["anthropicKey", "ollamaUrl", "ollamaModel", "enhanceProvider"],
+} as const satisfies Record<TestProvider, readonly string[]>;
+
+export type ConnectionSetting = (typeof PROVIDER_SETTINGS)[TestProvider][number];
+
+export const isTestProvider = (p: unknown): p is TestProvider => typeof p === "string" && Object.hasOwn(PROVIDER_SETTINGS, p);
+
+/**
+ * The unsaved values a test request carries, kept to the settings that provider's test reads:
+ * `values` by setting name, or `value` for the provider's main one (its key, or ComfyUI's address).
+ */
+export function candidateValues(provider: TestProvider, values?: unknown, value?: unknown): Partial<Record<ConnectionSetting, string>> {
+ const allowed: readonly ConnectionSetting[] = PROVIDER_SETTINGS[provider];
+ const out: Partial<Record<ConnectionSetting, string>> = {};
+ if (typeof value === "string") out[allowed[0]] = value.trim();
+ if (values && typeof values === "object") {
+ for (const [k, v] of Object.entries(values)) if (typeof v === "string" && allowed.includes(k as ConnectionSetting)) out[k as ConnectionSetting] = v.trim();
+ }
+ return out;
+}
+
+/** Where to get a fal.ai key (the guide and Settings link to it). */
+export const FAL_KEYS_URL = "https://fal.ai/dashboard/keys";
+/** The ComfyUI address a local install listens on. */
+export const DEFAULT_COMFY_URL = "http://127.0.0.1:8188";
+/** Fuobe's source, for the install scripts and licences. */
+export const FUOBE_REPO = "https://github.com/workingprototype/fuobe";
+/** How to install ComfyUI with every node pack Fuobe's workflows use. */
+export const COMFY_INSTALL_DOCS = `${FUOBE_REPO}/blob/main/scripts/comfy/README.md`;
+export const COMFY_INSTALL_COMMAND = "bash scripts/comfy/install-comfyui.sh";
+
+/** key_id:key_secret, both halves present and no spaces. */
+const KEY_PAIR = /^[^\s:]+:[^\s:]+$/;
+
+function addressProblem(v: string, example: string): string | null {
+ try {
+ const u = new URL(v);
+ return u.protocol === "http:" || u.protocol === "https:" ? null : `Use an http:// or https:// address, like ${example}`;
+ } catch {
+ return /^[\w.-]+(:\d+)?(\/\S*)?$/.test(v) ? `Add http:// in front: http://${v}` : `That isn't a web address — try ${example}`;
+ }
+}
+
+/**
+ * What's wrong with a value typed into a connection field, said the way to fix it; null when it
+ * looks right (or is empty, which clears it). A warning only: the test has the final word.
+ */
+export function settingProblem(name: string, raw: string): string | null {
+ const v = raw.trim();
+ if (!v) return null;
+ switch (name) {
+ case "falKey":
+ if (KEY_PAIR.test(v)) return null;
+ return v.includes(":") ? "Both halves of key_id:key_secret are needed, without spaces — copy the key again" : "fal.ai keys look like key_id:key_secret — paste the whole key, with the part after the colon";
+ case "higgsfieldKey":
+ if (KEY_PAIR.test(v)) return null;
+ return "Higgsfield keys look like KEY_ID:KEY_SECRET (both parts from console.higgsfield.ai)";
+ case "replicateToken":
+ return /^r8_\S+$/.test(v) ? null : "Replicate tokens start with r8_";
+ case "anthropicKey":
+ return /^sk-ant-\S+$/.test(v) ? null : "Anthropic keys start with sk-ant-";
+ case "comfyUrl":
+ return addressProblem(v, DEFAULT_COMFY_URL);
+ case "comfyIsolatedUrl":
+ return addressProblem(v, "http://127.0.0.1:8189");
+ case "ollamaUrl":
+ return addressProblem(v, "http://127.0.0.1:11434");
+ }
+ return null;
+}
+
+// ---------------------------------------------------------------------------
+// What's connected
+
+export type EngineModeName = "both" | "open" | "cloud";
+
+export interface ConnectionState {
+ providers: Record<string, { configured: boolean } | undefined>;
+ engineMode: EngineModeName;
+ /** The first-run guide was dismissed, or something tested green (Settings → `onboarded`). */
+ onboarded?: boolean;
+}
+
+const CLOUD_PROVIDERS = ["fal", "replicate", "higgsfield"] as const;
+
+/** Whether a paid API and ComfyUI are connected. */
+export function connectedEngines(s: ConnectionState): { cloud: boolean; open: boolean } {
+ return { cloud: CLOUD_PROVIDERS.some((p) => s.providers[p]?.configured), open: !!s.providers.comfyui?.configured };
+}
+
+/** Nothing this install's engine mode uses is connected, so every run is a demo. */
+export function nothingConnected(s: ConnectionState): boolean {
+ const c = connectedEngines(s);
+ return s.engineMode === "open" ? !c.open : s.engineMode === "cloud" ? !c.cloud : !c.cloud && !c.open;
+}
+
+/** The first-run guide shows until something is connected or it was dismissed. Unknown status: not yet. */
+export function showFirstRun(s: ConnectionState | undefined): boolean {
+ return !!s && !s.onboarded && nothingConnected(s);
+}
+
+export const ENGINE_MODE_LABEL: Record<EngineModeName, string> = { both: "Open source + paid", open: "Open source only", cloud: "Paid APIs only" };
+
+export interface ConnectionItem {
+ id: "fal" | "replicate" | "higgsfield" | "comfyui" | "llm";
+ label: string;
+ ok: boolean;
+ /** "Key set", "Online", "Off"… */
+ text: string;
+ /** The Settings section to jump to. */
+ href: string;
+ /** The engine mode doesn't use it. */
+ unused: boolean;
+}
+
+/** One line per connection for Settings' status strip, in the order the page lists them. */
+export function connectionSummary(s: ConnectionState): ConnectionItem[] {
+ const key = (id: "fal" | "replicate" | "higgsfield", label: string): ConnectionItem => {
+ const ok = !!s.providers[id]?.configured;
+ return { id, label, ok, text: ok ? "Key set" : "Not set", href: `#${id}`, unused: s.engineMode === "open" };
+ };
+ const comfy = !!s.providers.comfyui?.configured;
+ const llm = !!s.providers.llm?.configured;
+ return [
+ key("fal", "fal.ai"),
+ key("replicate", "Replicate"),
+ key("higgsfield", "Higgsfield"),
+ { id: "comfyui", label: "ComfyUI", ok: comfy, text: comfy ? "Online" : "Offline", href: "#comfyui", unused: s.engineMode === "cloud" },
+ { id: "llm", label: "Claude / Ollama", ok: llm, text: llm ? "On" : "Off", href: "#text-ai", unused: false },
+ ];
+}
diff --git a/src/lib/starter-prices.ts b/src/lib/starter-prices.ts
new file mode 100644
index 00000000..eb645a0a
--- /dev/null
+++ b/src/lib/starter-prices.ts
@@ -0,0 +1,18 @@
+import { getModel } from "@/lib/catalog";
+import { estimateCost } from "@/lib/catalog/plan";
+import { formatCost } from "@/lib/format";
+import { IMAGE_STUDIO, VIDEO_STUDIO } from "@/lib/studios";
+
+/**
+ * What a first image and a first clip cost on the default paid models, for the first-run guide
+ * ("Nano Banana Pro ≈ $0.15 an image · Seedance 2.5 ≈ $0.60 a 5 s clip"). Server side: it reads
+ * the catalog, which stays out of the browser. Empty when no price is known.
+ */
+export function starterPriceLine(): string {
+ const quote = (id: string, what: (d?: number) => string) => {
+ const m = getModel(id);
+ const usd = m ? estimateCost(m, { ...m.defaults }) : null;
+ return m && usd ? `${m.name} ≈ ${formatCost(usd)} ${what(m.defaults?.duration)}` : "";
+ };
+ return [quote(IMAGE_STUDIO.defaultModels.cloud, () => "an image"), quote(VIDEO_STUDIO.defaultModels.cloud, (d) => (d ? `a ${d} s clip` : "a clip"))].filter(Boolean).join(" · ");
+}
diff --git a/src/server/providers/fal.ts b/src/server/providers/fal.ts
index 33c873c5..883c506d 100644
--- a/src/server/providers/fal.ts
+++ b/src/server/providers/fal.ts
@@ -113,9 +113,15 @@ export const falProvider: ProviderAdapter = {
async test() {
if (!key()) return { ok: false, detail: "No key set" };
// Status lookup of a bogus request id: 401/403 means bad key, 404/422 means the key works.
- const res = await fetch(`${QUEUE}/fal-ai/flux/dev/requests/00000000-0000-0000-0000-000000000000/status`, {
- headers: { Authorization: `Key ${key()}` },
- });
+ let res: Response;
+ try {
+ res = await fetch(`${QUEUE}/fal-ai/flux/dev/requests/00000000-0000-0000-0000-000000000000/status`, {
+ headers: { Authorization: `Key ${key()}` },
+ signal: AbortSignal.timeout(15_000),
+ });
+ } catch (e) {
+ return { ok: false, detail: `Can't reach fal.ai (${(e as Error).message})` };
+ }
if (res.status === 401 || res.status === 403) return { ok: false, detail: `Key rejected (${res.status})` };
return { ok: true, detail: "Key accepted" };
},
diff --git a/src/server/providers/llm.ts b/src/server/providers/llm.ts
index afd6f760..fb63ee47 100644
--- a/src/server/providers/llm.ts
+++ b/src/server/providers/llm.ts
@@ -391,6 +391,33 @@ async function runJob(op: string, input: GenInput, backends: Backend[], job: Llm
return [textOutput(done.join("\n\n"), null, { language: lang })];
}
+/** Is the Anthropic key accepted? Listing one model costs nothing. */
+async function testClaude(): Promise<{ ok: boolean; detail: string }> {
+ try {
+ await new Anthropic({ apiKey: getSetting("anthropicKey") }).models.list({ limit: 1 }, { timeout: 15_000, maxRetries: 0 });
+ return { ok: true, detail: "Claude key accepted" };
+ } catch (e) {
+ if (e instanceof Anthropic.AuthenticationError) return { ok: false, detail: "Anthropic rejected the key (401)" };
+ if (e instanceof Anthropic.PermissionDeniedError) return { ok: false, detail: "That Anthropic key can't use the API (403)" };
+ if (e instanceof Anthropic.APIError && e.status) return { ok: false, detail: `Anthropic answered ${e.status}: ${e.message}` };
+ return { ok: false, detail: `Can't reach Anthropic (${(e as Error).message})` };
+ }
+}
+
+/** Does Ollama answer, and has it pulled the model Settings names? */
+async function testOllama(): Promise<{ ok: boolean; detail: string }> {
+ const model = getSetting("ollamaModel");
+ try {
+ const res = await fetch(`${ollamaUrl()}/api/tags`, { signal: AbortSignal.timeout(3000) });
+ if (!res.ok) return { ok: false, detail: `Ollama answered HTTP ${res.status}` };
+ const names = (((await res.json()) as { models?: { name?: string }[] }).models ?? []).map((m) => m.name ?? "");
+ const has = names.some((n) => n === model || n === `${model}:latest` || n.split(":")[0] === model);
+ return has ? { ok: true, detail: `Ollama · ${model} ready` } : { ok: false, detail: `Ollama answers, but ${model} isn't pulled — run: ollama pull ${model}` };
+ } catch (e) {
+ return { ok: false, detail: `Can't reach Ollama at ${ollamaUrl()} (${(e as Error).message})` };
+ }
+}
+
export const llmProvider: ProviderAdapter = {
id: "llm",
label: "Claude or Ollama",
@@ -429,9 +456,17 @@ export const llmProvider: ProviderAdapter = {
jobs().delete(externalId);
},
+ /** Checks each LLM text steps would use: Claude's key (a free model list call) and that Ollama has its model. */
async test() {
+ if (getSetting("enhanceProvider") === "none") return { ok: false, detail: "Text steps are off (Enhancer: Offline rewriter)" };
await probeOllama(true);
const b = llmBackends({ endpoint: "auto" });
- return b.length ? { ok: true, detail: `Text steps run on ${b.map((x) => BACKEND_LABEL[x]).join(", then ")}` } : { ok: false, detail: "Add an Anthropic key or start Ollama" };
+ if (!b.length) {
+ return { ok: false, detail: engineMode() === "open" && getSetting("anthropicKey") ? `Open source only mode skips Claude, and Ollama doesn't answer at ${ollamaUrl()}` : `Add an Anthropic key, or start Ollama (nothing answers at ${ollamaUrl()})` };
+ }
+ const checks = await Promise.all(b.map((x) => (x === "claude" ? testClaude() : x === "ollama" ? testOllama() : Promise.resolve({ ok: true, detail: BACKEND_LABEL[x] }))));
+ const detail = checks.map((c) => c.detail).join(" · ");
+ // Fine when the first one works (the rest are fallbacks); otherwise say what failed.
+ return { ok: checks[0].ok, detail: b.length > 1 && checks[0].ok ? `Text steps run on ${b.map((x) => BACKEND_LABEL[x]).join(", then ")} · ${detail}` : detail };
},
};
diff --git a/src/server/settings.ts b/src/server/settings.ts
index eadd3061..588539c2 100644
--- a/src/server/settings.ts
+++ b/src/server/settings.ts
@@ -1,4 +1,5 @@
import "server-only";
+import { AsyncLocalStorage } from "node:async_hooks";
import { db } from "./db";
/**
@@ -43,13 +44,27 @@ export const SETTINGS = {
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" },
+ /** "1" once the first-run guide was dismissed or something tested green: Home stops offering it. */
+ onboarded: { key: "onboarding.done", default: "0", options: ["0", "1"] },
} satisfies Record<string, SettingDef>;
export type SettingName = keyof typeof SETTINGS;
+/** Unsaved values a connection test runs with (withCandidates), in place of the saved ones. */
+const candidates = new AsyncLocalStorage<Partial<Record<SettingName, string>>>();
+
+/**
+ * Run `fn` as if these settings were saved: Settings' "Save & test" tests a typed key or URL before
+ * writing it. An empty value reads as unset (the environment variable or the default). Nothing is stored.
+ */
+export function withCandidates<T>(values: Partial<Record<SettingName, string>>, fn: () => T): T {
+ return candidates.run(values, fn);
+}
+
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;
+ const candidate = candidates.getStore()?.[name];
+ const row = candidate !== undefined ? { value: candidate.trim() } : (db().prepare("SELECT value FROM settings WHERE key = ?").get(def.key) as { value: string } | undefined);
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 ?? "";
diff --git a/tests/connections.test.ts b/tests/connections.test.ts
new file mode 100644
index 00000000..dd351354
--- /dev/null
+++ b/tests/connections.test.ts
@@ -0,0 +1,187 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, describe, expect, it, vi } from "vitest";
+import { candidateValues, connectionSummary, isTestProvider, nothingConnected, settingProblem, showFirstRun, type ConnectionState } from "@/lib/connections";
+
+/** Settings' "Save & test", the first-run guide's rule and the connection status strip (R4-02, R4-03, R4-33). */
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-connections-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+delete process.env.FAL_KEY;
+delete process.env.ANTHROPIC_API_KEY;
+const { POST: testRoute } = await import("@/app/api/providers/test/route");
+const { GET: statusRoute } = await import("@/app/api/status/route");
+const { getSetting, setSetting, withCandidates } = await import("@/server/settings");
+const { starterPriceLine } = await import("@/lib/starter-prices");
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+/** Answer fetches by URL prefix (status, JSON body); remembers each request's URL and headers. */
+async function withFetch<T>(answers: Record<string, [number, unknown]>, fn: () => Promise<T>) {
+ const real = globalThis.fetch;
+ const seen: { url: string; auth?: string }[] = [];
+ globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
+ const url = input instanceof Request ? input.url : String(input);
+ const headers = new Headers(input instanceof Request ? input.headers : init?.headers);
+ seen.push({ url, auth: headers.get("authorization") ?? headers.get("x-api-key") ?? undefined });
+ const hit = Object.keys(answers).find((k) => url.startsWith(k));
+ if (!hit) throw new TypeError("fetch failed");
+ const [status, body] = answers[hit];
+ return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
+ }) as typeof fetch;
+ try {
+ return { result: await fn(), seen };
+ } finally {
+ globalThis.fetch = real;
+ }
+}
+
+const post = async (body: unknown) => {
+ const res = await testRoute(new Request("http://localhost/api/providers/test", { method: "POST", body: JSON.stringify(body) }));
+ return { status: res.status, body: (await res.json()) as { ok: boolean; detail: string } };
+};
+
+describe("key and address checks", () => {
+ it("wants fal.ai keys as key_id:key_secret", () => {
+ expect(settingProblem("falKey", "1a2b3c-uuid:9f8e7d6c")).toBeNull();
+ expect(settingProblem("falKey", "fal_abcdef")).toMatch(/key_id:key_secret/);
+ expect(settingProblem("falKey", "abc:")).toMatch(/Both halves/);
+ expect(settingProblem("falKey", "abc: def")).toMatch(/Both halves/);
+ // Empty clears the key: nothing to warn about.
+ expect(settingProblem("falKey", " ")).toBeNull();
+ });
+
+ it("knows the other keys' shapes and wants web addresses for servers", () => {
+ expect(settingProblem("higgsfieldKey", "KEY")).toMatch(/KEY_ID:KEY_SECRET/);
+ expect(settingProblem("replicateToken", "abc")).toMatch(/r8_/);
+ expect(settingProblem("replicateToken", "r8_abc")).toBeNull();
+ expect(settingProblem("anthropicKey", "sk-ant-api03-x")).toBeNull();
+ expect(settingProblem("anthropicKey", "sk-proj-x")).toMatch(/sk-ant-/);
+ expect(settingProblem("comfyUrl", "http://127.0.0.1:8188")).toBeNull();
+ expect(settingProblem("comfyUrl", "127.0.0.1:8188")).toBe("Add http:// in front: http://127.0.0.1:8188");
+ expect(settingProblem("ollamaUrl", "ftp://box")).toMatch(/http:\/\//);
+ expect(settingProblem("comfyUrl", "not a url")).toMatch(/isn't a web address/);
+ expect(settingProblem("ollamaModel", "anything")).toBeNull();
+ });
+
+ it("keeps a test's unsaved values to the settings that provider reads", () => {
+ expect(isTestProvider("fal")).toBe(true);
+ expect(isTestProvider("mock")).toBe(false);
+ expect(isTestProvider("toString")).toBe(false);
+ expect(candidateValues("fal", undefined, " a:b ")).toEqual({ falKey: "a:b" });
+ expect(candidateValues("comfyui", { comfyUrl: "http://x:8188", falKey: "no", comfyToken: 5 })).toEqual({ comfyUrl: "http://x:8188" });
+ expect(candidateValues("llm", { ollamaModel: "llama3" })).toEqual({ ollamaModel: "llama3" });
+ });
+});
+
+describe("first-run guide and status strip", () => {
+ const state = (configured: string[], engineMode: ConnectionState["engineMode"] = "both", onboarded = false): ConnectionState => ({
+ providers: Object.fromEntries(["fal", "replicate", "higgsfield", "comfyui", "llm", "mock"].map((p) => [p, { configured: configured.includes(p) || p === "mock" }])),
+ engineMode,
+ onboarded,
+ });
+
+ it("shows the guide until something the engine mode uses is connected, or it was put away", () => {
+ expect(showFirstRun(undefined)).toBe(false);
+ expect(showFirstRun(state([]))).toBe(true);
+ expect(showFirstRun(state(["fal"]))).toBe(false);
+ expect(showFirstRun(state(["comfyui"]))).toBe(false);
+ expect(showFirstRun(state([], "both", true))).toBe(false);
+ // An LLM alone makes nothing.
+ expect(showFirstRun(state(["llm"]))).toBe(true);
+ // A key doesn't help an open-source-only install, nor ComfyUI a paid-only one.
+ expect(nothingConnected(state(["fal"], "open"))).toBe(true);
+ expect(nothingConnected(state(["comfyui"], "cloud"))).toBe(true);
+ expect(nothingConnected(state(["higgsfield"], "cloud"))).toBe(false);
+ });
+
+ it("says what each connection is doing, and which ones the mode doesn't use", () => {
+ const s = connectionSummary(state(["replicate", "comfyui"], "open"));
+ expect(s.map((c) => [c.id, c.text, c.ok, c.unused])).toEqual([
+ ["fal", "Not set", false, true],
+ ["replicate", "Key set", true, true],
+ ["higgsfield", "Not set", false, true],
+ ["comfyui", "Online", true, false],
+ ["llm", "Off", false, false],
+ ]);
+ expect(s.map((c) => c.href)).toEqual(["#fal", "#replicate", "#higgsfield", "#comfyui", "#text-ai"]);
+ });
+
+ it("quotes a first image and clip on the default paid models", () => {
+ expect(starterPriceLine()).toMatch(/^Nano Banana Pro ≈ \$[\d.]+ an image · Seedance 2\.5 ≈ \$[\d.]+ a 5 s clip$/);
+ });
+});
+
+describe("POST /api/providers/test with unsaved values", () => {
+ it("tests a typed fal.ai key without saving it, and says what a key looks like when it's rejected", async () => {
+ setSetting("falKey", "saved-id:saved-secret");
+ const ok = await withFetch({ "https://queue.fal.run/": [404, { detail: "Request not found" }] }, () => post({ provider: "fal", value: "new-id:new-secret" }));
+ expect(ok.result.body).toEqual({ ok: true, detail: "Key accepted" });
+ expect(ok.seen[0].auth).toBe("Key new-id:new-secret");
+ expect(getSetting("falKey")).toBe("saved-id:saved-secret");
+
+ const bad = await withFetch({ "https://queue.fal.run/": [401, { detail: "Unauthorized" }] }, () => post({ provider: "fal", values: { falKey: "fal_only_half" } }));
+ expect(bad.result.body.ok).toBe(false);
+ expect(bad.result.body.detail).toMatch(/^Key rejected \(401\) — fal\.ai keys look like key_id:key_secret/);
+ // Without values it tests the saved key.
+ const saved = await withFetch({ "https://queue.fal.run/": [404, {}] }, () => post({ provider: "fal" }));
+ expect(saved.seen[0].auth).toBe("Key saved-id:saved-secret");
+ setSetting("falKey", "");
+ });
+
+ it("tests a ComfyUI address before it's saved, and says so when nothing answers", async () => {
+ const stats = { system: { comfyui_version: "0.41.0" }, devices: [{ name: "cpu", vram_total: 0 }] };
+ const ok = await withFetch({ "http://10.1.2.3:8188/system_stats": [200, stats] }, () => post({ provider: "comfyui", value: "http://10.1.2.3:8188/" }));
+ expect(ok.result.body).toEqual({ ok: true, detail: "ComfyUI 0.41.0 · cpu" });
+ expect(getSetting("comfyUrl")).toBe("http://127.0.0.1:9");
+ const down = await withFetch({}, () => post({ provider: "comfyui", values: { comfyUrl: "http://10.9.9.9:8188" } }));
+ expect(down.result.body).toMatchObject({ ok: false, detail: expect.stringMatching(/^Can't reach ComfyUI at http:\/\/10\.9\.9\.9:8188/) });
+ });
+
+ it("tests Ollama's address and model, and an Anthropic key, for text steps", async () => {
+ const tags = { models: [{ name: "qwen3:8b" }] };
+ const ready = await withFetch({ "http://10.0.0.5:11434/api/tags": [200, tags] }, () => post({ provider: "llm", values: { ollamaUrl: "http://10.0.0.5:11434" } }));
+ expect(ready.result.body).toEqual({ ok: true, detail: "Ollama · qwen3:8b ready" });
+ const missing = await withFetch({ "http://10.0.0.5:11434/api/tags": [200, tags] }, () => post({ provider: "llm", values: { ollamaUrl: "http://10.0.0.5:11434", ollamaModel: "llama3.3" } }));
+ expect(missing.result.body).toEqual({ ok: false, detail: "Ollama answers, but llama3.3 isn't pulled — run: ollama pull llama3.3" });
+ const none = await withFetch({}, () => post({ provider: "llm" }));
+ expect(none.result.body).toMatchObject({ ok: false, detail: expect.stringMatching(/Add an Anthropic key, or start Ollama/) });
+
+ const rejected = await withFetch(
+ { "https://api.anthropic.com/v1/models": [401, { type: "error", error: { type: "authentication_error", message: "invalid x-api-key" } }] },
+ () => post({ provider: "llm", values: { anthropicKey: "sk-ant-wrong" } }),
+ );
+ expect(rejected.result.body).toEqual({ ok: false, detail: "Anthropic rejected the key (401)" });
+ expect(rejected.seen.some((r) => r.url.startsWith("https://api.anthropic.com/v1/models") && r.auth === "sk-ant-wrong")).toBe(true);
+ const accepted = await withFetch({ "https://api.anthropic.com/v1/models": [200, { data: [{ id: "claude-opus-5-5", type: "model" }], has_more: false }] }, () =>
+ post({ provider: "llm", values: { anthropicKey: "sk-ant-good" } }),
+ );
+ expect(accepted.result.body).toEqual({ ok: true, detail: "Claude key accepted" });
+ expect(getSetting("anthropicKey")).toBe("");
+ });
+
+ it("refuses unknown providers and values a setting doesn't allow", async () => {
+ expect((await post({ provider: "mock" })).status).toBe(400);
+ expect((await post({ provider: "llm", values: { enhanceProvider: "gpt" } })).body).toMatchObject({ ok: false, detail: expect.stringMatching(/enhanceProvider must be one of/) });
+ });
+
+ it("reads candidates only inside the test", () => {
+ setSetting("ollamaModel", "qwen3:8b");
+ expect(withCandidates({ ollamaModel: "llama3" }, () => getSetting("ollamaModel"))).toBe("llama3");
+ // An empty candidate reads as unset: the environment or the default.
+ expect(withCandidates({ ollamaModel: "" }, () => getSetting("ollamaModel"))).toBe("qwen3:8b");
+ expect(getSetting("ollamaModel")).toBe("qwen3:8b");
+ });
+});
+
+describe("GET /api/status", () => {
+ it("says whether the first-run guide was put away", async () => {
+ expect(((await (await statusRoute()).json()) as { onboarded: boolean }).onboarded).toBe(false);
+ setSetting("onboarded", "1");
+ expect(((await (await statusRoute()).json()) as { onboarded: boolean }).onboarded).toBe(true);
+ });
+});