Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

fix(web): address review on model prefs (validation, OpenAI levels, load, lookups)

Frank Arenae54da0582ac3
diff --git a/src/providers/chatgpt-web.ts b/src/providers/chatgpt-web.ts
index c6917c19..8b3ef4b9 100644
--- a/src/providers/chatgpt-web.ts
+++ b/src/providers/chatgpt-web.ts
@@ -6,7 +6,7 @@ import type { LLMResponse, LLMStreamChunk } from './base.js';
import { getValidChatGPTSession, getChatGPTSession } from '../auth/chatgpt-auth.js';
import { CHATGPT_BACKEND_API } from '../auth/chatgpt-session.js';
import { logger } from '../utils/logger.js';
-import { applyReasoningToBody, getModelPref } from '../utils/model-prefs.js';
+import { applyReasoningToBody, effectiveReasoning } from '../utils/model-prefs.js';
// Fields the codex endpoint does not accept
const UNSUPPORTED_FIELDS = [
@@ -22,7 +22,7 @@ function sanitiseBody(raw: string, providerName: string): string {
const body = JSON.parse(raw);
// User-chosen reasoning level for this model (dashboard reasoning picker).
- if (typeof body.model === 'string') applyReasoningToBody(body, getModelPref(providerName, body.model).reasoning);
+ if (typeof body.model === 'string') applyReasoningToBody(body, effectiveReasoning(providerName, body.model));
// Required
body.store = false;
diff --git a/src/providers/openai-compat.reasoning.test.ts b/src/providers/openai-compat.reasoning.test.ts
index d13f73a0..91c97473 100644
--- a/src/providers/openai-compat.reasoning.test.ts
+++ b/src/providers/openai-compat.reasoning.test.ts
@@ -68,6 +68,11 @@ describe('OpenAICompatProvider reasoning preference', () => {
expect(await send('ollamaLocal')).not.toHaveProperty('reasoning_effort');
});
+ it('never sends an effort to an OpenAI model that rejects it, even if one was saved', async () => {
+ setModelPref('openai', 'qwen3.8:27b', { reasoning: 'high' });
+ expect(await send('openai')).not.toHaveProperty('reasoning_effort');
+ });
+
it('leaves providers without a reasoning control untouched', async () => {
setModelPref('lmStudio', 'qwen3.8:27b', { reasoning: 'high' });
expect(await send('lmStudio')).not.toHaveProperty('reasoning_effort');
diff --git a/src/providers/openai-compat.ts b/src/providers/openai-compat.ts
index f080dd8f..5f6fa56b 100644
--- a/src/providers/openai-compat.ts
+++ b/src/providers/openai-compat.ts
@@ -5,7 +5,7 @@ import type { ProviderConfig } from '../utils/config.js';
import type { LLMResponse, LLMStreamChunk } from './base.js';
import { logger } from '../utils/logger.js';
import { aimlapiHeaders } from './aimlapi-attribution.js';
-import { applyReasoningToBody, getModelPref, reasoningLevelsFor } from '../utils/model-prefs.js';
+import { applyReasoningToBody, effectiveReasoning, providerHasReasoningControl } from '../utils/model-prefs.js';
/**
* fetch that applies the user's reasoning level for the requested model.
@@ -17,7 +17,8 @@ function withReasoningPref(providerName: string): typeof fetch {
if (typeof init?.body === 'string') {
try {
const body = JSON.parse(init.body) as Record<string, unknown>;
- const level = typeof body.model === 'string' ? getModelPref(providerName, body.model).reasoning : undefined;
+ // Only levels this model accepts (e.g. never an effort for gpt-4o).
+ const level = typeof body.model === 'string' ? effectiveReasoning(providerName, body.model) : undefined;
if (level) {
applyReasoningToBody(body, level);
init = { ...init, body: JSON.stringify(body) };
@@ -47,7 +48,7 @@ export class OpenAICompatProvider extends BaseProvider {
headers: aimlapiHeaders(config.baseUrl),
// Only providers with a reasoning control get the hook; the rest keep
// the SDK's default fetch untouched.
- fetch: reasoningLevelsFor(config.name).length ? withReasoningPref(config.name) : undefined,
+ fetch: providerHasReasoningControl(config.name) ? withReasoningPref(config.name) : undefined,
});
this.modelInstance = useChatApi
? this.client.chat(config.model)
diff --git a/src/utils/model-prefs.test.ts b/src/utils/model-prefs.test.ts
index 129833dc..c3c0ba9d 100644
--- a/src/utils/model-prefs.test.ts
+++ b/src/utils/model-prefs.test.ts
@@ -1,11 +1,13 @@
-import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import {
applyReasoningToBody,
displayModelName,
+ effectiveReasoning,
getModelPref,
+ isValidModelRef,
humanizeModelName,
modelGroupLabel,
reasoningLevelsFor,
@@ -36,6 +38,20 @@ describe('humanizeModelName', () => {
});
});
+describe('isValidModelRef', () => {
+ it.each([
+ ['qwen3.8:27b', true],
+ ['hf.co/user/Model-GGUF:Q4_K_M', true],
+ ['', false],
+ ['x'.repeat(257), false],
+ ['tab here', false],
+ [42, false],
+ [null, false],
+ ])('%j → %s', (value, ok) => {
+ expect(isValidModelRef(value)).toBe(ok);
+ });
+});
+
describe('modelGroupLabel', () => {
it('separates Ollama cloud models served through the local daemon', () => {
expect(modelGroupLabel('ollamaLocal', 'glm-5.3:cloud')).toBe('Ollama Cloud · via this PC');
@@ -52,6 +68,14 @@ describe('reasoning', () => {
expect(reasoningLevelsFor('deepseek')).toEqual([]);
});
+ it('offers OpenAI API levels only for reasoning models', () => {
+ // gpt-4o / gpt-4.1 answer 400 "Unsupported parameter" to an effort.
+ expect(reasoningLevelsFor('openai', 'gpt-4o')).toEqual([]);
+ expect(reasoningLevelsFor('openai', 'gpt-4.1-mini')).toEqual([]);
+ expect(reasoningLevelsFor('openai', 'o3-mini')).toEqual(['low', 'medium', 'high']);
+ expect(reasoningLevelsFor('openai', 'gpt-5.2')).toEqual(['low', 'medium', 'high']);
+ });
+
it('sets reasoning.effort on Responses API bodies, keeping other reasoning fields', () => {
const body: Record<string, unknown> = { input: [], reasoning: { summary: 'auto' } };
applyReasoningToBody(body, 'high');
@@ -107,6 +131,35 @@ describe('model prefs store', () => {
expect(displayModelName('chatgptWeb', 'gpt-6-sol')).toBe('GPT-6 Sol');
});
+ it('only treats a saved level as effective while the model supports it', () => {
+ setModelPref('openai', 'gpt-4o', { reasoning: 'high' });
+ expect(effectiveReasoning('openai', 'gpt-4o')).toBeUndefined();
+ setModelPref('openai', 'o3', { reasoning: 'high' });
+ expect(effectiveReasoning('openai', 'o3')).toBe('high');
+ });
+
+ it('keeps only well-formed entries from a hand-edited file', () => {
+ writeFileSync(join(home, 'model-prefs.json'), JSON.stringify({
+ 'ollamaLocal::good': { label: ' Good ', reasoning: 'off' },
+ 'ollamaLocal::bad-fields': { label: 42, reasoning: 'turbo' },
+ 'ollamaLocal::mixed': { label: 'Kept', reasoning: { effort: 'high' } },
+ 'no-separator': { label: 'x' },
+ '::no-provider': { label: 'x' },
+ 'ollamaLocal::array': ['x'],
+ }));
+ resetModelPrefsCache();
+ expect(getModelPref('ollamaLocal', 'good')).toEqual({ label: 'Good', reasoning: 'off' });
+ expect(getModelPref('ollamaLocal', 'bad-fields')).toEqual({});
+ expect(getModelPref('ollamaLocal', 'mixed')).toEqual({ label: 'Kept' });
+ expect(getModelPref('ollamaLocal', 'array')).toEqual({});
+ });
+
+ it('survives a corrupt prefs file', () => {
+ writeFileSync(join(home, 'model-prefs.json'), '{not json');
+ resetModelPrefsCache();
+ expect(getModelPref('ollamaLocal', 'm')).toEqual({});
+ });
+
it('ignores unknown reasoning values', () => {
setModelPref('ollamaLocal', 'm', { reasoning: 'turbo' as never });
expect(getModelPref('ollamaLocal', 'm')).toEqual({});
diff --git a/src/utils/model-prefs.ts b/src/utils/model-prefs.ts
index 01b7d04b..55ae48ce 100644
--- a/src/utils/model-prefs.ts
+++ b/src/utils/model-prefs.ts
@@ -22,9 +22,39 @@ export interface ModelPref {
const REASONING_LEVELS: readonly ReasoningLevel[] = ['off', 'low', 'medium', 'high'];
const MAX_LABEL_LENGTH = 80;
+/** Same bound Agent.switchProvider applies to model ids. */
+const MAX_REF_LENGTH = 256;
let prefs: Record<string, ModelPref> | null = null;
+/**
+ * A provider name or model id fit to key prefs: a non-empty string of at most
+ * 256 characters without control characters (mirrors Agent.switchProvider).
+ */
+export function isValidModelRef(value: unknown): value is string {
+ return typeof value === 'string'
+ && value.length > 0
+ && value.length <= MAX_REF_LENGTH
+ && ![...value].some((ch) => ch.charCodeAt(0) < 32 || ch.charCodeAt(0) === 127);
+}
+
+/** Keep only well-formed entries and fields from a parsed prefs file. */
+function sanitize(raw: unknown): Record<string, ModelPref> {
+ const clean: Record<string, ModelPref> = Object.create(null);
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return clean;
+ for (const [entryKey, value] of Object.entries(raw)) {
+ const sep = entryKey.indexOf('::');
+ if (sep <= 0 || !isValidModelRef(entryKey.slice(0, sep)) || !isValidModelRef(entryKey.slice(sep + 2))) continue;
+ if (!value || typeof value !== 'object' || Array.isArray(value)) continue;
+ const { label, reasoning } = value as Record<string, unknown>;
+ const pref: ModelPref = {};
+ if (typeof label === 'string' && label.trim()) pref.label = label.trim().slice(0, MAX_LABEL_LENGTH);
+ if (isReasoningLevel(reasoning)) pref.reasoning = reasoning;
+ if (pref.label !== undefined || pref.reasoning !== undefined) clean[entryKey] = pref;
+ }
+ return clean;
+}
+
function prefsPath(): string {
return join(getMercuryHome(), 'model-prefs.json');
}
@@ -37,9 +67,10 @@ function load(): Record<string, ModelPref> {
if (prefs) return prefs;
try {
const path = prefsPath();
- prefs = existsSync(path) ? (JSON.parse(readFileSync(path, 'utf-8')) as Record<string, ModelPref>) : {};
+ // Hand edits must not reach the wire or the UI unchecked.
+ prefs = sanitize(existsSync(path) ? JSON.parse(readFileSync(path, 'utf-8')) : {});
} catch {
- prefs = {};
+ prefs = Object.create(null) as Record<string, ModelPref>;
}
return prefs;
}
@@ -94,17 +125,33 @@ export function resetModelPrefsCache(): void {
// ─── Reasoning ───────────────────────────────────────────────────────────────
+/** OpenAI API models that accept a reasoning effort: o-series and GPT-5 family. */
+const OPENAI_REASONING_MODEL = /^(o\d|gpt-5)/i;
+
+/** Providers with any reasoning control (decides whether to hook requests at all). */
+export function providerHasReasoningControl(provider: string): boolean {
+ return ['chatgptWeb', 'openai', 'ollamaLocal', 'ollamaCloud'].includes(provider);
+}
+
/**
- * Levels a provider can honour. ChatGPT/OpenAI models may reject "none", so
- * they get no Off; Ollama maps Off to reasoning_effort "none" (thinking off).
- * Providers not listed have no reasoning control.
+ * Levels a model can honour. ChatGPT/OpenAI models may reject "none", so they
+ * get no Off; Ollama maps Off to reasoning_effort "none" (thinking off). On
+ * the OpenAI API only reasoning models accept an effort at all: gpt-4o or
+ * gpt-4.1 would answer 400 "Unsupported parameter". Anything else: none.
*/
-export function reasoningLevelsFor(provider: string): ReasoningLevel[] {
- if (provider === 'chatgptWeb' || provider === 'openai') return ['low', 'medium', 'high'];
+export function reasoningLevelsFor(provider: string, model?: string): ReasoningLevel[] {
+ if (provider === 'chatgptWeb') return ['low', 'medium', 'high'];
+ if (provider === 'openai') return model && OPENAI_REASONING_MODEL.test(model) ? ['low', 'medium', 'high'] : [];
if (provider === 'ollamaLocal' || provider === 'ollamaCloud') return ['off', 'low', 'medium', 'high'];
return [];
}
+/** The saved level for a model, only if that model can still honour it. */
+export function effectiveReasoning(provider: string, model: string): ReasoningLevel | undefined {
+ const level = getModelPref(provider, model).reasoning;
+ return level && reasoningLevelsFor(provider, model).includes(level) ? level : undefined;
+}
+
/**
* Apply a reasoning level to an outgoing OpenAI-style request body, in place.
* Done at the HTTP layer because the AI SDK drops reasoningEffort for model
diff --git a/src/web/api/chat.ts b/src/web/api/chat.ts
index 5cb4577f..a6caec0b 100644
--- a/src/web/api/chat.ts
+++ b/src/web/api/chat.ts
@@ -7,7 +7,7 @@ import { getMercuryHome, loadConfig, getActiveProviders } from '../../utils/conf
import type { SessionRepository } from '../../sessions/index.js';
import {
getModelPref, setModelPref, humanizeModelName, modelGroupLabel,
- reasoningLevelsFor, isReasoningLevel, type ReasoningLevel,
+ reasoningLevelsFor, effectiveReasoning, isReasoningLevel, isValidModelRef, type ReasoningLevel,
} from '../../utils/model-prefs.js';
let webChannel: WebChannel | null = null;
@@ -220,15 +220,32 @@ chat.post('/api/chat/permission/:id', async (c) => {
// ─── Models / Provider Switching ─────────────────────────────
+/**
+ * Failed model lookups are remembered briefly so that opening the picker
+ * while Ollama is down (or ChatGPT is signed out) doesn't wait on a timeout
+ * every time.
+ */
+const LOOKUP_RETRY_MS = 30_000;
+const failedLookups = new Map<string, number>();
+
+function recentlyFailed(key: string): boolean {
+ const at = failedLookups.get(key);
+ return at !== undefined && Date.now() - at < LOOKUP_RETRY_MS;
+}
+
/** Every model the local Ollama server has pulled (empty if unreachable). */
async function listOllamaModels(baseUrl: string): Promise<string[]> {
+ const root = baseUrl.replace(/\/+$/, '').replace(/\/(v1|api)$/, '');
+ const lookup = `ollama:${root}`;
+ if (recentlyFailed(lookup)) return [];
try {
- const root = baseUrl.replace(/\/+$/, '').replace(/\/(v1|api)$/, '');
const res = await fetch(`${root}/api/tags`, { signal: AbortSignal.timeout(3000) });
- if (!res.ok) return [];
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = (await res.json()) as { models?: { name?: string }[] };
+ failedLookups.delete(lookup);
return (data.models ?? []).map((m) => m.name ?? '').filter(Boolean).sort();
} catch {
+ failedLookups.set(lookup, Date.now());
return [];
}
}
@@ -241,15 +258,18 @@ async function listChatGPTModels(): Promise<string[]> {
if (chatgptModelCache && Date.now() - chatgptModelCache.at < CHATGPT_MODEL_TTL_MS) {
return chatgptModelCache.models;
}
+ if (recentlyFailed('chatgpt')) return [];
try {
const { getValidChatGPTSession } = await import('../../auth/chatgpt-session.js');
const { fetchChatGPTModels } = await import('../../auth/chatgpt-models.js');
const session = await getValidChatGPTSession();
- if (!session) return [];
+ if (!session) throw new Error('not signed in');
const catalog = await fetchChatGPTModels(session.accessToken, session.accountId);
chatgptModelCache = { at: Date.now(), models: catalog.models };
+ failedLookups.delete('chatgpt');
return catalog.models;
} catch {
+ failedLookups.set('chatgpt', Date.now());
return [];
}
}
@@ -269,8 +289,8 @@ function describeModel(provider: string, model: string) {
autoLabel: humanizeModelName(model),
customLabel: pref.label ?? null,
group: modelGroupLabel(provider, model),
- reasoning: pref.reasoning ?? 'auto',
- reasoningLevels: reasoningLevelsFor(provider),
+ reasoning: effectiveReasoning(provider, model) ?? 'auto',
+ reasoningLevels: reasoningLevelsFor(provider, model),
};
}
@@ -298,20 +318,30 @@ chat.get('/api/chat/models', async (c) => {
/** Rename a model (label) and/or set its reasoning level. null / '' / 'auto' resets. */
chat.post('/api/chat/models/prefs', async (c) => {
- const body = await c.req.json<{ provider?: string; model?: string; label?: string | null; reasoning?: string | null }>();
- const provider = body.provider?.trim();
- const model = body.model?.trim();
- if (!provider || !model) {
- return c.json({ error: 'provider and model are required' }, 400);
- }
- if (body.reasoning != null && body.reasoning !== 'auto') {
- if (!isReasoningLevel(body.reasoning) || !reasoningLevelsFor(provider).includes(body.reasoning)) {
- return c.json({ error: `Reasoning level '${body.reasoning}' is not supported for ${provider}` }, 400);
+ const body = await c.req.json<Record<string, unknown>>().catch(() => null);
+ // Same id rules as /api/chat/models/switch; anything else is a 400, not a 500.
+ if (!body || !isValidModelRef(body.provider) || !isValidModelRef(body.model)) {
+ return c.json({ error: 'provider and model must be non-empty strings of at most 256 characters' }, 400);
+ }
+ const { provider, model, label, reasoning } = body as { provider: string; model: string; label?: unknown; reasoning?: unknown };
+ if (label !== undefined && label !== null && typeof label !== 'string') {
+ return c.json({ error: 'label must be a string or null' }, 400);
+ }
+ if (reasoning !== undefined && reasoning !== null && typeof reasoning !== 'string') {
+ return c.json({ error: 'reasoning must be a string or null' }, 400);
+ }
+ // Only active providers: keeps model-prefs.json from growing unbounded.
+ if (!getActiveProviders(loadConfig()).some((p) => p.name === provider)) {
+ return c.json({ error: `Provider \`${provider}\` is not configured` }, 400);
+ }
+ if (typeof reasoning === 'string' && reasoning !== 'auto') {
+ if (!isReasoningLevel(reasoning) || !reasoningLevelsFor(provider, model).includes(reasoning)) {
+ return c.json({ error: `Reasoning level '${reasoning}' is not supported for ${model}` }, 400);
}
}
setModelPref(provider, model, {
- label: body.label,
- reasoning: body.reasoning === undefined ? undefined : (body.reasoning as ReasoningLevel | 'auto' | null),
+ label: label as string | null | undefined,
+ reasoning: reasoning as ReasoningLevel | 'auto' | null | undefined,
});
return c.json({ ok: true, ...describeModel(provider, model) });
});
diff --git a/src/web/api/model-prefs-route.test.ts b/src/web/api/model-prefs-route.test.ts
new file mode 100644
index 00000000..24d52c5c
--- /dev/null
+++ b/src/web/api/model-prefs-route.test.ts
@@ -0,0 +1,102 @@
+import { readFileSync, rmSync } from 'node:fs';
+import { join } from 'node:path';
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+
+// mercury.yaml's path is fixed when config.ts loads, so point MERCURY_HOME at
+// a temp dir with one active provider before importing the routes.
+const home = await vi.hoisted(async () => {
+ const fs = await import('node:fs');
+ const os = await import('node:os');
+ const path = await import('node:path');
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mercury-prefs-route-'));
+ fs.writeFileSync(path.join(dir, 'mercury.yaml'), [
+ 'identity:',
+ ' owner: Test',
+ 'providers:',
+ ' default: ollamaLocal',
+ ' ollamaLocal:',
+ ' name: ollamaLocal',
+ ' baseUrl: http://127.0.0.1:9/v1',
+ ' model: qwen3.8:27b',
+ ' enabled: true',
+ '',
+ ].join('\n'));
+ process.env.MERCURY_HOME = dir;
+ return dir;
+});
+
+import chat from './chat.js';
+import { resetModelPrefsCache } from '../../utils/model-prefs.js';
+
+function post(body: unknown) {
+ return chat.request('http://127.0.0.1/api/chat/models/prefs', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: typeof body === 'string' ? body : JSON.stringify(body),
+ });
+}
+
+function prefsOnDisk(): Record<string, unknown> {
+ try {
+ return JSON.parse(readFileSync(join(home, 'model-prefs.json'), 'utf-8'));
+ } catch {
+ return {};
+ }
+}
+
+afterAll(() => rmSync(home, { recursive: true, force: true }));
+
+describe('POST /api/chat/models/prefs validation', () => {
+ beforeEach(() => {
+ rmSync(join(home, 'model-prefs.json'), { force: true });
+ resetModelPrefsCache();
+ });
+
+ it('saves a label and reasoning for an active provider', async () => {
+ const res = await post({ provider: 'ollamaLocal', model: 'qwen3.8:27b', label: 'Qwen', reasoning: 'off' });
+ expect(res.status).toBe(200);
+ expect(prefsOnDisk()['ollamaLocal::qwen3.8:27b']).toEqual({ label: 'Qwen', reasoning: 'off' });
+ });
+
+ it.each([
+ ['non-string provider', { provider: 42, model: 'm' }],
+ ['non-string model', { provider: 'ollamaLocal', model: { x: 1 } }],
+ ['empty model', { provider: 'ollamaLocal', model: '' }],
+ ['oversized model', { provider: 'ollamaLocal', model: 'm'.repeat(257) }],
+ ['control characters', { provider: 'ollamaLocal', model: 'qwen\u0000' }],
+ ['non-string label', { provider: 'ollamaLocal', model: 'm', label: 5 }],
+ ['non-string reasoning', { provider: 'ollamaLocal', model: 'm', reasoning: ['high'] }],
+ ['unknown reasoning', { provider: 'ollamaLocal', model: 'm', reasoning: 'turbo' }],
+ ['unconfigured provider', { provider: 'openai', model: 'gpt-4o', label: 'x' }],
+ ['__proto__ provider', { provider: '__proto__', model: 'm', label: 'x' }],
+ ])('rejects %s with 400 and writes nothing', async (_name, body) => {
+ const res = await post(body);
+ expect(res.status).toBe(400);
+ expect(prefsOnDisk()).toEqual({});
+ expect(({} as Record<string, unknown>).label).toBeUndefined();
+ });
+
+ it('rejects a malformed JSON body with 400', async () => {
+ const res = await post('{not json');
+ expect(res.status).toBe(400);
+ });
+});
+
+describe('GET /api/chat/models', () => {
+ it('does not retry a failed Ollama lookup on every picker open', async () => {
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('ECONNREFUSED'));
+ try {
+ const first = await chat.request('http://127.0.0.1/api/chat/models');
+ const second = await chat.request('http://127.0.0.1/api/chat/models');
+ expect(first.status).toBe(200);
+ expect(second.status).toBe(200);
+ const tagCalls = fetchSpy.mock.calls.filter(([url]) => String(url).endsWith('/api/tags'));
+ expect(tagCalls).toHaveLength(1);
+ // Falls back to the configured model while Ollama is unreachable.
+ const body = await second.json() as { providers: { model: string }[] };
+ expect(body.providers.map((p) => p.model)).toEqual(['qwen3.8:27b']);
+ } finally {
+ fetchSpy.mockRestore();
+ }
+ });
+});