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: Smart and Free pick from every connected model, and say which
Adarsh8d337bcb12a2
diff --git a/src/lib/assist-models.ts b/src/lib/assist-models.tsnew file mode 100644index 00000000..9530494f--- /dev/null+++ b/src/lib/assist-models.ts@@ -0,0 +1,370 @@+import { ASSIST_EFFORTS, type AssistEffort } from "./assist";+import { KNOWN_LOCAL_MODELS, LLM_PROVIDERS, priceOn, type LlmModelDef, type LlmProviderDef, type PriceStep } from "./catalog/llm-providers";++/**+ * Which model Assist's Smart and Free use, and what Manual lists, from what the owner has connected.+ * Pure functions over the registry (src/lib/catalog/llm-providers.ts): the server builds the World+ * from Settings and the local servers' answers, and the browser only gets the results (GET /api/assist).+ *+ * Smart takes the best connected model: quality tier first, then a model Assist has really been run+ * with, then speed, price (input-heavy: (3 × in + out) ÷ 4) and a choice with no daily cap, then the+ * larger context; a maker's own API before a host's copy. Free takes the best free one, with no daily+ * cap first (a free limit that runs out mid-chat costs a step), and says what comes after it.+ */++export interface ConnectedProvider {+ id: string;+ /** The free-plan tick in Settings (Gemini free tier, Mistral Free mode, Cohere trial key, Groq Free plan). */+ freeTick?: boolean;+ /** A China region: prices in CNY. */+ cny?: boolean;+ /** The last real call said the key is wrong. */+ rejected?: boolean;+ /** OpenRouter: no credits bought yet, so only its free models run. */+ freeTier?: boolean;+ /** OpenRouter: free requests left today, and the day's limit. */+ freeLeft?: number | null;+ freeLimit?: number | null;+}++export interface LocalWorld {+ kind: string;+ /** "Ollama", "LM Studio"… */+ label: string;+ /** It answers with a model to use. */+ ok: boolean;+ /** The model a chat uses by default. */+ model: string | null;+ models: { id: string; vision?: boolean }[];+}++export interface World {+ providers: ConnectedProvider[];+ local: LocalWorld | null;+ /** Settings → Engine: Open source only. */+ openOnly: boolean;+ /** Settings → AI helper → Use. */+ helper: "auto" | "anthropic" | "local" | "none";+ /** Settings → AI helper → Smart plans with: "auto", or "provider|model". */+ smartPlan: string;+ /** Settings → AI helper → Free uses. */+ freeOrder: "best" | "local";+ /** YYYY-MM-DD, for dated prices and free models that expire. */+ today: string;+ /** A model that can see checks pictures for a planner that can't (check_generations look). */+ checker: boolean;+}++export interface Choice {+ /** "anthropic", "openai"…; a local server's kind for local models. */+ provider: string;+ model: string;+ name: string;+ providerLabel: string;+ /** The provider's name in a sentence ("Google"). */+ providerShort: string;+ agent: "claude" | "hosted" | "local";+ tier: 1 | 2 | 3 | 4;+ speed: "fast" | "normal" | "slow";+ context: number;+ sees: boolean;+ /** Costs nothing here: local, a free model, or a free plan the owner ticked. */+ free: boolean;+ /** A daily or monthly cap (free models and plans). */+ cap: boolean;+ /** The cap covers every free model of the provider (OpenRouter's). */+ sharedCap: boolean;+ local: boolean;+ tested: boolean;+ /** A host's copy of a maker's model. */+ host: boolean;+ /** For a host's copy: the maker's own model ("zai/glm-5.3"). */+ same?: string;+ router: boolean;+ tools: boolean;+ manualOnly?: string;+ price?: PriceStep;+ next?: PriceStep;+ cny?: boolean;+ priceNote?: string;+ limits?: string;+ /** "37 left today". */+ left?: string;+ caveat?: string;+ /** Open weights and the licence ("MIT"); absent: closed or unknown. */+ licence?: string;+ nonCommercial?: boolean;+ /** The levels this model offers, in the effort row's order. */+ efforts: AssistEffort[];+ note?: string;+ /** Why it can't be picked now (greyed in Manual, skipped by Smart and Free). */+ disabled?: string;+ /** Registry order, the last tie-break. */+ order: number;+}++const SPEED = { fast: 0, normal: 1, slow: 2 } as const;+/** Ollama Cloud models (gpt-oss:120b-cloud…) run on Ollama's servers and are billed: never Free. */+const CLOUD = /-cloud$|:cloud$/;++/** Input-heavy (an Assist step sends about 9,000 tokens and gets 300–2,000 back): (3 × in + out) ÷ 4 per million. */+const blended = (c: Choice) => (c.free ? 0 : c.price ? (3 * c.price.in + c.price.out) / 4 : Infinity);++const effortsOf = (m: Pick<LlmModelDef, "efforts">): AssistEffort[] => ASSIST_EFFORTS.map((e) => e.id).filter((e) => m.efforts?.[e] !== undefined && m.efforts?.[e] !== null);++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 (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";+ return undefined;+}++/** Every model of the connected providers and the local server, with why each can't run now. */+export function choices(w: World): Choice[] {+ const out: Choice[] = [];+ let order = 0;+ for (const p of LLM_PROVIDERS) {+ if (p.adapter === "local") continue;+ const conn = w.providers.find((x) => x.id === p.id);+ 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 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;+ const limits = free ? (m.free === "model" ? p.freeLimits?.text : p.freePlan?.limits) : undefined;+ const shared = free && !!p.freeLimits?.shared && m.free === "model";+ out.push({+ provider: p.id,+ model: m.id,+ name: m.name,+ providerLabel: p.label,+ providerShort: p.short,+ agent: p.adapter === "anthropic" ? "claude" : "hosted",+ tier: m.tier,+ speed: m.speed,+ context: m.context,+ sees: m.vision,+ free,+ cap: free,+ sharedCap: shared,+ local: false,+ tested: !!m.tested,+ host: !!m.same,+ ...(m.same && { same: m.same }),+ router: !!m.router,+ tools: m.tools === true,+ ...(m.manualOnly && { manualOnly: m.manualOnly }),+ ...(price && { price }),+ ...(next && { next }),+ ...(conn.cny && m.priceCny && { cny: true }),+ ...(m.priceNote && { priceNote: m.priceNote }),+ ...(limits && { limits }),+ ...(shared && typeof conn.freeLeft === "number" && { left: `${conn.freeLeft} left today` }),+ ...(free && (m.free === "model" ? p.freeLimits?.caveat : p.freePlan?.caveat) && { caveat: (m.free === "model" ? p.freeLimits?.caveat : p.freePlan?.caveat)! }),+ ...(m.open && { licence: m.open.licence, ...(m.open.nonCommercial && { nonCommercial: true }) }),+ efforts: effortsOf(m),+ ...(m.note && { note: m.note }),+ ...(disabledWhy(w, p, m, conn) && { disabled: disabledWhy(w, p, m, conn) }),+ order: order++,+ });+ }+ }+ const l = w.local;+ if (l) {+ const ids = l.models.length ? l.models : l.model ? [{ id: l.model }] : [];+ for (const lm of ids) {+ const known = KNOWN_LOCAL_MODELS.find((k) => k.match.test(lm.id));+ const cloud = CLOUD.test(lm.id);+ out.push({+ provider: l.kind,+ model: lm.id,+ name: lm.id,+ providerLabel: l.label,+ providerShort: l.label,+ agent: "local",+ tier: 4,+ speed: "normal",+ context: 0,+ sees: lm.vision ?? known?.vision ?? false,+ free: !cloud,+ cap: false,+ sharedCap: false,+ local: true,+ tested: false,+ host: false,+ router: false,+ tools: true,+ ...(known && { licence: known.licence }),+ efforts: [],+ ...(cloud && { note: "Ollama Cloud · paid" }),+ ...(w.helper === "none" ? { disabled: "The AI helper is off (Settings)" } : !l.ok ? { disabled: `${l.label} isn't ready` } : {}),+ order: order++,+ });+ }+ }+ return out;+}++type Cmp = (a: Choice, b: Choice) => number;+const by =+ (...keys: ((c: Choice) => number)[]): Cmp =>+ (a, b) => {+ for (const k of keys) {+ const d = k(a) - k(b);+ if (d) return d;+ }+ return 0;+ };+const tierOf = (c: Choice) => (c.router ? 5 : c.tier);+const KEYS = {+ tier: tierOf,+ tested: (c: Choice) => (c.tested ? 0 : 1),+ speed: (c: Choice) => SPEED[c.speed],+ price: blended,+ cap: (c: Choice) => (c.cap ? 1 : 0),+ context: (c: Choice) => -c.context,+ host: (c: Choice) => (c.host ? 1 : 0),+ order: (c: Choice) => c.order,+};++/** A host's copy right after its maker's own model when both are in the list (the maker's API comes first). */+function makerFirst(sorted: Choice[]): Choice[] {+ const key = (c: Choice) => `${c.provider}/${c.model}`;+ const present = new Set(sorted.map(key));+ const copies = sorted.filter((c) => c.same && present.has(c.same));+ const out = sorted.filter((c) => !copies.includes(c));+ for (const c of copies) out.splice(out.findLastIndex((x) => key(x) === c.same || x.same === c.same) + 1, 0, c);+ return out;+}++/** Smart's order: tier, run with Assist for real, speed, price, no cap, context, registry order; a maker before a host's copy of its model. */+export const rank = (list: Choice[]): Choice[] => makerFirst([...list].sort(by(KEYS.tier, KEYS.tested, KEYS.speed, KEYS.price, KEYS.cap, KEYS.context, KEYS.host, KEYS.order)));++/** Free's order: as Smart's, with no daily cap before speed (prices are all 0). */+const rankFree = (list: Choice[]): Choice[] => makerFirst([...list].sort(by(KEYS.tier, KEYS.tested, KEYS.cap, KEYS.speed, KEYS.context, KEYS.host, KEYS.order)));++/** The checker's order: short one-shot calls, so speed comes before tier among the strong models (T1–T2). */+const rankCheck = (list: Choice[]): Choice[] => makerFirst([...list].sort(by((c) => (tierOf(c) <= 2 ? 1 : tierOf(c)), KEYS.speed, KEYS.tier, KEYS.price, KEYS.cap, KEYS.context, KEYS.host, KEYS.order)));++/** Smart and Free may pick it: it can run now, calls tools for sure, and isn't Manual-only. */+const usable = (c: Choice) => !c.disabled && c.tools && !c.manualOnly;++/** Only the local server's default model stands for "the local model" in Smart and Free. */+const pickable = (w: World) => choices(w).filter((c) => usable(c) && (!c.local || c.model === w.local?.model));++/** "GPT-6.1 Sol (OpenAI)": the provider in brackets unless the name already says it. */+function who(c: Choice, extra?: string): string {+ if (c.local) return `${c.name} on ${c.providerLabel}`;+ const said = c.name.toLowerCase().startsWith(c.providerShort.toLowerCase());+ const bits = [...(said ? [] : [c.providerShort]), ...(extra ? [extra] : [])];+ return bits.length ? `${c.name} (${bits.join(", ")})` : c.name;+}++export interface SmartPick {+ plan: Choice | null;+ /** A model that can see, for a planner that can't (null: the planner checks, or nothing can see). */+ check: Choice | null;+ text: string;+}++/** Smart: the best connected model plans and picks models; the best one that can see checks pictures when the planner can't. */+export function smartPick(w: World): SmartPick {+ const all = pickable(w);+ const [pid, mid] = w.smartPlan.split("|");+ 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.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.` };+ }+ const through = plan.host || plan.provider === "openrouter" ? `${plan.name} through ${plan.providerLabel}` : who(plan, plan.free ? "free plan" : undefined);+ if (plan.sees) return { plan, check: null, text: `Smart uses ${through} to plan, pick models and check results.` };+ const check = w.checker ? (rankCheck(all.filter((c) => c.sees))[0] ?? null) : null;+ if (check) return { plan, check, text: `Smart uses ${through} to plan and pick models, and ${who(check, check.free && !check.local ? "free plan" : undefined)} to check pictures.` };+ return { plan, check: null, text: `Smart uses ${through} to plan and pick models. It can't see pictures, so it checks results by their prompts — connect a model that can see (Google, OpenAI…) for picture checks.` };+}++export interface FreePick {+ pick: Choice | null;+ /** What comes next when the pick's free limit runs out (other providers first: a shared cap ends all of a provider's free models). */+ then: Choice[];+ text: string;+}++const NOTHING_FREE =+ "Nothing free is connected. Add an OpenRouter key (free models) or a Z.ai key (free GLM Flash models), or start Ollama, LM Studio or Unsloth Studio. Until then, the offline planner takes simple requests.";++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. */+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 [pick, ...rest] = ordered;+ if (!pick) return { pick: null, then: [], text: NOTHING_FREE };+ const sharing = (c: Choice) => pick.sharedCap && c.sharedCap && c.provider === pick.provider;+ const then = [...rest.filter((c) => !sharing(c) && !c.router), ...rest.filter((c) => sharing(c) && !c.router), ...rest.filter((c) => c.router)];+ if (pick.local) return { pick, then, text: `Runs on ${pick.name} through ${pick.providerLabel} — free, on this machine.` };+ const after = then.find((c) => !sharing(c));+ const left = pick.left ? ` (${pick.left})` : "";+ return { pick, then, text: `Runs on ${runsOn(pick)} — free: ${pick.limits ?? "limits not published"}${left}.${after ? ` When those run out: ${runsOn(after)}.` : ""}` };+}++export interface ManualGroup {+ id: string;+ label: string;+ /** "Key set", "Free plan", "No credits yet", "Key rejected", or the local server's state. */+ status: string;+ models: Choice[];+}++/** Manual: each connected provider's models, grouped in the registry's order (local last), and the providers to add a key for. */+export function manualGroups(w: World): { groups: ManualGroup[]; missing: { id: string; label: string }[] } {+ const all = choices(w);+ const groups: ManualGroup[] = [];+ for (const p of LLM_PROVIDERS) {+ if (p.adapter === "local") continue;+ const conn = w.providers.find((x) => x.id === p.id);+ if (!conn) continue;+ const status = conn.rejected ? "Key rejected" : conn.freeTick && p.freePlan?.kind === "plan" ? "Free plan" : conn.freeTier ? "Free models only" : "Key set";+ groups.push({ id: p.id, label: p.label, status, models: all.filter((c) => c.provider === p.id && !c.local) });+ }+ const local = all.filter((c) => c.local);+ if (w.local && local.length) groups.push({ id: w.local.kind, label: w.local.label, status: w.local.ok ? "On this machine" : "Not ready", models: local });+ const missing = LLM_PROVIDERS.filter((p) => p.adapter !== "local" && !w.providers.some((x) => x.id === p.id)).map((p) => ({ id: p.id, label: p.label }));+ return { groups, missing };+}++const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];+/** "$2", "$0.30", "$0.0375": whole amounts plain, cents with two places, smaller ones as the page gives them. */+const money = (n: number, cny?: boolean) => `${cny ? "¥" : "$"}${Number.isInteger(n) ? n : Number(n.toFixed(2)) === n ? n.toFixed(2) : Number(n.toFixed(4)).toString()}`;+const day = (iso: string) => `${Number(iso.slice(8, 10))} ${MONTHS[Number(iso.slice(5, 7)) - 1]}`;++/** "$2 in, $10 out per million tokens", "… until 30 Nov, then $4 / $20", "Free · 20 a minute, 50 a day", "Free, on this machine". */+export function priceText(c: Choice): string {+ if (c.local) return c.free ? "Free, on this machine" : "Ollama Cloud · paid";+ if (c.free) return c.limits ? `Free · ${c.limits}` : "Free";+ if (!c.price) return c.priceNote ?? "Price not published";+ const now = `${money(c.price.in, c.cny)} in, ${money(c.price.out, c.cny)} out per million tokens`;+ return c.next && c.price.until ? `${now} until ${day(c.price.until)}, then ${money(c.next.in, c.cny)} / ${money(c.next.out, c.cny)}` : now;+}++/** "Open weights · MIT · runs on DeepSeek's servers"; 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`;+ return `Open weights · ${licence} · ${where}`;+}diff --git a/tests/assist-model-pick.test.ts b/tests/assist-model-pick.test.tsnew file mode 100644index 00000000..d1f4d930--- /dev/null+++ b/tests/assist-model-pick.test.ts@@ -0,0 +1,175 @@+import { describe, expect, it } from "vitest";+import { freePick, manualGroups, openLabel, priceText, rank, smartPick, choices, type World } from "@/lib/assist-models";++/*+ * Which model Smart and Free use, and what Manual lists, from what the owner has connected: pure+ * functions over the registry. Smart takes the best connected model (quality tier, then what Assist has+ * really been run with, then no daily cap, speed, price and context), Free the best free one, and both+ * say which model they use. Open source only, the AI helper setting, free-plan ticks and OpenRouter's+ * free tier narrow what may run.+ */++const world = (w: Partial<World> = {}): World => ({ providers: [], local: null, openOnly: false, helper: "auto", smartPlan: "auto", freeOrder: "best", today: "2026-10-31", checker: false, ...w });+const ollama = (model = "qwen3.8:27b", models = [model]) => ({ kind: "ollama", label: "Ollama", ok: true, model, models: models.map((id) => ({ id })) });+const names = (list: { name: string }[]) => list.map((c) => c.name);++describe("Smart", () => {+ it("keeps Claude Opus first while Anthropic is connected, then ranks the rest by tier, cap, speed, price and context", () => {+ const all = ["anthropic", "openai", "google", "xai", "moonshot", "qwen", "deepseek", "zai"].map((id) => ({ id }));+ const s = smartPick(world({ providers: all }));+ expect(s.plan).toMatchObject({ provider: "anthropic", model: "claude-opus-5-5" });+ expect(s.text).toBe("Smart uses Claude Opus 5.5 (Anthropic) to plan, pick models and check results.");+ const order = rank(choices(world({ providers: all })).filter((c) => !c.disabled && !c.manualOnly && c.tier === 1));+ expect(names(order)).toEqual(["Claude Opus 5.5", "Qwen3.8-Max", "Grok 4.7", "GPT-6.1 Sol", "Kimi K3.1 Pro", "Gemini 4 Argon"]);+ });++ it("isn't Claude-only: it names the best model connected, from any provider", () => {+ expect(smartPick(world({ providers: [{ id: "openai" }, { id: "deepseek" }] })).text).toBe("Smart uses GPT-6.1 Sol (OpenAI) to plan, pick models and check results.");+ const ds = smartPick(world({ providers: [{ id: "deepseek" }] }));+ expect(ds.plan).toMatchObject({ provider: "deepseek", model: "deepseek-v4-pro", sees: false });+ expect(ds.text).toBe("Smart uses DeepSeek V4 Pro to plan and pick models. It can't see pictures, so it checks results by their prompts — connect a model that can see (Google, OpenAI…) for picture checks.");+ });++ it("with the picture checker on, a model that can see checks for a planner that can't", () => {+ const s = smartPick(world({ providers: [{ id: "deepseek" }], checker: true }));+ expect(s.check).toMatchObject({ provider: "deepseek", model: "deepseek-flash" });+ expect(s.text).toBe("Smart uses DeepSeek V4 Pro to plan and pick models, and DeepSeek V4.1 Flash to check pictures.");+ const z = smartPick(world({ providers: [{ id: "zai" }, { id: "google", freeTick: true }], checker: true }));+ expect(z.plan).toMatchObject({ model: "glm-5.3" });+ expect(z.check).toMatchObject({ provider: "google", model: "gemini-3.8-flash" });+ expect(z.text).toBe("Smart uses GLM-5.3 (Z.ai) to plan and pick models, and Gemini 3.8 Flash (Google, free plan) to check pictures.");+ });++ it("OpenRouter without credits plans on its best free model; with credits, on its best paid one", () => {+ const free = smartPick(world({ providers: [{ id: "openrouter", freeTier: true }] }));+ expect(free.plan).toMatchObject({ model: "nvidia/nemotron-3-ultra-550b-a55b:free" });+ expect(free.text).toBe("Smart uses Nemotron 3 Ultra (free, through OpenRouter). Credits on OpenRouter, or a paid key (Anthropic, OpenAI, Google…), give better plans.");+ const paid = smartPick(world({ providers: [{ id: "openrouter" }] }));+ expect(paid.plan?.provider).toBe("openrouter");+ expect(paid.plan?.tier).toBe(1);+ expect(paid.text).toMatch(/^Smart uses .+ through OpenRouter to plan, pick models and check results\.$/);+ });++ it("the same model on its maker's API comes before a host's copy", () => {+ const list = rank(choices(world({ providers: [{ id: "together" }, { id: "zai" }] })).filter((c) => c.name === "GLM-5.3"));+ expect(list.map((c) => c.provider)).toEqual(["zai", "together"]);+ });++ 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());+ expect(none.plan).toBeNull();+ expect(none.text).toBe("Smart needs a model: add a key in Settings (Anthropic, OpenAI, Google, OpenRouter…) or start a local model.");+ });++ it("never picks Manual-only models, models whose tool calling isn't confirmed, or a rejected key", () => {+ const s = smartPick(world({ providers: [{ id: "moonshot" }] }));+ expect(s.plan?.model).toBe("kimi-k3.1-pro");+ expect(smartPick(world({ providers: [{ id: "google", freeTick: true }] })).plan?.model).not.toBe("gemma-4-31b-it");+ expect(smartPick(world({ providers: [{ id: "deepseek", rejected: true }] })).plan).toBeNull();+ });++ it("follows the owner's override when that model is connected", () => {+ const w = world({ providers: [{ id: "anthropic" }, { id: "deepseek" }], smartPlan: "deepseek|deepseek-v4-pro" });+ expect(smartPick(w).plan).toMatchObject({ provider: "deepseek", model: "deepseek-v4-pro" });+ 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", () => {+ 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(world({ providers: [{ id: "anthropic" }, { id: "openai" }], helper: "anthropic", openOnly: true })).plan).toMatchObject({ provider: "anthropic" });+ });+});++describe("Free", () => {+ it("offers OpenRouter's free models before a local one, with the limits and what comes next", () => {+ const f = freePick(world({ providers: [{ id: "openrouter", freeLeft: 37, freeLimit: 50 }], local: ollama() }));+ expect(f.pick).toMatchObject({ provider: "openrouter", model: "nvidia/nemotron-3-ultra-550b-a55b:free", free: true });+ expect(f.text).toBe("Runs on Nemotron 3 Ultra through OpenRouter — free: 20 a minute, 50 a day (1,000 a day once you've bought 10 credits) (37 left today). When those run out: qwen3.8:27b on Ollama.");+ // Every OpenRouter free model shares the day's cap: the next choice after them is the local one.+ expect(f.then[0]).toMatchObject({ local: true });+ expect(f.then.at(-1)!.model).toBe("openrouter/free");+ });++ it("puts the local model first when the owner asks, and says when nothing free is connected", () => {+ const f = freePick(world({ providers: [{ id: "openrouter" }], local: ollama(), freeOrder: "local" }));+ expect(f.pick).toMatchObject({ local: true });+ expect(freePick(world({ local: ollama() })).text).toBe("Runs on qwen3.8:27b through Ollama — free, on this machine.");+ const none = freePick(world({ providers: [{ id: "openai" }] }));+ expect(none.pick).toBeNull();+ expect(none.text).toBe("Nothing free is connected. Add an OpenRouter key (free models) or a Z.ai key (free GLM Flash models), or start Ollama, LM Studio or Unsloth Studio. Until then, the offline planner takes simple requests.");+ });++ it("counts a free plan only with the owner's tick, and then offers only that provider's free models", () => {+ expect(freePick(world({ providers: [{ id: "google" }] })).pick).toBeNull();+ const ticked = world({ providers: [{ id: "google", freeTick: true }] });+ const f = freePick(ticked);+ expect(f.pick).toMatchObject({ provider: "google", model: "gemini-3.8-flash" });+ expect(f.pick?.caveat).toBe("Google uses free-tier prompts to improve its products.");+ expect(choices(ticked).find((c) => c.model === "gemini-4-argon")!.disabled).toBe("Your Google key is on the free plan");+ });++ it("never counts trials as free, keeps Groq's free plan out (too small for Assist), and marks Ollama Cloud as paid", () => {+ expect(freePick(world({ providers: [{ id: "qwen" }, { id: "cerebras" }] })).pick).toBeNull();+ const groq = world({ providers: [{ id: "groq", freeTick: true }] });+ expect(freePick(groq).pick).toBeNull();+ expect(choices(groq).find((c) => c.model === "openai/gpt-oss-120b")!.disabled).toMatch(/Too small for Assist/);+ const cloud = freePick(world({ local: ollama("gpt-oss:120b-cloud") }));+ expect(cloud.pick).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 });+ expect(["glm-4.7-flash", "glm-4.6v-flash"]).toContain(f.pick!.model);+ });+});++describe("Open source only", () => {+ it("allows open-weight models wherever they run, with a label that says where; unknown counts as closed", () => {+ 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).+ expect(smartPick(w).plan).toMatchObject({ provider: "openrouter", model: "nvidia/nemotron-3-ultra-550b-a55b:free" });+ 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");+ });+});++describe("Manual and the words for prices", () => {+ it("groups connected providers first, then one Add key line for the rest", () => {+ const m = manualGroups(world({ providers: [{ id: "deepseek" }, { id: "anthropic" }], local: ollama("qwen3.8:27b", ["qwen3.8:27b", "gemma4:31b"]) }));+ expect(m.groups.map((g) => g.label)).toEqual(["Anthropic", "DeepSeek", "Ollama"]);+ expect(m.groups[0].models.map((x) => x.name)).toEqual(["Claude Opus 5.5", "Claude Sonnet 5.5", "Claude Haiku 5.5", "Claude Fable 5.1"]);+ expect(m.groups[2].models.map((x) => x.model)).toEqual(["qwen3.8:27b", "gemma4:31b"]);+ expect(m.missing.map((p) => p.id)).toContain("openrouter");+ expect(m.missing.map((p) => p.id)).not.toContain("deepseek");+ expect(m.missing.map((p) => p.id)).not.toContain("ollama");+ });++ it("reads prices like the rest of the app, with dated changes, CNY regions and free limits", () => {+ const c = (provider: string, model: string, w: Partial<World> = {}) => choices(world({ providers: [{ id: provider }], ...w })).find((x) => x.model === model)!;+ expect(priceText(c("openai", "gpt-6.1-sol"))).toBe("$2 in, $10 out per million tokens");+ expect(priceText(c("deepseek", "deepseek-flash"))).toBe("$0.30 in, $1.20 out per million tokens");+ expect(priceText(c("cohere", "command-r7b-12-2024"))).toBe("$0.0375 in, $0.15 out per million tokens");+ expect(priceText(c("google", "gemini-4-argon"))).toBe("$2 in, $10 out per million tokens until 30 Nov, then $4 / $20");+ expect(priceText(choices(world({ providers: [{ id: "moonshot", cny: true }] })).find((x) => x.model === "kimi-k3")!)).toBe("¥20 in, ¥100 out per million tokens");+ expect(priceText(c("openrouter", "nvidia/nemotron-3-ultra-550b-a55b:free"))).toBe("Free · 20 a minute, 50 a day (1,000 a day once you've bought 10 credits)");+ expect(priceText(c("cohere", "command-a-03-2025"))).toBe("Cohere's price page doesn't list it");+ expect(priceText(choices(world({ local: ollama() })).find((x) => x.local)!)).toBe("Free, on this machine");+ });++ it("lists the effort levels each model offers", () => {+ const c = choices(world({ providers: [{ id: "openai" }, { id: "minimax" }] }));+ expect(c.find((x) => x.model === "gpt-5.4-mini")!.efforts).toEqual(["low", "medium", "high", "xhigh"]);+ expect(c.find((x) => x.model === "MiniMax-M3")!.efforts).toEqual([]);+ });+});