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
Assist: the mode picker and Settings show every provider
Adarsh42fa75c42f90
diff --git a/src/app/api/llm/route.ts b/src/app/api/llm/route.tsindex 79199a27..cc80a591 100644--- a/src/app/api/llm/route.ts+++ b/src/app/api/llm/route.ts@@ -1,24 +1,37 @@import { connection } from "next/server";import { z } from "zod";+import { availability } from "@/server/assist/agent";import { activeLocal, aiHelper, llmContext, localStatuses, pinnedKind, reloadLmStudio, testLocal } from "@/server/llm";+import { tryHosted } from "@/server/llm/hosted";/**- * The local LLM servers for Settings → AI helper. GET: each server's status (up, key, its chat- * models, the model a call would use, what's wrong), `?refresh=1` asks them again now. Keys never- * leave the server. POST {action: "test", kind?}: a tiny call, timed. POST {action: "load", model?}:- * reloads an LM Studio model with the context from Settings.+ * The LLMs for Settings → AI helper. GET: each local server's status (up, key, its chat models, the model a+ * call would use, what's wrong), `?refresh=1` asks them again now; and the hosted providers Assist can use+ * (which are connected, the model Smart plans with and the one Free runs on, in words). Keys never leave the+ * server. POST {action: "test", kind?}: a tiny call to a local server, timed. POST {action: "load", model?}:+ * reloads an LM Studio model with the context from Settings. POST {action: "try", provider, model?}: a tiny+ * call to a hosted provider, timed (a fraction of a cent on a paid model).*/export async function GET(request: Request) {await connection();const refresh = new URL(request.url).searchParams.get("refresh") === "1";const servers = await localStatuses(refresh);- const active = await activeLocal();- return Response.json({ helper: aiHelper(), provider: pinnedKind() ?? "auto", context: llmContext(), active: active?.server.kind ?? null, servers });+ const [active, can] = await Promise.all([activeLocal(), availability()]);+ const hosted = {+ checked: can.checked,+ smart: can.smart.text,+ free: can.free.text,+ providers: can.manual.groups+ .filter((g) => g.models.some((m) => m.agent !== "local"))+ .map((g) => ({ id: g.id, status: g.status, models: g.models.filter((m) => !m.disabled && !m.manualOnly).map((m) => ({ model: m.model, name: m.name })) })),+ };+ return Response.json({ helper: aiHelper(), provider: pinnedKind() ?? "auto", context: llmContext(), active: active?.server.kind ?? null, servers, hosted });}const Action = z.discriminatedUnion("action", [z.object({ action: z.literal("test"), kind: z.enum(["ollama", "lmstudio", "unsloth", "custom"]).nullish() }),z.object({ action: z.literal("load"), model: z.string().trim().max(200).nullish() }),+ z.object({ action: z.literal("try"), provider: z.string().regex(/^[a-z0-9-]{2,32}$/), model: z.string().trim().max(200).nullish() }),]);export async function POST(request: Request) {@@ -26,6 +39,7 @@ export async function POST(request: Request) {if (!parsed.success) return Response.json({ ok: false, detail: "Unknown action" }, { status: 400 });const a = parsed.data;if (a.action === "test") return Response.json(await testLocal(a.kind));+ if (a.action === "try") return Response.json(await tryHosted(a.provider, a.model));try {const r = await reloadLmStudio(a.model);return Response.json({ ok: true, detail: `LM Studio loaded ${r.model}${r.context ? ` with ${r.context.toLocaleString("en-US")} tokens of context` : ""}${r.seconds ? ` in ${r.seconds.toFixed(1)} s` : ""}`, ...r });diff --git a/src/components/assist/mode-picker.tsx b/src/components/assist/mode-picker.tsxindex 59f1efb6..561449ed 100644--- a/src/components/assist/mode-picker.tsx+++ b/src/components/assist/mode-picker.tsx@@ -1,6 +1,6 @@"use client";-import { Bot, ChevronDown, Cpu, Gauge, Sparkles } from "lucide-react";+import { Bot, ChevronDown, Cloud, Cpu, Gauge, Sparkles } from "lucide-react";import Link from "next/link";import { useMemo, useState, useSyncExternalStore } from "react";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";@@ -13,7 +13,9 @@ import {normalizeAgent,type AssistAgent,type AssistAvailability,+ type AssistEffort,type AssistModeChoice,+ type AssistModelOption,} from "@/lib/assist";import { cn } from "@/lib/utils";import { radioKeys, radioTab } from "@/components/studio/radio-keys";@@ -71,31 +73,80 @@ export function modeChipLabel(c: AssistModeChoice | null, can?: AssistAvailabiliif (c.mode !== "manual") return c.mode === "smart" ? "Smart" : "Free";if (c.agent === "offline") return "Offline planner";if (c.agent === "local") return c.model ?? can?.local.model ?? "Local";+ const effort = ASSIST_EFFORTS.find((e) => e.id === (c.effort ?? DEFAULT_EFFORT))?.label;+ if (c.agent === "hosted") {+ const m = can?.manual.groups.flatMap((g) => g.models).find((x) => x.provider === c.provider && x.model === c.model);+ const name = m?.name ?? c.model ?? "Model";+ return m && !m.efforts.length ? name : `${name} · ${effort}`;+ }const m = CLAUDE_MODELS.find((x) => x.id === (c.model ?? DEFAULT_CLAUDE_MODEL))?.label.replace("Claude ", "") ?? "Claude";- return `${m} · ${ASSIST_EFFORTS.find((e) => e.id === (c.effort ?? DEFAULT_EFFORT))?.label}`;+ return `${m} · ${effort}`;}const MODE_ICON = { smart: Sparkles, free: Cpu, manual: Gauge } as const;const sameChoice = (a: AssistModeChoice | null, b: AssistModeChoice | null) =>- (a?.mode ?? null) === (b?.mode ?? null) && (a?.agent ?? null) === (b?.agent ?? null) && (a?.model ?? null) === (b?.model ?? null) && (a?.effort ?? null) === (b?.effort ?? null);+ (a?.mode ?? null) === (b?.mode ?? null) &&+ (a?.agent ?? null) === (b?.agent ?? null) &&+ (a?.provider ?? null) === (b?.provider ?? null) &&+ (a?.model ?? null) === (b?.model ?? null) &&+ (a?.effort ?? null) === (b?.effort ?? null);interface ModelOption {key: string;on: boolean;- disabled?: boolean;+ disabled?: string;pick: Partial<AssistModeChoice>;icon: typeof Bot;title: React.ReactNode;hint: string;+ /** Searched by the filter box. */+ text: string;+ /** The effort levels it offers (none: no effort row). */+ efforts: AssistEffort[];+}++/** The local model server's models, as today: "Local, through LM Studio · free". */+function localOptions(can: AssistAvailability | undefined, on: (name: string) => boolean): ModelOption[] {+ const names = can?.local.models.length ? can.local.models : can?.local.ok && can.local.model ? [can.local.model] : [];+ return names.map((name) => ({+ key: `local:${name}`,+ on: on(name),+ pick: { agent: "local" as const, provider: null, model: name, effort: null },+ icon: Cpu,+ title: <span className="block truncate font-mono text-[12px]">{name}</span>,+ hint: /-cloud$|:cloud$/.test(name) ? `Ollama Cloud · paid, through ${can?.local.label ?? "Ollama"}` : `Local, through ${can?.local.label ?? "your local server"} · free`,+ text: name,+ efforts: [],+ }));+}++/** One model of a connected provider: its name, then a line with the price, what it is and where its weights are open. */+function hostedOption(m: AssistModelOption, shown: AssistModeChoice | null): ModelOption {+ const claude = m.agent === "claude";+ const picked = claude ? shown?.agent === "claude" && (shown?.model ?? DEFAULT_CLAUDE_MODEL) === m.model : shown?.agent === "hosted" && shown?.provider === m.provider && shown?.model === m.model;+ const hint = [claude ? CLAUDE_MODELS.find((c) => c.id === m.model)?.hint : (m.manualOnly ?? m.note), m.price, m.open].filter(Boolean).join(" · ");+ return {+ key: `${m.provider}:${m.model}`,+ on: picked,+ ...(m.disabled && { disabled: m.disabled }),+ pick: claude ? { agent: "claude" as const, provider: null, model: m.model } : { agent: "hosted" as const, provider: m.provider, model: m.model },+ icon: claude ? Bot : Cloud,+ title: <span className="block text-[13px] font-medium">{m.name}</span>,+ hint,+ text: `${m.name} ${m.providerLabel} ${m.model}`,+ efforts: m.efforts,+ };}/**- * Supercomputer's Free / Smart / Manual, on Fuobe's agents (Claude, a local model on Ollama, LM Studio,- * Unsloth Studio or another OpenAI-compatible server, the offline planner).+ * Supercomputer's Free / Smart / Manual, on Fuobe's agents: Claude, the hosted providers the owner connected+ * (OpenAI, Gemini, DeepSeek, OpenRouter…), a local model (Ollama, LM Studio, Unsloth Studio or another+ * OpenAI-compatible server) and the offline planner. Smart and Free say which model they use; Manual lists the+ * connected providers' models in groups, and the others as one "Add a key" line.* With `applyOnClose` (an existing chat) choices are kept in the menu and sent once when it- * closes, so trying the tabs doesn't switch the chat at every click. Smart needs Claude: without- * an Anthropic key it can't be picked (and a saved Smart shows as the Free it runs as).+ * closes, so trying the tabs doesn't switch the chat at every click. Smart needs a model: with+ * nothing connected it can't be picked (and a saved Smart shows as the Free it runs as).*/export function ModePicker({value,@@ -112,8 +163,9 @@ export function ModePicker({}) {const [open, setOpen] = useState(false);const [draft, setDraft] = useState<AssistModeChoice | null>(null);+ const [find, setFind] = useState("");const shown = (applyOnClose && open ? draft : null) ?? value;- const smartOff = !!can && !can.claude;+ const smartOff = !!can && !can.smart?.plan;const picked = shown?.mode ?? can?.defaultMode ?? "smart";const mode = picked === "smart" && smartOff ? "free" : picked;// The label, its aria-label and the icon all come from this one resolved value.@@ -133,29 +185,31 @@ export function ModePicker({};const pending = applyOnClose && open && draft && !sameChoice(draft, value);- const models: ModelOption[] = [- ...CLAUDE_MODELS.map((m) => ({- key: m.id,- on: agent === "claude" && (shown?.model ?? DEFAULT_CLAUDE_MODEL) === m.id,- disabled: !can?.claude,- pick: { agent: "claude" as const, model: m.id },- icon: Bot,- title: <span className="block text-[13px] font-medium">{m.label}</span>,- hint: m.hint,- })),- ...(can?.local.models.length ? can.local.models : can?.local.ok && can.local.model ? [can.local.model] : []).map((name) => ({- key: `local:${name}`,- on: agent === "local" && (shown?.model ?? can?.local.model) === name,- pick: { agent: "local" as const, model: name, effort: null },- icon: Cpu,- title: <span className="block truncate font-mono text-[12px]">{name}</span>,- hint: `Local, through ${can?.local.label ?? "your local server"} · free`,- })),- { key: "offline", on: agent === "offline", pick: { agent: "offline", model: null, effort: null }, icon: Gauge, title: <span className="block text-[13px] font-medium">Offline planner</span>, hint: "Rules, no LLM — simple requests only" },+ // Manual: each connected provider's models (Claude's first when Anthropic is connected), the local server's, then the offline planner.+ const groups: { id: string; label: string; status?: string; models: ModelOption[] }[] = [+ ...(can?.manual?.groups ?? []).filter((g) => g.models.some((m) => m.agent !== "local")).map((g) => ({ id: g.id, label: g.label, status: g.status, models: g.models.map((m) => hostedOption(m, shown)) })),+ ...(can?.local.models.length || can?.local.ok ? [{ id: "local", label: can.local.label, status: "On this machine", models: localOptions(can, (name) => agent === "local" && (shown?.model ?? can?.local.model) === name) }] : []),+ {+ id: "offline",+ label: "No LLM",+ models: [{ key: "offline", on: agent === "offline", pick: { agent: "offline", provider: null, model: null, effort: null }, icon: Gauge, title: <span className="block text-[13px] font-medium">Offline planner</span>, hint: "Rules, no LLM — simple requests only", text: "offline planner", efforts: [] }],+ },];+ const all = groups.flatMap((g) => g.models);+ const q = find.trim().toLowerCase();+ const listed = q ? groups.map((g) => ({ ...g, models: g.models.filter((m) => m.text.toLowerCase().includes(q)) })).filter((g) => g.models.length) : groups;// One Tab stop per group: the picked option, or the first one that can be picked.- const modelStop = models.find((m) => m.on && !m.disabled)?.key ?? models.find((m) => !m.disabled)?.key;+ const modelStop = all.find((m) => m.on && !m.disabled)?.key ?? all.find((m) => !m.disabled)?.key;+ const current = all.find((m) => m.on);+ const efforts = agent === "claude" ? ASSIST_EFFORTS.map((e) => e.id) : (current?.efforts ?? []);const effort = shown?.effort ?? DEFAULT_EFFORT;+ const missing = can?.manual?.missing ?? [];+ // Manual starts on Smart's model (or the local one, or the offline planner) until one is picked.+ const manualStart = (): Partial<AssistModeChoice> => {+ const plan = can?.smart?.plan;+ if (plan && plan.agent !== "local") return plan.agent === "claude" ? { agent: "claude", provider: null, model: plan.model } : { agent: "hosted", provider: plan.provider, model: plan.model };+ return { agent: can?.local.ok ? "local" : "offline" };+ };return (<Popover open={open} onOpenChange={onOpenChange}>@@ -173,7 +227,7 @@ export function ModePicker({<ChevronDown className="size-3 shrink-0 opacity-60 max-sm:hidden" /></button></PopoverTrigger>- <PopoverContent align="start" collisionPadding={12} className="w-[min(92vw,360px)] p-3">+ <PopoverContent align="start" collisionPadding={12} className="max-h-[var(--radix-popover-content-available-height)] w-[min(92vw,360px)] overflow-y-auto overscroll-contain p-3">{can?.aiOff && (<p className="mb-3 rounded-lg bg-highlight/25 px-3 py-2 text-[12px]">The AI helper is off in{" "}@@ -194,8 +248,8 @@ export function ModePicker({aria-checked={mode === m.id}tabIndex={radioTab(mode === m.id)}disabled={off}- title={off ? "Needs an Anthropic API key (Settings)" : undefined}- onClick={() => set({ mode: m.id, ...(m.id === "manual" && !shown?.agent && { agent: can?.claude ? "claude" : can?.local.ok ? "local" : "offline" }) })}+ title={off ? "Needs a model: add a key or start a local model (Settings)" : undefined}+ onClick={() => set({ mode: m.id, ...(m.id === "manual" && !shown?.agent && manualStart()) })}className={cn("h-8 rounded-full text-[13px] font-medium transition-colors disabled:opacity-45", mode === m.id ? "bg-background text-foreground shadow-soft" : "text-muted-foreground enabled:hover:text-foreground")}>{m.label}@@ -204,68 +258,97 @@ export function ModePicker({})}</div><p className="mt-2 px-1 text-[12px] text-muted-foreground">{ASSIST_MODES.find((m) => m.id === mode)?.hint}</p>+ {mode === "smart" && can?.smart?.plan && <p className="mt-2 px-1 text-[12px]">{can.smart.text}</p>}{smartOff && (<p className="mt-2 px-1 text-[12px] text-warning">- Smart and the Claude models need an Anthropic API key —{" "}- <Link href="/settings#text-ai" className="underline underline-offset-2">- add one in Settings- </Link>- .+ Smart needs a model —{" "}+ <Link href="/settings#llm-providers" className="underline underline-offset-2">+ add a key in Settings+ </Link>{" "}+ (Anthropic, OpenAI, Google, OpenRouter…) or start a local model.</p>)}- {mode === "free" && (- <p className="mt-2 px-1 text-[12px] text-muted-foreground">- {can?.local.ok ? (- <>- Runs on <span className="font-mono">{can.local.model}</span> through {can.local.label} — free, on this machine.- </>- ) : can?.local.problem ? (- `${can.local.problem} Until then, the offline planner takes simple requests.`- ) : (- "No local model is answering, so the offline planner takes simple requests. Start Ollama, LM Studio or Unsloth Studio for a real local assistant."- )}- </p>+ {mode === "free" && can?.free && (+ <div className="mt-2 space-y-1 px-1 text-[12px] text-muted-foreground">+ <p>{can.free.pick || !can.local.problem ? can.free.text : `${can.local.problem} Until then, the offline planner takes simple requests.`}</p>+ {can.free.caveat && <p className="text-[11px]">{can.free.caveat}</p>}+ </div>+ )}+ {can?.openOnly && mode !== "free" && (+ <p className="mt-2 px-1 text-[11px] text-muted-foreground">Open source only: open-weight models only. Ones that run on a provider's servers are paid unless they are free.</p>)}{mode === "manual" && (<div className="mt-3 space-y-3">- <div role="radiogroup" aria-label="Model" onKeyDown={radioKeys} className="space-y-1">- {models.map((m) => (- <button- key={m.key}- type="button"- role="radio"- aria-checked={m.on}- tabIndex={m.key === modelStop ? 0 : -1}- disabled={m.disabled}- onClick={() => set(m.pick)}- className={cn("flex w-full items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left transition-colors hover:bg-accent disabled:opacity-50 disabled:hover:bg-transparent", m.on && "bg-brand-faint hover:bg-brand-faint-hover")}- >- <m.icon className="size-4 shrink-0 text-muted-foreground" />- <span className="min-w-0 flex-1">- {m.title}- <span className="block text-[11px] text-muted-foreground">{m.hint}</span>- </span>- </button>- ))}- </div>- {agent === "claude" && (- <div>- <p className="mb-1.5 px-1 text-[12px] font-medium">Effort</p>- <div role="radiogroup" aria-label="Effort" onKeyDown={radioKeys} className="grid grid-cols-5 gap-0.5 rounded-full bg-muted p-0.5">- {ASSIST_EFFORTS.map((e) => (+ {all.length > 12 && (+ <input+ type="search"+ value={find}+ onChange={(e) => setFind(e.target.value)}+ placeholder="Find a model"+ aria-label="Find a model"+ className="h-8 w-full rounded-lg border bg-background px-2.5 text-[13px] outline-none focus-visible:ring-2 focus-visible:ring-ring"+ />+ )}+ <div role="radiogroup" aria-label="Model" onKeyDown={radioKeys} className="max-h-[40vh] space-y-2 overflow-y-auto overscroll-contain">+ {listed.map((g) => (+ <div key={g.id} className="space-y-0.5">+ <p className="px-2.5 pt-1 text-[11px] font-medium text-muted-foreground">+ {g.label}+ {g.status && g.status !== "Key set" ? ` · ${g.status}` : ""}+ </p>+ {g.models.map((m) => (<button- key={e.id}+ key={m.key}type="button"role="radio"- aria-checked={effort === e.id}- tabIndex={radioTab(effort === e.id)}- onClick={() => set({ effort: e.id })}- className={cn("h-7 rounded-full text-[12px] font-medium transition-colors", effort === e.id ? "bg-background text-foreground shadow-soft" : "text-muted-foreground hover:text-foreground")}+ aria-checked={m.on}+ tabIndex={m.key === modelStop ? 0 : -1}+ disabled={!!m.disabled}+ title={m.disabled}+ onClick={() => set(m.pick)}+ className={cn("flex w-full items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left transition-colors hover:bg-accent disabled:opacity-50 disabled:hover:bg-transparent", m.on && "bg-brand-faint hover:bg-brand-faint-hover")}>- {e.label}+ <m.icon className="size-4 shrink-0 text-muted-foreground" />+ <span className="min-w-0 flex-1">+ {m.title}+ <span className="block text-[11px] text-muted-foreground">{m.disabled ?? m.hint}</span>+ </span></button>))}</div>+ ))}+ </div>+ {missing.length > 0 && (+ <p className="px-1 text-[11px] leading-relaxed text-muted-foreground">+ Add a key:{" "}+ <Link href="/settings#llm-providers" className="underline underline-offset-2">+ {missing.map((p) => p.label).join(" · ")}+ </Link>+ </p>+ )}+ {efforts.length > 0 && (+ <div>+ <p className="mb-1.5 px-1 text-[12px] font-medium">Effort</p>+ <div role="radiogroup" aria-label="Effort" onKeyDown={radioKeys} className="grid grid-cols-5 gap-0.5 rounded-full bg-muted p-0.5">+ {ASSIST_EFFORTS.map((e) => {+ const offered = efforts.includes(e.id);+ return (+ <button+ key={e.id}+ type="button"+ role="radio"+ aria-checked={effort === e.id}+ tabIndex={radioTab(effort === e.id)}+ disabled={!offered}+ title={offered ? undefined : "This model doesn't offer this level"}+ onClick={() => set({ effort: e.id })}+ className={cn("h-7 rounded-full text-[12px] font-medium transition-colors disabled:opacity-40", effort === e.id ? "bg-background text-foreground shadow-soft" : "text-muted-foreground enabled:hover:text-foreground")}+ >+ {e.label}+ </button>+ );+ })}+ </div><p className="mt-1.5 px-1 text-[11px] text-muted-foreground">Higher effort thinks longer and costs more per reply.</p></div>)}diff --git a/src/components/llm-provider-settings.tsx b/src/components/llm-provider-settings.tsxnew file mode 100644index 00000000..c1011653--- /dev/null+++ b/src/components/llm-provider-settings.tsx@@ -0,0 +1,225 @@+"use client";++import { useMutation, useQuery } from "@tanstack/react-query";+import { ChevronDown, ExternalLink, Loader2 } from "lucide-react";+import { useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { Label } from "@/components/ui/label";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { ConnectField, type PublicSetting } from "@/components/connect-field";+import { LLM_PROVIDERS, type LlmProviderDef, type ProviderGroup } from "@/lib/catalog/llm-providers";+import { cn } from "@/lib/utils";++/** What GET /api/llm says about the hosted providers (no keys). */+interface HostedInfo {+ checked: string;+ smart: string;+ free: string;+ providers: { id: string; status: string; models: { model: string; name: string }[] }[];+}++const GROUPS: { id: ProviderGroup; title: string }[] = [+ { id: "labs", title: "Big labs" },+ { id: "china", title: "China" },+ { id: "hosts", title: "Hosts and routers" },+];++/** Anthropic has its own field above; the local servers have theirs below. */+const ROWS = LLM_PROVIDERS.filter((p) => p.adapter === "openai-chat" || p.adapter === "openai-responses");++const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];+const longDay = (iso: string) => `${Number(iso.slice(8, 10))} ${MONTHS[Number(iso.slice(5, 7)) - 1]} ${iso.slice(0, 4)}`;++/** "sk-or-…" from "OpenRouter keys start with sk-or-". */+const placeholderOf = (p: LlmProviderDef) => {+ const start = p.keyHint && /start with (\S+?)(?: \(|$)/.exec(p.keyHint.text)?.[1];+ return start ? `${start}…` : "Paste the key";+};++/** Free models on any key, or a free plan the owner can tick. */+const hasFree = (p: LlmProviderDef) => p.models.some((m) => m.free === "model") || p.freePlan?.kind === "plan";++function ProviderRow({ p, info, get, set }: { p: LlmProviderDef; info?: HostedInfo["providers"][number]; get: (n: string) => PublicSetting | undefined; set: (n: string) => (v: string) => void }) {+ const [open, setOpen] = useState(false);+ const keySet = !!(p.keySetting && get(p.keySetting)?.isSet);+ const status = info ? info.status : keySet && p.workspaceSetting ? "Needs the workspace id" : keySet ? "Key set" : "Not set";+ const tick = p.freePlan?.kind === "plan" && p.freePlan.setting ? p.freePlan.setting : null;+ const region = p.regionSetting && p.regions && p.regions.length > 1 ? p.regionSetting : null;+ const regionValue = region ? get(region)?.value || p.regions![0].id : null;+ const note = p.regions?.find((r) => r.id === regionValue)?.note;+ const tryIt = useMutation({+ mutationFn: async () =>+ (await (await fetch("/api/llm", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "try", provider: p.id }) })).json()) as { ok: boolean; detail: string },+ onSuccess: (r) => (r.ok ? toast.success(r.detail) : toast.error(r.detail)),+ });+ const bodyId = `llm-${p.id}-body`;++ return (+ <li id={`llm-${p.id}`} className="scroll-mt-28 md:scroll-mt-20">+ <button+ type="button"+ onClick={() => setOpen(!open)}+ aria-expanded={open}+ aria-controls={bodyId}+ className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-[13px] transition-colors hover:bg-accent"+ >+ <span className={cn("size-2 shrink-0 rounded-full", info ? (status === "Key rejected" ? "bg-warning" : "bg-success") : "bg-subtle-foreground")} />+ <span className="min-w-0 flex-1 truncate font-medium">{p.label}</span>+ {hasFree(p) && <span className="shrink-0 rounded-md bg-brand-faint px-1.5 py-0.5 text-[11px] text-brand-text">Free</span>}+ <span className="shrink-0 text-[12px] text-muted-foreground">{status}</span>+ <ChevronDown className={cn("size-3.5 shrink-0 text-muted-foreground transition-transform", open && "rotate-180")} />+ </button>+ {open && (+ <div id={bodyId} className="mt-1 mb-3 space-y-4 rounded-lg border p-3">+ {p.keySetting && (+ <ConnectField+ name={p.keySetting}+ setting={get(p.keySetting)}+ provider="llm"+ label={`${p.label} API key`}+ placeholder={placeholderOf(p)}+ hint={p.modelsPath || p.id === "openrouter" ? "Test checks the key with a free call (its model list)." : "Test sends one tiny message (a fraction of a cent)."}+ />+ )}+ {p.workspaceSetting && (+ <ConnectField+ name={p.workspaceSetting}+ setting={get(p.workspaceSetting)}+ provider="llm"+ label="Workspace id"+ placeholder="ws-…"+ hint="From Model Studio's Workspace page: Fuobe builds the official address from it and the region."+ />+ )}+ {region && p.regions && (+ <div className="space-y-1.5">+ <Label htmlFor={`${p.id}-region`} className="text-[13px]">+ Region+ </Label>+ <Select value={regionValue ?? undefined} onValueChange={set(region)}>+ <SelectTrigger id={`${p.id}-region`} className="w-full sm:w-auto sm:min-w-56">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {p.regions.map((r) => (+ <SelectItem key={r.id} value={r.id}>+ {r.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ {note && <p className="text-[12px] text-muted-foreground">{note}</p>}+ </div>+ )}+ {tick && p.freePlan && (+ <label className="flex items-start gap-2 text-[13px]">+ <input type="checkbox" className="mt-0.5" checked={get(tick)?.value === "1"} onChange={(e) => set(tick)(e.target.checked ? "1" : "0")} />+ <span>+ My key is on {p.short}'s free plan+ <span className="block text-[12px] text-muted-foreground">+ {p.freePlan.limits}.{p.freePlan.caveat ? ` ${p.freePlan.caveat}` : ""}+ {p.freePlan.tooSmall ? ` ${p.freePlan.tooSmall}.` : " Free then offers its free models only."}+ </span>+ </span>+ </label>+ )}+ {p.freeLimits && (+ <p className="text-[12px] text-muted-foreground">+ Free models: {p.freeLimits.text}.{p.freeLimits.caveat ? ` ${p.freeLimits.caveat}` : ""}+ </p>+ )}+ {p.freePlan?.kind === "trial" && <p className="text-[12px] text-muted-foreground">Trial: {p.freePlan.limits}. A trial isn't counted as free.</p>}+ <div className="flex flex-wrap items-center gap-2">+ {p.keysUrl && (+ <Button asChild variant="outline" size="sm" className="h-8 text-[12px]">+ <a href={p.keysUrl} target="_blank" rel="noreferrer">+ Get a key <ExternalLink />+ </a>+ </Button>+ )}+ <Button variant="outline" size="sm" className="h-8 text-[12px]" disabled={!info || tryIt.isPending} onClick={() => tryIt.mutate()}>+ {tryIt.isPending && <Loader2 className="animate-spin" />} Try a reply+ </Button>+ <span className="text-[11px] text-muted-foreground">One tiny message, timed. On a paid model it costs a fraction of a cent.</span>+ </div>+ </div>+ )}+ </li>+ );+}++/**+ * Settings → AI helper: the hosted providers Assist can plan with (src/lib/catalog/llm-providers.ts), one row+ * each, and the two choices Smart and Free make. Keys stay on the server: rows show "Key set", never a key.+ */+export function LlmProviderSettings({ get, set }: { get: (n: string) => PublicSetting | undefined; set: (n: string) => (v: string) => void }) {+ const llm = useQuery({+ queryKey: ["llm"],+ queryFn: async () => (await (await fetch("/api/llm")).json()) as { hosted?: HostedInfo },+ refetchInterval: 30_000,+ });+ const hosted = llm.data?.hosted;+ const plan = get("smartPlan")?.value || "auto";+ const options = [+ { value: "auto", label: "Automatic (the best connected model)" },+ ...(hosted?.providers ?? []).flatMap((g) => g.models.map((m) => ({ value: `${g.id}|${m.model}`, label: `${m.name} · ${LLM_PROVIDERS.find((p) => p.id === g.id)?.short ?? g.id}` }))),+ ];++ return (+ <div className="min-w-0 space-y-4 rounded-xl border p-4">+ <div className="space-y-1">+ <p className="text-[13px] font-medium">Providers for Assist</p>+ <p className="text-[12px] leading-relaxed text-muted-foreground">+ Add a key and Assist can plan with that provider's models: Smart picks the best one you've connected, Free uses the free ones, and Manual lists them all. Keys stay on this server.+ </p>+ </div>+ {GROUPS.map((g) => (+ <div key={g.id} className="space-y-1">+ <p className="px-2 text-[12px] font-medium text-muted-foreground">{g.title}</p>+ <ul className="space-y-0.5">+ {ROWS.filter((p) => p.group === g.id).map((p) => (+ <ProviderRow key={p.id} p={p} info={hosted?.providers.find((x) => x.id === p.id)} get={get} set={set} />+ ))}+ </ul>+ </div>+ ))}+ <div className="space-y-4 border-t pt-4">+ <div className="space-y-1.5">+ <Label htmlFor="setting-smart-plan" className="text-[13px]">+ Smart plans with+ </Label>+ <Select value={options.some((o) => o.value === plan) ? plan : "auto"} onValueChange={set("smartPlan")}>+ <SelectTrigger id="setting-smart-plan" 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>+ {hosted && <p className="text-[12px] text-muted-foreground">{hosted.smart}</p>}+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="setting-free-order" className="text-[13px]">+ Free uses+ </Label>+ <Select value={get("freeOrder")?.value === "local" ? "local" : "best"} onValueChange={set("freeOrder")}>+ <SelectTrigger id="setting-free-order" className="w-full sm:w-auto sm:min-w-56">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="best">The best free model</SelectItem>+ <SelectItem value="local">My local model first</SelectItem>+ </SelectContent>+ </Select>+ {hosted && <p className="text-[12px] text-muted-foreground">{hosted.free}</p>}+ </div>+ {hosted && <p className="text-[11px] text-muted-foreground">Model list checked {longDay(hosted.checked)}, from each provider's own pages.</p>}+ </div>+ </div>+ );+}diff --git a/src/components/settings-form.tsx b/src/components/settings-form.tsxindex 62f8b131..6d827f28 100644--- a/src/components/settings-form.tsx+++ b/src/components/settings-form.tsx@@ -13,6 +13,7 @@ import { Skeleton } from "@/components/ui/skeleton";import { AccountsChip } from "@/components/accounts-admin";import { ConnectField, useSettings, type PublicSetting } from "@/components/connect-field";import { GetStarted } from "@/components/get-started";+import { LlmProviderSettings } from "@/components/llm-provider-settings";import { LoraSettings } from "@/components/lora-settings";import { useStatus, type StatusInfo } from "@/lib/api";import { AI_TOOLKIT_REPO, connectionSummary, DEFAULT_AI_TOOLKIT_URL, ENGINE_MODE_LABEL, FAL_KEYS_URL, showFirstRun } from "@/lib/connections";@@ -649,8 +650,8 @@ export function SettingsForm({ prices }: { prices?: string }) {<Sectionid="text-ai"- title="AI helper · Claude or a local model"- description="The LLM that writes for Fuobe: the Enhance toggle, storyboards, translations and scripts, ad copy, brand research, and the Assist agent. Use Claude, a local model (Ollama, LM Studio, Unsloth Studio or another OpenAI-compatible server: fully open source), or the built-in offline rewriter. In Open source only mode, Automatic skips Claude. Save & test checks a key or address before saving it."+ title="AI helper · models and providers"+ description="The LLMs that write for Fuobe. Use (below) picks the one for the Enhance toggle, storyboards, translations and scripts, ad copy and brand research: Claude, a local model (Ollama, LM Studio, Unsloth Studio or another OpenAI-compatible server: fully open source), or the built-in offline rewriter. The Assist agent can also plan with the providers you add a key for (OpenAI, Gemini, DeepSeek, Kimi, GLM, OpenRouter and more). In Open source only mode, Automatic skips Claude. Save & test checks a key or address before saving it."><ChoiceFieldid="setting-enhancer"@@ -666,6 +667,9 @@ export function SettingsForm({ prices }: { prices?: string }) {]}/><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 id="llm-providers" className="scroll-mt-28 md:scroll-mt-20">+ <LlmProviderSettings get={get} set={set} />+ </div><LocalLlmSettings get={get} set={set} /></Section>diff --git a/src/server/assist/agent.ts b/src/server/assist/agent.tsindex c4c704b5..31c45812 100644--- a/src/server/assist/agent.ts+++ b/src/server/assist/agent.ts@@ -761,7 +761,8 @@ export const claude: ModelCall = async ({ system, messages, tools, settings, conexport function forAnthropic(messages: Stored[]): MessageParam[] {return messages.map((m) => {if (!("replay" in m)) return m;- const { replay: _replay, ...rest } = m;+ const rest = { ...m };+ delete rest.replay;return rest;});}@@ -879,7 +880,7 @@ export const offline: ModelCall = async ({ messages, ctx, skills }) => {};/** Under every offline plan: the rule-based planner is a fallback, not the assistant. */-export const OFFLINE_NOTE = "Offline planner — connect Claude or a local model (Ollama, LM Studio or Unsloth Studio) in Settings for better plans.";+export const OFFLINE_NOTE = "Offline planner — connect a model in Settings → AI helper (Anthropic, OpenAI, Google, OpenRouter… or a local model) for better plans.";/** What to offer next, by what was just started. */const FOLLOW_UP: Record<MediaKind, string> = {diff --git a/src/server/providers/llm.ts b/src/server/providers/llm.tsindex 4827b6ed..1623c31f 100644--- a/src/server/providers/llm.ts+++ b/src/server/providers/llm.ts@@ -4,6 +4,7 @@ import { nanoid } from "nanoid";import { getModel } from "@/lib/catalog";import { cueText, parseCues, toSrt, type Cue } from "@/lib/cues";import type { GenInput, ModelRoute, Operation } from "@/lib/catalog/types";+import { HOSTED_PROVIDERS, testHosted } from "../llm/hosted";import { aiHelper, chatLocal, checkLocal, emptyReply, LOCAL_LABELS, localLabel, localProblem, localReady, localServers, localWhat, pinnedKind, probeLocal, type JsonSpec, type LocalKind, type Ready } from "../llm";import { engineMode, getSetting } from "../settings";import { toDataUri } from "../storage";@@ -390,6 +391,11 @@ const LOCAL_FOCUS: Partial<Record<string, LocalKind>> = {llmKey: "custom",};+/** A hosted provider's key, region and workspace settings: Save & test checks that provider (Assist's models). */+const HOSTED_FOCUS: Partial<Record<string, string>> = Object.fromEntries(+ HOSTED_PROVIDERS.flatMap((p) => [p.keySetting, p.regionSetting, p.workspaceSetting].flatMap((s) => (s ? [[s, p.id]] : []))),+);+/** "Ollama, LM Studio or Unsloth Studio", or the server Settings pins. */const localNames = () => {const pinned = pinnedKind();@@ -469,6 +475,8 @@ export const llmProvider: ProviderAdapter = {}const kind = opts?.focus ? LOCAL_FOCUS[opts.focus] : undefined;if (kind) return checkLocal(kind);+ const hosted = opts?.focus ? HOSTED_FOCUS[opts.focus] : undefined;+ if (hosted) return testHosted(hosted);if (aiHelper() === "none") return { ok: false, detail: "Text steps are off (AI helper: Offline rewriter)" };await probeLocal(true);const b = llmBackends({ endpoint: "auto" });diff --git a/tests/assist-providers.test.ts b/tests/assist-providers.test.tsindex ef8828d0..f33a1684 100644--- a/tests/assist-providers.test.ts+++ b/tests/assist-providers.test.ts@@ -22,7 +22,7 @@ process.env.COMFYUI_URL = "http://127.0.0.1:9";process.env.OLLAMA_URL = "http://127.0.0.1:9";for (const k of Object.keys(process.env)) if (/_API_KEY$|^HF_TOKEN$|^FUOBE_LLM_|^LM_API_TOKEN$|^LMSTUDIO_|^UNSLOTH_|^FUOBE_ENHANCE_PROVIDER$/.test(k)) delete process.env[k];-const { setSetting, SETTINGS } = await import("@/server/settings");+const { setSetting } = await import("@/server/settings");const agent = await import("@/server/assist/agent");const { modeLabel } = await import("@/lib/assist");const { LLM_PROVIDERS, getLlmProvider } = await import("@/lib/catalog/llm-providers");@@ -40,7 +40,7 @@ async function fake(mode: Mode, provider: string = mode): Promise<FakeLlm> {}/** Every provider key off, and the local server pinned to an address nothing answers. */function disconnect() {- for (const p of LLM_PROVIDERS) if (p.keySetting) setSetting(p.keySetting as keyof typeof SETTINGS, "");+ for (const p of LLM_PROVIDERS) if (p.keySetting) setSetting(p.keySetting as Parameters<typeof setSetting>[0], "");setSetting("llmProvider", "custom");setSetting("llmUrl", "http://127.0.0.1:9/v1");setSetting("llmKey", "");diff --git a/tests/assist-runtime.test.ts b/tests/assist-runtime.test.tsindex f0f7df58..a37509d9 100644--- a/tests/assist-runtime.test.ts+++ b/tests/assist-runtime.test.ts@@ -82,7 +82,7 @@ describe("offline planner (U18)", () => {expect(said.text).not.toContain(agent.OFFLINE_NOTE);const at = v.thread.items.findIndex((i) => i.role === "approval");expect(v.thread.items[at + 1]).toMatchObject({ role: "notice", tone: "info", text: agent.OFFLINE_NOTE });- expect(agent.OFFLINE_NOTE).toBe("Offline planner — connect Claude or a local model (Ollama, LM Studio or Unsloth Studio) in Settings for better plans.");+ expect(agent.OFFLINE_NOTE).toBe("Offline planner — connect a model in Settings → AI helper (Anthropic, OpenAI, Google, OpenRouter… or a local model) for better plans.");const card = v.thread.items.find((i) => i.role === "approval") as { jobs: { kind: string; op: string; error?: string }[] };expect(card.jobs.map((j) => [j.kind, j.op, j.error])).toEqual([["image", "t2i", undefined],diff --git a/tests/llm-settings-security.test.ts b/tests/llm-settings-security.test.tsnew file mode 100644index 00000000..7e26f82d--- /dev/null+++ b/tests/llm-settings-security.test.ts@@ -0,0 +1,152 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";+import { fakeLlm, type FakeLlm } from "./helpers/fake-llm";++/*+ * The hosted providers' keys are the owner's secrets: they never appear in a response (settings, Assist's+ * picker, the LLM status), only the owner reaches the routes that use them, an account's or a guest's work+ * never reaches them, a key typed into Save & test goes only to that provider's official host, and region and+ * workspace settings can't turn into an address of someone else's choosing.+ */++vi.setConfig({ testTimeout: 60_000 });+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-llm-security-"));+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";+process.env.FUOBE_PUBLIC_SIGNUP = "1";+delete process.env.FUOBE_PASSWORD;+for (const k of Object.keys(process.env)) if (/_API_KEY$|^HF_TOKEN$|^FUOBE_LLM_/.test(k)) delete process.env[k];++const { setSetting } = await import("@/server/settings");+const auth = await import("@/server/auth");+const { proxy } = await import("@/proxy");+const { ownerOnly } = await import("@/lib/guest-access");+const { runAsTenant } = await import("@/server/tenant");+const hosted = await import("@/server/llm/hosted");+const agent = await import("@/server/assist/agent");+const settingsRoute = await import("@/app/api/settings/route");+const llmRoute = await import("@/app/api/llm/route");+const assistRoute = await import("@/app/api/assist/route");+const testRoute = await import("@/app/api/providers/test/route");++const KEYS: Record<string, string> = {+ openrouterKey: "sk-or-v1-SECRETopenrouter0123456789",+ deepseekKey: "sk-SECRETdeepseek0123456789abcd",+ googleKey: "AIzaSECRETgoogle0123456789abcdefgh",+ xaiKey: "xai-SECRETxai0123456789abcdefgh",+ huggingfaceToken: "hf_SECREThuggingface0123456789",+ qwenKey: "sk-SECRETqwen0123456789abcdefgh",+};++let ds: FakeLlm;+beforeAll(async () => {+ ds = fakeLlm("deepseek", KEYS.deepseekKey);+ await ds.start();+ ds.models = ["deepseek-v4-pro", "deepseek-flash"];+ // OpenRouter's key check goes to an address nothing answers: no test reaches a real provider.+ process.env.FUOBE_LLM_TEST_BASE = `deepseek=${ds.url},openrouter=http://127.0.0.1:9/api/v1`;+ for (const [k, v] of Object.entries(KEYS)) setSetting(k as Parameters<typeof setSetting>[0], v);+ setSetting("llmProvider", "custom");+ setSetting("llmUrl", "http://127.0.0.1:9/v1");+ auth.setPassword("install password");+});+afterAll(async () => {+ await ds.close();+ delete process.env.FUOBE_LLM_TEST_BASE;+ delete process.env.FUOBE_PUBLIC_SIGNUP;+ try {+ fs.rmSync(dir, { recursive: true, force: true });+ } catch {}+});++/** No key, and no long piece of one, anywhere in a body. */+function noKeys(body: string, where: string) {+ for (const key of Object.values(KEYS)) {+ for (let i = 0; i + 12 <= key.length; i++) expect(body.includes(key.slice(i, i + 12)), `${where} shows part of ${key.slice(0, 6)}…`).toBe(false);+ }+}++describe("keys never leave the server", () => {+ it("in Settings, Assist's picker, the LLM status and the connection test", async () => {+ noKeys(await (await settingsRoute.GET()).text(), "GET /api/settings");+ const llm = await (await llmRoute.GET(new Request("http://localhost/api/llm"))).text();+ noKeys(llm, "GET /api/llm");+ expect(JSON.parse(llm).hosted.providers.map((p: { id: string }) => p.id)).toEqual(expect.arrayContaining(["deepseek", "openrouter", "google", "xai"]));+ const assist = await (await assistRoute.GET(new Request("http://localhost/api/assist"))).text();+ noKeys(assist, "GET /api/assist");+ expect(JSON.parse(assist).availability.smart.plan).toBeTruthy();+ noKeys(JSON.stringify(await agent.availability()), "availability()");+ // A wrong key's error comes back without it.+ const r = await testRoute.POST(new Request("http://localhost/api/providers/test", { method: "POST", body: JSON.stringify({ provider: "llm", field: "deepseekKey", values: { deepseekKey: "sk-WRONGwrongwrong0123456789" } }) }));+ const text = await r.text();+ expect(JSON.parse(text)).toMatchObject({ ok: false, detail: expect.stringMatching(/DeepSeek rejected the key/) });+ expect(text).not.toContain("WRONGwrongwr");+ });++ it("Save & test sends a typed key to the provider's official host only, and the saved key stays put", async () => {+ const before = ds.seen.length;+ const ok = await (await testRoute.POST(new Request("http://localhost/api/providers/test", { method: "POST", body: JSON.stringify({ provider: "llm", field: "deepseekKey", values: { deepseekKey: KEYS.deepseekKey } }) }))).json();+ expect(ok).toMatchObject({ ok: true, detail: "Key works · 2 models listed" });+ expect(ds.seen.slice(before).every((s) => s.auth === `Bearer ${KEYS.deepseekKey}`)).toBe(true);+ // A region that isn't one of the provider's own hosts is refused before anything is sent.+ const bad = await testRoute.POST(new Request("http://localhost/api/providers/test", { method: "POST", body: JSON.stringify({ provider: "llm", field: "xaiRegion", values: { xaiRegion: "evil.example.com" } }) }));+ expect(bad.status).toBe(400);+ });+});++describe("addresses come from the registry only", () => {+ it("refuses a region or workspace that isn't one, and a Smart override that isn't provider|model", async () => {+ for (const body of [{ openaiRegion: "https://evil.example.com" }, { qwenWorkspace: "evil.example.com/x" }, { qwenWorkspace: "a@b" }, { smartPlan: "openai|gpt;rm -rf" }, { googleFreeTier: "yes" }]) {+ const res = await settingsRoute.PUT(new Request("http://localhost/api/settings", { method: "PUT", body: JSON.stringify(body) }));+ expect(res.status, JSON.stringify(body)).toBe(400);+ }+ setSetting("qwenWorkspace", "ws-1234");+ expect(hosted.endpointFor("qwen")!.baseUrl).toBe("https://ws-1234.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1");+ for (const p of hosted.HOSTED_PROVIDERS) for (const u of [...(p.regions?.map((r) => r.baseUrl) ?? []), ...(p.baseUrl ? [p.baseUrl] : [])]) expect(u.startsWith("https://"), u).toBe(true);+ });+});++describe("only the owner", () => {+ const req = (url: string, method = "GET", cookie?: string) =>+ new NextRequest(`http://localhost:3000${url}`, { method, headers: cookie ? { cookie: `${auth.SESSION_COOKIE}=${cookie}` } : {}, ...(method !== "GET" && { body: "{}" }) });++ it("reaches the routes that read or use the keys", () => {+ for (const [m, p] of [+ ["POST", "/api/llm"],+ ["PUT", "/api/settings"],+ ["POST", "/api/providers/test"],+ ]) expect(ownerOnly(m, p), `${m} ${p}`).toBe(true);+ const a = auth.createAccount("[email protected]", "long enough");+ const account = auth.createSession(a.id).value;+ for (const [m, p] of [+ ["GET", "/api/llm"],+ ["POST", "/api/llm"],+ ["GET", "/api/settings"],+ ["PUT", "/api/settings"],+ ["POST", "/api/providers/test"],+ ["POST", "/api/assist"],+ ]) {+ expect(proxy(req(p, m, account)).status, `account ${m} ${p}`).toBe(403);+ expect(proxy(req(p, m)).status, `guest ${m} ${p}`).toBe(401);+ }+ const owner = auth.createSession().value;+ expect(proxy(req("/api/llm", "GET", owner)).headers.get("x-middleware-next")).toBe("1");+ });++ it("an account's or a guest's work never reaches a key, even past the routes", async () => {+ for (const t of [{ kind: "account" as const, id: "a1" }, { kind: "guest" as const }]) {+ expect(runAsTenant(t, () => hosted.connectedHosted())).toEqual([]);+ expect(() => runAsTenant(t, () => hosted.endpointFor("deepseek"))).toThrow(/studio's own LLM keys/);+ expect(await runAsTenant(t, () => hosted.testHosted("deepseek"))).toMatchObject({ ok: false });+ }+ const ep = hosted.endpointFor("deepseek")!;+ const before = ds.seen.length;+ await expect(runAsTenant({ kind: "account", id: "a1" }, () => hosted.chatHosted(ep, ep.provider.models[0], { messages: [{ role: "user", content: "hi" }] }))).rejects.toThrow(/studio's own LLM keys/);+ expect(ds.seen.length).toBe(before);+ });+});diff --git a/vitest.config.ts b/vitest.config.tsindex a6c1a783..44b402c7 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -13,6 +13,36 @@ export default defineConfig({environment: "node",// Local LLM servers on this machine (LM Studio on :1234, Unsloth Studio on :8888) stay out of the// tests: Automatic would find them. Tests that need one start a stand-in and point Settings at it.- env: { LMSTUDIO_URL: "http://127.0.0.1:9", UNSLOTH_URL: "http://127.0.0.1:9" },+ // Hosted LLM keys from this machine's environment stay out too, so no test reaches a real provider: tests that need+ // one set a key in Settings and point the provider at a stand-in (FUOBE_LLM_TEST_BASE).+ env: {+ LMSTUDIO_URL: "http://127.0.0.1:9",+ UNSLOTH_URL: "http://127.0.0.1:9",+ ...Object.fromEntries(+ [+ "OPENAI_API_KEY",+ "GEMINI_API_KEY",+ "GOOGLE_API_KEY",+ "XAI_API_KEY",+ "FUOBE_META_API_KEY",+ "MISTRAL_API_KEY",+ "CO_API_KEY",+ "COHERE_API_KEY",+ "DEEPSEEK_API_KEY",+ "MOONSHOT_API_KEY",+ "ZAI_API_KEY",+ "ZHIPUAI_API_KEY",+ "DASHSCOPE_API_KEY",+ "MINIMAX_API_KEY",+ "OPENROUTER_API_KEY",+ "GROQ_API_KEY",+ "CEREBRAS_API_KEY",+ "TOGETHER_API_KEY",+ "FIREWORKS_API_KEY",+ "HF_TOKEN",+ "FUOBE_LLM_TEST_BASE",+ ].map((k) => [k, ""]),+ ),+ },},});