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 providers: fixes from the review
Adarsh004dc384d431
diff --git a/src/components/assist-view.tsx b/src/components/assist-view.tsxindex ac719ab8..331f4062 100644--- a/src/components/assist-view.tsx+++ b/src/components/assist-view.tsx@@ -22,7 +22,7 @@ import { SkillIcon } from "@/components/assist/skill-icon";import { Transcript } from "@/components/assist/transcript";import { AssistVisitorNote } from "@/components/assist/visitor-note";import { useAssistActions, useAssistThread, useEngine } from "@/lib/api";-import { ASSIST_SUGGESTIONS, modeLabel, type AssistAvailability, type AssistModeChoice, type AssistProject, type AssistThread, type SkillSummary } from "@/lib/assist";+import { ASSIST_SUGGESTIONS, modeLabel, threadModeChoice, type AssistAvailability, type AssistModeChoice, type AssistProject, type AssistThread, type SkillSummary } from "@/lib/assist";import type { Generation } from "@/lib/catalog/types";import { cn } from "@/lib/utils";import { toastError } from "@/lib/refusals";@@ -243,7 +243,7 @@ export function AssistView() {thread && (<><ModePicker- value={{ mode: thread.mode ?? "smart", agent: thread.agent, model: thread.model, effort: thread.effort }}+ value={threadModeChoice(thread)}availability={can}disabled={thread.status === "running"}applyOnClose@@ -271,7 +271,7 @@ export function AssistView() {attachments: first?.role === "user" ? first.attachments : undefined,projectId: thread.projectId ?? null,engine: thread.engine,- mode: { mode: thread.mode ?? "smart", agent: thread.agent, model: thread.model, effort: thread.effort },+ mode: threadModeChoice(thread),};})()}/>diff --git a/src/components/assist/mode-picker.tsx b/src/components/assist/mode-picker.tsxindex 561449ed..78e879fd 100644--- a/src/components/assist/mode-picker.tsx+++ b/src/components/assist/mode-picker.tsx@@ -248,7 +248,7 @@ export function ModePicker({aria-checked={mode === m.id}tabIndex={radioTab(mode === m.id)}disabled={off}- title={off ? "Needs a model: add a key or start a local model (Settings)" : undefined}+ title={off ? can?.smart?.text : 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")}>@@ -259,13 +259,13 @@ 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>}+ {/* Why Smart can't run: nothing connected, or what blocks the models that are (a rejected key, Open source only…). */}{smartOff && (<p className="mt-2 px-1 text-[12px] text-warning">- Smart needs a model —{" "}+ {can?.smart?.text}{" "}<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.+ Open Settings+ </Link></p>)}{mode === "free" && can?.free && (@@ -275,7 +275,10 @@ export function ModePicker({</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>+ <p className="mt-2 px-1 text-[11px] text-muted-foreground">+ Open source only: open-weight models that cost nothing, on this machine or a provider's free ones+ {can.claude ? ", and Claude (AI helper is set to Claude)." : ". Nothing goes to a paid API."}+ </p>)}{mode === "manual" && (<div className="mt-3 space-y-3">diff --git a/src/components/llm-provider-settings.tsx b/src/components/llm-provider-settings.tsxindex c1011653..eec18585 100644--- a/src/components/llm-provider-settings.tsx+++ b/src/components/llm-provider-settings.tsx@@ -8,7 +8,7 @@ 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 { LLM_PROVIDERS, offersFree, 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). */@@ -37,9 +37,6 @@ const placeholderOf = (p: LlmProviderDef) => {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);@@ -66,7 +63,7 @@ function ProviderRow({ p, info, get, set }: { p: LlmProviderDef; info?: HostedIn><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>}+ {offersFree(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>diff --git a/src/lib/assist-models.ts b/src/lib/assist-models.tsindex 7a39b58b..6f06f527 100644--- a/src/lib/assist-models.ts+++ b/src/lib/assist-models.ts@@ -43,7 +43,7 @@ export interface World {local: LocalWorld | null;/** Settings → Engine: Open source only. */openOnly: boolean;- /** Settings → AI helper → Use. */+ /** Settings → AI helper → Use: "none" turns Assist's models off; "local" makes Free (local first) the default; "anthropic" allows Claude on Open source only. */helper: "auto" | "anthropic" | "local" | "none";/** Settings → AI helper → Smart plans with: "auto", or "provider|model". */smartPlan: string;@@ -114,16 +114,27 @@ const blended = (c: Choice) => (c.free ? 0 : c.price ? (3 * c.price.in + c.priceconst effortsOf = (m: Pick<LlmModelDef, "efforts">): AssistEffort[] => ASSIST_EFFORTS.map((e) => e.id).filter((e) => m.efforts?.[e] !== undefined && m.efforts?.[e] !== null);+/** $0 on this account: a free model, or a free-plan model while the owner's tick is on. */+const costsNothing = (p: LlmProviderDef, m: LlmModelDef, conn: ConnectedProvider) => m.free === "model" || (m.free === "plan" && p.freePlan?.kind === "plan" && !!conn.freeTick);++/**+ * Why a model can't run now. Open source only runs open weights that cost nothing (Settings → Engine: "nothing is+ * sent to paid APIs"); AI helper set to Claude is the owner's way to use Claude there anyway, as before.+ */function disabledWhy(w: World, p: LlmProviderDef, m: LlmModelDef, conn: ConnectedProvider): string | undefined {if (w.helper === "none") return "The AI helper is off (Settings)";if (conn.rejected) return `${p.label} rejected the key — check it in Settings`;- if (w.helper === "local") return "AI helper is set to Local model only (Settings)";- if (w.openOnly && !m.open && !(p.id === "anthropic" && w.helper === "anthropic")) return "Not open weights — Open source only is on (Settings)";+ if (w.openOnly && !(p.id === "anthropic" && w.helper === "anthropic")) {+ if (!m.open) return "Not open weights — Open source only is on (Settings)";+ if (!costsNothing(p, m, conn)) return "Paid API — Open source only is on (Settings)";+ }if (p.freePlan?.kind === "plan" && conn.freeTick) {if (m.free !== "plan") return `Your ${p.short} key is on the free plan`;if (p.freePlan.tooSmall) return p.freePlan.tooSmall;}if (p.id === "openrouter" && conn.freeTier && m.free !== "model") return "No credits on OpenRouter yet: only its free models run";+ // OpenRouter's key check: no free request left today.+ if (m.free === "model" && conn.freeLeft === 0) return `${p.short}'s free requests for today are used up`;if (w.spent?.includes(p.id) && (m.free === "model" || (m.free === "plan" && conn.freeTick))) return `${p.short}'s free requests are used up for now`;return undefined;}@@ -138,8 +149,7 @@ export function choices(w: World): Choice[] {if (!conn) continue;for (const m of p.models) {if (m.expires && m.expires < w.today) continue;- const tick = p.freePlan?.kind === "plan" && !!conn.freeTick;- const free = m.free === "model" || (m.free === "plan" && tick);+ const free = costsNothing(p, m, conn);const steps = conn.cny && m.priceCny ? m.priceCny : m.price;const price = priceOn(steps, w.today);const next = price?.until ? steps?.[steps.indexOf(price) + 1] : undefined;@@ -154,7 +164,7 @@ export function choices(w: World): Choice[] {agent: p.adapter === "anthropic" ? "claude" : "hosted",tier: m.tier,speed: m.speed,- context: m.context,+ context: Math.min(m.context, m.maxIn ?? Infinity),sees: m.vision,free,cap: free,@@ -286,7 +296,12 @@ export function smartPick(w: World): SmartPick {const fixed = w.smartPlan !== "auto" ? all.find((c) => c.provider === pid && c.model === mid) : undefined;const claude = w.helper === "anthropic" ? all.find((c) => c.provider === "anthropic" && c.model === "claude-opus-5-5") : undefined;const plan = fixed ?? claude ?? rank(all)[0] ?? null;- if (!plan) return { plan: null, check: null, text: "Smart needs a model: add a key in Settings (Anthropic, OpenAI, Google, OpenRouter…) or start a local model." };+ if (!plan) {+ // Models are connected but none can run now (a rejected key, Open source only…): say why, not "add a key".+ const blocked = rank(choices(w).filter((c) => c.disabled && c.tools && !c.manualOnly && (!c.local || c.model === w.local?.model)))[0];+ const text = blocked ? `Smart can't plan with ${who(blocked)}: ${blocked.disabled}.` : "Smart needs a model: add a key in Settings (Anthropic, OpenAI, Google, OpenRouter…) or start a local model.";+ return { plan: null, check: null, text };+ }if (plan.local) return { plan, check: null, text: `Smart uses ${plan.name} on ${plan.providerLabel}, on this machine.` };if (plan.free && plan.provider === "openrouter") {return { plan, check: null, text: `Smart uses ${plan.name} (free, through OpenRouter). Credits on OpenRouter, or a paid key (Anthropic, OpenAI, Google…), give better plans.` };@@ -310,10 +325,10 @@ const NOTHING_FREE =const runsOn = (c: Choice) => (c.local ? `${c.name} on ${c.providerLabel}` : `${c.name} through ${c.providerLabel}`);-/** Free: the best free model (or the local one first, if the owner asks), then the next ones, then the offline planner. */+/** Free: the best free model (or the local one first, if the owner asks or AI helper is Local model only), then the next ones, then the offline planner. */export function freePick(w: World): FreePick {const free = rankFree(pickable(w).filter((c) => c.free));- const ordered = w.freeOrder === "local" ? [...free.filter((c) => c.local), ...free.filter((c) => !c.local)] : free;+ const ordered = w.freeOrder === "local" || w.helper === "local" ? [...free.filter((c) => c.local), ...free.filter((c) => !c.local)] : free;const [pick, ...rest] = ordered;if (!pick) return { pick: null, then: [], text: NOTHING_FREE };const sharing = (c: Choice) => pick.sharedCap && c.sharedCap && c.provider === pick.provider;@@ -384,11 +399,30 @@ export function toOption(c: Choice): AssistModelOption {};}-/** "Open weights · MIT · runs on DeepSeek's servers"; undefined for a closed (or not confirmed open) model. */+/** Hugging Face's router: the provider an id's suffix names runs the model ("zai-org/GLM-5.3:deepinfra"). */+const ROUTED: Record<string, string> = {+ deepinfra: "DeepInfra",+ novita: "Novita",+ baseten: "Baseten",+ cerebras: "Cerebras",+ groq: "Groq",+ together: "Together AI",+ "fireworks-ai": "Fireworks AI",+ nebius: "Nebius",+ sambanova: "SambaNova",+};+const routedTo = (c: Choice) => {+ const suffix = c.provider === "huggingface" ? /:([\w-]+)$/.exec(c.model)?.[1] : undefined;+ return suffix ? (ROUTED[suffix] ?? suffix) : undefined;+};++/** "Open weights · MIT · runs on DeepSeek's servers", "… · runs on DeepInfra, through Hugging Face"; undefined for a closed (or not confirmed open) model. */export function openLabel(c: Choice): string | undefined {if (c.local) return "Open weights · on this machine";if (!c.licence) return undefined;const licence = c.nonCommercial ? `${c.licence} (non-commercial)` : c.licence;- const where = c.provider === "openrouter" ? (c.free ? "free through OpenRouter" : "runs through OpenRouter") : `runs on ${c.providerShort}'s servers`;+ const host = routedTo(c);+ const where =+ c.provider === "openrouter" ? (c.free ? "free through OpenRouter" : "runs through OpenRouter") : host ? `runs on ${host}, through ${c.providerLabel}` : `runs on ${c.providerShort}'s servers`;return `Open weights · ${licence} · ${where}`;}diff --git a/src/lib/assist.ts b/src/lib/assist.tsindex 227c6f9a..4ec9c772 100644--- a/src/lib/assist.ts+++ b/src/lib/assist.ts@@ -163,6 +163,15 @@ export interface AssistModeChoice {effort?: AssistEffort | null;}+/** A chat's mode as the picker shows it and Schedule this request saves it: with a hosted model's provider, or Manual can't find the model. */+export const threadModeChoice = (t: Pick<AssistThread, "mode" | "agent" | "provider" | "model" | "effort">): AssistModeChoice => ({+ mode: t.mode ?? "smart",+ agent: t.agent,+ provider: t.provider ?? null,+ model: t.model ?? null,+ effort: t.effort ?? null,+});+/** A model the mode picker offers (GET /api/assist): words and flags only, never a key or an address. */export interface AssistModelOption {provider: string;diff --git a/src/lib/catalog/llm-providers.ts b/src/lib/catalog/llm-providers.tsindex 6a48b801..6f10a4db 100644--- a/src/lib/catalog/llm-providers.ts+++ b/src/lib/catalog/llm-providers.ts@@ -35,6 +35,8 @@ export interface LlmModelDef {/** Tokens. */context: number;maxOut: number;+ /** Tokens in at most, where the docs give a limit apart from the context (GPT-5.4 Mini: 400K context, 272K in). */+ maxIn?: number;/** "unverified": the docs don't say it calls tools on this API, so Smart and Free skip it. */tools: true | "unverified";vision: boolean;@@ -152,6 +154,8 @@ export interface LlmProviderDef {freePlan?: FreePlan;/** Free models' account-wide limits (OpenRouter's :free cap covers every free model on the key). */freeLimits?: { text: string; caveat?: string; shared?: true };+ /** The time zone whose midnight resets the free daily limits (Gemini: Pacific). Default UTC (OpenRouter's day). */+ freeDayZone?: string;/** Not wired yet: shown greyed with this line. */soon?: string;models: LlmModelDef[];@@ -218,7 +222,7 @@ export const LLM_PROVIDERS: LlmProviderDef[] = [{ id: "gpt-6.1-sol", name: "GPT-6.1 Sol", tier: 1, speed: "normal", context: 1_050_000, maxOut: 128_000, tools: true, vision: true, price: [usd(2, 10)], efforts: EVERY, longContext: OPENAI_LONG },{ id: "gpt-6.1-terra", name: "GPT-6.1 Terra", tier: 3, speed: "fast", context: 1_050_000, maxOut: 128_000, tools: true, vision: true, price: [usd(1, 5)], efforts: EVERY, longContext: OPENAI_LONG, note: "Fast, with strong visual reasoning" },{ id: "gpt-6-luna", name: "GPT-6 Luna", tier: 3, speed: "fast", context: 1_050_000, maxOut: 128_000, tools: true, vision: true, price: [usd(0.1, 0.5)], efforts: LOW_MED_HIGH, longContext: OPENAI_LONG, note: "OpenAI's cheapest" },- { id: "gpt-5.4-mini", name: "GPT-5.4 Mini", tier: 3, speed: "fast", context: 400_000, maxOut: 128_000, tools: true, vision: true, price: [usd(0.75, 4.5)], efforts: { low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: null }, longContext: OPENAI_LONG },+ { id: "gpt-5.4-mini", name: "GPT-5.4 Mini", tier: 3, speed: "fast", context: 400_000, maxIn: 272_000, maxOut: 128_000, tools: true, vision: true, price: [usd(0.75, 4.5)], efforts: { low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: null } },{ id: "gpt-6-astra", name: "GPT-6 Astra", tier: 1, speed: "slow", manualOnly: "Flagship; slowest and priciest", context: 1_050_000, maxOut: 128_000, tools: true, vision: true, price: [usd(10, 50)], efforts: EVERY, longContext: OPENAI_LONG },],sources: [@@ -249,6 +253,7 @@ export const LLM_PROVIDERS: LlmProviderDef[] = [limits: "Limits per project, shown only in Google AI Studio; daily limits reset at midnight Pacific",caveat: "Google uses free-tier prompts to improve its products.",},+ freeDayZone: "America/Los_Angeles",models: [{id: "gemini-4-argon",@@ -811,6 +816,12 @@ export const getLlmProvider = (id: string | null | undefined): LlmProviderDef |export const getLlmModel = (provider: string | null | undefined, model: string | null | undefined): LlmModelDef | undefined => getLlmProvider(provider)?.models.find((m) => m.id === model);+/**+ * Settings' Free tag: free models on any key, or a free plan the owner can tick that is big enough for Assist+ * (Groq's isn't: 8,000 tokens a minute). Trials run out, so they never count.+ */+export const offersFree = (p: LlmProviderDef): boolean => p.models.some((m) => m.free === "model") || (p.freePlan?.kind === "plan" && !p.freePlan.tooSmall);+/** The price in effect on a day (YYYY-MM-DD): the first step whose `until` hasn't passed. */export function priceOn(steps: PriceStep[] | undefined, day: string): PriceStep | undefined {return steps?.find((s) => !s.until || day <= s.until) ?? steps?.at(-1);diff --git a/src/server/llm/hosted-errors.ts b/src/server/llm/hosted-errors.tsindex 3213fc67..bc79af9a 100644--- a/src/server/llm/hosted-errors.ts+++ b/src/server/llm/hosted-errors.ts@@ -48,7 +48,17 @@ export class HostedError extends Error {const CONTEXT = /context_length_exceeded|context (?:length|window|size)|maximum context|prompt is too long|too many tokens|input is too long|exceeds? the (?:model'?s? )?(?:context|maximum)/i;const NO_MODEL = /model[^.]{0,80}(?:not found|does not exist|doesn't exist|is not available|unknown|no such|invalid|not supported)|unknown model|model_not_found|no such model|invalid model/i;-const FREE_CAP = /free[- ]models?-per-(day|min)|free_model|free tier|free-tier|quota|free requests/i;+/** A free limit for the whole day: "per day", "daily", RPD, Gemini's quota_exceeded. Anything else is a minute's (OpenRouter's free-models-per-min). */+const DAY_CAP = /per[- ]?day|daily|today|\brpd\b|quota_exceeded/i;+/** A 403 that is about the key itself. Others are about one model or request (Qwen's free quota for a model, Gemini's permission_denied). */+const KEY_REFUSED = /invalid[ _-]?(?:api[ _-]?)?(?:key|token)|incorrect api key|api[ _-]?key (?:is )?(?:not valid|invalid|expired)|unauthenticated|invalid_authentication|(?:key|token) (?:has )?expired/i;++/** The provider refused the key (401, or a 403 that names the key): Assist skips its models until the key works again. */+export const keyRefused = (status: number, body: string): boolean => status === 401 || (status === 403 && KEY_REFUSED.test(body));++/** A free limit that ran out: for the day, or for the moment. */+export const freeLimit = (p: Pick<LlmProviderDef, "id" | "label">, span: "day" | "minute"): FreeLimitError =>+ new FreeLimitError(span === "day" ? `${p.label}'s free requests for today are used up` : `${p.label}'s free requests are used up for the moment`, span, p.id);/** "This chat is too long for GPT-6.1 Sol (about 1.1M tokens)…" */export function tooLongText(model: Pick<LlmModelDef, "name">, tokens?: number): string {@@ -74,9 +84,14 @@ export function hostedError(p: LlmProviderDef, status: number, body: string, modconst label = p.label;const where = `Settings → AI helper → ${label}`;const said = detail ? ` (${detail})` : "";- if (status === 401 || status === 403) {- const extra = p.id === "zai" ? " Z.ai's Standard and Coding Plan keys are separate." : p.id === "qwen" ? " Model Studio keys only work in the region they were made in." : p.id === "huggingface" ? " It needs a fine-grained token with Inference Providers on." : "";- return new HostedError(`${label} rejected the key${said}. Check it in ${where}.${extra}`, status, p.id);+ const hint = p.id === "zai" ? " Z.ai's Standard and Coding Plan keys are separate." : p.id === "qwen" ? " Model Studio keys only work in the region they were made in." : p.id === "huggingface" ? " It needs a fine-grained token with Inference Providers on." : "";+ if (keyRefused(status, body)) return new HostedError(`${label} rejected the key${said}. Check it in ${where}.${hint}`, status, p.id);+ if (status === 403) {+ // Free Quota Only on, and this model's free quota used up (Model Studio's free quota is per model).+ if (/AllocationQuota\.FreeTierOnly/.test(body)) {+ return new HostedError(`${p.short}'s free quota for ${model?.name ?? "this model"} is used up, and Free Quota Only is on in Model Studio. Pick another model in Manual, or turn Free Quota Only off for it.`, 403, p.id);+ }+ return new HostedError(`${label} refused this request${said}.${model ? " Pick another model in Manual, or check" : " Check"} your account's access on ${p.short}'s site.${p.id === "huggingface" ? hint : ""}`, 403, p.id);}if (status === 402 || /billing_not_configured|insufficient[_ ]balance|insufficient credits|no credit/i.test(body)) {const billing = p.billingUrl ?? p.keysUrl;@@ -89,10 +104,8 @@ export function hostedError(p: LlmProviderDef, status: number, body: string, mod}if (status === 404 || NO_MODEL.test(detail)) return new HostedError(`${label} has no model ${model?.id ?? "by that name"} today (it may have been retired). Pick another in Manual.`, status, p.id);if (status === 429) {- if (opts.free) {- const day = /per[- ]day|daily|today|per-day|rpd/i.test(detail) || FREE_CAP.test(detail);- return new FreeLimitError(day ? `${label}'s free requests for today are used up` : `${label}'s free requests are used up for the moment`, day ? "day" : "minute", p.id);- }+ // OpenRouter's body is the same for its minute and day caps: hosted.ts asks its key check which it was.+ if (opts.free) return freeLimit(p, DAY_CAP.test(detail) || DAY_CAP.test(body) ? "day" : "minute");const wait = opts.wait ? ` Try again in ${opts.wait} s.` : " Try again in a minute.";return new HostedError(`${label} is rate-limited right now.${wait}`, 429, p.id);}diff --git a/src/server/llm/hosted.ts b/src/server/llm/hosted.tsindex aaeaa17e..79881244 100644--- a/src/server/llm/hosted.ts+++ b/src/server/llm/hosted.ts@@ -6,7 +6,7 @@ import { getLlmProvider, LLM_PROVIDERS, type LlmModelDef, type LlmProviderDef, timport { isPrivateAddress } from "../remote-fetch";import { getSetting, type SettingName } from "../settings";import { tenant } from "../tenant";-import { ContextError, hostedError, HostedError, retryAfter, scrubKey, tooLongText } from "./hosted-errors";+import { ContextError, FreeLimitError, freeLimit, hostedError, HostedError, keyRefused, retryAfter, scrubKey, tooLongText } from "./hosted-errors";import { FITS_ID } from "./hosted-messages";import { healToolCalls } from "./messages";import { chatResponses } from "./responses";@@ -267,8 +267,9 @@ export async function postHosted(ep: Endpoint, path: string, body: unknown, optsrejected().delete(keyName(ep));return res;}- if (res.status === 401 || res.status === 403) rejected().add(keyName(ep));const text = await res.text().catch(() => "");+ // Only a refusal of the key itself: a 403 about one model or request (Qwen's free quota, Gemini's permission_denied) isn't.+ if (keyRefused(res.status, text)) rejected().add(keyName(ep));const wait = retryAfter(res.headers.get("retry-after"));if (attempt === 0 && RETRY.has(res.status) && (wait ?? 2) <= 30) {await sleep((wait ?? 2) * 1000);@@ -291,10 +292,40 @@ const keyName = (ep: Endpoint) => createHash("sha256").update(`${ep.provider.id}/** The provider rejected this key on a real call (and it hasn't worked since). */export const isRejected = (ep: Endpoint): boolean => rejected().has(keyName(ep));-/** A free limit ran out: the provider's free models are skipped until the day's (UTC) or the minute's limit resets. */+/** Midnight after `now` in a time zone, in ms. */+function nextMidnight(zone: string, now: number): number {+ const fmt = new Intl.DateTimeFormat("en-US", { timeZone: zone, hourCycle: "h23", year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric", second: "numeric" });+ const parts = (t: number) => Object.fromEntries(fmt.formatToParts(t).map((p) => [p.type, Number(p.value)])) as Record<string, number>;+ // The zone's offset at an instant: its wall clock read as UTC, less the instant.+ const offset = (t: number) => {+ const p = parts(t);+ return Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second) - Math.floor(t / 1000) * 1000;+ };+ const p = parts(now);+ const wall = Date.UTC(p.year, p.month - 1, p.day + 1);+ return wall - offset(wall - offset(now));+}++/** When a free limit that ran out comes back: a minute later, or at the provider's midnight (UTC; Gemini's is Pacific). */+export function freeResetAt(provider: string, span: "day" | "minute", now = Date.now()): number {+ return span === "minute" ? now + 60_000 : nextMidnight(getLlmProvider(provider)?.freeDayZone ?? "UTC", now);+}++/** A free limit ran out: the provider's free models are skipped until it resets. */export function markFreeSpent(provider: string, span: "day" | "minute"): void {- const now = new Date();- spent().set(provider, span === "day" ? Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + 1) : now.getTime() + 60_000);+ spent().set(provider, freeResetAt(provider, span));+}++/**+ * OpenRouter answers its per-minute and per-day free caps with the same 429 body: its key check (GET /key, free)+ * says which. The day's only when no free request is left today; without an answer, the error's words stand.+ */+async function freeSpan(ep: Endpoint, e: unknown): Promise<unknown> {+ if (!(e instanceof FreeLimitError) || ep.provider.id !== "openrouter") return e;+ const left = (await openRouterKey(true).catch(() => null))?.left;+ if (typeof left !== "number") return e;+ const span = left <= 0 ? "day" : "minute";+ return span === e.span ? e : freeLimit(ep.provider, span);}/** Providers whose free requests are used up right now. */@@ -315,7 +346,7 @@ export async function chatHosted(ep: Endpoint, model: LlmModelDef, req: HostedReconst p = ep.provider;const room = outputRoom(p, model, req.effort, req.maxTokens);const tokens = estimateTokens(req.messages, req.tools);- if (tokens > model.context - room) throw new ContextError(tooLongText(model, tokens));+ if (tokens > Math.min(model.context - room, model.maxIn ?? Infinity)) throw new ContextError(tooLongText(model, tokens));if (p.adapter === "openai-responses") return chatResponses(ep, model, { ...req, maxTokens: room });const q = p.quirks;const free = isFree(p, model);@@ -327,13 +358,15 @@ export async function chatHosted(ep: Endpoint, model: LlmModelDef, req: HostedRetimeoutMs,signal: req.signal,headers: q.chatHeader && req.threadKey ? { [q.chatHeader]: chatName(req.threadKey) } : undefined,+ }).catch(async (e) => {+ throw await freeSpan(ep, e);});if (!res.body) throw new HostedError(`${p.label} sent an empty answer`, 502, p.id);let out;try {out = await readChatStream(res.body, { errorEnvelope: q.errorEnvelope });} catch (e) {- if (e instanceof StreamError) throw hostedError(p, e.status ?? 502, JSON.stringify({ error: { message: e.message, code: e.code } }), model, ep.key, { free });+ if (e instanceof StreamError) throw await freeSpan(ep, hostedError(p, e.status ?? 502, JSON.stringify({ error: { message: e.message, code: e.code } }), model, ep.key, { free }));throw e;}const toolIds: Record<string, string> = {};@@ -373,14 +406,18 @@ export async function chatHosted(ep: Endpoint, model: LlmModelDef, req: HostedRe// ---------------------------------------------------------------------------// Settings: Test and Try a reply-/** GET with the key (a free call), never following a redirect. */+/** GET with the key (a free call), never following a redirect. A key that works here isn't "rejected" any more; a 401 is. */async function getHosted(ep: Endpoint, path: string): Promise<Response> {const url = `${checkBase(ep)}${path}`;+ let res: Response;try {- return await fetch(url, { headers: { authorization: `Bearer ${ep.key}`, ...ep.provider.quirks.headers }, redirect: "error", signal: AbortSignal.timeout(15_000) });+ res = await fetch(url, { headers: { authorization: `Bearer ${ep.key}`, ...ep.provider.quirks.headers }, redirect: "error", signal: AbortSignal.timeout(15_000) });} catch (e) {throw new HostedError(`Couldn't reach ${ep.provider.label} (${reason(e, ep.key)})`, 0, ep.provider.id);}+ if (res.ok) rejected().delete(keyName(ep));+ else if (res.status === 401) rejected().add(keyName(ep));+ return res;}export interface OpenRouterKey {diff --git a/src/server/settings.ts b/src/server/settings.tsindex c5c75e83..dc569e9d 100644--- a/src/server/settings.ts+++ b/src/server/settings.ts@@ -25,11 +25,14 @@ export const SETTINGS = {falKey: { key: "fal.key", env: "FAL_KEY", secret: true },replicateToken: { key: "replicate.token", env: "REPLICATE_API_TOKEN", secret: true },openaiKey: { key: "openai.key", env: "OPENAI_API_KEY", secret: true },- googleKey: { key: "google.key", env: ["GEMINI_API_KEY", "GOOGLE_API_KEY"], secret: true },+ googleKey: { key: "google.key", env: "GEMINI_API_KEY", secret: true },anthropicKey: { key: "anthropic.key", env: "ANTHROPIC_API_KEY", secret: true },/** Assist's hosted LLM providers (src/lib/catalog/llm-providers.ts): a key each, the region where the* provider has several official hosts, and the tick for a free plan Fuobe can't see from the key.+ * A key is read only from a name meant for that API: never one other tools set for something else+ * (HF_TOKEN is for downloads, GOOGLE_API_KEY for other Google Cloud APIs), which would connect a paid+ * provider the owner never added.*/xaiKey: { key: "xai.key", env: "XAI_API_KEY", secret: true },/** Meta's docs name no environment variable for Model API keys. */@@ -46,7 +49,7 @@ export const SETTINGS = {cerebrasKey: { key: "cerebras.key", env: "CEREBRAS_API_KEY", secret: true },togetherKey: { key: "together.key", env: "TOGETHER_API_KEY", secret: true },fireworksKey: { key: "fireworks.key", env: "FIREWORKS_API_KEY", secret: true },- huggingfaceToken: { key: "huggingface.token", env: "HF_TOKEN", secret: true },+ huggingfaceToken: { key: "huggingface.token", env: "FUOBE_HF_TOKEN", secret: true },openaiRegion: { key: "openai.region", default: "global", options: ["global", "us", "eu"] },xaiRegion: { key: "xai.region", default: "global", options: ["global", "us"] },moonshotRegion: { key: "moonshot.region", default: "international", options: ["international", "china"] },diff --git a/tests/assist-model-pick.test.ts b/tests/assist-model-pick.test.tsindex d1f4d930..909938a0 100644--- a/tests/assist-model-pick.test.ts+++ b/tests/assist-model-pick.test.ts@@ -55,6 +55,11 @@ describe("Smart", () => {expect(list.map((c) => c.provider)).toEqual(["zai", "together"]);});+ it("says why when every model connected is blocked, rather than asking for a key that is set", () => {+ expect(smartPick(world({ providers: [{ id: "deepseek", rejected: true }] })).text).toBe("Smart can't plan with DeepSeek V4 Pro: DeepSeek rejected the key — check it in Settings.");+ expect(smartPick(world({ providers: [{ id: "deepseek" }], openOnly: true })).text).toBe("Smart can't plan with DeepSeek V4 Pro: Paid API — Open source only is on (Settings).");+ });+it("on a local model only, says so; with nothing, can't be picked", () => {expect(smartPick(world({ local: ollama() })).text).toBe("Smart uses qwen3.8:27b on Ollama, on this machine.");const none = smartPick(world());@@ -75,10 +80,11 @@ describe("Smart", () => {expect(smartPick({ ...w, smartPlan: "openai|gpt-6.1-sol" }).plan).toMatchObject({ provider: "anthropic" });});- it("AI helper set to Local model only keeps hosted models out; set to Claude, Smart is Claude", () => {+ it("AI helper set to Local model only leaves Smart and Manual as they are (it sets the default: Free, local first); set to Claude, Smart is Claude", () => {const local = world({ providers: [{ id: "anthropic" }, { id: "openai" }], local: ollama(), helper: "local" });- expect(smartPick(local).plan).toMatchObject({ local: true });- expect(choices(local).find((c) => c.provider === "openai")!.disabled).toBe("AI helper is set to Local model only (Settings)");+ expect(smartPick(local).plan).toMatchObject({ provider: "anthropic", model: "claude-opus-5-5" });+ expect(choices(local).filter((c) => c.disabled)).toEqual([]);+ expect(freePick({ ...local, providers: [{ id: "openrouter" }] }).pick).toMatchObject({ local: true });expect(smartPick(world({ providers: [{ id: "anthropic" }, { id: "openai" }], helper: "anthropic", openOnly: true })).plan).toMatchObject({ provider: "anthropic" });});});@@ -120,6 +126,13 @@ describe("Free", () => {expect(cloud.pick).toBeNull();});+ it("skips OpenRouter's free models once the day's free requests are gone (its key check says 0 left)", () => {+ const w = world({ providers: [{ id: "openrouter", freeTier: true, freeLeft: 0, freeLimit: 50 }], local: ollama() });+ expect(choices(w).find((c) => c.model === "nvidia/nemotron-3-ultra-550b-a55b:free")!.disabled).toBe("OpenRouter's free requests for today are used up");+ expect(freePick(w).pick).toMatchObject({ local: true });+ expect(smartPick({ ...w, local: null }).plan).toBeNull();+ });+it("Z.ai's GLM Flash models are free on any key", () => {const f = freePick(world({ providers: [{ id: "zai" }] }));expect(f.pick).toMatchObject({ provider: "zai", free: true });@@ -128,19 +141,32 @@ describe("Free", () => {});describe("Open source only", () => {- it("allows open-weight models wherever they run, with a label that says where; unknown counts as closed", () => {+ it("runs only open-weight models that cost nothing: on this machine, or a provider's free ones; nothing goes to a paid API", () => {const w = world({ providers: [{ id: "anthropic" }, { id: "moonshot" }, { id: "deepseek" }, { id: "openrouter" }], openOnly: true, local: ollama() });const all = choices(w);expect(all.find((c) => c.model === "kimi-k3.1-pro")!.disabled).toBe("Not open weights — Open source only is on (Settings)");expect(all.find((c) => c.model === "claude-opus-5-5")!.disabled).toBeTruthy();- expect(smartPick({ ...w, providers: w.providers.filter((x) => x.id !== "openrouter") }).plan).toMatchObject({ provider: "deepseek", model: "deepseek-v4-pro" });- // OpenRouter's free open models count too (its best is free, so it comes first at its tier).+ // Open weights on a paid API: off, as Settings → Engine promises.+ expect(all.find((c) => c.model === "deepseek-v4-pro")!.disabled).toBe("Paid API — Open source only is on (Settings)");+ expect(all.find((c) => c.provider === "openrouter" && c.model === "x-ai/grok-4.7")!.disabled).toBeTruthy();+ // Paid keys alone: Smart plans on the local model, and nothing paid is the default.+ expect(smartPick({ ...w, providers: w.providers.filter((x) => x.id !== "openrouter") }).plan).toMatchObject({ local: true });+ expect(smartPick({ ...w, local: null, providers: [{ id: "deepseek" }] }).plan).toBeNull();+ // OpenRouter's free open models count (its best is free, so it comes first at its tier), and a free plan the owner ticked.expect(smartPick(w).plan).toMatchObject({ provider: "openrouter", model: "nvidia/nemotron-3-ultra-550b-a55b:free" });+ expect(choices(world({ providers: [{ id: "google", freeTick: true }], openOnly: true })).find((c) => c.model === "gemma-4-31b-it")!.disabled).toBeUndefined();+ // AI helper set to Claude is still the owner's way to use Claude on an open-source-only install.+ expect(smartPick({ ...w, helper: "anthropic" }).plan).toMatchObject({ provider: "anthropic" });expect(openLabel(all.find((c) => c.model === "deepseek-v4-pro")!)).toBe("Open weights · MIT · runs on DeepSeek's servers");expect(openLabel(all.find((c) => c.model === "google/gemma-4-31b-it:free")!)).toBe("Open weights · Apache-2.0 · free through OpenRouter");expect(openLabel(all.find((c) => c.local)!)).toBe("Open weights · on this machine");const r7b = choices(world({ providers: [{ id: "cohere" }] })).find((c) => c.model === "command-r7b-12-2024")!;expect(openLabel(r7b)).toBe("Open weights · CC-BY-NC-4.0 (non-commercial) · runs on Cohere's servers");+ // Hugging Face routes each id to the provider its suffix names: that provider runs it.+ const hf = choices(world({ providers: [{ id: "huggingface" }] }));+ expect(openLabel(hf.find((c) => c.model === "zai-org/GLM-5.3:deepinfra")!)).toBe("Open weights · GLM licence (other) · runs on DeepInfra, through Hugging Face");+ expect(openLabel(hf.find((c) => c.model === "deepseek-ai/DeepSeek-V4.1-Flash-1017:novita")!)).toBe("Open weights · MIT · runs on Novita, through Hugging Face");+ expect(openLabel(hf.find((c) => c.model.endsWith(":baseten"))!)).toMatch(/runs on Baseten, through Hugging Face$/);});});diff --git a/tests/assist-providers.test.ts b/tests/assist-providers.test.tsindex f33a1684..506658c1 100644--- a/tests/assist-providers.test.ts+++ b/tests/assist-providers.test.ts@@ -20,11 +20,12 @@ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-assist-providers-"));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";-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];+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 } = await import("@/server/settings");const agent = await import("@/server/assist/agent");-const { modeLabel } = await import("@/lib/assist");+const { modeLabel, threadModeChoice } = await import("@/lib/assist");+const hosted = await import("@/server/llm/hosted");const { LLM_PROVIDERS, getLlmProvider } = await import("@/lib/catalog/llm-providers");const fakes: FakeLlm[] = [];@@ -175,14 +176,69 @@ describe("Free", () => {const r = await agent.resolveMode({ mode: "free" });expect(r).toMatchObject({ mode: "free", agent: "hosted", provider: "openrouter", model: "nvidia/nemotron-3-ultra-550b-a55b:free" });const t = agent.createThread({ engine: "open", agent: r.agent, mode: r.mode, provider: r.provider, model: r.model, effort: r.effort });+ // The last 3 go elsewhere meanwhile: after the 429, OpenRouter's key check says none are left today.+ or.keyInfo = { is_free_tier: true, free_model_daily_requests: { used: 50, limit: 50, remaining: 0 } };agent.addMessage(t.id, "A fox in snow");await agent.run(t.id);const thread = agent.getThread(t.id)!.thread;expect(thread.items.find((i) => i.role === "notice")).toMatchObject({ text: expect.stringMatching(/^OpenRouter's free requests are used up for today, so this chat goes on with the local model \(your local server\) instead of Nemotron 3 Ultra \(OpenRouter\)\.$/) });expect(thread.items.at(-1)).toMatchObject({ role: "assistant", text: "Here's the plan, from this machine." });expect(thread).toMatchObject({ agent: "local", mode: "free" });- // Free never moves to a paid model, and later Free chats skip OpenRouter until the limit resets.+ // Free never moves to a paid model, and later Free chats skip OpenRouter until the limit resets (midnight UTC).expect((await agent.resolveMode({ mode: "free" })).agent).toBe("local");+ const now = new Date();+ expect(globalThis.__fuobeFreeSpent?.get("openrouter")).toBe(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + 1));+ });++ it("a per-minute free cap moves the chat on for the moment, and OpenRouter is back a minute later", async () => {+ const or = await fake("openrouter");+ or.keyInfo = { is_free_tier: true, free_model_daily_requests: { used: 20, limit: 50, remaining: 30 } };+ or.replies = [{ status: 429, headers: { "retry-after": "0" }, error: { error: { code: 429, message: "Rate limit exceeded", metadata: { error_type: "rate_limit_exceeded" } } } }];+ const local = fakeLlm("local", "sk-local-0123456789");+ await local.start();+ fakes.push(local);+ local.models = ["qwen3.8:27b"];+ local.replies = [{ text: "From this machine." }];+ setSetting("llmUrl", `${local.url}/v1`);+ setSetting("llmKey", local.key);+ const r = await agent.resolveMode({ mode: "free" });+ const t = agent.createThread({ engine: "open", agent: r.agent, mode: r.mode, provider: r.provider, model: r.model, effort: r.effort });+ agent.addMessage(t.id, "A fox in snow");+ const before = Date.now();+ await agent.run(t.id);+ expect(items(t.id).find((i) => i.role === "notice")).toMatchObject({ text: expect.stringMatching(/^OpenRouter's free requests are used up for the moment, so this chat goes on with/) });+ const until = globalThis.__fuobeFreeSpent!.get("openrouter")!;+ expect(until - before).toBeGreaterThanOrEqual(60_000);+ expect(until - Date.now()).toBeLessThanOrEqual(60_000);+ });+});++describe("keys other tools set in the environment", () => {+ it("HF_TOKEN (for gated downloads) and GOOGLE_API_KEY connect nothing: a local model stays the default", async () => {+ const local = fakeLlm("local", "sk-local-0123456789");+ await local.start();+ fakes.push(local);+ local.models = ["qwen3.8:27b"];+ setSetting("llmUrl", `${local.url}/v1`);+ setSetting("llmKey", local.key);+ process.env.HF_TOKEN = "hf_downloads0123456789abcdefgh";+ process.env.GOOGLE_API_KEY = "AIzaCloudTools0123456789abcdefgh";+ try {+ expect(hosted.connectedHosted()).toEqual([]);+ expect(await agent.resolveMode()).toMatchObject({ mode: "free", agent: "local" });+ expect((await agent.availability()).defaultMode).toBe("free");+ // With no local model either, new chats stay on the offline planner.+ setSetting("llmUrl", "http://127.0.0.1:9/v1");+ expect(await agent.resolveMode()).toMatchObject({ mode: "free", agent: "offline" });+ expect((await agent.availability()).defaultMode).toBe("free");+ // Fuobe's own name for an Assist token is the owner saying so.+ process.env.FUOBE_HF_TOKEN = "hf_inference0123456789abcdefgh";+ expect(hosted.endpointFor("huggingface")).not.toBeNull();+ } finally {+ delete process.env.HF_TOKEN;+ delete process.env.GOOGLE_API_KEY;+ delete process.env.FUOBE_HF_TOKEN;+ }});});@@ -196,12 +252,45 @@ describe("Manual", () => {try {await fake("moonshot");expect(await agent.resolveMode({ mode: "manual", agent: "hosted", provider: "moonshot", model: "kimi-k3.1-pro" })).toMatchObject({ mode: "free", note: expect.stringMatching(/Not open weights/) });- expect(await agent.resolveMode({ mode: "smart" })).toMatchObject({ agent: "hosted", provider: "deepseek", model: "deepseek-v4-pro" });+ // Open source only sends nothing to a paid API (Settings → Engine): open weights on a paid key don't run, and never by default.+ expect(await agent.resolveMode({ mode: "manual", agent: "hosted", provider: "deepseek", model: "deepseek-v4-pro" })).toMatchObject({ mode: "free", agent: "offline", note: "DeepSeek V4 Pro can't run here: Paid API — Open source only is on (Settings) — using Free instead." });+ expect(await agent.resolveMode({ mode: "smart" })).toMatchObject({ mode: "free", agent: "offline", note: expect.stringMatching(/^Smart can't plan with .+: .+Open source only is on \(Settings\)\. Using Free instead\.$/) });+ expect(await agent.resolveMode()).toMatchObject({ mode: "free", agent: "offline" });+ expect((await agent.availability()).defaultMode).toBe("free");} finally {setSetting("engineMode", "both");}});+ it("a Smart chat on a hosted model, switched to Manual without picking a model, stays on that provider and model", async () => {+ await fake("deepseek");+ const r = await agent.resolveMode({ mode: "smart" });+ const t = agent.createThread({ engine: "cloud", agent: r.agent, mode: r.mode, provider: r.provider, model: r.model, effort: r.effort });+ // What the picker starts from (and sends when it closes on the Manual tab), and what Schedule this request saves.+ const shown = threadModeChoice(agent.getThread(t.id)!.thread);+ expect(shown).toMatchObject({ mode: "smart", agent: "hosted", provider: "deepseek", model: "deepseek-v4-pro" });+ await agent.updateThread(t.id, { mode: { ...shown, mode: "manual" } });+ const after = agent.getThread(t.id)!.thread;+ expect(after).toMatchObject({ mode: "manual", agent: "hosted", provider: "deepseek", model: "deepseek-v4-pro", effort: "medium" });+ expect(after.items.filter((i) => i.role === "notice")).toEqual([]);+ expect(modeLabel(after)).toBe("DeepSeek V4 Pro · Medium");+ // A scheduled run from it starts on the same model.+ expect(await agent.resolveMode(threadModeChoice(after))).toMatchObject({ mode: "manual", agent: "hosted", provider: "deepseek", model: "deepseek-v4-pro" });+ });++ it("AI helper set to Local model only sets the default (Free) and leaves Smart and Manual's Claude as they were", async () => {+ setSetting("anthropicKey", "sk-ant-test-0123456789");+ setSetting("enhanceProvider", "local");+ try {+ expect(await agent.resolveMode({ mode: "smart" })).toMatchObject({ mode: "smart", agent: "claude", model: "claude-opus-5-5" });+ expect(await agent.resolveMode({ mode: "manual", agent: "claude", model: "claude-sonnet-5-5" })).toMatchObject({ mode: "manual", agent: "claude", model: "claude-sonnet-5-5" });+ expect(await agent.resolveMode()).toMatchObject({ mode: "free" });+ expect((await agent.availability()).defaultMode).toBe("free");+ } finally {+ setSetting("enhanceProvider", "auto");+ }+ });+it("Smart picks again, and says so, when its provider's key is removed", async () => {await fake("deepseek");const local = fakes.find((f) => f.mode === "local")!;diff --git a/tests/llm-hosted.test.ts b/tests/llm-hosted.test.tsindex a15e1d30..cf8c2f3d 100644--- a/tests/llm-hosted.test.ts+++ b/tests/llm-hosted.test.ts@@ -17,12 +17,12 @@ import { fakeLlm, type FakeLlm, type Mode } from "./helpers/fake-llm";const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-llm-hosted-"));process.env.FUOBE_DATA_DIR = dir;-for (const k of Object.keys(process.env)) if (/_API_KEY$|^HF_TOKEN$|^FUOBE_LLM_TEST_BASE$/.test(k)) delete process.env[k];+for (const k of Object.keys(process.env)) if (/_API_KEY$|HF_TOKEN$|^FUOBE_LLM_TEST_BASE$/.test(k)) delete process.env[k];const { setSetting } = await import("@/server/settings");const hosted = await import("@/server/llm/hosted");const { toHostedMessages } = await import("@/server/llm/hosted-messages");-const { ContextError, FreeLimitError, HostedError } = await import("@/server/llm/hosted-errors");+const { ContextError, FreeLimitError, HostedError, hostedError } = await import("@/server/llm/hosted-errors");const { runAsTenant } = await import("@/server/tenant");type Stored = Anthropic.Beta.BetaMessageParam & { replay?: unknown };@@ -272,12 +272,80 @@ describe("errors, in words that say what to do", () => {expect(f.seen.length - n).toBe(1);});- it("a free model's 429 is its free limit running out", async () => {+ it("a free model's 429 is its free limit running out: OpenRouter's key check says whether for the day or the minute", async () => {const or = fakes.find((x) => x.mode === "openrouter")!;- or.replies = [{ status: 429, headers: { "retry-after": "0" }, error: { error: { code: 429, message: "Rate limit exceeded: free-models-per-day", metadata: { error_type: "rate_limit_exceeded" } } } }];- const e = await call("openrouter", "nvidia/nemotron-3-ultra-550b-a55b:free", [{ role: "user", content: "hi" }]).catch((x) => x);- expect(e).toBeInstanceOf(FreeLimitError);- expect((e as InstanceType<typeof FreeLimitError>).span).toBe("day");+ const span = async () => {+ globalThis.__fuobeOpenRouterKey = undefined;+ const e = await call("openrouter", "nvidia/nemotron-3-ultra-550b-a55b:free", [{ role: "user", content: "hi" }]).catch((x) => x);+ expect(e).toBeInstanceOf(FreeLimitError);+ return (e as InstanceType<typeof FreeLimitError>).span;+ };+ // OpenRouter's documented body is the same for both caps (its limits page).+ const documented = { error: { code: 429, message: "Rate limit exceeded", metadata: { error_type: "rate_limit_exceeded" } } };+ or.replies = [{ status: 429, headers: { "retry-after": "0" }, error: documented }];+ or.keyInfo = { is_free_tier: true, free_model_daily_requests: { used: 38, limit: 50, remaining: 12 } };+ expect(await span()).toBe("minute");+ or.keyInfo = { is_free_tier: true, free_model_daily_requests: { used: 50, limit: 50, remaining: 0 } };+ expect(await span()).toBe("day");+ // Even a message that says per-day: 12 left means it was the minute's cap.+ or.replies = [{ status: 429, headers: { "retry-after": "0" }, error: { error: { code: 429, message: "Rate limit exceeded: free-models-per-day" } } }];+ or.keyInfo = { is_free_tier: true, free_model_daily_requests: { used: 38, limit: 50, remaining: 12 } };+ expect(await span()).toBe("minute");+ // Without the key check, the words decide: a minute's cap is never read as the day's.+ or.keyInfo = undefined;+ expect(await span()).toBe("day");+ or.replies = [{ status: 429, headers: { "retry-after": "0" }, error: { error: { code: 429, message: "Rate limit exceeded: free-models-per-min" } } }];+ expect(await span()).toBe("minute");+ or.replies = [{ status: 429, headers: { "retry-after": "0" }, error: documented }];+ expect(await span()).toBe("minute");+ });++ it("reads Gemini's daily quota apart from its per-minute limit (its error codes)", () => {+ const google = getLlmProvider("google")!;+ const flash = getLlmModel("google", "gemini-3.8-flash")!;+ const err = (code: string, message: string) => hostedError(google, 429, JSON.stringify({ error: { code, message } }), flash, "AIzaKEY0123456789", { free: true }) as InstanceType<typeof FreeLimitError>;+ expect(err("quota_exceeded", "You have exceeded your daily quota.").span).toBe("day");+ expect(err("rate_limit_exceeded", "You exceeded your current quota for requests per minute.").span).toBe("minute");+ expect(err("too_many_requests", "Too many requests").span).toBe("minute");+ });++ it("a day's free limit lasts until the provider's own midnight: UTC for OpenRouter, Pacific for Gemini", () => {+ const at = Date.parse("2026-10-31T20:00:00Z");+ expect(new Date(hosted.freeResetAt("openrouter", "day", at)).toISOString()).toBe("2026-11-01T00:00:00.000Z");+ expect(new Date(hosted.freeResetAt("google", "day", at)).toISOString()).toBe("2026-11-01T07:00:00.000Z");+ // Pacific winter time: midnight is 08:00 UTC.+ expect(new Date(hosted.freeResetAt("google", "day", Date.parse("2026-12-10T09:30:00Z"))).toISOString()).toBe("2026-12-11T08:00:00.000Z");+ expect(new Date(hosted.freeResetAt("google", "day", Date.parse("2026-12-10T07:30:00Z"))).toISOString()).toBe("2026-12-10T08:00:00.000Z");+ expect(hosted.freeResetAt("openrouter", "minute", at)).toBe(at + 60_000);+ });++ it("a 403 about one model or request isn't a rejected key; a key that works again (Settings → Test) is cleared", async () => {+ const q = await fake("qwen");+ setSetting("qwenWorkspace", "ws-abc123");+ q.models = ["qwen3.8-max"];+ const ep = () => hosted.endpointFor("qwen")!;+ const qwen = (m = "qwen3.8-max") => hosted.chatHosted(ep(), getLlmModel("qwen", m)!, { messages: [{ role: "user", content: "hi" }] });+ // Free Quota Only on, and this model's free quota is used up (Model Studio's docs): one model, not the key.+ q.replies = [{ status: 403, error: { code: "AllocationQuota.FreeTierOnly", message: "The free tier of the model has been exhausted." } }];+ const free = (await qwen().catch((x) => x)) as Error;+ expect(free.message).toBe("Qwen's free quota for Qwen3.8-Max is used up, and Free Quota Only is on in Model Studio. Pick another model in Manual, or turn Free Quota Only off for it.");+ expect(hosted.isRejected(ep())).toBe(false);+ // Another 403 says the provider's words, not "rejected the key".+ q.replies = [{ status: 403, error: { error: { code: "permission_denied", message: "Your API key does not have permission for this resource, or your project's API access is restricted." } } }];+ const denied = (await qwen().catch((x) => x)) as Error;+ expect(denied.message).toMatch(/refused this request \(Your API key does not have permission/);+ expect(denied.message).not.toMatch(/rejected the key/);+ expect(hosted.isRejected(ep())).toBe(false);+ // A 403 that names the key, and a 401, are the key.+ q.replies = [{ status: 403, error: { code: "InvalidApiKey", message: "Invalid API-key provided." } }];+ expect(((await qwen().catch((x) => x)) as Error).message).toMatch(/rejected the key/);+ expect(hosted.isRejected(ep())).toBe(true);+ // Settings → Test with the same key works: the key isn't marked rejected any more.+ expect(await hosted.testHosted("qwen")).toMatchObject({ ok: true });+ expect(hosted.isRejected(ep())).toBe(false);+ setSetting("qwenWorkspace", "");+ setSetting("qwenKey", "");+ process.env.FUOBE_LLM_TEST_BASE = (process.env.FUOBE_LLM_TEST_BASE ?? "").split(",").filter((x) => !x.startsWith("qwen=")).join(",");});it("stops before the call when the chat can't fit the model's context", async () => {@@ -285,6 +353,11 @@ describe("errors, in words that say what to do", () => {const n = f.seen.length;await expect(call("together", "openai/gpt-oss-120b", [{ role: "user", content: big }])).rejects.toThrow(/This chat is too long for gpt-oss-120b/);expect(f.seen.length).toBe(n);+ // GPT-5.4 Mini: 400K context, but 272K tokens in at most.+ const oa = await fake("openai");+ const before = oa.seen.length;+ await expect(call("openai", "gpt-5.4-mini", [{ role: "user", content: "word ".repeat(250_000) }])).rejects.toThrow(/This chat is too long for GPT-5\.4 Mini \(about 31\dK tokens\)/);+ expect(oa.seen.length).toBe(before);});});diff --git a/tests/llm-registry.test.ts b/tests/llm-registry.test.tsindex 32ba2e0d..82053d56 100644--- a/tests/llm-registry.test.ts+++ b/tests/llm-registry.test.ts@@ -3,7 +3,7 @@ import os from "node:os";import path from "node:path";import { describe, expect, it } from "vitest";import { ASSIST_EFFORTS } from "@/lib/assist";-import { getLlmModel, LLM_PROVIDERS, LLM_REGISTRY_CHECKED, priceOn } from "@/lib/catalog/llm-providers";+import { getLlmModel, LLM_PROVIDERS, LLM_REGISTRY_CHECKED, offersFree, priceOn } from "@/lib/catalog/llm-providers";/** The provider registry is data: these checks keep it honest (official https hosts only, a price or a@@ -150,4 +150,31 @@ describe("LLM provider registry", () => {}expect(settings.anthropicKey.secret).toBe(true);});++ it("reads keys only from names meant for that provider's API, never a token other tools set for something else", () => {+ const env = (name: string) => [(SETTINGS as Record<string, { env?: string | string[] }>)[name]?.env ?? []].flat();+ // HF_TOKEN is what Fuobe's own download commands ask for; GOOGLE_API_KEY is set by Google Cloud tools for other APIs.+ expect(env("huggingfaceToken")).toEqual(["FUOBE_HF_TOKEN"]);+ expect(env("googleKey")).toEqual(["GEMINI_API_KEY"]);+ const all = Object.keys(SETTINGS).flatMap(env);+ expect(all).not.toContain("HF_TOKEN");+ expect(all).not.toContain("GOOGLE_API_KEY");+ });++ it("tags a provider Free only when Assist can run on its free models", () => {+ const tagged = LLM_PROVIDERS.filter(offersFree).map((p) => p.id);+ expect(tagged).toEqual(expect.arrayContaining(["openrouter", "google", "zai", "mistral"]));+ // Groq's free plan allows 8,000 tokens a minute: one Assist step is more.+ expect(tagged).not.toContain("groq");+ // Trials run out: never tagged.+ expect(tagged).not.toContain("cerebras");+ expect(tagged).not.toContain("qwen");+ });++ it("keeps a model's input limit where the docs give one apart from the context (GPT-5.4 Mini: 400K context, 272K in)", () => {+ const mini = getLlmModel("openai", "gpt-5.4-mini")!;+ expect(mini).toMatchObject({ context: 400_000, maxIn: 272_000 });+ // The over-272K price step can't happen on a model that takes 272K at most.+ expect(mini.longContext).toBeUndefined();+ });});diff --git a/tests/llm-settings-security.test.ts b/tests/llm-settings-security.test.tsindex 7e26f82d..619ef75f 100644--- a/tests/llm-settings-security.test.ts+++ b/tests/llm-settings-security.test.ts@@ -20,7 +20,7 @@ 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];+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");diff --git a/vitest.config.ts b/vitest.config.tsindex 44b402c7..0ad2cdf1 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -22,7 +22,6 @@ export default defineConfig({["OPENAI_API_KEY","GEMINI_API_KEY",- "GOOGLE_API_KEY","XAI_API_KEY","FUOBE_META_API_KEY","MISTRAL_API_KEY",@@ -39,7 +38,7 @@ export default defineConfig({"CEREBRAS_API_KEY","TOGETHER_API_KEY","FIREWORKS_API_KEY",- "HF_TOKEN",+ "FUOBE_HF_TOKEN","FUOBE_LLM_TEST_BASE",].map((k) => [k, ""]),),