Skip to content

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

fix(router): never route a disabled model at request time (#641)

Tashfeene3c4fafa3d78
diff --git a/server/src/__tests__/routes/disabled-model-routing.test.ts b/server/src/__tests__/routes/disabled-model-routing.test.ts
new file mode 100644
index 00000000..e6285f68
--- /dev/null
+++ b/server/src/__tests__/routes/disabled-model-routing.test.ts
@@ -0,0 +1,254 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import type { Express } from 'express';
+import { createApp } from '../../app.js';
+import { initDb, getDb, getUnifiedApiKey } from '../../db/index.js';
+import { encrypt } from '../../lib/crypto.js';
+import { resolveRoutingChain, setRoutingStrategy, getOrderedFusionChain } from '../../services/router.js';
+import { mintDashboardToken, isGatedApiPath } from '../helpers/auth.js';
+
+let app: Express;
+let dashToken = '';
+
+async function request(method: string, path: string, body?: any, headers: Record<string, string> = {}) {
+ const server = app.listen(0);
+ const addr = server.address() as any;
+ const res = await fetch(`http://127.0.0.1:${addr.port}${path}`, {
+ method,
+ headers: {
+ ...(body ? { 'Content-Type': 'application/json' } : {}),
+ ...(isGatedApiPath(path) && !('Authorization' in headers) ? { Authorization: `Bearer ${dashToken}` } : {}),
+ ...headers,
+ },
+ body: body ? JSON.stringify(body) : undefined,
+ });
+ const text = await res.text();
+ server.close();
+ let json: any = null;
+ try { json = JSON.parse(text); } catch { /* SSE / non-JSON */ }
+ return { status: res.status, body: json, text };
+}
+
+function authHeaders() {
+ return { Authorization: `Bearer ${getUnifiedApiKey()}` };
+}
+
+function activeProfileId(): number | null {
+ const row = getDb().prepare("SELECT value FROM settings WHERE key = 'active_profile_id'").get() as { value: string } | undefined;
+ return row ? Number(row.value) : null;
+}
+
+function addKey(platform: string): void {
+ const secret = encrypt(`${platform}-disabled-routing-key`);
+ getDb().prepare(`
+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled)
+ VALUES (?, 'disabled-routing', ?, ?, ?, 'healthy', 1)
+ `).run(platform, secret.encrypted, secret.iv, secret.authTag);
+}
+
+// A two-model catalog at fixed priorities: with the 'priority' strategy the
+// routed model is fully deterministic, so "which model served" is a clean
+// assertion. Unique model ids also make each model its own unify group, so an
+// explicit request resolves to exactly one row.
+function addModel(modelId: string, priority: number): number {
+ const db = getDb();
+ const inserted = db.prepare(`
+ INSERT INTO models (
+ platform, model_id, display_name, intelligence_rank, speed_rank, size_label,
+ rpm_limit, rpd_limit, tpm_limit, tpd_limit, monthly_token_budget,
+ context_window, enabled, supports_vision, supports_tools
+ )
+ VALUES ('groq', ?, ?, ?, ?, 'Small', NULL, NULL, NULL, NULL, '~1M', 128000, 1, 0, 1)
+ `).run(modelId, `Disabled Routing ${modelId}`, priority, priority);
+ const id = Number(inserted.lastInsertRowid);
+ db.prepare('INSERT INTO fallback_config (model_db_id, priority, enabled) VALUES (?, ?, 1)').run(id, priority);
+ const profileId = activeProfileId();
+ if (profileId != null) {
+ db.prepare('INSERT INTO profile_models (profile_id, model_db_id, priority, enabled) VALUES (?, ?, ?, 1)')
+ .run(profileId, id, priority);
+ }
+ return id;
+}
+
+function mockUpstream() {
+ const origFetch = global.fetch;
+ vi.spyOn(global, 'fetch').mockImplementation(async (url, init) => {
+ const u = typeof url === 'string' ? url : url.toString();
+ if (u.includes('api.groq.com')) {
+ return {
+ ok: true,
+ status: 200,
+ headers: new Headers(),
+ json: () => Promise.resolve({
+ id: 'chatcmpl-x', object: 'chat.completion', created: 1, model: 'default',
+ choices: [{ index: 0, message: { role: 'assistant', content: 'ok' }, finish_reason: 'stop' }],
+ usage: { prompt_tokens: 2, completion_tokens: 1, total_tokens: 3 },
+ }),
+ } as any;
+ }
+ return origFetch(url, init);
+ });
+}
+
+function lastServedModel(): string {
+ const row = getDb().prepare('SELECT model_id FROM requests ORDER BY id DESC LIMIT 1').get() as { model_id: string } | undefined;
+ return row?.model_id ?? '';
+}
+
+// A follow-up turn in the same conversation: an assistant message is what makes
+// the sticky map readable at all (see getStickyModel).
+const FOLLOW_UP = [
+ { role: 'user', content: 'hello' },
+ { role: 'assistant', content: 'ok' },
+ { role: 'user', content: 'again' },
+];
+
+let alphaId = 0;
+
+beforeEach(() => {
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ initDb(':memory:');
+ app = createApp();
+ dashToken = mintDashboardToken();
+ setRoutingStrategy('priority');
+ const db = getDb();
+ db.prepare('DELETE FROM api_keys').run();
+ db.prepare('DELETE FROM profile_models').run();
+ db.prepare('DELETE FROM fallback_config').run();
+ db.prepare('DELETE FROM models').run();
+ addKey('groq');
+ alphaId = addModel('alpha-model', 1);
+ addModel('beta-model', 2);
+ mockUpstream();
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+// #634: a model the operator switched off must never be selected at request
+// time, on any surface. Two flavors of "off" are covered here because they leak
+// differently: catalog-off (models.enabled = 0) and auto-routing-off
+// (fallback_config / profile_models .enabled = 0). Explicitly NAMING a model
+// that is only auto-routing-off still works — that is the documented contract
+// (see routing-semantics.test.ts) — but nothing may pick it implicitly.
+describe('disabled models are never routed (#634)', () => {
+ describe('sticky sessions', () => {
+ // The sticky map holds a db id for 30 minutes, so it outlives a disable.
+ // routeRequest treats an off-chain preferred id as an explicit pin and
+ // injects it ahead of the chain — which resurrected the disabled model.
+ it.each([
+ ['catalog', { enabled: false }],
+ ['chain', { fallbackEnabled: false }],
+ ])('/v1/chat/completions falls through to auto when the pinned model is %s-disabled mid-session', async (_flavor, patch) => {
+ const sessionId = `sess-chat-${_flavor}`;
+ const first = await request('POST', '/v1/chat/completions', {
+ messages: [{ role: 'user', content: 'hello' }],
+ }, { ...authHeaders(), 'x-session-id': sessionId });
+ expect(first.status).toBe(200);
+ expect(lastServedModel()).toBe('alpha-model');
+
+ expect((await request('PATCH', `/api/models/${alphaId}`, patch)).status).toBe(200);
+
+ const second = await request('POST', '/v1/chat/completions', {
+ messages: FOLLOW_UP,
+ }, { ...authHeaders(), 'x-session-id': sessionId });
+ expect(second.status).toBe(200);
+ expect(lastServedModel()).toBe('beta-model');
+ });
+
+ it('/v1/responses falls through to auto when the pinned model is chain-disabled mid-session', async () => {
+ const first = await request('POST', '/v1/responses', { input: 'hello' }, {
+ ...authHeaders(), 'x-session-id': 'sess-responses',
+ });
+ expect(first.status).toBe(200);
+ expect(lastServedModel()).toBe('alpha-model');
+
+ expect((await request('PATCH', `/api/models/${alphaId}`, { fallbackEnabled: false })).status).toBe(200);
+
+ const second = await request('POST', '/v1/responses', { input: FOLLOW_UP }, {
+ ...authHeaders(), 'x-session-id': 'sess-responses',
+ });
+ expect(second.status).toBe(200);
+ expect(lastServedModel()).toBe('beta-model');
+ });
+
+ it('/v1/messages falls through to auto when the pinned model is chain-disabled mid-session', async () => {
+ const first = await request('POST', '/v1/messages', {
+ model: 'claude-sonnet-4', max_tokens: 64,
+ messages: [{ role: 'user', content: 'hello' }],
+ }, { ...authHeaders(), 'x-session-id': 'sess-messages' });
+ expect(first.status).toBe(200);
+ expect(lastServedModel()).toBe('alpha-model');
+
+ expect((await request('PATCH', `/api/models/${alphaId}`, { fallbackEnabled: false })).status).toBe(200);
+
+ const second = await request('POST', '/v1/messages', {
+ model: 'claude-sonnet-4', max_tokens: 64, messages: FOLLOW_UP,
+ }, { ...authHeaders(), 'x-session-id': 'sess-messages' });
+ expect(second.status).toBe(200);
+ expect(lastServedModel()).toBe('beta-model');
+ });
+ });
+
+ describe('auto chain building', () => {
+ // 'auto:smart' & friends rank the whole catalog instead of following the
+ // chain's ORDER. They must still drop what the operator switched off.
+ it.each([['auto:smart'], ['auto:fast'], ['auto:cheap'], ['auto:reliable']])(
+ '%s excludes a chain-disabled model', async (modelString) => {
+ expect((await request('PATCH', `/api/models/${alphaId}`, { fallbackEnabled: false })).status).toBe(200);
+ expect(resolveRoutingChain(modelString).chain.map(row => row.model_db_id)).not.toContain(alphaId);
+ },
+ );
+
+ it('auto:smart still spans models that were never touched in the chain', async () => {
+ const chain = resolveRoutingChain('auto:smart').chain.map(row => row.model_db_id);
+ expect(chain).toContain(alphaId);
+ });
+
+ it('auto:smart excludes a catalog-disabled model', async () => {
+ expect((await request('PATCH', `/api/models/${alphaId}`, { enabled: false })).status).toBe(200);
+ expect(resolveRoutingChain('auto:smart').chain.map(row => row.model_db_id)).not.toContain(alphaId);
+ });
+
+ it('the default auto chain drops a model the moment it is disabled', async () => {
+ expect((await request('PATCH', `/api/models/${alphaId}`, { enabled: false })).status).toBe(200);
+ const { status } = await request('POST', '/v1/chat/completions', {
+ model: 'auto', messages: [{ role: 'user', content: 'hi' }],
+ }, authHeaders());
+ expect(status).toBe(200);
+ expect(lastServedModel()).toBe('beta-model');
+ });
+ });
+
+ describe('fusion panels', () => {
+ it('an auto panel drops a model disabled after the panel was last built', async () => {
+ expect(getOrderedFusionChain(100).map(c => c.modelDbId)).toContain(alphaId);
+ expect((await request('PATCH', `/api/models/${alphaId}`, { fallbackEnabled: false })).status).toBe(200);
+ expect(getOrderedFusionChain(100).map(c => c.modelDbId)).not.toContain(alphaId);
+ });
+
+ it('an explicit panel drops a catalog-disabled member instead of dispatching it', async () => {
+ expect((await request('PATCH', `/api/models/${alphaId}`, { enabled: false })).status).toBe(200);
+ const { status, body } = await request('POST', '/v1/chat/completions', {
+ model: 'fusion',
+ messages: [{ role: 'user', content: 'hi' }],
+ fusion: { models: ['alpha-model', 'beta-model'], expose_panel: true },
+ }, authHeaders());
+ expect(status).toBe(200);
+ expect(body.x_fusion.panel.map((p: any) => p.model)).toEqual(['beta-model']);
+ expect(body.x_fusion.dropped).toContain('alpha-model (unknown or disabled)');
+ });
+ });
+
+ describe('explicit model requests', () => {
+ it.each([
+ ['/v1/chat/completions', { model: 'alpha-model', messages: [{ role: 'user', content: 'hi' }] }],
+ ['/v1/completions', { model: 'alpha-model', prompt: 'hi' }],
+ ])('%s returns model_not_found for a catalog-disabled model', async (path, body) => {
+ expect((await request('PATCH', `/api/models/${alphaId}`, { enabled: false })).status).toBe(200);
+ const res = await request('POST', path, body, authHeaders());
+ expect(res.status).toBe(404);
+ expect(res.body.error.code).toBe('model_not_found');
+ });
+ });
+});
diff --git a/server/src/__tests__/routes/responses.test.ts b/server/src/__tests__/routes/responses.test.ts
index db380229..2cf2e621 100644
--- a/server/src/__tests__/routes/responses.test.ts
+++ b/server/src/__tests__/routes/responses.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, beforeAll, vi } from 'vitest';
+import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';
// Mock only routeRequest so we don't need real provider keys; keep the rest of
// the router module (recordSuccess / recordRateLimitHit) intact.
@@ -10,18 +10,19 @@ vi.mock('../../services/router.js', async (importOriginal) => {
import type { Express } from 'express';
import { createApp } from '../../app.js';
-import { initDb, getUnifiedApiKey } from '../../db/index.js';
+import { initDb, getDb, getUnifiedApiKey } from '../../db/index.js';
+import { setStickyModel } from '../../routes/proxy.js';
function fakeRoute(provider: any) {
return { provider, modelId: 'fake-model', modelDbId: 9999, apiKey: 'k', keyId: 1, platform: 'fake', displayName: 'Fake Model' };
}
-async function post(app: Express, path: string, body: any, key?: string) {
+async function post(app: Express, path: string, body: any, key?: string, headers: Record<string, string> = {}) {
const server = app.listen(0);
const addr = server.address() as any;
const res = await fetch(`http://127.0.0.1:${addr.port}${path}`, {
method: 'POST',
- headers: { 'Content-Type': 'application/json', ...(key ? { Authorization: `Bearer ${key}` } : {}) },
+ headers: { 'Content-Type': 'application/json', ...(key ? { Authorization: `Bearer ${key}` } : {}), ...headers },
body: JSON.stringify(body),
});
const text = await res.text();
@@ -195,3 +196,129 @@ describe('POST /v1/responses (#96)', () => {
expect(body.error.message).toContain('rejected the request as invalid');
});
});
+
+// #579 gave this endpoint the same model resolution /v1/chat/completions has —
+// explicit model > sticky session > auto — but shipped without a regression
+// test. This is it. routeRequest is mocked, so the assertions read the routing
+// DECISION off its arguments: [2] is the preferred (pinned/sticky) model db id
+// and [6] is the strict chain an explicit model resolves to.
+describe('POST /v1/responses model routing priority (#579)', () => {
+ let app: Express;
+ let key: string;
+ let pinnedId = 0;
+ let stickyId = 0;
+ let disabledId = 0;
+
+ // Unique model ids make each model its own unify group, so an explicit
+ // request resolves to exactly one row and the chain assertion is unambiguous.
+ function addModel(modelId: string, priority: number, enabled = true): number {
+ const db = getDb();
+ const inserted = db.prepare(`
+ INSERT INTO models (
+ platform, model_id, display_name, intelligence_rank, speed_rank, size_label,
+ rpm_limit, rpd_limit, tpm_limit, tpd_limit, monthly_token_budget,
+ context_window, enabled, supports_vision, supports_tools
+ )
+ VALUES ('groq', ?, ?, ?, ?, 'Small', NULL, NULL, NULL, NULL, '~1M', 128000, ?, 0, 1)
+ `).run(modelId, `Responses Priority ${modelId}`, priority, priority, enabled ? 1 : 0);
+ const id = Number(inserted.lastInsertRowid);
+ db.prepare('INSERT INTO fallback_config (model_db_id, priority, enabled) VALUES (?, ?, 1)').run(id, priority);
+ const profile = db.prepare("SELECT value FROM settings WHERE key = 'active_profile_id'").get() as { value: string } | undefined;
+ if (profile) {
+ db.prepare('INSERT INTO profile_models (profile_id, model_db_id, priority, enabled) VALUES (?, ?, ?, 1)')
+ .run(Number(profile.value), id, priority);
+ }
+ return id;
+ }
+
+ beforeAll(() => {
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ initDb(':memory:');
+ app = createApp();
+ key = getUnifiedApiKey();
+ const db = getDb();
+ db.prepare('DELETE FROM profile_models').run();
+ db.prepare('DELETE FROM fallback_config').run();
+ db.prepare('DELETE FROM models').run();
+ pinnedId = addModel('pinned-responses-model', 1);
+ stickyId = addModel('sticky-responses-model', 2);
+ disabledId = addModel('disabled-responses-model', 3, false);
+ });
+
+ beforeEach(() => {
+ mockRouteRequest.mockReset();
+ mockRouteRequest.mockReturnValue(fakeRoute({
+ async chatCompletion() {
+ return {
+ id: 'c', object: 'chat.completion', created: 0, model: 'fake-model',
+ choices: [{ index: 0, message: { role: 'assistant', content: 'ok' }, finish_reason: 'stop' }],
+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
+ };
+ },
+ async *streamChatCompletion() { /* unused */ },
+ }));
+ });
+
+ // With a session header the sticky key is the header itself, so the message
+ // list here is irrelevant — but the REQUEST must carry an assistant turn for
+ // getStickyModel to read the map at all.
+ const followUp = [
+ { role: 'user', content: 'hello' },
+ { role: 'assistant', content: 'ok' },
+ { role: 'user', content: 'again' },
+ ];
+
+ function routingCall() {
+ const call = mockRouteRequest.mock.calls.at(-1);
+ return { preferredModelDbId: call?.[2] as number | undefined, chain: call?.[6] as { model_db_id: number }[] | undefined };
+ }
+
+ it('an explicit model wins over a sticky session', async () => {
+ setStickyModel([], stickyId, 'sess-explicit-wins');
+ const { status } = await post(app, '/v1/responses', {
+ model: 'pinned-responses-model',
+ input: followUp,
+ }, key, { 'x-session-id': 'sess-explicit-wins' });
+
+ expect(status).toBe(200);
+ const { preferredModelDbId, chain } = routingCall();
+ expect(chain?.map(row => row.model_db_id)).toEqual([pinnedId]);
+ expect(preferredModelDbId).not.toBe(stickyId);
+ });
+
+ it('a sticky session wins over auto routing when no model is sent', async () => {
+ setStickyModel([], stickyId, 'sess-sticky-wins');
+ const { status } = await post(app, '/v1/responses', {
+ input: followUp,
+ }, key, { 'x-session-id': 'sess-sticky-wins' });
+
+ expect(status).toBe(200);
+ const { preferredModelDbId, chain } = routingCall();
+ expect(preferredModelDbId).toBe(stickyId);
+ expect(chain).toBeUndefined();
+ });
+
+ it('auto routing applies when there is neither an explicit model nor a sticky session', async () => {
+ const { status } = await post(app, '/v1/responses', {
+ input: followUp,
+ }, key, { 'x-session-id': 'sess-no-sticky' });
+
+ expect(status).toBe(200);
+ const { preferredModelDbId, chain } = routingCall();
+ expect(preferredModelDbId).toBeUndefined();
+ expect(chain).toBeUndefined();
+ });
+
+ it.each([
+ ['unknown', 'no-such-model-anywhere'],
+ ['disabled', 'disabled-responses-model'],
+ ])('returns 400 model_not_found for an %s explicit model', async (_flavor, model) => {
+ void disabledId;
+ const { status, text } = await post(app, '/v1/responses', { model, input: 'hi' }, key);
+ expect(status).toBe(400);
+ const body = JSON.parse(text);
+ expect(body.error.code).toBe('model_not_found');
+ expect(body.error.type).toBe('invalid_request_error');
+ expect(mockRouteRequest).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/src/lib/inbound-chat.ts b/server/src/lib/inbound-chat.ts
index e95c36ea..4da58a5f 100644
--- a/server/src/lib/inbound-chat.ts
+++ b/server/src/lib/inbound-chat.ts
@@ -8,6 +8,7 @@ import type {
import { getDb } from '../db/index.js';
import {
routeRequest,
+ resolveStickyPreference,
routingReserveTokens,
resolveModelGroupCandidates,
type ChainRow,
@@ -109,7 +110,7 @@ function resolvePin(model: string | undefined, messages: ChatMessage[], sessionI
const auto = !requested || requested.toLowerCase() === 'auto' || requested.toLowerCase().startsWith('auto:');
if (auto) {
return {
- preferredModel: getStickyModel(messages, sessionId),
+ preferredModel: resolveStickyPreference(getStickyModel(messages, sessionId)),
pinnedLabel: null,
};
}
diff --git a/server/src/routes/anthropic.ts b/server/src/routes/anthropic.ts
index 9ce4e016..4a0c1314 100644
--- a/server/src/routes/anthropic.ts
+++ b/server/src/routes/anthropic.ts
@@ -9,7 +9,7 @@ import type {
ChatToolChoice,
ChatContentBlock,
} from '@freellmapi/shared/types.js';
-import { routeRequest, routingReserveTokens, type RouteResult } from '../services/router.js';
+import { routeRequest, resolveStickyPreference, routingReserveTokens, type RouteResult } from '../services/router.js';
import { getSetting, getUnifiedApiKey } from '../db/index.js';
import { contentToString } from '../lib/content.js';
import { repairToolArguments, toolSchemaMap } from '../lib/tool-args.js';
@@ -502,7 +502,7 @@ anthropicRouter.post('/messages', async (req: Request, res: Response) => {
const rawSession = req.headers['x-claude-code-session-id'] ?? req.headers['x-session-id'];
const sessionId = Array.isArray(rawSession) ? rawSession[0] : rawSession;
let preferredModel = resolved.preferredModelDbId;
- if (preferredModel == null) preferredModel = getStickyModel(messages, sessionId);
+ if (preferredModel == null) preferredModel = resolveStickyPreference(getStickyModel(messages, sessionId));
// Thin adapter over the shared fallback loop (lib/fallback-loop.ts): the
// cooldown/skip/penalty/exhaustion machinery is shared, only the Anthropic
diff --git a/server/src/routes/proxy.ts b/server/src/routes/proxy.ts
index 0b50d079..5fd6512e 100644
--- a/server/src/routes/proxy.ts
+++ b/server/src/routes/proxy.ts
@@ -3,7 +3,7 @@ import { Router } from 'express';
import type { Request, Response } from 'express';
import { z } from 'zod';
import type { ChatMessage, ChatToolCall, ModelListRow } from '@freellmapi/shared/types.js';
-import { routeRequest, resolveRoutingChain, resolveModelGroupCandidates, recordRateLimitHit, recordSuccess, hasEnabledVisionModel, hasEnabledToolsModel, hasOtherUsableKey, routingReserveTokens, type RouteResult, type ResolvedChain, type ChainRow } from '../services/router.js';
+import { routeRequest, resolveRoutingChain, resolveModelGroupCandidates, resolveStickyPreference, recordRateLimitHit, recordSuccess, hasEnabledVisionModel, hasEnabledToolsModel, hasOtherUsableKey, routingReserveTokens, type RouteResult, type ResolvedChain, type ChainRow } from '../services/router.js';
import { recordRequest, recordTokens, setCooldown, getCooldownDurationForLimit, PAYMENT_REQUIRED_COOLDOWN_MS, MODEL_FORBIDDEN_COOLDOWN_MS, learnLimitFromError } from '../services/ratelimit.js';
import { runEmbeddings, EmbeddingsError } from '../services/embeddings.js';
import { runImageGeneration, runSpeech, runTranscription, MediaError, MAX_TRANSCRIPTION_BYTES } from '../services/media.js';
@@ -1563,7 +1563,7 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
let stickyStrategyKey: string | undefined = strategyKey;
if (isAutoModel(requestedModel)) {
- preferredModel = getStickyModel(messages, sessionIdHeader, strategyKey);
+ preferredModel = resolveStickyPreference(getStickyModel(messages, sessionIdHeader, strategyKey), resolvedChain?.chain);
} else if (requestedModel) {
const db = getDb();
// Unify ON: a requested id (canonical slug OR any provider's model_id) maps
@@ -1623,7 +1623,7 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {
}
}
} else {
- preferredModel = getStickyModel(messages, sessionIdHeader, strategyKey);
+ preferredModel = resolveStickyPreference(getStickyModel(messages, sessionIdHeader, strategyKey), resolvedChain?.chain);
}
// For analytics: the model id the client pinned, null when auto-routed
diff --git a/server/src/routes/responses.ts b/server/src/routes/responses.ts
index aeb8b763..e4ba2a50 100644
--- a/server/src/routes/responses.ts
+++ b/server/src/routes/responses.ts
@@ -9,7 +9,7 @@ import type {
ChatToolChoice,
Platform,
} from '@freellmapi/shared/types.js';
-import { routeRequest, hasEnabledToolsModel, routingReserveTokens, resolveModelGroupCandidates, type RouteResult, type ChainRow } from '../services/router.js';
+import { routeRequest, hasEnabledToolsModel, resolveStickyPreference, routingReserveTokens, resolveModelGroupCandidates, type RouteResult, type ChainRow } from '../services/router.js';
import { getDb, getUnifiedApiKey } from '../db/index.js';
import { isUnifyEnabled, getModelGroups, resolveRequestedIdToMembers } from '../services/model-groups.js';
import { contentToString } from '../lib/content.js';
@@ -421,7 +421,7 @@ responsesRouter.post('/responses', async (req: Request, res: Response) => {
let groupChain: ChainRow[] | undefined;
if (isAutoModel(requestedModelLabel)) {
- preferredModel = getStickyModel(messages, sessionIdHeader);
+ preferredModel = resolveStickyPreference(getStickyModel(messages, sessionIdHeader));
} else {
const db = getDb();
const members = isUnifyEnabled() ? resolveRequestedIdToMembers(requestedModelLabel, getModelGroups()) : null;
diff --git a/server/src/services/router.ts b/server/src/services/router.ts
index 3c33107b..4d95b587 100644
--- a/server/src/services/router.ts
+++ b/server/src/services/router.ts
@@ -640,6 +640,14 @@ function getChainByProfileName(db: Db, name: string): ChainRow[] | null {
}
function getChainByGlobalSort(db: Db, globalAxis: string): ChainRow[] {
+ // A global sort ignores the chain's ORDER, not its enable flags: a model the
+ // operator switched off — in the catalog or just for auto routing — stays off
+ // here too (#634). Models with no chain row yet (fresh catalog rows) default
+ // to in, so the sort still spans the whole catalog.
+ const profileId = getActiveProfileId(db);
+ const chainEnabled = profileId != null
+ ? 'COALESCE(pm.enabled, fc.enabled, 1) = 1'
+ : 'COALESCE(fc.enabled, 1) = 1';
const allEnabled = db.prepare(`
SELECT m.id as model_db_id, 0 as priority, 1 as enabled,
m.platform, m.model_id, m.display_name, m.intelligence_rank,
@@ -647,8 +655,10 @@ function getChainByGlobalSort(db: Db, globalAxis: string): ChainRow[] {
m.rpm_limit, m.rpd_limit, m.tpm_limit, m.tpd_limit, m.supports_vision,
m.supports_tools, m.context_window, m.key_id
FROM models m
- WHERE m.enabled = 1
- `).all() as ChainRow[];
+ LEFT JOIN fallback_config fc ON fc.model_db_id = m.id
+ ${profileId != null ? 'LEFT JOIN profile_models pm ON pm.profile_id = ? AND pm.model_db_id = m.id' : ''}
+ WHERE m.enabled = 1 AND ${chainEnabled}
+ `).all(...(profileId != null ? [profileId] : [])) as ChainRow[];
const strategyMap: Record<string, RoutingStrategy> = {
'smart': 'smartest',
@@ -1301,6 +1311,27 @@ export function getRoutingScores(): { strategy: RoutingStrategy; weights: Routin
return { strategy, weights: weightsFor(strategy), customWeights: getCustomWeights(), scores };
}
+/**
+ * Filter a sticky-session pin down to something still routable (#634).
+ *
+ * A sticky entry holds a model db id for up to 30 minutes, so it goes stale the
+ * moment the operator disables that model — in the catalog, or just for auto
+ * routing. It must NOT be handed to routeRequest as-is: an off-chain preferred
+ * id is treated as an explicit pin and injected ahead of the chain, which is
+ * right for a client that named the model and wrong for a pin the client never
+ * asked for. Dropping it here falls the request through to normal auto routing.
+ *
+ * Pass the same chain the request will route over (the prefetched auto chain);
+ * omit it to check the active chain, which is what routeRequest would use.
+ */
+export function resolveStickyPreference(stickyModelDbId: number | undefined, chain?: ChainRow[]): number | undefined {
+ if (stickyModelDbId == null) return undefined;
+ const rows = chain ?? getActiveChain(getDb());
+ return rows.some(entry => entry.model_db_id === stickyModelDbId && entry.enabled)
+ ? stickyModelDbId
+ : undefined;
+}
+
// Whether at least one vision-capable model is enabled in the fallback chain.
// Used to give image requests a clear "enable a vision model" error instead of
// the generic exhaustion message when none is configured (#118, #125).