7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
Make a fallback chain mean itself, empty or not (#1023)
Tashfeene852ff13a7d9
diff --git a/client/src/components/chain-manager.test.ts b/client/src/components/chain-manager.test.tsindex 9febc043..5d2708eb 100644--- a/client/src/components/chain-manager.test.ts+++ b/client/src/components/chain-manager.test.ts@@ -13,6 +13,7 @@ const localeDir = path.join(here, '../i18n/locales')const source = readFileSync(path.join(here, 'chain-manager.tsx'), 'utf8')const fallbackPage = readFileSync(path.join(here, '../pages/FallbackPage.tsx'), 'utf8')const app = readFileSync(path.join(here, '../App.tsx'), 'utf8')+const playground = readFileSync(path.join(here, '../pages/PlaygroundPage.tsx'), 'utf8')function locale(name: string): Record<string, unknown> {return JSON.parse(readFileSync(path.join(localeDir, `${name}.json`), 'utf8'))@@ -74,3 +75,29 @@ describe('chain manager', () => {expect(source).toContain('setCreateError')})})++// Switching the active chain has to change what the rest of the dashboard is+// looking at (#1021). Both of these were silently wrong: the routing table read+// one unscoped cache entry, so a switch re-rendered the previous chain's rows+// and a save wrote them into the new chain; and the Playground could only ever+// send 'auto', so a chain you had just built was untestable from the dashboard.+describe('chains reach the rest of the dashboard (#1021)', () => {+ it('scopes the fallback table and its staged edits to the active chain', () => {+ expect(fallbackPage).toContain("queryKey: ['profiles', 'active']")+ expect(fallbackPage).toContain("queryKey: ['fallback', 'chain', activeProfileId]")+ // Staged edits remember which chain they were made against instead of+ // following whichever one happens to be active at save time.+ expect(fallbackPage).toMatch(/staged\.profileId === activeProfileId/)+ })++ it('offers every custom chain in the playground picker as auto:<name>', () => {+ expect(playground).toContain("queryKey: ['profiles']")+ // The id has to be derived exactly as the server derives it in+ // routes/proxy.ts, or the picker offers models /v1/models never listed.+ expect(playground).toContain('`auto:${c.name.toLowerCase()}`')+ expect(playground).toContain('...chainOptions,')+ // A chain is server-picked like plain auto, so the "can't see images" hint+ // must not fire on one.+ expect(playground).toContain("!selectedModel.startsWith('auto:')")+ })+})diff --git a/client/src/components/chain-manager.tsx b/client/src/components/chain-manager.tsxindex 532d3173..a0d42dab 100644--- a/client/src/components/chain-manager.tsx+++ b/client/src/components/chain-manager.tsx@@ -29,7 +29,7 @@ function readCollapsed(): boolean {}}-interface Chain {+export interface Chain {id: numbername: stringemoji: stringdiff --git a/client/src/pages/FallbackPage.tsx b/client/src/pages/FallbackPage.tsxindex 25bbeb1c..62cbc3f0 100644--- a/client/src/pages/FallbackPage.tsx+++ b/client/src/pages/FallbackPage.tsx@@ -93,7 +93,10 @@ export default function FallbackPage() {const { t } = useI18n()const navigate = useNavigate()const queryClient = useQueryClient()- const [localEntries, setLocalEntries] = useState<FallbackEntry[] | null>(null)+ // Staged edits carry the chain they were made against, so switching chains+ // in the manager below discards them instead of letting one chain's unsaved+ // rows be saved into another (#1021).+ const [staged, setStaged] = useState<{ profileId: number | null; entries: FallbackEntry[] } | null>(null)const [optionsCollapsed, setOptionsCollapsed] = useState(readOptionsCollapsed)// Catalog search + filter state (#343).@@ -102,10 +105,27 @@ export default function FallbackPage() {const [filterTools, setFilterTools] = useState(false)const [minContext, setMinContext] = useState(0)- const { data: entries = [], isLoading } = useQuery<FallbackEntry[]>({- queryKey: ['fallback'],+ // The table edits the ACTIVE chain, so it is part of this query's identity+ // (#1021): keyed on 'fallback' alone, switching chains in the manager below+ // re-rendered the previous chain's rows from cache, and a save then wrote+ // them into the newly activated one. Held back until the active chain is+ // known so the first paint is already the right chain's.+ const { data: active, isPending: activePending } = useQuery<{ activeProfileId: number | null }>({+ queryKey: ['profiles', 'active'],+ queryFn: () => apiFetch('/api/profiles/active'),+ })+ const activeProfileId = active?.activeProfileId ?? null++ const { data: entries = [], isLoading: entriesLoading } = useQuery<FallbackEntry[]>({+ queryKey: ['fallback', 'chain', activeProfileId],queryFn: () => apiFetch('/api/fallback'),+ enabled: !activePending,})+ const isLoading = activePending || entriesLoading++ const localEntries = staged && staged.profileId === activeProfileId ? staged.entries : null+ const setLocalEntries = (entries: FallbackEntry[] | null) =>+ setStaged(entries === null ? null : { profileId: activeProfileId, entries })const { data: tokenUsage } = useQuery<TokenUsageData>({queryKey: ['fallback', 'token-usage'],diff --git a/client/src/pages/PlaygroundPage.tsx b/client/src/pages/PlaygroundPage.tsxindex 141262c7..7afcd60a 100644--- a/client/src/pages/PlaygroundPage.tsx+++ b/client/src/pages/PlaygroundPage.tsx@@ -4,6 +4,7 @@ import { ArrowUp, ChevronRight, CircleAlert, FileText, Paperclip, X } from 'luciimport { apiFetch } from '@/lib/api'import { Button } from '@/components/ui/button'import { buildModelOptions } from '@/lib/model-groups'+import type { Chain } from '@/components/chain-manager'import { Markdown } from '@/components/markdown'import { CopyButton } from '@/components/copy-button'import { toast } from '@/lib/toast'@@ -260,6 +261,25 @@ export default function PlaygroundPage() {queryFn: () => apiFetch('/api/fallback'),})+ // Named fallback chains (#1021). Every custom chain is served as an+ // `auto:<name>` model — /v1/models lists them and the send path already+ // routes them — but the picker only ever offered 'auto', so the one place+ // you could try a chain you had just built was a curl command. The id is+ // derived exactly as the server derives it (routes/proxy.ts).+ const { data: chains = [] } = useQuery<Chain[]>({+ queryKey: ['profiles'],+ queryFn: () => apiFetch('/api/profiles'),+ })+ const chainOptions = chains+ .filter(c => c.type === 'custom')+ .map(c => ({+ value: `auto:${c.name.toLowerCase()}`,+ label: c.emoji ? `${c.emoji} ${c.name}` : c.name,+ sub: `auto:${c.name.toLowerCase()}`,+ isNew: false,+ platforms: [] as string[],+ }))+// Unification is always on now (the on/off toggle was removed), so the picker// always collapses a model's providers into one option.const unifyOn = true@@ -277,8 +297,12 @@ export default function PlaygroundPage() {availableModels.filter(e => e.supportsVision).map(e => e.canonicalId ?? e.modelId),)const pendingImages = attachmentImages(attachments)+ // A chain (`auto:<name>`) is as server-picked as plain auto: the router+ // chooses a vision-capable member for an image request, so the hint would be+ // guesswork about a model that has not been picked yet.const modelBlindToImages = pendingImages.length > 0&& selectedModel !== 'auto' && selectedModel !== 'fusion'+ && !selectedModel.startsWith('auto:')&& !visionValues.has(selectedModel)// Follow the stream only while the reader is parked at the bottom. Judging@@ -795,6 +819,7 @@ export default function PlaygroundPage() {const pickerOptions = [{ value: 'auto', label: t('playground.autoModel'), sub: '', isNew: false, platforms: [] as string[] },{ value: 'fusion', label: t('playground.fusionModel'), sub: '', isNew: false, platforms: [] as string[] },+ ...chainOptions,...modelOptions.slice().sort((a, b) =>@@ -824,6 +849,10 @@ export default function PlaygroundPage() {? t('playground.autoModel'): selectedModel === 'fusion'? t('playground.fusionModel')+ : selectedModel.startsWith('auto:')+ // A remembered chain whose name has since changed (or been deleted) has no+ // option left to read a label from; the raw id is still the truth.+ ? chainOptions.find(o => o.value === selectedModel)?.label ?? selectedModel: modelOptions.find(o => o.value === selectedModel)?.label ?? selectedModelreturn (diff --git a/server/src/__tests__/helpers/chain.ts b/server/src/__tests__/helpers/chain.tsnew file mode 100644index 00000000..bd158b78--- /dev/null+++ b/server/src/__tests__/helpers/chain.ts@@ -0,0 +1,22 @@+import { getDb } from '../../db/index.js';+import { getActiveProfileId } from '../../services/profile-models.js';++/**+ * Put a model in the active fallback chain, the way a catalog sync does.+ *+ * A fixture that seeds `models` + `fallback_config` by hand has only built half+ * an install: on a real one every catalog model is mirrored into the active+ * profile's chain (services/profile-models.ts), and that chain — not the global+ * table — is what the router walks (#1021). No-op when nothing is active, which+ * is the legacy shape where `fallback_config` IS the chain.+ */+export function addToActiveChain(modelDbId: number, priority: number, enabled = true): void {+ const db = getDb();+ const profileId = getActiveProfileId(db);+ if (profileId == null) return;+ db.prepare(`+ INSERT INTO profile_models (profile_id, model_db_id, priority, enabled)+ VALUES (?, ?, ?, ?)+ ON CONFLICT(profile_id, model_db_id) DO UPDATE SET priority = excluded.priority, enabled = excluded.enabled+ `).run(profileId, modelDbId, priority, enabled ? 1 : 0);+}diff --git a/server/src/__tests__/routes/anthropic.test.ts b/server/src/__tests__/routes/anthropic.test.tsindex f7c449a0..e69c1ed9 100644--- a/server/src/__tests__/routes/anthropic.test.ts+++ b/server/src/__tests__/routes/anthropic.test.ts@@ -2,6 +2,7 @@ import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'viteimport type { Express } from 'express';import { createApp } from '../../app.js';import { initDb, getDb, getUnifiedApiKey } from '../../db/index.js';+import { addToActiveChain } from '../helpers/chain.js';import { encrypt } from '../../lib/crypto.js';import { setUnifyEnabled, setUnifyOverrides } from '../../services/model-groups.js';import { getRoutingStrategy, setRoutingStrategy, type RoutingStrategy } from '../../services/router.js';@@ -535,6 +536,7 @@ describe('Anthropic-compatible /v1/messages', () => {`).run(platform, modelId, displayName);const id = Number(info.lastInsertRowid);db.prepare('INSERT INTO fallback_config (model_db_id, priority, enabled) VALUES (?, ?, 1)').run(id, priority);+ addToActiveChain(id, priority);return id;}diff --git a/server/src/__tests__/routes/profiles-chains.test.ts b/server/src/__tests__/routes/profiles-chains.test.tsindex 10cb20d1..87888c36 100644--- a/server/src/__tests__/routes/profiles-chains.test.ts+++ b/server/src/__tests__/routes/profiles-chains.test.ts@@ -33,6 +33,19 @@ function chainSize(profileId: number): number {.get(profileId) as { n: number }).n;}+/** Enabled catalog models — what GET /api/fallback lists for any chain. */+function catalogSize(): number {+ return (getDb().prepare('SELECT COUNT(*) AS n FROM models WHERE enabled = 1')+ .get() as { n: number }).n;+}++/** The single global table every chain used to be aliased onto (#1021). */+function globalConfig(): { model_db_id: number; priority: number; enabled: number }[] {+ return getDb().prepare(+ 'SELECT model_db_id, priority, enabled FROM fallback_config ORDER BY model_db_id',+ ).all() as { model_db_id: number; priority: number; enabled: number }[];+}+function autoInclude(profileId: number): number {return (getDb().prepare('SELECT auto_include_new_models AS flag FROM profiles WHERE id = ?').get(profileId) as { flag: number }).flag;@@ -132,6 +145,89 @@ describe('named fallback chains', () => {expect(chainSize(chain.id)).toBe(0);});+ it('shows an empty active chain as the catalog with nothing turned on (#1021)', async () => {+ const empty = (await request('POST', '/api/profiles', { name: 'blank', empty: true })).body;+ expect((await request('POST', '/api/profiles/active', { profileId: empty.id })).status).toBe(200);++ const { status, body } = await request('GET', '/api/fallback');+ expect(status).toBe(200);+ // Every catalog model is listed — an empty chain is an empty set of+ // opt-ins, not an empty page — and not one of them is enabled. Before the+ // fix the zero-row chain fell through to the global table and displayed the+ // whole catalog switched ON.+ expect(body.length).toBe(catalogSize());+ expect(body.every((row: { enabled: boolean }) => row.enabled === false)).toBe(true);+ // Priorities stay monotonic so the table renders in a stable order.+ for (let i = 1; i < body.length; i++) {+ expect(body[i].priority).toBeGreaterThanOrEqual(body[i - 1].priority);+ }+ // Reading the chain never writes to it.+ expect(chainSize(empty.id)).toBe(0);+ });++ it('fills an empty chain on save without touching the global table (#1021)', async () => {+ const chain = (await request('POST', '/api/profiles', { name: 'built', empty: true })).body;+ await request('POST', '/api/profiles/active', { profileId: chain.id });++ const before = globalConfig();+ const listed = (await request('GET', '/api/fallback')).body as { modelDbId: number }[];+ const picked = [listed[0].modelDbId, listed[1].modelDbId];+ const saved = await request('PUT', '/api/fallback', listed.map((row, index) => ({+ modelDbId: row.modelDbId,+ priority: index + 1,+ enabled: picked.includes(row.modelDbId),+ })));+ expect(saved.status).toBe(200);++ // The two picks landed in THIS chain, enabled...+ const enabled = getDb().prepare(+ 'SELECT model_db_id FROM profile_models WHERE profile_id = ? AND enabled = 1 ORDER BY priority',+ ).all(chain.id) as { model_db_id: number }[];+ expect(enabled.map(r => r.model_db_id)).toEqual(picked);+ // ...and the global fallback_config every chain used to share is untouched.+ expect(globalConfig()).toEqual(before);+ });++ it('keeps two empty chains from sharing one configuration (#1021)', async () => {+ const a = (await request('POST', '/api/profiles', { name: 'chain-a', empty: true })).body;+ const b = (await request('POST', '/api/profiles', { name: 'chain-b', empty: true })).body;++ await request('POST', '/api/profiles/active', { profileId: a.id });+ const listed = (await request('GET', '/api/fallback')).body as { modelDbId: number }[];+ await request('PUT', '/api/fallback', listed.map((row, index) => ({+ modelDbId: row.modelDbId,+ priority: index + 1,+ enabled: index < 2,+ })));++ await request('POST', '/api/profiles/active', { profileId: b.id });+ const seenFromB = (await request('GET', '/api/fallback')).body as { enabled: boolean }[];+ expect(seenFromB.every(row => row.enabled === false)).toBe(true);++ // And switching back still shows A's own picks.+ await request('POST', '/api/profiles/active', { profileId: a.id });+ const seenFromA = (await request('GET', '/api/fallback')).body as { enabled: boolean }[];+ expect(seenFromA.filter(row => row.enabled).length).toBe(2);+ });++ it('sorts an empty chain into the chain, not the global table (#1021)', async () => {+ const chain = (await request('POST', '/api/profiles', { name: 'sorted', empty: true })).body;+ await request('POST', '/api/profiles/active', { profileId: chain.id });++ const before = globalConfig();+ const sorted = await request('POST', '/api/fallback/sort/speed');+ expect(sorted.status).toBe(200);++ const rows = getDb().prepare(+ 'SELECT model_db_id, priority, enabled FROM profile_models WHERE profile_id = ? ORDER BY priority',+ ).all(chain.id) as { model_db_id: number; priority: number; enabled: number }[];+ expect(rows.length).toBeGreaterThan(0);+ expect(rows.map(r => r.priority)).toEqual(rows.map((_, i) => i + 1));+ // A sort orders the list; it must never switch models on behind the operator.+ expect(rows.every(r => r.enabled === 0)).toBe(true);+ expect(globalConfig()).toEqual(before);+ });+it('reports the flag on the chain listing so the dashboard can show it', async () => {await request('POST', '/api/profiles', { name: 'curated', empty: true });const { status, body } = await request('GET', '/api/profiles');diff --git a/server/src/__tests__/routes/routing-semantics.test.ts b/server/src/__tests__/routes/routing-semantics.test.tsindex 4dd11731..bd9ee495 100644--- a/server/src/__tests__/routes/routing-semantics.test.ts+++ b/server/src/__tests__/routes/routing-semantics.test.ts@@ -183,6 +183,33 @@ describe('routing semantics', () => {expect(routed.modelDbId).not.toBe(disabledId);});+ it('refuses model:"auto" on an empty active chain instead of routing the catalog (#1021)', () => {+ const db = getDb();+ addKey('groq');+ // The chain the operator is on holds nothing — a chain created with+ // "start empty", or one pruned by hand. fallback_config still lists the+ // whole seeded catalog, which is exactly what must NOT be routed over.+ db.prepare('DELETE FROM profile_models WHERE profile_id = ?').run(activeProfileId());+ expect((db.prepare('SELECT COUNT(*) AS n FROM fallback_config').get() as { n: number }).n)+ .toBeGreaterThan(0);++ let thrown: any;+ try { resolveRoutingChain('auto'); } catch (err) { thrown = err; }+ expect(thrown).toBeDefined();+ expect(thrown.status).toBe(400);+ expect(thrown.message).toMatch(/no enabled models/i);+ // The named form of the same chain already behaved this way; both agree now.+ expect(() => resolveRoutingChain('auto:default')).toThrow(/no enabled models/i);+ });++ it('routes an active chain whose models are all switched off nowhere either', () => {+ const db = getDb();+ addKey('groq');+ db.prepare('UPDATE profile_models SET enabled = 0 WHERE profile_id = ?').run(activeProfileId());++ expect(() => resolveRoutingChain('auto')).toThrow(/no enabled models/i);+ });+it('explicit named routing can still use a model disabled only for auto routing', () => {const db = getDb();db.prepare('DELETE FROM fallback_config').run();diff --git a/server/src/__tests__/services/router-bandit.test.ts b/server/src/__tests__/services/router-bandit.test.tsindex 15728256..560d13a0 100644--- a/server/src/__tests__/services/router-bandit.test.ts+++ b/server/src/__tests__/services/router-bandit.test.ts@@ -9,6 +9,7 @@ import { BANDIT_PRESETS, DEFAULT_PEAK_HOURS } from '../../services/scoring.js';import { resetModelWeightOverrides } from '../../services/model-weight-overrides.js';import * as ratelimit from '../../services/ratelimit.js';import { getDb, initDb } from '../../db/index.js';+import { addToActiveChain } from '../helpers/chain.js';vi.mock('../../services/ratelimit.js', async () => {const actual = await vi.importActual('../../services/ratelimit.js');@@ -42,6 +43,7 @@ function addModel(opts: {const id = (db.prepare('SELECT id FROM models WHERE platform = ? AND model_id = ?').get(opts.platform, opts.modelId) as { id: number }).id;db.prepare('INSERT INTO fallback_config (model_db_id, priority, enabled) VALUES (?, ?, 1)').run(id, opts.priority);+ addToActiveChain(id, opts.priority);// every platform needs at least one healthy key to be routabledb.prepare(`INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled)diff --git a/server/src/__tests__/services/router-key-bandit.test.ts b/server/src/__tests__/services/router-key-bandit.test.tsindex c1d7e880..1f796477 100644--- a/server/src/__tests__/services/router-key-bandit.test.ts+++ b/server/src/__tests__/services/router-key-bandit.test.ts@@ -2,6 +2,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import { routeRequest, refreshStatsCache, setRoutingStrategy } from '../../services/router.js';import * as ratelimit from '../../services/ratelimit.js';import { getDb, initDb } from '../../db/index.js';+import { addToActiveChain } from '../helpers/chain.js';// Per-key scoring inside one model (#580): with the group merge, several keys// (and formerly several providers' identically-named models) share one routing@@ -39,6 +40,7 @@ function addModel(opts: {const id = (db.prepare('SELECT id FROM models WHERE platform = ? AND model_id = ?').get(opts.platform, opts.modelId) as { id: number }).id;db.prepare('INSERT INTO fallback_config (model_db_id, priority, enabled) VALUES (?, ?, 1)').run(id, opts.priority ?? 1);+ addToActiveChain(id, opts.priority ?? 1);return id;}diff --git a/server/src/__tests__/services/router-priority-penalty.test.ts b/server/src/__tests__/services/router-priority-penalty.test.tsindex b81b04e6..708984ac 100644--- a/server/src/__tests__/services/router-priority-penalty.test.ts+++ b/server/src/__tests__/services/router-priority-penalty.test.ts@@ -4,6 +4,7 @@ import {recordRateLimitHit, recordSuccess,} from '../../services/router.js';import { getDb, initDb } from '../../db/index.js';+import { addToActiveChain } from '../helpers/chain.js';vi.mock('../../services/ratelimit.js', async () => {const actual = await vi.importActual('../../services/ratelimit.js');@@ -42,6 +43,7 @@ function addModel(opts: { platform: string; modelId: string; priority: number })const id = (db.prepare('SELECT id FROM models WHERE platform = ? AND model_id = ?').get(opts.platform, opts.modelId) as { id: number }).id;db.prepare('INSERT INTO fallback_config (model_db_id, priority, enabled) VALUES (?, ?, 1)').run(id, opts.priority);+ addToActiveChain(id, opts.priority);db.prepare(`INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled)VALUES (?, 'k', 'enc', 'iv', 'tag', 'healthy', 1)diff --git a/server/src/__tests__/services/router-speed-scoring.test.ts b/server/src/__tests__/services/router-speed-scoring.test.tsindex a3a14d4b..96b4ec34 100644--- a/server/src/__tests__/services/router-speed-scoring.test.ts+++ b/server/src/__tests__/services/router-speed-scoring.test.ts@@ -6,6 +6,7 @@ import {import { observedSpeedRank, TIMEOUT_LATENCY_CAP_MS } from '../../services/scoring.js';import { upsertModelOverrides } from '../../services/model-state.js';import { getDb, initDb } from '../../db/index.js';+import { addToActiveChain } from '../helpers/chain.js';vi.mock('../../lib/crypto.js', async () => {const actual = await vi.importActual('../../lib/crypto.js');@@ -27,6 +28,7 @@ function addModel(opts: {.get(opts.platform, opts.modelId) as { id: number }).id;db.prepare('INSERT INTO fallback_config (model_db_id, priority, enabled) VALUES (?, ?, 1)').run(id, opts.priority ?? 1);+ addToActiveChain(id, opts.priority ?? 1);db.prepare(`INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled)VALUES (?, 'k', 'enc', 'iv', 'tag', 'healthy', 1)diff --git a/server/src/routes/fallback.ts b/server/src/routes/fallback.tsindex 35310d40..5c4875ef 100644--- a/server/src/routes/fallback.ts+++ b/server/src/routes/fallback.ts@@ -118,12 +118,10 @@ fallbackRouter.put('/routing', (req: Request, res: Response) => {});});-// Get fallback chain (with dynamic penalties)-fallbackRouter.get('/', (_req: Request, res: Response) => {- const db = getDb();- const activeProfileId = getActiveProfileId(db);- let rows = activeProfileId == null ? [] : db.prepare(`- SELECT pm.model_db_id, pm.priority, pm.enabled,+// The catalog columns every fallback row carries, whichever table supplies the+// priority/enabled pair. Kept in one place so the profile and the no-profile+// query can never drift apart.+const MODEL_COLUMNS = `m.platform, m.model_id, m.display_name, m.intelligence_rank,m.speed_rank, m.size_label, m.rpm_limit, m.rpd_limit,m.tpm_limit, m.tpd_limit, m.context_window,@@ -131,38 +129,76 @@ fallbackRouter.get('/', (_req: Request, res: Response) => {m.key_id, m.endpoint_scope, ak.label AS key_label,mo.overrides_json IS NOT NULL AS has_overrides,mo.overrides_json,- ts.source AS tombstone_source, ts.reason AS tombstone_reason- FROM profile_models pm- JOIN models m ON m.id = pm.model_db_id+ ts.source AS tombstone_source, ts.reason AS tombstone_reason`;++const MODEL_JOINS = `LEFT JOIN api_keys ak ON ak.id = m.key_idLEFT JOIN model_overrides mo ON mo.platform = m.platform AND mo.model_id = m.model_idLEFT JOIN catalog_model_tombstones ts- ON ts.kind = 'chat' AND ts.platform = m.platform AND ts.model_id = m.model_id- WHERE pm.profile_id = ? AND m.enabled = 1- ORDER BY pm.priority ASC- `).all(activeProfileId) as any[];+ ON ts.kind = 'chat' AND ts.platform = m.platform AND ts.model_id = m.model_id`;++// The whole catalog seen THROUGH one chain (#1021). A chain is a set of opt-ins,+// not a copy of the catalog: a model the chain names keeps the priority and the+// on/off flag stored against it, and a model it does not name is still listed —+// switched OFF, ranked after everything the chain does name. That is what makes+// a hand-built ("start empty") chain usable at all: it renders as "the catalog,+// nothing turned on yet" instead of an empty page, and turning a row on is the+// PUT below, which writes the row into the chain. Nothing is persisted by GET.+const PROFILE_CHAIN_SQL = `+ SELECT m.id AS model_db_id, pm.priority AS chain_priority, pm.enabled AS chain_enabled,+ fc.priority AS catalog_priority,+${MODEL_COLUMNS}+ FROM models m+ LEFT JOIN profile_models pm ON pm.profile_id = ? AND pm.model_db_id = m.id+ LEFT JOIN fallback_config fc ON fc.model_db_id = m.id+${MODEL_JOINS}+ WHERE m.enabled = 1+`;- if (rows.length === 0) {- rows = db.prepare(`+const GLOBAL_CHAIN_SQL = `SELECT fc.model_db_id, fc.priority, fc.enabled,- m.platform, m.model_id, m.display_name, m.intelligence_rank,- m.speed_rank, m.size_label, m.rpm_limit, m.rpd_limit,- m.tpm_limit, m.tpd_limit, m.context_window,- m.monthly_token_budget, m.supports_vision, m.supports_tools,- m.key_id, m.endpoint_scope, ak.label AS key_label,- mo.overrides_json IS NOT NULL AS has_overrides,- mo.overrides_json,- ts.source AS tombstone_source, ts.reason AS tombstone_reason+${MODEL_COLUMNS}FROM fallback_config fcJOIN models m ON m.id = fc.model_db_id- LEFT JOIN api_keys ak ON ak.id = m.key_id- LEFT JOIN model_overrides mo ON mo.platform = m.platform AND mo.model_id = m.model_id- LEFT JOIN catalog_model_tombstones ts- ON ts.kind = 'chat' AND ts.platform = m.platform AND ts.model_id = m.model_id+${MODEL_JOINS}WHERE m.enabled = 1ORDER BY fc.priority ASC- `).all() as any[];- }+`;++/**+ * Order a chain-scoped catalog read and give every row a priority.+ *+ * Rows the chain names come first, in their stored order and keeping their+ * stored numbers. Rows it does not name follow in catalog order, numbered after+ * the last stored one, so the list stays monotonic and stable between reads+ * without writing anything back.+ */+function orderProfileRows(rows: any[]): any[] {+ const inChain = rows.filter(r => r.chain_priority != null);+ const rest = rows.filter(r => r.chain_priority == null);+ inChain.sort((a, b) => a.chain_priority - b.chain_priority || a.model_db_id - b.model_db_id);+ rest.sort((a, b) =>+ (a.catalog_priority ?? Number.MAX_SAFE_INTEGER) - (b.catalog_priority ?? Number.MAX_SAFE_INTEGER)+ || a.model_db_id - b.model_db_id);++ const maxStored = inChain.length ? inChain[inChain.length - 1].chain_priority : 0;+ return [+ ...inChain.map(r => ({ ...r, priority: r.chain_priority, enabled: r.chain_enabled })),+ ...rest.map((r, i) => ({ ...r, priority: maxStored + 1 + i, enabled: 0 })),+ ];+}++// Get fallback chain (with dynamic penalties)+fallbackRouter.get('/', (_req: Request, res: Response) => {+ const db = getDb();+ const activeProfileId = getActiveProfileId(db);+ // `fallback_config` is the chain only for an install that has no profiles at+ // all. Once one is active it is authoritative even when it is empty — falling+ // through to the global table there is what made two different empty chains+ // show (and save) the same configuration (#1021).+ const rows = activeProfileId != null+ ? orderProfileRows(db.prepare(PROFILE_CHAIN_SQL).all(activeProfileId) as any[])+ : db.prepare(GLOBAL_CHAIN_SQL).all() as any[];// Count usable keys per platform — enabled AND healthy/unknown status. Unified// with /token-usage and the routing scorer (#456) so budget pooling is computed@@ -253,6 +289,15 @@ const updateSchema = z.array(z.object({enabled: z.boolean(),}));+/**+ * Model ids that actually exist, so a stale row in a client's snapshot cannot+ * turn an INSERT into a foreign-key failure (the old UPDATE simply matched+ * nothing).+ */+function knownModelIds(db: ReturnType<typeof getDb>): Set<number> {+ return new Set((db.prepare('SELECT id FROM models').all() as { id: number }[]).map(m => m.id));+}+// Update fallback chain (full replace)fallbackRouter.put('/', (req: Request, res: Response) => {const parsed = updateSchema.safeParse(req.body);@@ -263,20 +308,35 @@ fallbackRouter.put('/', (req: Request, res: Response) => {const db = getDb();const activeProfileId = getActiveProfileId(db);- const useProfile = activeProfileId != null && Boolean(- db.prepare('SELECT 1 FROM profile_models WHERE profile_id = ? LIMIT 1').get(activeProfileId),- );- const update = useProfile- ? db.prepare('UPDATE profile_models SET priority = ?, enabled = ? WHERE profile_id = ? AND model_db_id = ?')- : db.prepare('UPDATE fallback_config SET priority = ?, enabled = ? WHERE model_db_id = ?');-- const updateAll = db.transaction(() => {- for (const entry of parsed.data) {- if (useProfile) update.run(entry.priority, entry.enabled ? 1 : 0, activeProfileId, entry.modelDbId);- else update.run(entry.priority, entry.enabled ? 1 : 0, entry.modelDbId);- }- });- updateAll();++ // Writing to the active chain UPSERTS: the row may not be in the chain yet,+ // which is the normal state of every model in a hand-built one. The old+ // UPDATE-only write is why an empty chain could never gain its first model —+ // and why, having matched nothing, the edit was quietly redirected into the+ // single global table shared by every chain (#1021).+ const writeAll = activeProfileId != null+ ? (() => {+ const known = knownModelIds(db);+ const upsert = db.prepare(`+ INSERT INTO profile_models (profile_id, model_db_id, priority, enabled)+ VALUES (?, ?, ?, ?)+ ON CONFLICT(profile_id, model_db_id)+ DO UPDATE SET priority = excluded.priority, enabled = excluded.enabled+ `);+ return db.transaction(() => {+ for (const entry of parsed.data) {+ if (!known.has(entry.modelDbId)) continue;+ upsert.run(activeProfileId, entry.modelDbId, entry.priority, entry.enabled ? 1 : 0);+ }+ });+ })()+ : (() => {+ const update = db.prepare('UPDATE fallback_config SET priority = ?, enabled = ? WHERE model_db_id = ?');+ return db.transaction(() => {+ for (const entry of parsed.data) update.run(entry.priority, entry.enabled ? 1 : 0, entry.modelDbId);+ });+ })();+ writeAll();res.json({ success: true });});@@ -324,9 +384,6 @@ fallbackRouter.post('/sort/:preset', (req: Request, res: Response) => {const db = getDb();let models: { id: number }[] = [];const activeProfileId = getActiveProfileId(db);- const useProfile = activeProfileId != null && Boolean(- db.prepare('SELECT 1 FROM profile_models WHERE profile_id = ? LIMIT 1').get(activeProfileId),- );if (preset === 'budget') {const allModels = db.prepare(`SELECT id, monthly_token_budget, tpd_limit FROM models`).all() as any[];@@ -341,15 +398,28 @@ fallbackRouter.post('/sort/:preset', (req: Request, res: Response) => {models = db.prepare(`SELECT m.id FROM models m ORDER BY ${orderBy}`).all() as { id: number }[];}- const update = useProfile- ? db.prepare('UPDATE profile_models SET priority = ? WHERE profile_id = ? AND model_db_id = ?')- : db.prepare('UPDATE fallback_config SET priority = ? WHERE model_db_id = ?');- const reorder = db.transaction(() => {- for (let i = 0; i < models.length; i++) {- if (useProfile) update.run(i + 1, activeProfileId, models[i].id);- else update.run(i + 1, models[i].id);- }- });+ // Same upsert story as the PUT above: a preset sorts the list the dashboard+ // shows, which is the whole catalog seen through the chain, so a model the+ // chain has not named yet gets its row written here too — switched OFF, the+ // state it was displayed in. Sorting must never enable anything; a row+ // already in the chain keeps whatever flag it had.+ const reorder = activeProfileId != null+ ? (() => {+ const upsert = db.prepare(`+ INSERT INTO profile_models (profile_id, model_db_id, priority, enabled)+ VALUES (?, ?, ?, 0)+ ON CONFLICT(profile_id, model_db_id) DO UPDATE SET priority = excluded.priority+ `);+ return db.transaction(() => {+ for (let i = 0; i < models.length; i++) upsert.run(activeProfileId, models[i].id, i + 1);+ });+ })()+ : (() => {+ const update = db.prepare('UPDATE fallback_config SET priority = ? WHERE model_db_id = ?');+ return db.transaction(() => {+ for (let i = 0; i < models.length; i++) update.run(i + 1, models[i].id);+ });+ })();reorder();res.json({ success: true, preset });diff --git a/server/src/services/router.ts b/server/src/services/router.tsindex cf73540e..b87a861e 100644--- a/server/src/services/router.ts+++ b/server/src/services/router.ts@@ -1108,10 +1108,20 @@ const GLOBAL_SORT_ALIASES: Record<string, string> = {balanced: 'balanced',};+/**+ * The chain auto-routing walks.+ *+ * When a profile is active it IS the chain, empty or not (#1021). Falling+ * through to `fallback_config` on an empty one meant a chain the operator had+ * deliberately built by hand — or had not filled in yet — silently routed over+ * the entire catalog instead, while the same chain addressed by name+ * (`auto:<name>`) correctly refused. `fallback_config` is the chain only for an+ * install with no profile at all.+ */function getActiveChain(db: Db): ChainRow[] {const profileId = getActiveProfileId(db);if (profileId != null) {- const chain = db.prepare(`+ return db.prepare(`SELECT pm.model_db_id, pm.priority, pm.enabled,m.platform, m.model_id, m.display_name, m.intelligence_rank,m.size_label, m.monthly_token_budget,@@ -1122,8 +1132,6 @@ function getActiveChain(db: Db): ChainRow[] {WHERE pm.profile_id = ?ORDER BY pm.priority ASC`).all(profileId) as ChainRow[];-- if (chain.length > 0) return chain;}return db.prepare(`@@ -1188,21 +1196,45 @@ function getChainByGlobalSort(db: Db, globalAxis: string): ChainRow[] {return orderChain(allEnabled, strat);}+/**+ * The active chain, or a client-facing refusal when it has nothing enabled.+ *+ * Mirrors what `auto:<name>` already does for a named chain: say the chain is+ * empty rather than routing the request over models the operator never put in+ * it. Only when a profile is active — a legacy install with none keeps the+ * ordinary "all models exhausted" exhaustion path.+ */+function activeChainOrThrow(db: Db): ChainRow[] {+ const chain = getActiveChain(db);+ if (chain.some(entry => entry.enabled)) return chain;++ const profileId = getActiveProfileId(db);+ if (profileId == null) return chain;++ const profile = db.prepare('SELECT name FROM profiles WHERE id = ?').get(profileId) as { name: string } | undefined;+ const err = new Error(+ `The active fallback chain${profile ? ` '${profile.name}'` : ''} has no enabled models. `+ + 'Enable models for it on the Models page, switch the active chain, or name another one with "auto:<chain>".',+ ) as any;+ err.status = 400;+ throw err;+}+export function resolveRoutingChain(modelString: string | undefined): ResolvedChain {const db = getDb();if (!modelString || modelString.toLowerCase() === 'auto') {- return { chain: getActiveChain(db), strategyKey: 'auto' };+ return { chain: activeChainOrThrow(db), strategyKey: 'auto' };}const lower = modelString.toLowerCase();if (!lower.startsWith('auto:')) {- return { chain: getActiveChain(db), strategyKey: 'auto' };+ return { chain: activeChainOrThrow(db), strategyKey: 'auto' };}const suffix = lower.slice('auto:'.length).trim();if (!suffix) {- return { chain: getActiveChain(db), strategyKey: 'auto' };+ return { chain: activeChainOrThrow(db), strategyKey: 'auto' };}const globalAxis = GLOBAL_SORT_ALIASES[suffix];