Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

local-LLM fallback: skip embedding models, recognize content refusals, live model pickers + context limits

[._.]/ Adam Eivy47d67e406c5d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index efe5302aa7..f1baf8d0a9 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -4,10 +4,14 @@
- **Daily budgets for the Chief of Staff's domains** — each domain (Brain auto-classify, Memory auto-extract, CoS auto-run, Messages auto-send) can now carry a daily cap on how many automatic actions it takes and how many minutes of work it does. When a domain reaches its cap it pauses that automatic work for the rest of the day and resumes after the counters reset at midnight; the Chief of Staff config panel shows each domain's usage so far today. Caps are off by default (blank means unlimited), so nothing changes until you set one. This rounds out the per-domain guardrails alongside the off / dry-run / execute controls.
- **Scheduled "Claim Issue" task** — a new built-in CoS schedule (CoS → Schedule → Claim Issue) that runs the `/claim --issues` flow on a cadence: it picks the next open GitHub issue, creates its own `claim/issue-<num>` worktree, implements the fix, opens a PR that closes the issue, runs the configured reviewers, merges, and cleans up. Configurable per app via an **Issue Author Filter** — claim only issues filed by the repository owner (default) or any open issue regardless of author. Off by default; enable and pick a provider/model per app like the other improvement tasks.
+- **Scheduled "Refresh local-LLM catalog" task** — a new built-in CoS schedule that periodically researches the current best local models per category and opens a PR refreshing PortOS's bundled suggested-models catalog (`server/lib/localLlmCatalog.js`) and the editorial model ranking, so the in-app install picker and recommendations don't go stale. It no-ops on any repo lacking the catalog file, so it only does work when enabled on the PortOS app itself. Off by default; weekly when enabled, and it only opens a PR when the catalog is actually out of date.
- **Manuscript editorial review: "Start fresh" re-run mode** — re-running the editorial pass in the manuscript editor previously always *merged*, leaving every prior open note in place even when a later pass no longer flagged it. A new "Start fresh" checkbox next to "Run editorial review" reconciles the open list against the latest pass: open notes it still finds stay open, open notes it no longer finds are auto-dismissed, and genuinely-new findings are added. Your accepted and dismissed decisions are left untouched. Clearing is done by moving notes to dismissed (never by deleting them), so the change syncs correctly across federated machines instead of being resurrected by a peer. Merge stays the default.
## Changed
+- **Local model pickers now show what's actually installed** — the Fallback Model dropdown in the AI Provider editor and the provider/model selector in the manuscript editorial review previously only listed the models stored on the provider record, so models you'd pulled in Ollama later (e.g. Command R+, Gemma) never appeared. Both pickers now fold in the live list of installed Ollama / LM Studio models. Embedding-only models (e.g. `nomic-embed-text`) are filtered out of these generation pickers since they can't run a prompt.
+- **Editorial model recommendation** — the manuscript editorial review now suggests the best installed local model for editing/feedback (a one-tap "Recommended for editing" chip), ranking models that follow instructions tightly (Qwen/Llama/Gemma) ahead of chatty/RAG-tuned ones (Command R+) and skipping embedding/code/vision models. The pick is always among your *installed* models, so it auto-adapts as you pull newer versions.
+- **Model context windows are now visible** — each model card on Settings → Local LLM shows its native context length (e.g. "32K ctx"), and the provider/model selector dropdowns (AI Provider editor, manuscript editorial review) annotate each local model with its window as a parenthetical.
- Code quality: extracted the duplicated cron-expression validation in `cosJobRoutes.js` (job create/update) into a single `validateCronExpression()` helper, and unified the two slightly-divergent error messages.
- Code quality: replaced inline `8000` / `8` / `4` / `20 * 1024 * 1024` literals in the image-generation routes with named constants (`MAX_PROMPT_LENGTH`, `MAX_LORAS`, `MAX_REFERENCE_IMAGES`, `MAX_IMAGE_UPLOAD_BYTES`); the `referenceImageN` upload field list now derives from `MAX_REFERENCE_IMAGES` so it can't drift.
- Code quality: replaced the local `safeReadJson` reimplementation in `apps.js` with the shared `readJSONFile` helper from `fileUtils.js`, and named the repeated `1500` ms inter-action throttle in `agentActionExecutor.js` as `INTER_ACTION_DELAY_MS`.
@@ -19,3 +23,11 @@
- **[issue-984] Chief of Staff daily action cap holds firm when several jobs come due at once** — scheduled jobs that fired in the same instant could each slip past a small daily action cap before the others were counted, letting the cap be exceeded by one. The cap is now enforced the moment each job is admitted, so simultaneously-due jobs can no longer overshoot it.
- **[issue-968] A PM2 hiccup no longer makes running apps look offline** — when PortOS briefly can't read process state, affected apps now show "status unavailable" instead of being silently reported as stopped. The Apps list and detail pages replace the (misleading) Start button with a refresh-to-retry control, the dashboard counts these separately, the system health page flags the degraded read, and CyberCity no longer rains on apps whose status simply couldn't be read.
+
+- **Ollama fallback no longer picks an embedding model** — when a primary provider failed and PortOS fell back to Ollama, it could resolve `nomic-embed-text` (an embedding model that can't run a prompt) because that model was listed first and the provider had no default. The fallback now skips embedding-only models when resolving which model to run, so it lands on a real chat model (e.g. Qwen) instead of failing twice.
+
+- **A model declining a prompt on safety grounds is no longer treated as a provider outage** — when Codex/Claude refuses a prompt for content/safety reasons, PortOS used to spin up a Chief-of-Staff "investigate AI provider failure" task even though the cause is known. Refusals are now recognized: no investigation task is created, the provider isn't benched (it's healthy — it just declined that one prompt), PortOS still retries with a fallback model, and the UI shows a calm "model declined — attempting a fallback" notice instead of a red error.
+
+- **Manuscript editor honors the selected model instead of silently defaulting** — when you picked a provider (e.g. Ollama) with no configured default model, the model dropdown showed a model but actually held an empty selection, so the server fell through to the provider's first model — the embedding model `nomic-embed-text`, which then failed. The picker now pins a real, in-list model (the editorial recommendation, else the first generation model) the moment a provider is chosen, so what you see is what runs.
+
+- **A slow fallback that recovers no longer leaves a stray "investigate" task** — the auto-fixer deferred its investigation task for a few seconds to give a fallback time to recover, but a slow CLI fallback (Claude Code can take 20–30s) outran that window, so a failure that was successfully recovered still left a task in the plan. The suppression now follows the fallback's actual lifecycle instead of a fixed timer: the task is cancelled the moment a fallback starts and only fires if no fallback is attempted or the fallback itself fails.
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsx
index ff56cd1115..aaf32f7a9a 100644
--- a/client/src/components/settings/LocalLlmTab.jsx
+++ b/client/src/components/settings/LocalLlmTab.jsx
@@ -4,7 +4,7 @@ import { Cpu, Box, ArrowRightLeft, Download, Trash2, RefreshCw, Search, Plus, Ex
import toast from '../ui/Toast';
import ConfirmButtonPair from '../ui/ConfirmButtonPair';
import BrailleSpinner from '../BrailleSpinner';
-import { formatBytes, timeAgo } from '../../utils/formatters';
+import { formatBytes, formatContextLength, timeAgo } from '../../utils/formatters';
import { localLlmTargetKey } from '../../lib/localLlmTargetKey';
import {
getLocalLlmStatus, getLocalLlmCatalog, getLocalLlmHuggingFaceSearch, installLocalLlmModel,
@@ -792,7 +792,7 @@ export function LocalLlmTab() {
<div className="flex-1 min-w-0">
<div className="text-sm text-white truncate">{m.name}</div>
<div className="text-xs text-gray-500 truncate">
- {[m.params, m.quantization, m.family].filter(Boolean).join(' · ')}
+ {[m.params, m.quantization, m.family, formatContextLength(m.contextLength)].filter(Boolean).join(' · ')}
</div>
</div>
{m.size != null && <span className="text-xs text-gray-400 shrink-0">{formatBytes(m.size)}</span>}
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 62ee82869f..9811cd28e1 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -120,6 +120,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `usePostSession` | Post-render callback scheduling. | Generic post-action chaining. |
| `useRecordMerge` | Duplicate Universe/Series merge flow: open → dry-run preview → resolve field conflicts → execute, with an `onMerged` refresh callback. Drives `<MergeModal>`. | Surfacing the merge-duplicates UI anywhere (Sharing → Duplicates, Universes page). Don't re-implement the preview/execute dance. |
| `useProviderModels` | AI providers + two-step provider→model selection. | Any UI that picks a provider + model. |
+| `useLocalModels` | Live installed Ollama/LM Studio model ids per backend + the server's editorial recommendation. | Model pickers that must show currently-installed local models (not just a provider's stale stored `models`). Fold in via `mergeModelLists` + `localBackendForProvider`. |
| `useTheme` | Dark/light theme + paired-theme switching. | Theme picker. |
| `useSyncIntegrity` | Fetches per-kind integrity diff from every eligible online peer; reduces to worst-case `statusById` + `byPeer` breakdown maps. | Federated media sync integrity UI — badges, drawers, peer breakdown. |
| `useUniverse` | Loads the universe record for a `universeId` with mount/cancel guards; returns `[universe, setUniverse, loading, error]` (setter exposed for optimistic post-mutation updates). | Any surface that loads a linked universe (pipeline stages, etc.) — use instead of re-rolling the getUniverse-on-mount effect. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 493b960053..0fea6e2af6 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -24,6 +24,7 @@ export { default as useMounted } from './useMounted.js';
export { default as useNextEvalCountdown } from './useNextEvalCountdown.js';
export { default as usePendingListRows } from './usePendingListRows.js';
export { default as usePopoverPosition } from './usePopoverPosition.js';
+export { default as useLocalModels } from './useLocalModels.js';
export { default as usePreviewRoute } from './usePreviewRoute.js';
export { default as useProviderModels } from './useProviderModels.js';
export { default as useRowDraft } from './useRowDraft.js';
diff --git a/client/src/hooks/useErrorNotifications.js b/client/src/hooks/useErrorNotifications.js
index a227e9063e..17ae747a6c 100644
--- a/client/src/hooks/useErrorNotifications.js
+++ b/client/src/hooks/useErrorNotifications.js
@@ -30,6 +30,16 @@ export function useErrorNotifications() {
return;
}
+ // A model declined a prompt on content/safety grounds. Not an error —
+ // the server is auto-retrying with a fallback model. Surface a calm,
+ // informative notice (not a red error toast) so the user knows why their
+ // primary model balked. Handled before the warning-drop below.
+ if (error.code === 'AI_PROVIDER_CONTENT_REFUSED') {
+ toast(error.message, { duration: 7000, icon: '🛟' });
+ console.warn(`[${error.code}] ${error.message}`, error.context);
+ return;
+ }
+
// `severity: 'warning'` routes (e.g. speculative GET /api/media-jobs/:id
// 404s for jobs past the 24h archive TTL) opt out of toast + console
// surfacing entirely — the network-tab 404 is sufficient signal.
diff --git a/client/src/hooks/useLocalModels.js b/client/src/hooks/useLocalModels.js
new file mode 100644
index 0000000000..daf3040450
--- /dev/null
+++ b/client/src/hooks/useLocalModels.js
@@ -0,0 +1,58 @@
+import { useEffect, useState } from 'react';
+import { getLocalLlmStatus } from '../services/apiLocalLlm';
+
+/**
+ * Fetch the live list of installed local-LLM models (Ollama / LM Studio) once.
+ *
+ * A provider's stored `models` array goes stale as the user pulls new models in
+ * Ollama, so model pickers that only read `provider.models` hide models that are
+ * actually installed (the reported "Command R+ / Gemma missing from the fallback
+ * dropdown" bug). Components fold this hook's per-backend ids into their option
+ * lists via `mergeModelLists` + `localBackendForProvider`.
+ *
+ * Also surfaces the server's editorial recommendation per backend so editorial
+ * UIs can suggest a best-fit model.
+ *
+ * `ctxById` maps each installed model id to its native context window (tokens)
+ * so pickers can show a "(32K ctx)" parenthetical without a second fetch.
+ *
+ * @returns {{ ollama: string[], lmstudio: string[], recommendations: { ollama: object|null, lmstudio: object|null }, ctxById: Record<string, number>, loading: boolean }}
+ */
+export default function useLocalModels() {
+ const [state, setState] = useState({
+ ollama: [],
+ lmstudio: [],
+ recommendations: { ollama: null, lmstudio: null },
+ ctxById: {},
+ loading: true,
+ });
+
+ useEffect(() => {
+ let canceled = false;
+ // Secondary control — a failed fetch shouldn't toast over the host page.
+ getLocalLlmStatus({ silent: true })
+ .then((status) => {
+ if (canceled) return;
+ const ids = (list) => (list || []).map((m) => m.id || m.name).filter(Boolean);
+ const ctxById = {};
+ for (const m of [...(status?.ollama?.models || []), ...(status?.lmstudio?.models || [])]) {
+ const id = m.id || m.name;
+ if (id && Number(m.contextLength) > 0) ctxById[id] = m.contextLength;
+ }
+ setState({
+ ollama: ids(status?.ollama?.models),
+ lmstudio: ids(status?.lmstudio?.models),
+ recommendations: {
+ ollama: status?.ollama?.recommendations?.editorial || null,
+ lmstudio: status?.lmstudio?.recommendations?.editorial || null,
+ },
+ ctxById,
+ loading: false,
+ });
+ })
+ .catch(() => { if (!canceled) setState((s) => ({ ...s, loading: false })); });
+ return () => { canceled = true; };
+ }, []);
+
+ return state;
+}
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsx
index 3629cfdbed..20b489781c 100644
--- a/client/src/pages/AIProviders.jsx
+++ b/client/src/pages/AIProviders.jsx
@@ -2,7 +2,8 @@ import { useState, useEffect, useCallback } from 'react';
import toast from '../components/ui/Toast';
import * as api from '../services/api';
import socket from '../services/socket';
-import { filterSelectableModels, providerTypeClass, isTuiProvider, isApiProvider, isProcessProvider, isClaudeCodePlanCli } from '../utils/providers';
+import { filterSelectableModels, filterGenerationModels, mergeModelLists, localBackendForProvider, modelOptionLabel, providerTypeClass, isTuiProvider, isApiProvider, isProcessProvider, isClaudeCodePlanCli } from '../utils/providers';
+import useLocalModels from '../hooks/useLocalModels';
import EmptyState from '../components/EmptyState';
import {
formatDurationMs,
@@ -633,15 +634,28 @@ function ProviderForm({ provider, onClose, onSave, allProviders = [] }) {
const [newEnvValue, setNewEnvValue] = useState('');
const [newEnvSecret, setNewEnvSecret] = useState(false);
- const availableModels = formData.models || [];
+ // Live installed Ollama/LM Studio models, folded into the model pickers so a
+ // local provider shows what's actually installed — not just the stale `models`
+ // list stored on the provider record (the "Command R+ / Gemma missing" bug).
+ const localModels = useLocalModels();
+ const liveModelsFor = (p) => {
+ const backend = localBackendForProvider(p);
+ return backend ? localModels[backend] : [];
+ };
+
+ const availableModels = mergeModelLists(formData.models, liveModelsFor(formData));
// Filter out current provider from fallback options (treat undefined enabled as enabled)
const fallbackOptions = allProviders.filter(p => p.id !== provider?.id && p.enabled !== false);
// The fallback model is a model OF the selected fallback provider, so its
- // option list comes from that provider's `models` — not this provider's.
+ // option list comes from that provider's `models` — merged with the live
+ // installed list for local backends, and embedding-only models dropped (a
+ // fallback runs prompts, so `nomic-embed-text` must never be selectable here).
const selectedFallbackProvider = allProviders.find(p => p.id === formData.fallbackProvider);
- const fallbackModelOptions = selectedFallbackProvider?.models || [];
+ const fallbackModelOptions = filterGenerationModels(
+ mergeModelLists(selectedFallbackProvider?.models, liveModelsFor(selectedFallbackProvider)),
+ );
const handleSubmit = async (e) => {
e.preventDefault();
@@ -860,7 +874,7 @@ function ProviderForm({ provider, onClose, onSave, allProviders = [] }) {
>
<option value="">None</option>
{availableModels.map(model => (
- <option key={model} value={model}>{model}</option>
+ <option key={model} value={model}>{modelOptionLabel(model, localModels.ctxById)}</option>
))}
</select>
) : (
@@ -896,7 +910,7 @@ function ProviderForm({ provider, onClose, onSave, allProviders = [] }) {
>
<option value="">None</option>
{availableModels.map(model => (
- <option key={model} value={model}>{model}</option>
+ <option key={model} value={model}>{modelOptionLabel(model, localModels.ctxById)}</option>
))}
</select>
) : (
@@ -922,7 +936,7 @@ function ProviderForm({ provider, onClose, onSave, allProviders = [] }) {
>
<option value="">None</option>
{availableModels.map(model => (
- <option key={model} value={model}>{model}</option>
+ <option key={model} value={model}>{modelOptionLabel(model, localModels.ctxById)}</option>
))}
</select>
) : (
@@ -948,7 +962,7 @@ function ProviderForm({ provider, onClose, onSave, allProviders = [] }) {
>
<option value="">None</option>
{availableModels.map(model => (
- <option key={model} value={model}>{model}</option>
+ <option key={model} value={model}>{modelOptionLabel(model, localModels.ctxById)}</option>
))}
</select>
) : (
@@ -1030,7 +1044,7 @@ function ProviderForm({ provider, onClose, onSave, allProviders = [] }) {
>
<option value="">Use fallback provider's default</option>
{fallbackModelOptions.map(model => (
- <option key={model} value={model}>{model}</option>
+ <option key={model} value={model}>{modelOptionLabel(model, localModels.ctxById)}</option>
))}
</select>
) : (
diff --git a/client/src/pages/PipelineManuscriptEditor.jsx b/client/src/pages/PipelineManuscriptEditor.jsx
index 2140355959..d6be61df5e 100644
--- a/client/src/pages/PipelineManuscriptEditor.jsx
+++ b/client/src/pages/PipelineManuscriptEditor.jsx
@@ -26,7 +26,8 @@ import InlineDiff from '../components/ui/InlineDiff';
import toast from '../components/ui/Toast';
import { useAsyncAction } from '../hooks/useAsyncAction';
import { timeAgo } from '../utils/formatters';
-import { filterSelectableModels } from '../utils/providers';
+import { filterGenerationModels, mergeModelLists, localBackendForProvider, modelOptionLabel } from '../utils/providers';
+import useLocalModels from '../hooks/useLocalModels';
import {
getPipelineSeries, updatePipelineSeries, getPipelineManuscript, getPipelineManuscriptReview,
patchPipelineManuscriptComment, savePipelineManuscriptSection, restorePipelineStageVersion,
@@ -153,7 +154,43 @@ export default function PipelineManuscriptEditor() {
}, []);
const overrideProvider = providers.find((p) => p.id === overrideProviderId) || null;
- const overrideModels = filterSelectableModels(overrideProvider?.models || [overrideProvider?.defaultModel]);
+ // Live installed local-LLM models, so a local provider's picker shows what's
+ // actually installed in Ollama/LM Studio — not just its stale stored `models`.
+ const localModels = useLocalModels();
+ const overrideBackend = localBackendForProvider(overrideProvider);
+ // Memoized so the array identity is stable across renders — it's a dependency
+ // of the auto-select effect below, which would otherwise re-run every render.
+ const overrideModels = useMemo(
+ () => filterGenerationModels(
+ mergeModelLists(
+ overrideProvider?.models || [overrideProvider?.defaultModel],
+ overrideBackend ? localModels[overrideBackend] : [],
+ ),
+ ),
+ [overrideProvider, overrideBackend, localModels],
+ );
+ // Best installed model for editorial review/editing (Ollama/LM Studio only).
+ const editorialPick = overrideBackend ? localModels.recommendations?.[overrideBackend] : null;
+ const showEditorialPick = Boolean(
+ editorialPick?.id && overrideModels.includes(editorialPick.id) && overrideModel !== editorialPick.id,
+ );
+
+ // Keep the model selection honest. A controlled <select> whose value isn't one
+ // of its options shows the first option but holds an empty value — so a
+ // provider with no defaultModel (Ollama: defaultModel null) looked like a real
+ // model was picked while the override sent to the server was empty, and the
+ // server fell through to models[0] (the embedding model). Once a provider is
+ // chosen, pin a concrete in-list model (the editorial recommendation when
+ // available, else the first) so what the user sees is what actually runs.
+ useEffect(() => {
+ if (!overrideProviderId || overrideModels.length === 0) return;
+ if (overrideModel && overrideModels.includes(overrideModel)) return;
+ const pick = (editorialPick?.id && overrideModels.includes(editorialPick.id))
+ ? editorialPick.id
+ : overrideModels[0];
+ setOverrideModel(pick);
+ }, [overrideProviderId, overrideModels, editorialPick, overrideModel]);
+
// undefined (not '') so the server treats it as "no override" → system default.
const providerOverride = overrideProviderId || undefined;
const modelOverride = overrideModel || undefined;
@@ -161,6 +198,8 @@ export default function PipelineManuscriptEditor() {
const changeOverrideProvider = (id) => {
setOverrideProviderId(id);
const p = providers.find((pr) => pr.id === id);
+ // Provisional; the effect above pins a valid in-list model once the
+ // (possibly async) live model list resolves.
setOverrideModel(p?.defaultModel || '');
};
@@ -419,10 +458,23 @@ export default function PipelineManuscriptEditor() {
onChange={(e) => setOverrideModel(e.target.value)}
className="flex-1 min-w-0 px-2 py-1.5 bg-port-bg border border-port-border rounded text-sm text-white"
>
- {overrideModels.map((m) => <option key={m} value={m}>{m}</option>)}
+ {overrideModels.map((m) => <option key={m} value={m}>{modelOptionLabel(m, localModels.ctxById)}</option>)}
</select>
) : null}
</div>
+ {/* One-tap suggestion of the best installed local model for editorial
+ work — only when a local provider is selected and the pick isn't
+ already chosen. */}
+ {showEditorialPick ? (
+ <button
+ type="button"
+ onClick={() => setOverrideModel(editorialPick.id)}
+ title={editorialPick.reason}
+ className="inline-flex items-center gap-1 text-[11px] text-port-accent hover:underline"
+ >
+ <Sparkles size={11} /> Recommended for editing: {editorialPick.id}
+ </button>
+ ) : null}
<button
type="button"
onClick={() => runEditorialReview(freshReview ? 'fresh' : 'merge')}
diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.js
index ada9c096c3..f5471caca3 100644
--- a/client/src/utils/formatters.js
+++ b/client/src/utils/formatters.js
@@ -114,6 +114,24 @@ export function formatBytes(bytes, decimals = 1) {
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(decimals))} ${sizes[i]}`;
}
+/**
+ * Format a model context window (in tokens) compactly, e.g. 32768 → "32K ctx",
+ * 131072 → "128K ctx", 1048576 → "1M ctx". Returns null for missing/invalid
+ * values so callers can omit the label entirely.
+ * @param {number|null|undefined} tokens
+ * @returns {string|null}
+ */
+export function formatContextLength(tokens) {
+ const n = Number(tokens);
+ if (!Number.isFinite(n) || n <= 0) return null;
+ if (n >= 1024 * 1024) {
+ const m = n / (1024 * 1024);
+ return `${parseFloat(m.toFixed(m % 1 ? 1 : 0))}M ctx`;
+ }
+ if (n >= 1024) return `${Math.round(n / 1024)}K ctx`;
+ return `${n} ctx`;
+}
+
/**
* Count whitespace-separated words in a string. Matches the server-side
* countWords in writers-room storage so client + server agree.
diff --git a/client/src/utils/formatters.test.js b/client/src/utils/formatters.test.js
index 1a3b1d576e..e61f63163e 100644
--- a/client/src/utils/formatters.test.js
+++ b/client/src/utils/formatters.test.js
@@ -1,5 +1,23 @@
import { describe, it, expect } from 'vitest';
-import { formatDurationMin, formatEventDateTime, timeAgo } from './formatters.js';
+import { formatContextLength, formatDurationMin, formatEventDateTime, timeAgo } from './formatters.js';
+
+describe('formatContextLength', () => {
+ it('formats common context windows compactly', () => {
+ expect(formatContextLength(4096)).toBe('4K ctx');
+ expect(formatContextLength(8192)).toBe('8K ctx');
+ expect(formatContextLength(32768)).toBe('32K ctx');
+ expect(formatContextLength(131072)).toBe('128K ctx');
+ expect(formatContextLength(1048576)).toBe('1M ctx');
+ });
+
+ it('returns null for missing/invalid values', () => {
+ expect(formatContextLength(null)).toBeNull();
+ expect(formatContextLength(undefined)).toBeNull();
+ expect(formatContextLength(0)).toBeNull();
+ expect(formatContextLength(-5)).toBeNull();
+ expect(formatContextLength('nope')).toBeNull();
+ });
+});
describe('formatDurationMin', () => {
it('formats sub-hour, exact-hour, and hour+min durations', () => {
diff --git a/client/src/utils/providers.js b/client/src/utils/providers.js
index 4aa3271c97..fd46396005 100644
--- a/client/src/utils/providers.js
+++ b/client/src/utils/providers.js
@@ -1,3 +1,5 @@
+import { formatContextLength } from './formatters.js';
+
/**
* Sentinel value used by the Codex provider to indicate the model is configured
* via ~/.codex/config.toml rather than PortOS. Filter this out of selectable
@@ -29,6 +31,77 @@ export const PROVIDER_TYPES = Object.freeze({
export const filterSelectableModels = (models) =>
(models || []).filter(m => m !== CODEX_CONFIGURED_DEFAULT && m !== ANTIGRAVITY_CONFIGURED_DEFAULT);
+/**
+ * Embedding-only model detector — mirror of `isEmbeddingModel` in
+ * server/lib/localModelHeuristics.js. Keep the two regexes in lockstep (the
+ * server lib can't be imported here). Used to keep embedding models (e.g.
+ * `nomic-embed-text`) out of generation/chat model pickers.
+ * @param {string} id
+ * @returns {boolean}
+ */
+export const isEmbeddingModel = (id) =>
+ typeof id === 'string' && id.length > 0 &&
+ /(?:^|[-_/:])(?:embed|embedding|bge|nomic|mxbai|gte|e5|snowflake-arctic-embed)(?:[-_/:]|$)|text-embedding/i.test(id);
+
+/**
+ * Selectable models for a generation/chat picker: drops internal sentinels AND
+ * embedding-only models. Use anywhere the user picks a model that will run a
+ * prompt (provider editor model lists, fallback model, manuscript review).
+ * @param {string[]} models
+ * @returns {string[]}
+ */
+export const filterGenerationModels = (models) =>
+ filterSelectableModels(models).filter((m) => !isEmbeddingModel(m));
+
+/**
+ * Classify a provider as a local-LLM backend by its endpoint/name, so callers
+ * can fold in live-installed models (Ollama/LM Studio) that aren't in the
+ * provider's stored `models` list. Ollama's native + OpenAI-compat ports are
+ * 11434; LM Studio defaults to 1234.
+ * @param {{endpoint?:string,name?:string}} provider
+ * @returns {'ollama'|'lmstudio'|null}
+ */
+export const localBackendForProvider = (provider) => {
+ const endpoint = String(provider?.endpoint || '');
+ const name = String(provider?.name || '').toLowerCase();
+ if (/:11434\b/.test(endpoint) || name.includes('ollama')) return 'ollama';
+ if (/:1234\b/.test(endpoint) || name.includes('lm studio') || name.includes('lmstudio')) return 'lmstudio';
+ return null;
+};
+
+/**
+ * Union of one or more model-id lists, de-duplicated, order-preserving, falsy
+ * values dropped. Used to merge a provider's stored `models` with the live
+ * installed list for local backends.
+ * @param {...(string[]|undefined)} lists
+ * @returns {string[]}
+ */
+export const mergeModelLists = (...lists) => {
+ const seen = new Set();
+ const out = [];
+ for (const list of lists) {
+ for (const m of list || []) {
+ if (m && !seen.has(m)) { seen.add(m); out.push(m); }
+ }
+ }
+ return out;
+};
+
+/**
+ * Display label for a model `<option>`: the id plus a "(32K ctx)" parenthetical
+ * when the model's context window is known (local models, via the `ctxById` map
+ * from `useLocalModels`). The option's `value` stays the raw id — only the label
+ * carries the annotation.
+ * @param {string} id
+ * @param {Record<string, number>} [ctxById]
+ * @returns {string}
+ */
+export const modelOptionLabel = (id, ctxById) => {
+ const ctx = ctxById?.[id];
+ const label = formatContextLength(ctx);
+ return label ? `${id} (${label})` : id;
+};
+
/**
* Check if a provider is a TUI-backed agent provider. Mirror of
* `isTuiProvider` in server/services/agentCliSpawning.js.
diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.js
index d963b23b11..07d575a284 100644
--- a/client/src/utils/providers.test.js
+++ b/client/src/utils/providers.test.js
@@ -4,6 +4,11 @@ import {
CODEX_CONFIGURED_DEFAULT,
PROVIDER_TYPES,
filterSelectableModels,
+ filterGenerationModels,
+ isEmbeddingModel,
+ localBackendForProvider,
+ mergeModelLists,
+ modelOptionLabel,
isTuiProvider,
isCliProvider,
isApiProvider,
@@ -174,3 +179,63 @@ describe('getProviderTimeout', () => {
expect(getProviderTimeout(providers, 'ghost', 'also-ghost')).toBeUndefined();
});
});
+
+describe('isEmbeddingModel / filterGenerationModels', () => {
+ it('flags embedding models and not chat models', () => {
+ expect(isEmbeddingModel('nomic-embed-text:latest')).toBe(true);
+ expect(isEmbeddingModel('mxbai-embed-large')).toBe(true);
+ expect(isEmbeddingModel('qwen3.6:35b')).toBe(false);
+ expect(isEmbeddingModel('')).toBe(false);
+ });
+
+ it('drops sentinels and embedding models from generation lists', () => {
+ expect(filterGenerationModels([
+ CODEX_CONFIGURED_DEFAULT,
+ 'nomic-embed-text:latest',
+ 'qwen3.6:35b',
+ 'llama3.2:latest',
+ ])).toEqual(['qwen3.6:35b', 'llama3.2:latest']);
+ });
+});
+
+describe('localBackendForProvider', () => {
+ it('detects Ollama by endpoint or name', () => {
+ expect(localBackendForProvider({ endpoint: 'http://localhost:11434/v1' })).toBe('ollama');
+ expect(localBackendForProvider({ name: 'Ollama' })).toBe('ollama');
+ });
+
+ it('detects LM Studio by endpoint or name', () => {
+ expect(localBackendForProvider({ endpoint: 'http://localhost:1234/v1' })).toBe('lmstudio');
+ expect(localBackendForProvider({ name: 'LM Studio' })).toBe('lmstudio');
+ });
+
+ it('returns null for cloud providers', () => {
+ expect(localBackendForProvider({ endpoint: 'https://api.openai.com/v1', name: 'OpenAI' })).toBeNull();
+ expect(localBackendForProvider({})).toBeNull();
+ expect(localBackendForProvider(null)).toBeNull();
+ });
+});
+
+describe('modelOptionLabel', () => {
+ it('appends a context parenthetical when known', () => {
+ expect(modelOptionLabel('qwen3.6:35b', { 'qwen3.6:35b': 32768 })).toBe('qwen3.6:35b (32K ctx)');
+ });
+
+ it('returns the bare id when context is unknown', () => {
+ expect(modelOptionLabel('gpt-4o', {})).toBe('gpt-4o');
+ expect(modelOptionLabel('gpt-4o')).toBe('gpt-4o');
+ expect(modelOptionLabel('gpt-4o', { 'gpt-4o': 0 })).toBe('gpt-4o');
+ });
+});
+
+describe('mergeModelLists', () => {
+ it('unions lists, de-dupes, preserves order, drops falsy', () => {
+ expect(mergeModelLists(['a', 'b'], ['b', 'c'], undefined, [null, 'd', '']))
+ .toEqual(['a', 'b', 'c', 'd']);
+ });
+
+ it('returns [] for no input', () => {
+ expect(mergeModelLists()).toEqual([]);
+ expect(mergeModelLists(undefined, null)).toEqual([]);
+ });
+});
diff --git a/server/index.js b/server/index.js
index b9281b5627..9580834887 100644
--- a/server/index.js
+++ b/server/index.js
@@ -133,6 +133,7 @@ import { setHttpsEnabledAtBoot } from './lib/httpsState.js';
import { initTaskLearning } from './services/taskLearning.js';
import { recordSession, recordMessages } from './services/usage.js';
import { errorEvents } from './lib/errorHandler.js';
+import { ERROR_CATEGORIES } from './lib/aiToolkit/errorDetection.js';
import { initSpawner } from './services/subAgentSpawner.js';
import * as automationScheduler from './services/automationScheduler.js';
import * as agentActionExecutor from './services/agentActionExecutor.js';
@@ -241,11 +242,20 @@ const aiToolkitHooks = {
},
onRunFailed: (metadata, error, output) => {
const errorMessage = error?.message ?? String(error);
+ // A content/safety refusal is a known, self-explanatory outcome — not a
+ // provider fault. Emit a distinct code + warning severity so (a) the
+ // autofixer skips it (it only spawns investigation tasks for
+ // AI_PROVIDER_EXECUTION_FAILED) and (b) the client shows a calm "model
+ // declined, trying a fallback" notice instead of a red error toast. The
+ // fallback retry itself is driven by promptRunner.js.
+ const isRefusal = metadata.errorAnalysis?.category === ERROR_CATEGORIES.CONTENT_REFUSAL;
errorEvents.emit('error', {
- code: 'AI_PROVIDER_EXECUTION_FAILED',
- message: `AI provider ${metadata.providerName} execution failed: ${errorMessage}`,
- severity: 'error',
- canAutoFix: true,
+ code: isRefusal ? 'AI_PROVIDER_CONTENT_REFUSED' : 'AI_PROVIDER_EXECUTION_FAILED',
+ message: isRefusal
+ ? `${metadata.providerName} declined this prompt on content/safety grounds — attempting a fallback model.`
+ : `AI provider ${metadata.providerName} execution failed: ${errorMessage}`,
+ severity: isRefusal ? 'warning' : 'error',
+ canAutoFix: !isRefusal,
timestamp: Date.now(),
context: {
runId: metadata.id,
diff --git a/server/lib/README.md b/server/lib/README.md
index 0bf3703425..26d1a3624c 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -171,6 +171,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `civitai.js` | Civitai URL parsing + API client. |
| `localLlmCatalog.js` | Curated cross-backend (Ollama↔LM Studio) local-LLM catalog + install-id mapping for the migrate flow. Pure. |
| `localLlmDisk.js` | Pure on-disk reasoning for the migrate "copy GGUF locally instead of re-downloading" fast-path (Ollama manifest/blob parsing, LM Studio path layout, MLX/projector/shard detection). |
+| `localModelHeuristics.js` | Capability heuristics for untyped local (Ollama/LM Studio) models. `isEmbeddingModel`/`isGenerationModel` (so a generation/fallback run never picks an embedding model like `nomic-embed-text`); `recommendEditorialModel(models)` ranks installed models for editorial review/editing. Pure. Mirror `isEmbeddingModel` in `client/src/utils/providers.js`. |
| `issueLength.js` | Per-issue size targets fed into text stages. |
| `mediaItemKey.js` | `<kind>:<ref>` key vocabulary for media items. |
| `navManifest.js` | Single source of truth for nav (`⌘K` palette + voice). Add an entry when you add a page. |
diff --git a/server/lib/aiToolkit/errorDetection.js b/server/lib/aiToolkit/errorDetection.js
index 8155f12870..56b8ec9dbe 100644
--- a/server/lib/aiToolkit/errorDetection.js
+++ b/server/lib/aiToolkit/errorDetection.js
@@ -13,11 +13,30 @@ export const ERROR_CATEGORIES = {
NETWORK_ERROR: 'network-error',
TIMEOUT: 'timeout',
QUOTA_EXCEEDED: 'quota-exceeded',
+ // A frontier model declined the prompt on content/safety grounds. NOT a
+ // provider fault — the provider is healthy and other prompts still work, so
+ // this must not bench the provider or spawn an investigation task. We do try
+ // a fallback (a local model often doesn't refuse) and tell the UI what
+ // happened. See server/index.js#onRunFailed + autoFixer.handleAIProviderError.
+ CONTENT_REFUSAL: 'content-refusal',
UNKNOWN: 'unknown'
};
// Order matters — more specific patterns first.
const ERROR_PATTERNS = [
+ {
+ // High-precision markers for a model safety/content refusal. Codex (OpenAI)
+ // returns "Invalid prompt: we've limited access to this content for safety
+ // reasons. This type of information may be used to benefit or to harm…";
+ // Anthropic surfaces a `refusal` stop reason. Matched FIRST so a refusal is
+ // never misclassified as an auth/unknown failure that would bench the
+ // provider and queue a CoS investigation task.
+ pattern: /limited access to this content for safety|may be used to benefit or to harm|content[_ ]policy[_ ]violation|stop_reason["']?\s*:\s*["']?refusal|"type"\s*:\s*"refusal"/i,
+ category: ERROR_CATEGORIES.CONTENT_REFUSAL,
+ requiresFallback: true,
+ actionable: false,
+ suggestedFix: 'Model declined the prompt on content/safety grounds — retrying with a fallback model.'
+ },
{
pattern: /billing|payment|credit|insufficient funds/i,
category: ERROR_CATEGORIES.QUOTA_EXCEEDED,
diff --git a/server/lib/aiToolkit/errorDetection.test.js b/server/lib/aiToolkit/errorDetection.test.js
index 71d4794c0f..56814e2535 100644
--- a/server/lib/aiToolkit/errorDetection.test.js
+++ b/server/lib/aiToolkit/errorDetection.test.js
@@ -10,6 +10,26 @@ import {
describe('Error Detection', () => {
describe('analyzeError', () => {
+ it('detects a Codex/OpenAI content-safety refusal', () => {
+ const result = analyzeError(
+ "Invalid prompt: we've limited access to this content for safety reasons. This type of information may be used to benefit or to harm people."
+ );
+ expect(result.hasError).toBe(true);
+ expect(result.category).toBe(ERROR_CATEGORIES.CONTENT_REFUSAL);
+ expect(result.requiresFallback).toBe(true);
+ expect(result.actionable).toBe(false);
+ });
+
+ it('detects an Anthropic refusal stop reason', () => {
+ const result = analyzeError('{"stop_reason":"refusal"}');
+ expect(result.category).toBe(ERROR_CATEGORIES.CONTENT_REFUSAL);
+ });
+
+ it('does not misclassify a generic failure as a refusal', () => {
+ const result = analyzeError('Process exited with code 1', 1);
+ expect(result.category).toBe(ERROR_CATEGORIES.UNKNOWN);
+ });
+
it('should detect rate limit errors', () => {
const result = analyzeError('API Error: 429 Too Many Requests');
expect(result.hasError).toBe(true);
diff --git a/server/lib/index.js b/server/lib/index.js
index 84b4b993b2..bfcc78ac21 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -144,6 +144,7 @@ export * from './capabilityMap.js';
export * from './civitai.js';
export * from './localLlmCatalog.js';
export * from './localLlmDisk.js';
+export * from './localModelHeuristics.js';
export * from './issueLength.js';
export * from './mediaItemKey.js';
export * from './navManifest.js';
diff --git a/server/lib/localModelHeuristics.js b/server/lib/localModelHeuristics.js
new file mode 100644
index 0000000000..6b78b2de2b
--- /dev/null
+++ b/server/lib/localModelHeuristics.js
@@ -0,0 +1,113 @@
+/**
+ * Local-model capability heuristics.
+ *
+ * Local backends (Ollama / LM Studio) don't tag their models with a capability
+ * type, so PortOS infers one from the model id / family string. Kept pure and
+ * dependency-free so every consumer shares one source of truth:
+ * - ollamaManager.getEmbeddings (auto-discover an embedding model)
+ * - promptRunner.resolveEffectiveModel (never pick an embedding model for a
+ * generation/fallback run — the cause of the nomic-embed-text fallback bug)
+ * - localLlm.getStatus (recommend a best-fit editorial model)
+ *
+ * The client mirrors `isEmbeddingModel` in client/src/utils/providers.js — keep
+ * the two regexes in lockstep (the aiToolkit/lib dirs can't be imported there).
+ */
+
+// Embedding-only models — never valid for chat/generation. The bge/nomic/e5/gte
+// markers are anchored so they don't match mid-word inside an unrelated id.
+const EMBEDDING_RE =
+ /(?:^|[-_/:])(?:embed|embedding|bge|nomic|mxbai|gte|e5|snowflake-arctic-embed)(?:[-_/:]|$)|text-embedding/i;
+
+/**
+ * @param {string} id model id (e.g. "nomic-embed-text:latest")
+ * @returns {boolean} true when the id names an embedding-only model
+ */
+export function isEmbeddingModel(id) {
+ return typeof id === 'string' && id.length > 0 && EMBEDDING_RE.test(id);
+}
+
+/**
+ * A model usable for chat/generation — anything that isn't an embedding model.
+ * @param {string} id
+ * @returns {boolean}
+ */
+export function isGenerationModel(id) {
+ return typeof id === 'string' && id.length > 0 && !isEmbeddingModel(id);
+}
+
+// Families ranked for EDITORIAL FIX GENERATION, best-first. This task needs
+// tight instruction-following and clean, constrained output (rewrite a passage,
+// emit only the rewrite) — NOT chatty long-form generation. So instruction-tuned
+// models lead; Cohere Command (R/R+) is demoted because it's RAG/long-form-tuned
+// and tends to leak commentary/preamble into the output (observed: `# New page`
+// notes and a `PANNEL` typo bleeding into a manuscript fix). Order is
+// "most-preferred first"; `command-r-plus` must precede `command-r`/`command`
+// so the longest substring match wins.
+const EDITORIAL_FAMILY_RANK = [
+ 'qwen', // Qwen — top-tier instruction-following + clean structured output
+ 'llama', // Llama 3.x instruct
+ 'gemma', // Gemma 2/3 instruct
+ 'mixtral', 'mistral', // Mistral family
+ 'command-r-plus', 'command-r', 'command', // Cohere Command — capable but chatty/RAG-tuned
+ 'deepseek', // capable, leans code/math
+ 'phi', // smaller but capable
+ 'gpt-oss', // open-weights GPT
+];
+
+// Models we never recommend for editorial prose: embeddings, code-specialized,
+// vision/multimodal, and media-generation weights that may be installed.
+const NON_EDITORIAL_RE =
+ /(?:^|[-_/:])(?:embed|embedding|bge|nomic|mxbai|gte|e5)(?:[-_/:]|$)|text-embedding|coder|code-|starcoder|codellama|codegemma|(?:^|[-_/:])vision(?:[-_/:]|$)|llava|moondream|minicpm-v|whisper|(?:^|[-_/:])tts(?:[-_/:]|$)|stable-?diffusion|sdxl|flux/i;
+
+/** Parse a parameter count in billions from a model's `params`/id (e.g. "35B"). */
+function parseParamsB(model) {
+ const src = `${model?.params || ''} ${model?.id || model?.name || ''}`;
+ const m = src.match(/(\d+(?:\.\d+)?)\s*[bB]\b/);
+ return m ? parseFloat(m[1]) : null;
+}
+
+/** Score model size for editorial quality — bigger is better, peaking ~27–80B. */
+function sizeScore(b) {
+ if (b == null) return 0.4; // unknown — neutral
+ if (b < 4) return 0.1; // too small for nuanced editing
+ if (b < 8) return 0.5;
+ if (b < 14) return 0.7;
+ if (b < 24) return 0.85;
+ if (b <= 80) return 1.0; // sweet spot for quality editing
+ return 0.9; // very large — great quality, slower
+}
+
+/** Score the model family against the editorial preference list. */
+function familyScore(id) {
+ const lower = String(id).toLowerCase();
+ const idx = EDITORIAL_FAMILY_RANK.findIndex((fam) => lower.includes(fam));
+ if (idx === -1) return 0.3; // unknown family — usable but unranked
+ return 1.0 - (idx / EDITORIAL_FAMILY_RANK.length) * 0.5; // [1.0 .. 0.5], best-first
+}
+
+/**
+ * Recommend the best installed model for editorial feedback / line editing.
+ *
+ * @param {Array<string|{id?:string,name?:string,params?:string,family?:string}>} models
+ * @returns {{ id: string, reason: string }|null} null when nothing is suitable
+ */
+export function recommendEditorialModel(models) {
+ const candidates = (models || [])
+ .map((m) => (typeof m === 'string' ? { id: m } : m))
+ .filter((m) => m?.id && !NON_EDITORIAL_RE.test(m.id));
+ if (!candidates.length) return null;
+
+ let best = null;
+ for (const m of candidates) {
+ const paramsB = parseParamsB(m);
+ const score = familyScore(m.id) * 0.6 + sizeScore(paramsB) * 0.4;
+ if (!best || score > best.score) best = { id: m.id, score, paramsB };
+ }
+ if (!best) return null;
+
+ const sizeLabel = best.paramsB ? `${best.paramsB}B params` : 'size unknown';
+ return {
+ id: best.id,
+ reason: `Best installed fit for editorial review/editing (${sizeLabel}) — tight instruction-following and clean, constrained output for generating fixes.`,
+ };
+}
diff --git a/server/lib/localModelHeuristics.test.js b/server/lib/localModelHeuristics.test.js
new file mode 100644
index 0000000000..7741fbc9cf
--- /dev/null
+++ b/server/lib/localModelHeuristics.test.js
@@ -0,0 +1,93 @@
+import { describe, it, expect } from 'vitest';
+import { isEmbeddingModel, isGenerationModel, recommendEditorialModel } from './localModelHeuristics.js';
+
+describe('localModelHeuristics', () => {
+ describe('isEmbeddingModel', () => {
+ it('flags known embedding models', () => {
+ for (const id of [
+ 'nomic-embed-text:latest',
+ 'mxbai-embed-large',
+ 'bge-m3',
+ 'snowflake-arctic-embed:latest',
+ 'text-embedding-3-small',
+ 'gte-large',
+ ]) {
+ expect(isEmbeddingModel(id), id).toBe(true);
+ }
+ });
+
+ it('does not flag chat/generation models', () => {
+ for (const id of [
+ 'qwen3.6:35b',
+ 'gpt-oss:20b',
+ 'llama3.2:latest',
+ 'command-r-plus:latest',
+ 'gemma2:27b',
+ 'mistral-small:latest',
+ ]) {
+ expect(isEmbeddingModel(id), id).toBe(false);
+ }
+ });
+
+ it('handles non-strings', () => {
+ expect(isEmbeddingModel(null)).toBe(false);
+ expect(isEmbeddingModel(undefined)).toBe(false);
+ expect(isEmbeddingModel('')).toBe(false);
+ });
+
+ it('isGenerationModel is the inverse for real ids', () => {
+ expect(isGenerationModel('qwen3.6:35b')).toBe(true);
+ expect(isGenerationModel('nomic-embed-text:latest')).toBe(false);
+ expect(isGenerationModel('')).toBe(false);
+ });
+ });
+
+ describe('recommendEditorialModel', () => {
+ it('prefers a large general instruct model over a small one', () => {
+ const rec = recommendEditorialModel([
+ { id: 'llama3.2:latest', params: '3.2B' },
+ { id: 'qwen3.6:35b', params: '35B' },
+ ]);
+ expect(rec?.id).toBe('qwen3.6:35b');
+ expect(rec.reason).toMatch(/editorial/i);
+ });
+
+ it('never recommends an embedding model', () => {
+ const rec = recommendEditorialModel([
+ { id: 'nomic-embed-text:latest' },
+ { id: 'llama3.2:latest', params: '3.2B' },
+ ]);
+ expect(rec?.id).toBe('llama3.2:latest');
+ });
+
+ it('skips code-specialized and vision models', () => {
+ const rec = recommendEditorialModel([
+ { id: 'codellama:13b', params: '13B' },
+ { id: 'llava:13b', params: '13B' },
+ { id: 'gemma2:9b', params: '9B' },
+ ]);
+ expect(rec?.id).toBe('gemma2:9b');
+ });
+
+ it('accepts plain string ids', () => {
+ const rec = recommendEditorialModel(['command-r-plus:latest', 'phi3:mini']);
+ expect(rec?.id).toBe('command-r-plus:latest');
+ });
+
+ it('prefers an instruction-tuned model over chatty Command R+ for fix generation', () => {
+ // Command R+ is larger but RAG/long-form-tuned and leaks commentary into
+ // structured fixes; an instruction-tight model is the better editorial pick.
+ const rec = recommendEditorialModel([
+ { id: 'command-r-plus:latest', params: '104B' },
+ { id: 'qwen3.6:35b', params: '35B' },
+ ]);
+ expect(rec?.id).toBe('qwen3.6:35b');
+ });
+
+ it('returns null when nothing is suitable', () => {
+ expect(recommendEditorialModel([])).toBeNull();
+ expect(recommendEditorialModel(['nomic-embed-text:latest', 'mxbai-embed-large'])).toBeNull();
+ expect(recommendEditorialModel(null)).toBeNull();
+ });
+ });
+});
diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.js
index c1747cb5fa..01069ed3b7 100644
--- a/server/lib/promptRunner.js
+++ b/server/lib/promptRunner.js
@@ -32,17 +32,17 @@ import { executeTuiRun } from './tuiPromptRunner.js';
import { ServerError } from './errorHandler.js';
import { PROVIDER_TYPES } from './aiToolkit/constants.js';
import { analyzeError, ERROR_CATEGORIES } from './aiToolkit/errorDetection.js';
+import { isGenerationModel } from './localModelHeuristics.js';
import { getAIToolkitInstance } from './aiToolkitState.js';
import { createSingleFlight } from './singleFlight.js';
-// noteFallbackHandled lives in services/autoFixer.js, which transitively
-// pulls in services/cos.js (PM2 + fs + sockets). Importing it lazily on
-// the failure path keeps anything that imports promptRunner.js from
-// dragging the CoS stack along on the happy path. Node caches the module
-// after the first dynamic import, so the cost is one-time.
-async function loadNoteFallbackHandled() {
- const mod = await import('../services/autoFixer.js');
- return mod.noteFallbackHandled;
+// The fallback-lifecycle notifiers live in services/autoFixer.js, which
+// transitively pulls in services/cos.js (PM2 + fs + sockets). Importing it
+// lazily on the failure path keeps anything that imports promptRunner.js from
+// dragging the CoS stack along on the happy path. Node caches the module after
+// the first dynamic import, so the cost is one-time.
+function loadAutoFixer() {
+ return import('../services/autoFixer.js');
}
export const DEFAULT_TIMEOUT_MS = 300000;
@@ -107,13 +107,27 @@ export const providerHonorsModelOverride = (provider) => (
*/
export function resolveEffectiveModel(provider, callerModel) {
if (providerHonorsModelOverride(provider)) {
- return callerModel || provider?.defaultModel || provider?.models?.[0] || null;
+ return callerModel || provider?.defaultModel || firstGenerationModel(provider) || null;
}
// Non-honoring CLI/TUI path: args-baked model id wins over defaultModel.
const baked = (provider?.type === PROVIDER_TYPES.CLI || provider?.type === PROVIDER_TYPES.TUI) && hasModelFlag(provider?.args)
? extractBakedModel(provider.args)
: null;
- return baked || provider?.defaultModel || provider?.models?.[0] || null;
+ return baked || provider?.defaultModel || firstGenerationModel(provider) || null;
+}
+
+/**
+ * First model in `provider.models` usable for generation (skips embedding-only
+ * models). Without this, a local provider whose `models[0]` is an embedding
+ * model (e.g. Ollama with `nomic-embed-text:latest` listed first and a null
+ * defaultModel) would resolve the embedding model for a chat/fallback run and
+ * fail — the exact nomic-embed-text fallback bug. Falls back to `models[0]`
+ * only when every listed model looks like an embedding model (better to try
+ * something than resolve null).
+ */
+function firstGenerationModel(provider) {
+ const models = provider?.models || [];
+ return models.find((m) => m && isGenerationModel(m)) || models[0] || null;
}
/**
@@ -269,6 +283,21 @@ export async function runPromptThroughProvider(args) {
console.log(`⚡ Retrying ${args.source} with fallback ${fallback.name} (primary ${failed.name} failed: ${firstError.message})`);
+ // Tell the autofixer a fallback is now in flight for this failure so it
+ // suppresses the deferred investigation task IMMEDIATELY — before the
+ // backstop timer (TASK_DEFER_MS) can fire. Without this, a slow CLI
+ // fallback (Claude Code can take 20–30s) outruns the timer and a
+ // successfully-recovered failure still leaves a task in the user's plan.
+ // Keys must match what server/index.js's onRunFailed hook published
+ // (metadata.providerName + metadata.model). Best-effort throughout: a
+ // failure here must never turn a working fallback into a user-visible error.
+ const fallbackKey = { provider: failed.name || failed.id, model: failedModel };
+ const autoFixer = await loadAutoFixer().catch((err) => {
+ console.error(`❌ autoFixer load failed (investigation task not suppressed): ${err.message}`);
+ return null;
+ });
+ try { autoFixer?.noteFallbackStarted(fallbackKey); } catch { /* best-effort */ }
+
// Run the fallback as a fresh attempt. Pass the configured `fallbackModel`
// when one is set (so the user's chosen fallback provider+model pair is
// honored); otherwise `undefined` lets the fallback pick its own default.
@@ -283,27 +312,16 @@ export async function runPromptThroughProvider(args) {
runId: undefined, // fresh runId so the failed primary's record stays intact
});
} catch (fallbackError) {
- // Both failed — let both deferred tasks fire and rethrow.
+ // Both failed — release the primary's suppression (the fallback's own
+ // failure already queued its investigation task) and rethrow.
+ try { autoFixer?.noteFallbackFailed(fallbackKey); } catch { /* best-effort */ }
throw stripFallbackContext(fallbackError);
}
- // Fallback succeeded — cancel the queued investigation task that fired
- // for the provider that actually failed, so the user doesn't see a
- // noisy "investigate" entry in their plan for a failure that was
- // auto-recovered. Keys must match what server/index.js's onRunFailed
- // hook published (metadata.providerName + metadata.model).
- //
- // Best-effort: a failure to load the autoFixer module or in the
- // suppress call itself must not turn a successful fallback run into
- // a user-visible error. The worst case is a stale investigation
- // task in the user's plan — the actual result still flows through.
- try {
- const noteFallbackHandled = await loadNoteFallbackHandled();
- noteFallbackHandled({
- provider: failed.name || failed.id,
- model: failedModel,
- });
- } catch (suppressErr) {
+ // Fallback succeeded — clear the primary's suppression so the user doesn't
+ // see a noisy "investigate" entry in their plan for a failure that was
+ // auto-recovered.
+ try { autoFixer?.noteFallbackHandled(fallbackKey); } catch (suppressErr) {
console.error(`❌ noteFallbackHandled failed (investigation task not suppressed): ${suppressErr.message}`);
}
@@ -400,6 +418,12 @@ async function markProviderUnavailableFromError(failed, errorMessage, runnerAnal
: analyzeError(errorMessage || '');
const category = analysis?.category || ERROR_CATEGORIES.UNKNOWN;
+ // A content/safety refusal is prompt-specific, not a provider outage — the
+ // provider is healthy and other prompts still work. Don't bench it (which
+ // would route every subsequent task to the fallback for a full cooldown);
+ // this single call still falls back via the caller's retry path.
+ if (category === ERROR_CATEGORIES.CONTENT_REFUSAL) return;
+
if (category === ERROR_CATEGORIES.USAGE_LIMIT) {
await providerStatus.markUsageLimit(failed.id, {
message: analysis.message || errorMessage,
diff --git a/server/lib/promptRunner.test.js b/server/lib/promptRunner.test.js
index d8d996f23c..9275b4bc42 100644
--- a/server/lib/promptRunner.test.js
+++ b/server/lib/promptRunner.test.js
@@ -43,7 +43,9 @@ vi.mock('../services/providers.js', () => ({
// to a spy so tests can assert it was/wasn't invoked without wiring up the
// full task system.
vi.mock('../services/autoFixer.js', () => ({
+ noteFallbackStarted: vi.fn(),
noteFallbackHandled: vi.fn(),
+ noteFallbackFailed: vi.fn(),
}));
// aiToolkitState lookups gate the retry path on a real providerStatus
@@ -59,7 +61,7 @@ const tuiRunner = await import('./tuiPromptRunner.js');
const providers = await import('../services/providers.js');
const autoFixer = await import('../services/autoFixer.js');
const toolkitState = await import('./aiToolkitState.js');
-const { runPromptThroughProvider, resolveProviderAndModel } = await import('./promptRunner.js');
+const { runPromptThroughProvider, resolveProviderAndModel, resolveEffectiveModel } = await import('./promptRunner.js');
const apiProvider = (extra = {}) => ({
id: 'mock-api', type: 'api', defaultModel: 'm-default', ...extra,
@@ -678,10 +680,17 @@ describe('promptRunner — retry-with-fallback', () => {
reason: expect.any(String),
}));
expect(status.getFallbackProvider).toHaveBeenCalledWith('primary-cli', expect.any(Object));
+ // The fallback lifecycle is announced up front (so a slow fallback can't
+ // outrun the backstop timer) and resolved on success.
+ expect(autoFixer.noteFallbackStarted).toHaveBeenCalledWith({
+ provider: 'Primary CLI',
+ model: 'primary-model',
+ });
expect(autoFixer.noteFallbackHandled).toHaveBeenCalledWith({
provider: 'Primary CLI',
model: 'primary-model',
});
+ expect(autoFixer.noteFallbackFailed).not.toHaveBeenCalled();
});
it('runs the configured fallbackModel on the fallback (never the primary model) when one is pinned', async () => {
@@ -793,8 +802,11 @@ describe('promptRunner — retry-with-fallback', () => {
source: 'test',
})).rejects.toThrow(/fallback also boom/);
- // noteFallbackHandled is reserved for SUCCESSFUL fallback — when both
- // fail the user must see both deferred investigation tasks fire.
+ // noteFallbackHandled is reserved for SUCCESSFUL fallback. When both fail,
+ // the primary's suppression is released via noteFallbackFailed (the
+ // fallback provider's own failure already queued its investigation task).
+ expect(autoFixer.noteFallbackStarted).toHaveBeenCalledWith({ provider: 'Primary CLI', model: 'primary-model' });
+ expect(autoFixer.noteFallbackFailed).toHaveBeenCalledWith({ provider: 'Primary CLI', model: 'primary-model' });
expect(autoFixer.noteFallbackHandled).not.toHaveBeenCalled();
});
@@ -1082,6 +1094,28 @@ describe('promptRunner — retry-with-fallback', () => {
});
});
+describe('resolveEffectiveModel — embedding-model skip', () => {
+ it('skips an embedding-first models list when defaultModel is null (the nomic-embed-text fallback bug)', () => {
+ // Mirrors the real Ollama provider: defaultModel null, embedding model
+ // listed first. A generation/fallback run must NOT resolve the embedding.
+ const ollama = {
+ id: 'ollama', type: 'api', defaultModel: null,
+ models: ['nomic-embed-text:latest', 'qwen3.6:35b', 'gpt-oss:20b'],
+ };
+ expect(resolveEffectiveModel(ollama, null)).toBe('qwen3.6:35b');
+ });
+
+ it('still honors an explicit defaultModel', () => {
+ const p = { id: 'ollama', type: 'api', defaultModel: 'llama3.2:latest', models: ['nomic-embed-text:latest', 'llama3.2:latest'] };
+ expect(resolveEffectiveModel(p, null)).toBe('llama3.2:latest');
+ });
+
+ it('falls back to models[0] only when every model is an embedding model', () => {
+ const p = { id: 'ollama', type: 'api', defaultModel: null, models: ['nomic-embed-text:latest', 'mxbai-embed-large'] };
+ expect(resolveEffectiveModel(p, null)).toBe('nomic-embed-text:latest');
+ });
+});
+
describe('resolveProviderAndModel', () => {
beforeEach(() => {
providers.getActiveProvider.mockReset();
diff --git a/server/services/autoFixer.js b/server/services/autoFixer.js
index be696a0c2f..a1cdb3c1a6 100644
--- a/server/services/autoFixer.js
+++ b/server/services/autoFixer.js
@@ -7,25 +7,31 @@
import { addTask, isRunning } from './cos.js';
import { errorEvents } from '../lib/errorHandler.js';
+import { ERROR_CATEGORIES } from '../lib/aiToolkit/errorDetection.js';
// Track recent errors to prevent duplicate auto-fix tasks
const recentErrors = new Map();
const ERROR_DEDUPE_WINDOW = 60000; // 1 minute
-// Defer task creation so an in-flight fallback retry (driven by
-// promptRunner.js) has a chance to handle the failure first. If
-// `noteFallbackHandled(provider, model)` fires within the window we cancel
-// the task — the user got a result via fallback and shouldn't see noise in
-// their plan. 5s covers the common case where the fallback is a fast API
-// (claude-code, codex) responding within seconds; a slower fallback whose
-// retry exceeds this window will produce both a result AND an investigation
-// task, which is acceptable (the user sees what failed and what recovered).
+// Defer task creation as a backstop for the case where NO fallback is
+// attempted (e.g. no fallback configured) — the timer fires and the
+// investigation task is created. When a fallback IS attempted, promptRunner.js
+// drives the lifecycle explicitly (noteFallbackStarted → noteFallbackHandled /
+// noteFallbackFailed), which is authoritative regardless of how long the
+// fallback takes. The fixed timer alone was a bug: a slow CLI fallback (Claude
+// Code can take 20–30s) outran the window, so a successfully-recovered failure
+// still left an investigation task in the user's plan.
const TASK_DEFER_MS = 5000;
// Invariant: every path that removes a timer here MUST also delete the
// matching map entry (the setTimeout callback, noteFallbackHandled, and
// _resetAutoFixerForTests all uphold this) — otherwise the map grows
// unbounded across the lifetime of the process.
const deferredTasks = new Map(); // errorKey -> { timer }
+// Error keys whose failure is currently being retried via a fallback. While a
+// key is in this set, the backstop timer is suppressed (we wait for the
+// fallback's real outcome). Cleared by noteFallbackHandled (success → no task)
+// and noteFallbackFailed (failure → the fallback's own task already covers it).
+const inFlightFallbacks = new Set(); // errorKey
// Store pending tasks when CoS is not running (for later pickup)
const pendingAutoFixTasks = [];
@@ -53,15 +59,49 @@ function aiProviderErrorKey(providerName, model) {
*/
export function noteFallbackHandled({ provider, model }) {
const errorKey = aiProviderErrorKey(provider, model);
+ inFlightFallbacks.delete(errorKey);
const pending = deferredTasks.get(errorKey);
if (pending) {
clearTimeout(pending.timer);
deferredTasks.delete(errorKey);
- recentErrors.delete(errorKey);
console.log(`✅ Suppressed investigation task: fallback handled failure for ${provider} (${model})`);
- return true;
}
- return false;
+ // Always clear the dedupe entry — whether or not there was a timer to cancel
+ // (noteFallbackStarted may have already cancelled it) — so a *future*
+ // identical failure can still raise a task.
+ recentErrors.delete(errorKey);
+ return !!pending;
+}
+
+/**
+ * Mark that promptRunner is about to retry `provider`/`model` via a fallback.
+ * Cancels the deferred investigation task immediately and suppresses any that
+ * would otherwise be scheduled (handleAIProviderError checks the in-flight set),
+ * so a slow fallback that exceeds TASK_DEFER_MS can't leave a task behind. The
+ * fallback's eventual outcome (noteFallbackHandled / noteFallbackFailed) clears
+ * the in-flight marker.
+ */
+export function noteFallbackStarted({ provider, model }) {
+ const errorKey = aiProviderErrorKey(provider, model);
+ inFlightFallbacks.add(errorKey);
+ const pending = deferredTasks.get(errorKey);
+ if (pending) {
+ clearTimeout(pending.timer);
+ deferredTasks.delete(errorKey);
+ }
+}
+
+/**
+ * Mark that the fallback retry for `provider`/`model` ALSO failed. Releases the
+ * in-flight suppression without creating a task for the primary: the fallback
+ * provider's own failure already queued its investigation task, so one task per
+ * user action is enough. Also clears the dedupe entry so a later retry isn't
+ * silently suppressed.
+ */
+export function noteFallbackFailed({ provider, model }) {
+ const errorKey = aiProviderErrorKey(provider, model);
+ inFlightFallbacks.delete(errorKey);
+ recentErrors.delete(errorKey);
}
/**
@@ -135,6 +175,7 @@ export function clearPendingAutoFixTasks() {
export function _resetAutoFixerForTests() {
for (const { timer } of deferredTasks.values()) clearTimeout(timer);
deferredTasks.clear();
+ inFlightFallbacks.clear();
recentErrors.clear();
pendingAutoFixTasks.length = 0;
}
@@ -147,8 +188,28 @@ export function _resetAutoFixerForTests() {
*/
async function handleAIProviderError(error) {
const ctx = error.context || {};
+
+ // A content/safety refusal is not a provider fault — we know exactly why it
+ // failed (the model declined the prompt), so there's nothing for a CoS agent
+ // to investigate. promptRunner.js already retries with a fallback and the UI
+ // is told what happened. Bail before deferring/creating a task. (server's
+ // onRunFailed already emits a distinct code for refusals so this handler
+ // normally isn't even reached; this guard covers any other emitter.)
+ if (ctx.errorAnalysis?.category === ERROR_CATEGORIES.CONTENT_REFUSAL) {
+ console.log(`🛟 AI model refused prompt on content/safety grounds: ${ctx.provider} (${ctx.model}) — no investigation task (fallback handles it)`);
+ return;
+ }
+
const errorKey = aiProviderErrorKey(ctx.provider, ctx.model);
+ // A fallback retry for this exact failure is already in flight (promptRunner
+ // called noteFallbackStarted). Don't schedule the backstop timer — the
+ // fallback's outcome decides whether to investigate. This covers the case
+ // where the fallback started before this handler ran (microtask ordering).
+ if (inFlightFallbacks.has(errorKey)) {
+ return;
+ }
+
if (isDuplicateError(errorKey)) {
console.log(`⏭️ Skipping duplicate AI provider error: ${ctx.provider} (${ctx.model})`);
return;
diff --git a/server/services/autoFixer.test.js b/server/services/autoFixer.test.js
index 313759fb23..8a54e19a80 100644
--- a/server/services/autoFixer.test.js
+++ b/server/services/autoFixer.test.js
@@ -70,6 +70,68 @@ describe('autoFixer — defer + noteFallbackHandled', () => {
});
});
+ it('never creates an investigation task for a content/safety refusal', async () => {
+ // A refusal is self-explanatory (the model declined the prompt) — there's
+ // nothing for a CoS agent to investigate, and the fallback path handles
+ // recovery. Even if the failure arrives via AI_PROVIDER_EXECUTION_FAILED
+ // with refusal analysis, the guard must suppress the task.
+ errorEvents.emit('error', {
+ code: 'AI_PROVIDER_EXECUTION_FAILED',
+ message: 'AI provider Codex CLI execution failed: content refused',
+ severity: 'error',
+ canAutoFix: true,
+ timestamp: Date.now(),
+ context: {
+ runId: 'run-refuse', provider: 'Codex CLI', providerId: 'codex', model: 'm-1',
+ errorAnalysis: { category: 'content-refusal' },
+ },
+ });
+ await vi.advanceTimersByTimeAsync(6000);
+ expect(cos.addTask).not.toHaveBeenCalled();
+ });
+
+ it('suppresses the task for a SLOW fallback that finishes after the defer window', async () => {
+ // The bug this fixes: a CLI fallback (Claude Code) can take 20–30s, far
+ // longer than TASK_DEFER_MS. noteFallbackStarted cancels the backstop timer
+ // immediately, so even though the success notice arrives late, no task fires.
+ const { noteFallbackStarted } = await import('./autoFixer.js');
+ emitProviderFailure({ provider: 'Ollama', model: 'command-r' });
+ await vi.advanceTimersByTimeAsync(0);
+
+ // Fallback starts almost immediately — cancels the deferred task.
+ noteFallbackStarted({ provider: 'Ollama', model: 'command-r' });
+
+ // The backstop window elapses with the fallback still running — no task.
+ await vi.advanceTimersByTimeAsync(6000);
+ expect(cos.addTask).not.toHaveBeenCalled();
+
+ // Fallback finally succeeds ~25s later — still no task.
+ noteFallbackHandled({ provider: 'Ollama', model: 'command-r' });
+ await vi.advanceTimersByTimeAsync(25000);
+ expect(cos.addTask).not.toHaveBeenCalled();
+ });
+
+ it('suppresses the task even when noteFallbackStarted races ahead of the error event', async () => {
+ // Microtask-ordering guard: if the fallback is announced before the error
+ // handler schedules its timer, the in-flight set still suppresses it.
+ const { noteFallbackStarted } = await import('./autoFixer.js');
+ noteFallbackStarted({ provider: 'Ollama', model: 'command-r' });
+ emitProviderFailure({ provider: 'Ollama', model: 'command-r' });
+ await vi.advanceTimersByTimeAsync(6000);
+ expect(cos.addTask).not.toHaveBeenCalled();
+ });
+
+ it('noteFallbackFailed releases suppression so a later identical failure can raise a task', async () => {
+ const { noteFallbackStarted, noteFallbackFailed } = await import('./autoFixer.js');
+ noteFallbackStarted({ provider: 'Ollama', model: 'command-r' });
+ noteFallbackFailed({ provider: 'Ollama', model: 'command-r' });
+
+ // A fresh failure with no fallback in flight now schedules + fires a task.
+ emitProviderFailure({ provider: 'Ollama', model: 'command-r' });
+ await vi.advanceTimersByTimeAsync(6000);
+ expect(cos.addTask).toHaveBeenCalledTimes(1);
+ });
+
it('cancels the deferred task when noteFallbackHandled fires within the window', async () => {
emitProviderFailure({ provider: 'Primary CLI', model: 'm-1' });
await vi.advanceTimersByTimeAsync(0);
diff --git a/server/services/localLlm.js b/server/services/localLlm.js
index 376f90a412..a5bbf0e0e6 100644
--- a/server/services/localLlm.js
+++ b/server/services/localLlm.js
@@ -31,6 +31,7 @@ import { Readable } from 'stream'
import { PATHS, atomicWrite } from '../lib/fileUtils.js'
import { isBackend, mapModelToBackend } from '../lib/localLlmCatalog.js'
import { sanitizeOllamaName } from '../lib/localLlmDisk.js'
+import { recommendEditorialModel } from '../lib/localModelHeuristics.js'
import * as ollamaManager from './ollamaManager.js'
import * as lmStudioManager from './lmStudioManager.js'
import { getProviderById, updateProvider } from './providers.js'
@@ -545,12 +546,14 @@ function normalizeModels(backend, models) {
if (backend === 'ollama') {
return models.map((m) => ({
id: m.id, name: m.name, size: m.size ?? null,
- params: m.params || null, quantization: m.quantization || null, family: m.family || null
+ params: m.params || null, quantization: m.quantization || null, family: m.family || null,
+ contextLength: m.contextLength ?? null
}))
}
return models.map((m) => ({
id: m.id, name: m.id, size: null,
- params: null, quantization: m.quantization || null, family: m.arch || null
+ params: null, quantization: m.quantization || null, family: m.arch || null,
+ contextLength: m.maxContextLength ?? null
}))
}
@@ -582,6 +585,8 @@ export async function getStatus() {
listModels('lmstudio', true).catch(() => [])
])
+ const ollamaModels = normalizeModels('ollama', ollamaStatus.models)
+ const lmStudioRecommendation = recommendEditorialModel(lmStudioModels)
return {
backend: getBackend(),
ollama: {
@@ -590,7 +595,10 @@ export async function getStatus() {
version: ollamaStatus.version,
baseUrl: ollamaStatus.baseUrl,
modelCount: ollamaStatus.modelCount,
- models: normalizeModels('ollama', ollamaStatus.models),
+ models: ollamaModels,
+ // Best installed model for editorial review/editing, surfaced so the
+ // manuscript editor can suggest it (and warn against the embedding model).
+ recommendations: { editorial: recommendEditorialModel(ollamaModels) },
canControl: ollamaCli || ollamaStatus.available,
service: ollamaStatus.service,
canAutoInstall: canAutoInstall('ollama'),
@@ -604,6 +612,7 @@ export async function getStatus() {
baseUrl: lmStudioStatus.baseUrl,
modelCount: lmStudioModels.length,
models: lmStudioModels,
+ recommendations: { editorial: lmStudioRecommendation },
// Non-null when LM Studio answered the availability probe but the model
// list call failed — lets the UI tell "0 models" from "couldn't list".
modelsError: lmStudioManager.getLastListError(),
diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.js
index 4ddf7c3b20..d5478db04b 100644
--- a/server/services/ollamaManager.js
+++ b/server/services/ollamaManager.js
@@ -25,6 +25,7 @@ import { readJSONFile, sha256File } from '../lib/fileUtils.js'
import {
parseOllamaManifest, parseOllamaModelRef, ollamaManifestRelPath, digestToBlobFilename, buildModelfile
} from '../lib/localLlmDisk.js'
+import { isEmbeddingModel } from '../lib/localModelHeuristics.js'
const execFileAsync = promisify(execFile)
const AVAILABILITY_CACHE_TTL_MS = 30_000
@@ -420,6 +421,43 @@ async function getVersion() {
return data?.version || null
}
+// A model's native context length is immutable for a given build, but Ollama's
+// /api/tags listing doesn't include it — only /api/show does (one POST per
+// model). Cache name → contextLength so enriching the model list on every
+// status poll doesn't re-hit /api/show. Busted alongside installedModels on
+// delete (a deleted name shouldn't linger), but a re-pull of the same name
+// yields the same value so we don't bust on pull.
+const modelContextCache = new Map() // name -> number|null
+
+/**
+ * Fetch a model's native maximum context length (in tokens) via /api/show.
+ * Ollama nests it under `model_info["<arch>.context_length"]`; the arch prefix
+ * varies by family so we scan for the suffix. Cached; returns null when the
+ * daemon doesn't report it.
+ * @param {string} name
+ * @returns {Promise<number|null>}
+ */
+async function getModelContextLength(name) {
+ if (!name) return null
+ if (modelContextCache.has(name)) return modelContextCache.get(name)
+ const data = await ollamaRequest('/api/show', { method: 'POST', body: JSON.stringify({ name }) }).catch(() => null)
+ const info = data?.model_info || {}
+ let ctx = null
+ for (const [key, value] of Object.entries(info)) {
+ if (key.endsWith('.context_length') && Number.isFinite(value)) { ctx = value; break }
+ }
+ modelContextCache.set(name, ctx)
+ return ctx
+}
+
+/** Add `contextLength` to each model (parallel, cached). */
+async function enrichWithContextLength(models) {
+ return Promise.all(models.map(async (m) => ({
+ ...m,
+ contextLength: await getModelContextLength(m.id || m.name)
+ })))
+}
+
/**
* Get embeddings for `text` from a loaded Ollama model.
*
@@ -444,7 +482,7 @@ async function getEmbeddings(text, options = {}) {
let model = options.model
if (!model) {
const models = await getInstalledModels()
- const guess = models.find((m) => /embed|bge|nomic|mxbai|gte|e5/i.test(m.id || m.name || ''))
+ const guess = models.find((m) => isEmbeddingModel(m.id || m.name || ''))
if (!guess) {
return { success: false, error: 'No embedding model installed in Ollama' }
}
@@ -732,6 +770,7 @@ async function deleteModel(modelId) {
return { success: false, error: result._err, modelId }
}
installedModels = null
+ modelContextCache.delete(modelId)
console.log(`🗑️ Ollama deleted: ${modelId}`)
return { success: true, modelId }
}
@@ -848,7 +887,10 @@ function getBaseUrl() {
*/
async function getStatus(forceRefresh = false) {
const available = await checkOllamaAvailable(forceRefresh)
- const models = available ? await getInstalledModels(true) : []
+ const baseModels = available ? await getInstalledModels(true) : []
+ // Enrich with native context length (cached /api/show per model) so the
+ // model cards + selector dropdowns can show each model's window.
+ const models = available ? await enrichWithContextLength(baseModels) : baseModels
const service = await getServiceStatus().catch(() => ({ supported: false, manager: null, running: false, runAtStartup: false, status: null }))
return {
available,