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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
self-heal a wrong Ollama/LM Studio model default instead of failing the run
[._.]/ Adam Eivyab6d418ffca7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 9368838cd8..2092278527 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -102,6 +102,10 @@- **[issue-1615] Series Autopilot now actively notifies you when a run pauses, instead of going silent until you check the status page.** A paused run (budget exhausted, too many High findings, a convergence gate that couldn't auto-resolve, a failed child stage) previously only emitted a live SSE frame — so if you weren't watching the page, the run could sit indefinitely. Every pause now also posts an in-app notification (in the header notification center) with the pause reason and a one-click resume link to the series. A prior pause banner for the same series is cleared first, so a resume→pause cycle leaves exactly one current notification rather than a stack. This is the one autopilot signal that's **on by default** — it's a zero-cost informational banner — but it's overridable per run and via a persisted setting (`pipelineEditorialChecks.notifyOnPause`) and exposed as a "Notify me when a run pauses" checkbox in Options. (`server/services/pipeline/seriesAutopilot.js`, `server/services/notifications.js`, `server/lib/validation.js`, `server/routes/pipeline/autopilot.js`, `client/src/components/pipeline/AutopilotPanel.jsx`)- **[issue-1617] Stopping a Series Autopilot run now gives you immediate feedback instead of looking frozen mid-step.** Cancellation is cooperative — it's honored between steps, so a Stop pressed during a long LLM call was only acted on once that call returned, with no acknowledgement in between. The server now emits a `cancel:acknowledged` SSE frame the instant you press Stop; the button switches to a disabled "Cancelling…" spinner and the live status reads "finishing the active step…" until the run unwinds and the terminal frame lands. The active step still finishes first (no mid-stream interruption) — this is purely the missing acknowledgement, now documented on the cancel route. (`server/services/pipeline/seriesAutopilot.js`, `server/routes/pipeline/autopilot.js`, `client/src/components/pipeline/AutopilotPanel.jsx`)+## AI Providers++- **A wrong local-model default now self-corrects instead of failing the run.** When an Ollama or LM Studio provider is pointed at a model that isn't actually installed (a stale or mis-typed `defaultModel`, or a model you've since deleted), an API call against it returned a dead-end "model not found" — the user had to notice, open settings, and pick a real model by hand. The shared `callProviderAISimple` path now catches that error, lists the backend's actually-installed models, picks the best fit (the editorial recommender's family/size ranking, skipping embedding-only weights), repoints the provider's `defaultModel` (and any tier slot pointing at a missing model), tells the user via a low-priority notification + activity log, and retries the call once — so the run succeeds and the bad config is fixed going forward. Remote/API and CLI providers are left untouched, since their installed models can't be enumerated. (`server/services/localModelHealing.js`, `server/lib/aiProvider.js`)+## Internal- **[issue-1627] Editorial checks can now share findings within a single run.** An editorial check may declare `dependsOn: [<checkId>...]`; the runner topologically orders the pass so declared dependencies run first and injects their findings into the dependent's `ctx.priorFindings` (+ `ctx.findingsByCheck(id)`), scoped to declared deps and frozen. This is the architecture for compound signals (a finding that references another check's finding); no check uses it yet, and a pass where nothing declares a dependency keeps the exact prior run order. Checks that declare no dependency stay pure functions of their `sources`. (`server/services/pipeline/editorial/checkRunner.js`, `server/lib/editorial/checkRegistry.js`)diff --git a/server/lib/aiProvider.js b/server/lib/aiProvider.jsindex da11c29c5c..6a012169a4 100644--- a/server/lib/aiProvider.js+++ b/server/lib/aiProvider.js@@ -6,6 +6,7 @@import { getAllProviders } from '../services/providers.js';import { startAIOp } from '../services/aiStatusEvents.js';import { ensureProviderReady as ensureOllamaProviderReady, isOllamaProvider } from '../services/ollamaManager.js';+import { healMissingLocalModel, isModelNotFoundError } from '../services/localModelHealing.js';import { readResponseJson } from './readResponseJson.js';const isAPI = (p) => p && p.type === 'api' && p.enabled !== false;@@ -243,19 +244,40 @@ export async function callProviderAISimple(provider, model, prompt, options = {}return { text: first.text };}+ // Recover by retrying the call against `retryModel` (already loaded/healed),+ // reporting completion or error under that model id. Shared by both local+ // recovery paths below, which differ only in how they pick `retryModel`.+ const retryWith = async (retryModel) => {+ const retry = await postChatCompletion(provider, retryModel, prompt, opts);+ if (!retry.error) {+ statusOp.complete(`${doneLabel} done (${elapsedSec()}s)`, { model: retryModel, ...throughput(retry.tokens) });+ return { text: retry.text };+ }+ statusOp.error(retry.error, { model: retryModel });+ return { error: retry.error };+ };+if (first.status === 400 && LM_STUDIO_NO_MODEL_RE.test(first.body || '')) {const loaded = await ensureLMStudioModelLoaded(provider, statusOp);if (loaded) {statusOp.update('start', `Calling ${provider.name || provider.id} (${loaded})…`, { model: loaded });- const retry = await postChatCompletion(provider, loaded, prompt, opts);- if (!retry.error) {- statusOp.complete(`${doneLabel} done (${elapsedSec()}s)`, { model: loaded, ...throughput(retry.tokens) });- return { text: retry.text };- }- statusOp.error(retry.error, { model: loaded });- return { error: retry.error };+ return retryWith(loaded);}}++ // The configured model isn't installed on the local backend (e.g. a stale or+ // mis-typed provider default). Auto-pick a real installed model, repoint the+ // provider, tell the user, and retry once — instead of surfacing a dead-end+ // "model not found". Only fires for Ollama / LM Studio providers; healing is+ // a no-op (returns null) for remote/CLI providers, leaving the error as-is.+ if (isModelNotFoundError(first.body || first.error)) {+ const healed = await healMissingLocalModel({ provider, requestedModel: model }).catch(() => null);+ if (healed) {+ statusOp.update('model:corrected', `"${model}" isn't installed — retrying with ${healed.model}…`, { model: healed.model });+ return retryWith(healed.model);+ }+ }+statusOp.error(first.error);return { error: first.error };}diff --git a/server/services/localModelHealing.js b/server/services/localModelHealing.jsnew file mode 100644index 0000000000..75fc20eca9--- /dev/null+++ b/server/services/localModelHealing.js@@ -0,0 +1,150 @@+/**+ * Self-heal a wrong local-model configuration.+ *+ * When a run targets an Ollama or LM Studio model that isn't actually installed+ * (typically a stale or mis-typed provider default), surfacing a raw "model not+ * found" is a dead end on a single-user box — the fix is mechanical: pick a real+ * installed model, repoint the provider so future runs use it, tell the user+ * what changed, and let the caller retry. This module owns that recovery so any+ * local-backend call path can adopt it instead of throwing.+ *+ * Only applies to the two local backends (Ollama / LM Studio). Remote/API and+ * CLI providers return null from `localBackendForProvider` and are left alone —+ * we can't enumerate their installed models, and their "model not found" is a+ * config error the user must fix deliberately.+ */++import { emitLog } from './cosEvents.js';+import { updateProvider } from './providers.js';+import { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } from './notifications.js';+import * as ollamaManager from './ollamaManager.js';+import * as lmStudioManager from './lmStudioManager.js';+import { recommendEditorialModel, isEmbeddingModel } from '../lib/localModelHeuristics.js';++// LM Studio's default OpenAI-compatible port; Ollama's is recognized by+// ollamaManager.isOllamaProvider. Matches `:1234` as host:port (with optional+// trailing path/colon) so a relocated install on the same port still resolves.+const LM_STUDIO_PORT_RE = /(^|[/:])(?:localhost|127\.0\.0\.1|\[::1\]):1234\b/i;++// A backend "model not found" — Ollama answers 404 `model "x" not found, try+// pulling it first`; LM Studio answers `model "x" not found`/`unknown model`.+// Deliberately does NOT match "no models loaded" (a load problem with its own+// recovery in aiProvider.js — auto-loading a downloaded model, not swapping the+// configured one).+const MODEL_NOT_FOUND_RE = /model\s*['"]?[\w./:-]*['"]?\s*(?:not found|does not exist|is not (?:found|installed|available))|not found, try pulling|unknown model|no such model/i;+const NO_MODELS_LOADED_RE = /no models loaded/i;++/**+ * Which local backend (if any) a provider maps to.+ * @returns {'ollama'|'lmstudio'|null}+ */+export function localBackendForProvider(provider) {+ if (ollamaManager.isOllamaProvider(provider)) return 'ollama';+ const endpoint = String(provider?.endpoint || '');+ if (provider?.id === 'lmstudio' || /lm[\s-]?studio/i.test(provider?.name || '') || LM_STUDIO_PORT_RE.test(endpoint)) {+ return 'lmstudio';+ }+ return null;+}++/**+ * True when an error string is a backend "configured model isn't installed"+ * failure (vs. "no models loaded", which is a separate recovery).+ */+export function isModelNotFoundError(text) {+ const s = String(text || '');+ if (NO_MODELS_LOADED_RE.test(s)) return false;+ return MODEL_NOT_FOUND_RE.test(s);+}++/**+ * Pick the best installed model to fall back to. Prefers the editorial+ * recommender (family + size ranking, already drops embeddings/media weights);+ * if it finds nothing usable, takes the first non-embedding model, then any —+ * embeddings can't serve a chat completion, so never auto-pick one.+ * @returns {string|null}+ */+export function chooseFallbackModel(models) {+ const recommended = recommendEditorialModel(models);+ if (recommended?.id) return recommended.id;+ const usable = (models || []).find((m) => m?.id && !isEmbeddingModel(m.id));+ return usable?.id || (models || [])[0]?.id || null;+}++/**+ * The provider patch that repoints a wrong config onto an installed model:+ * fixes the default when it's the missing model or otherwise not installed,+ * repoints any tier slot pointing at an uninstalled model, and ensures the+ * fallback is selectable in the model list. Pure — no I/O — so it's unit-tested.+ */+export function computeProviderPatch(provider, installedIds, fallback, requestedModel) {+ const installed = new Set(installedIds);+ const patch = {};+ if (provider?.defaultModel === requestedModel || !installed.has(provider?.defaultModel)) {+ patch.defaultModel = fallback;+ }+ for (const tier of ['lightModel', 'mediumModel', 'heavyModel']) {+ const v = provider?.[tier];+ if (v && !installed.has(v)) patch[tier] = fallback;+ }+ const models = Array.isArray(provider?.models) ? provider.models : [];+ if (!models.includes(fallback)) patch.models = [...models, fallback];+ return patch;+}++// Installed models that can actually serve a chat completion, freshly listed+// (the configured model may have just been deleted, so bypass the cache).+async function listInstalledChatModels(backend) {+ if (backend === 'ollama') {+ const models = await ollamaManager.getInstalledModels(true).catch(() => []);+ // /api/tags doesn't tag embeddings — drop obvious embedding ids by name.+ return models.filter((m) => m?.id && !isEmbeddingModel(m.id));+ }+ const models = await lmStudioManager.getAvailableModels(true).catch(() => []);+ // LM Studio tags embedding models `type: 'embeddings'`.+ return models.filter((m) => m?.id && m.type !== 'embeddings');+}++/**+ * Repoint a local provider off a missing model onto a real installed one,+ * persist the change, and notify the user. Returns `{ healed, backend, model,+ * previous, patch }` on success, or null when nothing could be (or needed to+ * be) healed — not a local backend, the requested model is actually installed,+ * or nothing installable exists to fall back to.+ *+ * @param {{ provider: object, requestedModel?: string|null }} args+ */+export async function healMissingLocalModel({ provider, requestedModel }) {+ const backend = localBackendForProvider(provider);+ if (!backend) return null;++ const installed = await listInstalledChatModels(backend);+ if (!installed.length) return null; // nothing installed — can't self-heal++ const installedIds = installed.map((m) => m.id);+ if (requestedModel && installedIds.includes(requestedModel)) return null; // present after all++ const fallback = chooseFallbackModel(installed);+ if (!fallback || fallback === requestedModel) return null;++ const patch = computeProviderPatch(provider, installedIds, fallback, requestedModel);+ if (provider?.id && Object.keys(patch).length) {+ await updateProvider(provider.id, patch).catch((err) => {+ console.error(`⚠️ Failed to repoint ${provider.id} to ${fallback}: ${err.message}`);+ });+ }++ const label = backend === 'ollama' ? 'Ollama' : 'LM Studio';+ const had = requestedModel ? `"${requestedModel}" isn't installed` : 'no model was configured';+ const message = `${label} model ${had} — switched to "${fallback}" and updated the provider default.`;+ emitLog('warn', message, { providerId: provider?.id, backend, requestedModel: requestedModel || null, fallbackModel: fallback });+ await addNotification({+ type: NOTIFICATION_TYPES.AGENT_WARNING,+ title: 'Local model auto-corrected',+ description: message,+ priority: PRIORITY_LEVELS.LOW,+ metadata: { providerId: provider?.id, backend, requestedModel: requestedModel || null, fallbackModel: fallback }+ }).catch((err) => console.error(`⚠️ heal notification failed: ${err.message}`));++ return { healed: true, backend, model: fallback, previous: requestedModel || null, patch };+}diff --git a/server/services/localModelHealing.test.js b/server/services/localModelHealing.test.jsnew file mode 100644index 0000000000..bfebce57c8--- /dev/null+++ b/server/services/localModelHealing.test.js@@ -0,0 +1,173 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++const mocks = vi.hoisted(() => ({+ updateProvider: vi.fn(async () => ({ success: true })),+ addNotification: vi.fn(async () => ({})),+ emitLog: vi.fn(),+ ollamaInstalled: vi.fn(async () => []),+ lmStudioAvailable: vi.fn(async () => [])+}));++vi.mock('./cosEvents.js', () => ({ emitLog: mocks.emitLog }));+vi.mock('./providers.js', () => ({ updateProvider: mocks.updateProvider }));+vi.mock('./notifications.js', () => ({+ addNotification: mocks.addNotification,+ NOTIFICATION_TYPES: { AGENT_WARNING: 'agent_warning' },+ PRIORITY_LEVELS: { LOW: 'low' }+}));+vi.mock('./ollamaManager.js', () => ({+ getInstalledModels: mocks.ollamaInstalled,+ // Mirror the real predicate so localBackendForProvider classifies correctly.+ isOllamaProvider: (p) => p?.id === 'ollama' ||+ /ollama/i.test(p?.name || '') ||+ /(^|[/:])(?:localhost|127\.0\.0\.1|\[::1\]):11434\b/i.test(String(p?.endpoint || ''))+}));+vi.mock('./lmStudioManager.js', () => ({ getAvailableModels: mocks.lmStudioAvailable }));++const {+ localBackendForProvider,+ isModelNotFoundError,+ chooseFallbackModel,+ computeProviderPatch,+ healMissingLocalModel+} = await import('./localModelHealing.js');++beforeEach(() => {+ vi.clearAllMocks();+ mocks.updateProvider.mockResolvedValue({ success: true });+ mocks.addNotification.mockResolvedValue({});+ mocks.ollamaInstalled.mockResolvedValue([]);+ mocks.lmStudioAvailable.mockResolvedValue([]);+});++describe('localBackendForProvider', () => {+ it('classifies Ollama by id, name, and port', () => {+ expect(localBackendForProvider({ id: 'ollama' })).toBe('ollama');+ expect(localBackendForProvider({ name: 'My Ollama' })).toBe('ollama');+ expect(localBackendForProvider({ endpoint: 'http://localhost:11434/v1' })).toBe('ollama');+ });++ it('classifies LM Studio by id, name, and port', () => {+ expect(localBackendForProvider({ id: 'lmstudio' })).toBe('lmstudio');+ expect(localBackendForProvider({ name: 'LM Studio' })).toBe('lmstudio');+ expect(localBackendForProvider({ name: 'lm-studio' })).toBe('lmstudio');+ expect(localBackendForProvider({ endpoint: 'http://127.0.0.1:1234/v1' })).toBe('lmstudio');+ });++ it('returns null for remote/CLI providers', () => {+ expect(localBackendForProvider({ id: 'anthropic', endpoint: 'https://api.anthropic.com/v1' })).toBeNull();+ expect(localBackendForProvider({ id: 'claude-code' })).toBeNull();+ expect(localBackendForProvider(null)).toBeNull();+ });+});++describe('isModelNotFoundError', () => {+ it('matches Ollama and LM Studio not-found messages', () => {+ expect(isModelNotFoundError('model "llama3" not found, try pulling it first')).toBe(true);+ expect(isModelNotFoundError('Provider returned 404: model \'foo\' not found')).toBe(true);+ expect(isModelNotFoundError('unknown model bar')).toBe(true);+ expect(isModelNotFoundError('model qwen does not exist')).toBe(true);+ });++ it('does NOT match "no models loaded" (separate recovery)', () => {+ expect(isModelNotFoundError('No models loaded')).toBe(false);+ });++ it('does not match unrelated errors', () => {+ expect(isModelNotFoundError('connection refused')).toBe(false);+ expect(isModelNotFoundError('')).toBe(false);+ expect(isModelNotFoundError(null)).toBe(false);+ });+});++describe('chooseFallbackModel', () => {+ it('prefers the editorial recommender', () => {+ const id = chooseFallbackModel([{ id: 'tiny:1b' }, { id: 'llama3.1:70b', params: '70B' }]);+ expect(id).toBe('llama3.1:70b');+ });++ it('falls back to the first non-embedding model when nothing ranks', () => {+ // recommendEditorialModel drops embeddings; chooseFallbackModel must too.+ const id = chooseFallbackModel([{ id: 'nomic-embed-text' }, { id: 'mystery-model' }]);+ expect(id).toBe('mystery-model');+ });++ it('returns null when given nothing', () => {+ expect(chooseFallbackModel([])).toBeNull();+ expect(chooseFallbackModel(null)).toBeNull();+ });+});++describe('computeProviderPatch', () => {+ it('repoints the default when it is the missing model', () => {+ const provider = { defaultModel: 'gone', models: ['gone'] };+ const patch = computeProviderPatch(provider, ['real'], 'real', 'gone');+ expect(patch.defaultModel).toBe('real');+ expect(patch.models).toEqual(['gone', 'real']);+ });++ it('repoints tier slots that point at uninstalled models', () => {+ const provider = { defaultModel: 'real', lightModel: 'gone', mediumModel: 'real', heavyModel: 'also-gone', models: ['real'] };+ const patch = computeProviderPatch(provider, ['real'], 'real', 'gone');+ expect(patch.lightModel).toBe('real');+ expect(patch.heavyModel).toBe('real');+ expect(patch.mediumModel).toBeUndefined(); // installed — left alone+ expect(patch.defaultModel).toBeUndefined(); // installed — left alone+ });++ it('does not duplicate the fallback in the models list', () => {+ const provider = { defaultModel: 'gone', models: ['gone', 'real'] };+ const patch = computeProviderPatch(provider, ['real'], 'real', 'gone');+ expect(patch.models).toBeUndefined();+ });+});++describe('healMissingLocalModel', () => {+ it('returns null for non-local providers (no enumeration possible)', async () => {+ const result = await healMissingLocalModel({ provider: { id: 'anthropic' }, requestedModel: 'claude-x' });+ expect(result).toBeNull();+ expect(mocks.updateProvider).not.toHaveBeenCalled();+ });++ it('returns null when nothing is installed to fall back to', async () => {+ mocks.ollamaInstalled.mockResolvedValue([]);+ const result = await healMissingLocalModel({ provider: { id: 'ollama', defaultModel: 'gone' }, requestedModel: 'gone' });+ expect(result).toBeNull();+ });++ it('returns null when the requested model is actually installed', async () => {+ mocks.ollamaInstalled.mockResolvedValue([{ id: 'llama3.1:8b' }]);+ const result = await healMissingLocalModel({ provider: { id: 'ollama', defaultModel: 'llama3.1:8b' }, requestedModel: 'llama3.1:8b' });+ expect(result).toBeNull();+ expect(mocks.updateProvider).not.toHaveBeenCalled();+ });++ it('repoints Ollama, persists, and notifies when the model is missing', async () => {+ mocks.ollamaInstalled.mockResolvedValue([{ id: 'llama3.1:70b', params: '70B' }, { id: 'tiny:1b' }]);+ const provider = { id: 'ollama', defaultModel: 'gone', models: ['gone'] };+ const result = await healMissingLocalModel({ provider, requestedModel: 'gone' });++ expect(result).toMatchObject({ healed: true, backend: 'ollama', model: 'llama3.1:70b', previous: 'gone' });+ expect(mocks.updateProvider).toHaveBeenCalledWith('ollama', expect.objectContaining({ defaultModel: 'llama3.1:70b' }));+ expect(mocks.addNotification).toHaveBeenCalledWith(expect.objectContaining({ type: 'agent_warning' }));+ expect(mocks.emitLog).toHaveBeenCalledWith('warn', expect.stringContaining('llama3.1:70b'), expect.any(Object));+ });++ it('excludes LM Studio embedding models from the fallback pick', async () => {+ mocks.lmStudioAvailable.mockResolvedValue([+ { id: 'nomic-embed', type: 'embeddings' },+ { id: 'qwen2.5-7b-instruct', type: 'llm' }+ ]);+ const provider = { id: 'lmstudio', endpoint: 'http://localhost:1234/v1', defaultModel: 'gone', models: [] };+ const result = await healMissingLocalModel({ provider, requestedModel: 'gone' });+ expect(result.model).toBe('qwen2.5-7b-instruct');+ });++ it('still returns the heal result when persistence fails (best-effort)', async () => {+ mocks.ollamaInstalled.mockResolvedValue([{ id: 'llama3.1:8b' }]);+ mocks.updateProvider.mockRejectedValue(new Error('disk full'));+ const provider = { id: 'ollama', defaultModel: 'gone', models: [] };+ const result = await healMissingLocalModel({ provider, requestedModel: 'gone' });+ expect(result).toMatchObject({ healed: true, model: 'llama3.1:8b' });+ });+});