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

fix: stop rejecting a local model pin that the daemon is already serving (#6151)

Adam Eivya1ac6691f905
diff --git a/server/lib/cliProviderRun.js b/server/lib/cliProviderRun.js
index 2a5010d53e..fb1c2f3dee 100644
--- a/server/lib/cliProviderRun.js
+++ b/server/lib/cliProviderRun.js
@@ -7,9 +7,10 @@
* process and the Google Calendar MCP sync — stop hardcoding `claude -p` and
* instead honor the configured provider/model like every other AI call.
*
- * Imports only node builtins + the pure arg builder, so the separate-process
- * autofixer (its own minimal package, only `express` installed) can import it
- * without dragging in the AI toolkit or data layer.
+ * Imports only node builtins + pure `server/lib` helpers (the arg builder and
+ * the local-runtime classifier), so the separate-process autofixer (its own
+ * minimal package, only `express` installed) can import it without dragging in
+ * the AI toolkit or data layer.
*
* For full-featured in-process runs (fallback chains, run records, SSE) use
* `runPromptThroughProvider` in `promptRunner.js` instead. This helper is the
@@ -20,6 +21,7 @@ import { spawn } from './childProcess.js';
import { buildCliArgs, prepareCliPrompt } from './cliProviderArgs.js';
import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn, guardChildStdin } from './bufferedSpawn.js';
import { buildCliChildEnv } from './cliChildEnv.js';
+import { modelPinIsOffered } from './localProviderRuntime.js';
// How much stderr to hand back to callers. Enough to carry a rate-limit banner
// or a stack's first frames, short enough to embed in an error message or a
@@ -58,8 +60,11 @@ export function pickCliProvider(providers, config = {}) {
// Honor the requested model only when the provider actually offers it;
// otherwise fall back to the provider's own default so a stale stored model
// (e.g. left over from a different provider) can't pin a nonexistent id.
- const offered = Array.isArray(provider.models) ? provider.models : [];
- const resolvedModel = model && offered.includes(model) ? model : (provider.defaultModel || null);
+ // `modelPinIsOffered` owns that rule — including the two pass-throughs a bare
+ // `includes` gets wrong: a provider that enumerates NO models has nothing to
+ // validate against, and a locally-backed one carries only a cached snapshot
+ // while the daemon on this machine is the authority.
+ const resolvedModel = model && modelPinIsOffered(provider, model) ? model : (provider.defaultModel || null);
return { provider, model: resolvedModel };
}
diff --git a/server/lib/cliProviderRun.test.js b/server/lib/cliProviderRun.test.js
index 801ceec692..494064dae9 100644
--- a/server/lib/cliProviderRun.test.js
+++ b/server/lib/cliProviderRun.test.js
@@ -74,6 +74,26 @@ describe('pickCliProvider', () => {
const result = pickCliProvider({ ollama: providers.ollama }, {});
expect(result.error).toMatch(/No enabled CLI provider/);
});
+
+ // A locally-backed provider's `models` array is a cached snapshot; the daemon
+ // is the authority. Judging the pin against the record drops a model the user
+ // just pulled and silently downgrades the run to the provider's default.
+ it('honors a model pin on a local-runtime provider whose cached list omits it', () => {
+ const local = cli('grok-ollama', {
+ command: 'grok', ollamaBacked: true,
+ models: ['qwen3-coder:30b'], defaultModel: 'qwen3-coder:30b',
+ });
+ const { model } = pickCliProvider([local], { providerId: 'grok-ollama', model: 'gemma3:27b' });
+ expect(model).toBe('gemma3:27b');
+ });
+
+ // A provider that enumerates nothing has no catalog to validate against, so
+ // the pin stands rather than collapsing to the provider default.
+ it('honors a model pin on a provider that enumerates no models', () => {
+ const bare = cli('bare-cli', { defaultModel: 'configured-default' });
+ const { model } = pickCliProvider([bare], { providerId: 'bare-cli', model: 'anything-goes' });
+ expect(model).toBe('anything-goes');
+ });
});
describe('runCliProviderPrompt', () => {
diff --git a/server/routes/brainSettings.js b/server/routes/brainSettings.js
index 5708d5adf9..8eb3f5bf28 100644
--- a/server/routes/brainSettings.js
+++ b/server/routes/brainSettings.js
@@ -10,6 +10,7 @@ import { getProviderById } from '../services/providers.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
import { settingsUpdateInputSchema } from '../lib/brainValidation.js';
+import { modelPinIsOffered } from '../lib/localProviderRuntime.js';
const router = Router();
@@ -47,21 +48,18 @@ router.put('/settings', asyncHandler(async (req, res) => {
});
}
- // Validate model exists in provider's models
- if (modelId) {
- if (!provider.models || provider.models.length === 0) {
- throw new ServerError(`Provider "${effectiveProviderId}" has no models configured`, {
- status: 400,
- code: 'NO_MODELS'
- });
- }
- if (!provider.models.includes(modelId)) {
- throw new ServerError(`Model "${modelId}" not found in provider "${effectiveProviderId}"`, {
- status: 400,
- code: 'INVALID_MODEL',
- context: { availableModels: provider.models }
- });
- }
+ // Validate the model against the provider's catalog — but only where that
+ // catalog is authoritative. `modelPinIsOffered` subsumes the old
+ // "no models configured" branch (an empty catalog validates nothing) and
+ // additionally passes a locally-backed provider through: its `models` array
+ // is a cached snapshot while the daemon on this machine is the authority,
+ // so rejecting here 400s a model the user just pulled and can serve.
+ if (modelId && !modelPinIsOffered(provider, modelId)) {
+ throw new ServerError(`Model "${modelId}" not found in provider "${effectiveProviderId}"`, {
+ status: 400,
+ code: 'INVALID_MODEL',
+ context: { availableModels: provider.models }
+ });
}
}
diff --git a/server/routes/brainSettings.test.js b/server/routes/brainSettings.test.js
new file mode 100644
index 0000000000..b926e95bdc
--- /dev/null
+++ b/server/routes/brainSettings.test.js
@@ -0,0 +1,94 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+const mocks = vi.hoisted(() => ({
+ loadMeta: vi.fn(),
+ updateMeta: vi.fn(),
+ getProviderById: vi.fn(),
+}));
+
+vi.mock('../services/brain.js', () => ({
+ loadMeta: (...args) => mocks.loadMeta(...args),
+ updateMeta: (...args) => mocks.updateMeta(...args),
+ getSummary: vi.fn(),
+}));
+vi.mock('../services/providers.js', () => ({
+ getProviderById: (...args) => mocks.getProviderById(...args),
+}));
+
+const settingsRoutes = (await import('./brainSettings.js')).default;
+
+const app = express();
+app.use(express.json());
+app.use('/api/brain', settingsRoutes);
+app.use(errorMiddleware);
+
+const put = (body) => request(app).put('/api/brain/settings').send(body);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.loadMeta.mockResolvedValue({ defaultProvider: 'claude-code', defaultModel: 'claude-opus-4-7' });
+ mocks.updateMeta.mockImplementation(async (data) => ({ defaultProvider: 'claude-code', ...data }));
+});
+
+describe('PUT /api/brain/settings', () => {
+ it('saves a model the provider offers', async () => {
+ mocks.getProviderById.mockResolvedValue({
+ id: 'claude-code', type: 'cli', models: ['claude-opus-4-7', 'claude-haiku-4-5'],
+ });
+
+ const response = await put({ defaultProvider: 'claude-code', defaultModel: 'claude-haiku-4-5' });
+
+ expect(response.status).toBe(200);
+ expect(mocks.updateMeta).toHaveBeenCalledWith({ defaultProvider: 'claude-code', defaultModel: 'claude-haiku-4-5' });
+ });
+
+ it('rejects a retired model on a cloud provider whose catalog is authoritative', async () => {
+ mocks.getProviderById.mockResolvedValue({
+ id: 'claude-code', type: 'cli', models: ['claude-opus-4-7', 'claude-haiku-4-5'],
+ });
+
+ const response = await put({ defaultProvider: 'claude-code', defaultModel: 'claude-2' });
+
+ expect(response.status).toBe(400);
+ expect(response.body.code).toBe('INVALID_MODEL');
+ expect(mocks.updateMeta).not.toHaveBeenCalled();
+ });
+
+ // The record's `models` is only a cached snapshot for a local daemon — a model
+ // pulled since the last refresh is installed and serving, so a 400 here blocks
+ // a save the user can legitimately make.
+ it('saves a model a local-runtime provider\'s cached list omits', async () => {
+ mocks.getProviderById.mockResolvedValue({
+ id: 'grok-ollama', type: 'cli', command: 'grok', ollamaBacked: true,
+ models: ['qwen3-coder:30b'], defaultModel: 'qwen3-coder:30b',
+ });
+
+ const response = await put({ defaultProvider: 'grok-ollama', defaultModel: 'gemma3:27b' });
+
+ expect(response.status).toBe(200);
+ expect(mocks.updateMeta).toHaveBeenCalledWith({ defaultProvider: 'grok-ollama', defaultModel: 'gemma3:27b' });
+ });
+
+ // An empty catalog validates nothing, so the pin is the caller's to choose —
+ // this replaced the old NO_MODELS 400.
+ it('saves a model on a provider that enumerates no models', async () => {
+ mocks.getProviderById.mockResolvedValue({ id: 'bare-cli', type: 'cli', models: [] });
+
+ const response = await put({ defaultProvider: 'bare-cli', defaultModel: 'anything-goes' });
+
+ expect(response.status).toBe(200);
+ expect(mocks.updateMeta).toHaveBeenCalledWith({ defaultProvider: 'bare-cli', defaultModel: 'anything-goes' });
+ });
+
+ it('rejects an unknown provider', async () => {
+ mocks.getProviderById.mockResolvedValue(null);
+
+ const response = await put({ defaultProvider: 'nope', defaultModel: 'x' });
+
+ expect(response.status).toBe(400);
+ expect(response.body.code).toBe('INVALID_PROVIDER');
+ });
+});
diff --git a/server/services/localLlm.js b/server/services/localLlm.js
index fb0e299ce6..a105462de7 100644
--- a/server/services/localLlm.js
+++ b/server/services/localLlm.js
@@ -641,6 +641,31 @@ export async function listModels(backend, forceRefresh = false) {
return normalizeModels(backend, raw)
}
+/**
+ * `listModels` plus the sentinel that tells "no models installed" apart from
+ * "the list could not be read".
+ *
+ * Both managers cache an EMPTY array on a failed read rather than throwing, so
+ * `[]` alone is ambiguous — and collapsing an unreadable list into "this
+ * backend has no models" is exactly the failure the sentinel rule in AGENTS.md
+ * forbids. Each manager's own error getter is the authoritative signal, so a
+ * caller that must not treat a transient daemon outage as an empty catalog
+ * reads `error` and falls back to whatever it had before.
+ *
+ * @param {string} backend - 'ollama' | 'lmstudio'
+ * @returns {Promise<{ models: Array|null, error: string|null }>} `models: null`
+ * means the listing was not readable.
+ */
+export async function listManagedBackendModels(backend, forceRefresh = false) {
+ if (!isBackend(backend)) return { models: null, error: `unknown backend '${backend}'` }
+ const models = await listModels(backend, forceRefresh).catch((err) => ({ error: err?.message || 'model list failed' }))
+ if (!Array.isArray(models)) return { models: null, error: models.error }
+ const error = backend === 'ollama'
+ ? ollamaManager.getLastInstalledModelsError()
+ : lmStudioManager.getLastListError()
+ return { models, error: error || null }
+}
+
/**
* Combined status for both backends plus the active marker.
*/
diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.js
index 6cd92d6ac3..6363dc959a 100644
--- a/server/services/localLlm.test.js
+++ b/server/services/localLlm.test.js
@@ -56,6 +56,7 @@ const mocks = vi.hoisted(() => ({
deleteModel: vi.fn(async (id) => ({ success: true, modelId: id })),
getLoadedModels: vi.fn(async () => []),
getLastLoadedModelsError: vi.fn(() => null),
+ getLastInstalledModelsError: vi.fn(() => null),
getModelsDir: vi.fn(() => '/tmp/portos-ollama-models'),
getStatus: vi.fn(async () => ({ available: true, baseUrl: 'x', version: '1', modelCount: 0, models: [] })),
startServer: vi.fn(async () => ({ success: true, running: true })),
@@ -946,3 +947,33 @@ describe('localLlm', () => {
});
});
});
+
+// Both managers cache an EMPTY array on a failed read rather than throwing, so
+// `[]` alone cannot say whether the backend has no models or could not be asked.
+// Callers that fall back to a stored list (the persistent-mind task catalog) and
+// callers that report the failure (the assessment report) both key on `error`.
+describe('listManagedBackendModels', () => {
+ it('reports a read backend with no models as a genuinely empty list', async () => {
+ mocks.ollama.getInstalledModels.mockResolvedValueOnce([]);
+ expect(await svc.listManagedBackendModels('ollama')).toEqual({ models: [], error: null });
+ });
+
+ it('separates an unreadable list from an empty one', async () => {
+ mocks.lmstudio.getAvailableModels.mockResolvedValueOnce([]);
+ mocks.lmstudio.getLastListError.mockReturnValueOnce('LM Studio is unavailable');
+ expect(await svc.listManagedBackendModels('lmstudio'))
+ .toEqual({ models: [], error: 'LM Studio is unavailable' });
+ });
+
+ it('reports a listing that threw outright, with no models', async () => {
+ mocks.ollama.getInstalledModels.mockRejectedValueOnce(new Error('Ollama unreachable'));
+ expect(await svc.listManagedBackendModels('ollama'))
+ .toEqual({ models: null, error: 'Ollama unreachable' });
+ });
+
+ it('refuses an unknown backend rather than answering an empty catalog', async () => {
+ const result = await svc.listManagedBackendModels('not-a-backend');
+ expect(result.models).toBeNull();
+ expect(result.error).toMatch(/unknown backend/);
+ });
+});
diff --git a/server/services/localModelAssessments.js b/server/services/localModelAssessments.js
index 2e1e013ee7..0ce6201933 100644
--- a/server/services/localModelAssessments.js
+++ b/server/services/localModelAssessments.js
@@ -98,16 +98,12 @@ import {
import { getMtplxServerEndpoint, getMtplxServerStatus, relaunchMtplxServerWithTuning } from './mtplxServerManager.js';
import { getSlotstreamServerEndpoint } from './slotstreamServerManager.js';
import { getSpecDecodePresetStatus } from './specDecodeModels.js';
-import { listModels } from './localLlm.js';
+import { listManagedBackendModels } from './localLlm.js';
import {
getLoadedModels as getLoadedOllamaModels,
- getLastInstalledModelsError as getOllamaListError,
restartWithEnv as restartOllamaWithEnv,
} from './ollamaManager.js';
-import {
- getLastListError as getLmStudioListError,
- loadModelWithArgs as loadLmStudioModelWithArgs,
-} from './lmStudioManager.js';
+import { loadModelWithArgs as loadLmStudioModelWithArgs } from './lmStudioManager.js';
// Re-exported so the store split stays an implementation detail for callers that
// only ever wanted "the assessments feature".
@@ -212,7 +208,7 @@ export async function runtimeApiKey(runtime) {
* did.
*
* The two paths differ in what "installed" even means. A managed backend has a
- * durable catalog on disk (`listModels`), so its list survives the daemon being
+ * durable catalog on disk (`listManagedBackendModels`), so its list survives the daemon being
* down. An endpoint runtime has no catalog at all — its models are whatever the
* running process reports from `GET /v1/models`, so a stopped daemon means "no
* models listable", which is an ERROR, never an empty catalog. Collapsing those
@@ -253,15 +249,10 @@ export async function durableRuntimeModels(runtime) {
}
export async function listRuntimeModels(runtime) {
- if (MANAGED_ASSESSMENT_BACKENDS.includes(runtime)) {
- const models = await listModels(runtime).catch((err) => ({ error: err?.message || 'model list failed' }));
- if (!Array.isArray(models)) return { models: null, error: models.error };
- // Both managers cache an EMPTY list on a failed read rather than throwing,
- // so `[]` alone cannot distinguish "no models" from "the list could not be
- // read". Each manager's own error getter is the authoritative signal.
- const error = runtime === 'ollama' ? getOllamaListError() : getLmStudioListError();
- return { models, error: error || null };
- }
+ // `listManagedBackendModels` carries the "empty vs unreadable" sentinel for
+ // these two backends (both managers cache `[]` on a failed read), so this
+ // path and every other consumer of that distinction agree.
+ if (MANAGED_ASSESSMENT_BACKENDS.includes(runtime)) return listManagedBackendModels(runtime);
const endpoint = await runtimeEndpoint(runtime);
if (!endpoint) return { models: null, error: 'no endpoint is configured for this runtime', offline: true };
diff --git a/server/services/localModelAssessments.test.js b/server/services/localModelAssessments.test.js
index c5960fa9ee..016d253c6b 100644
--- a/server/services/localModelAssessments.test.js
+++ b/server/services/localModelAssessments.test.js
@@ -78,29 +78,32 @@ vi.mock('./specDecodeModels.js', () => ({
getSpecDecodePresetStatus: (...args) => getSpecDecodePresetStatus(...args),
}));
-const listModels = vi.fn();
-vi.mock('./localLlm.js', () => ({ listModels: (...args) => listModels(...args) }));
+// The managed-backend listing carries its own "empty vs unreadable" sentinel
+// (`{ models, error }`), so these tests drive that shape directly rather than
+// re-deriving it from a manager error getter. Its composition is covered in
+// localLlm.test.js.
+const listManagedBackendModels = vi.fn();
+const managedModels = (models, error = null) => ({ models, error });
+vi.mock('./localLlm.js', () => ({
+ listManagedBackendModels: (...args) => listManagedBackendModels(...args),
+}));
const getLoadedModels = vi.fn();
-const getOllamaListError = vi.fn();
const ollamaVersion = vi.fn(async () => '0.0.0-test');
// Ollama's tuning knobs are daemon environment, so applying one restarts the
// daemon. Default to "it worked" and let a test override to assert the refusal path.
const restartOllamaWithEnv = vi.fn(async () => ({ applied: true, reason: 'restarted' }));
vi.mock('./ollamaManager.js', () => ({
getLoadedModels: (...args) => getLoadedModels(...args),
- getLastInstalledModelsError: () => getOllamaListError(),
// Recorded with each assessment so a backend UPDATE can later be detected as
// staleness — see localModelAssessmentStore.captureEnvironment.
getVersion: (...args) => ollamaVersion(...args),
restartWithEnv: (...args) => restartOllamaWithEnv(...args),
}));
-const getLmStudioListError = vi.fn();
// LM Studio's knobs are load-time, so applying one reloads the model via `lms load`.
const loadLmStudioModelWithArgs = vi.fn(async () => ({ success: true }));
vi.mock('./lmStudioManager.js', () => ({
- getLastListError: () => getLmStudioListError(),
loadModelWithArgs: (...args) => loadLmStudioModelWithArgs(...args),
}));
@@ -128,10 +131,8 @@ afterAll(() => rmSync(tempRoot, { recursive: true, force: true }));
beforeEach(() => {
rmSync(join(tempRoot, 'local-llm'), { recursive: true, force: true });
runLocalLlmTest.mockReset();
- listModels.mockReset().mockResolvedValue([{ id: 'example-model:7b', params: '7B' }]);
+ listManagedBackendModels.mockReset().mockResolvedValue(managedModels([{ id: 'example-model:7b', params: '7B' }]));
getLoadedModels.mockReset().mockResolvedValue([{ id: 'example-model:7b', name: 'example-model:7b', size: 5 * 2 ** 30 }]);
- getOllamaListError.mockReset().mockReturnValue(null);
- getLmStudioListError.mockReset().mockReturnValue(null);
runEndpointLlmTest.mockReset();
probeOpenAiModels.mockReset().mockResolvedValue({ reachable: true, models: [], error: null });
getLlamaServerEndpoint.mockReset().mockResolvedValue('http://127.0.0.1:5568/v1');
@@ -237,7 +238,7 @@ describe('loadAssessments / getAssessmentReport (read path)', () => {
// unanswered question — listing it here offered a Measure button that could
// only ever spend a provider call to prove it fails.
it('leaves embedding models out of the not-yet-measured list', async () => {
- listModels.mockImplementation(async (backend) => (backend === 'ollama'
+ listManagedBackendModels.mockImplementation(async (backend) => managedModels(backend === 'ollama'
? [{ id: 'example-model:7b', params: '7B' }, { id: 'all-minilm:latest' }, { id: 'nomic-embed-text:latest' }]
: []));
const report = await svc.getAssessmentReport();
@@ -249,7 +250,7 @@ describe('loadAssessments / getAssessmentReport (read path)', () => {
// The backend's own capability metadata outranks the name heuristic in both
// directions, so a chat model that merely LOOKS like an embedding one stays.
it('keeps a model the backend reports as chat-capable', async () => {
- listModels.mockImplementation(async (backend) => (backend === 'ollama'
+ listManagedBackendModels.mockImplementation(async (backend) => managedModels(backend === 'ollama'
? [{ id: 'all-minilm:latest', capabilities: ['completion'] }]
: []));
const report = await svc.getAssessmentReport();
@@ -258,19 +259,19 @@ describe('loadAssessments / getAssessmentReport (read path)', () => {
it('flags a backend whose model list could not be read, even though it returned []', async () => {
// Both managers cache an EMPTY list on a failed read instead of throwing, so
- // the manager's own error getter is the only signal that separates "no
- // models installed" from "the list could not be read".
- listModels.mockImplementation(async (backend) => (backend === 'lmstudio' ? [] : [{ id: 'example-model:7b', params: '7B' }]));
- getLmStudioListError.mockReturnValue('LM Studio is unavailable');
+ // the accompanying `error` is the only signal that separates "no models
+ // installed" from "the list could not be read".
+ listManagedBackendModels.mockImplementation(async (backend) => (backend === 'lmstudio'
+ ? managedModels([], 'LM Studio is unavailable')
+ : managedModels([{ id: 'example-model:7b', params: '7B' }])));
const report = await svc.getAssessmentReport();
expect(report.listErrors).toEqual(['lmstudio']);
});
it('still flags a backend when the model list throws outright', async () => {
- listModels.mockImplementation(async (backend) => {
- if (backend === 'ollama') throw new Error('Ollama unreachable');
- return [];
- });
+ listManagedBackendModels.mockImplementation(async (backend) => (backend === 'ollama'
+ ? managedModels(null, 'Ollama unreachable')
+ : managedModels([])));
expect((await svc.getAssessmentReport()).listErrors).toEqual(['ollama']);
});
@@ -283,7 +284,7 @@ describe('loadAssessments / getAssessmentReport (read path)', () => {
// `400 "<model>" does not support chat` — a failed run that also fires the
// provider-failure hook and files a CoS investigation task. Offering a
// Measure button for one, or sweeping it, is work that cannot succeed.
- listModels.mockImplementation(async (backend) => (backend === 'ollama'
+ listManagedBackendModels.mockImplementation(async (backend) => managedModels(backend === 'ollama'
? [{ id: 'example-model:7b', params: '7B' }, { id: 'nomic-embed-text:latest', params: '137M' }]
: []));
const report = await svc.getAssessmentReport();
@@ -506,7 +507,7 @@ describe('uninstalled models', () => {
runLocalLlmTest.mockResolvedValue(okRun());
await svc.runAssessment({ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512, 4096] });
- listModels.mockResolvedValue([]);
+ listManagedBackendModels.mockResolvedValue(managedModels([]));
const report = await svc.getAssessmentReport();
// It can no longer run, so it must not be ranked — but the measurement stays
// on disk so a re-install doesn't cost another run.
@@ -521,8 +522,7 @@ describe('uninstalled models', () => {
// An unreadable list returning [] must not be read as "everything was
// uninstalled" — that is the same failed-read-as-empty mistake.
- listModels.mockResolvedValue([]);
- getOllamaListError.mockReturnValue('Ollama is unavailable');
+ listManagedBackendModels.mockResolvedValue(managedModels([], 'Ollama is unavailable'));
const report = await svc.getAssessmentReport();
expect(report.ranked.map((r) => r.modelId)).toEqual(['example-model:7b']);
expect(report.uninstalled).toEqual([]);
diff --git a/server/services/persistentMindTaskCapability.js b/server/services/persistentMindTaskCapability.js
index b96b6f0331..fba71266c0 100644
--- a/server/services/persistentMindTaskCapability.js
+++ b/server/services/persistentMindTaskCapability.js
@@ -18,11 +18,13 @@ import { canonicalStringify } from '../lib/objects.js';
import { antigravityBaseModels, effortLevelsForProvider, filterSelectableModels } from '../lib/providerModels.js';
import { PR_COMPLETIONS } from '../lib/prDisposition.js';
import { sha256Text } from '../lib/fileUtils.js';
+import { MANAGED_ASSESSMENT_BACKENDS, localRuntimeKind } from '../lib/localProviderRuntime.js';
import { resolveAppWorkTracker } from '../lib/workTracker.js';
import { getActiveApps, getAppWorkTracker } from './apps.js';
import { loadState } from './cosState.js';
import { addTask, getTaskById } from './cosTaskStore.js';
import { getProviderPrerequisiteReadinessMap } from './providerPrerequisites.js';
+import { listManagedBackendModels } from './localLlm.js';
import { listProviders } from './providers.js';
import {
assessPersistentMindWorkspaceReadiness,
@@ -71,11 +73,49 @@ const boundedReadinessReasonCodes = (value) => (Array.isArray(value) ? value : [
.filter((code) => typeof code === 'string' && /^[a-z][a-zA-Z0-9-]{0,49}$/.test(code))
.slice(0, 10);
-const selectableModelIds = (provider) => {
- const stored = filterSelectableModels(antigravityBaseModels(provider?.models))
- .filter((model) => typeof model === 'string' && model.trim()
- && model.trim().length <= PERSISTENT_MIND_TASK_LIMITS.modelChars)
- .map((model) => model.trim());
+/**
+ * The ids a LOCAL provider can actually be dispatched against, from the daemon
+ * rather than the record.
+ *
+ * A provider backed by Ollama or LM Studio carries a `models` array that is only
+ * a cached snapshot — the daemon on this machine is the authority, and every
+ * model picker in PortOS already offers what it reports. Building the persistent
+ * mind's allowed-model list from the record instead means a model the user
+ * pulled after the record was last refreshed is rejected as "not configured",
+ * even though it is installed and serving.
+ *
+ * `null` (not readable) must NOT collapse to `[]` (no models installed): both
+ * managers cache an empty array on a failed read, so a daemon that is merely
+ * down would otherwise wipe every model off the catalog. `listManagedBackendModels`
+ * carries that sentinel; when it reports one, the caller keeps the record's list.
+ *
+ * Other local runtimes (llama.cpp, MTPLX, vLLM, SGLang, Slotstream) have no
+ * cached catalog inside PortOS — reading them means a live `GET /v1/models`
+ * probe, which this catalog builder runs on every wake and must not pay for.
+ * They keep the record's list.
+ *
+ * @returns {Promise<string[]|null>} `null` when no daemon list applies or it
+ * could not be read.
+ */
+const daemonModelIds = async (provider) => {
+ // `localRuntimeKind`, not `localBackendForProvider`: the marker-based lookup is
+ // what resolves a `claude-ollama`-shaped provider, which carries `ollamaBacked`
+ // without naming Ollama in its id, name, or endpoint.
+ const backend = localRuntimeKind(provider);
+ if (!MANAGED_ASSESSMENT_BACKENDS.includes(backend)) return null;
+ const { models, error } = await listManagedBackendModels(backend)
+ .catch(() => ({ models: null, error: 'model list failed' }));
+ if (error || !Array.isArray(models)) return null;
+ return models.map((model) => model?.id).filter((id) => typeof id === 'string' && id.trim());
+};
+
+const boundedModelIds = (models) => filterSelectableModels(antigravityBaseModels(models))
+ .filter((model) => typeof model === 'string' && model.trim()
+ && model.trim().length <= PERSISTENT_MIND_TASK_LIMITS.modelChars)
+ .map((model) => model.trim());
+
+const selectableModelIds = async (provider) => {
+ const stored = boundedModelIds((await daemonModelIds(provider)) ?? provider?.models);
const configuredDefault = filterSelectableModels([provider?.defaultModel])[0];
const withDefault = typeof configuredDefault === 'string' && configuredDefault.trim()
&& configuredDefault.trim().length <= PERSISTENT_MIND_TASK_LIMITS.modelChars
@@ -84,9 +124,9 @@ const selectableModelIds = (provider) => {
return [...new Set(withDefault)].slice(0, MAX_CATALOG_MODELS);
};
-const providerCatalogEntry = (provider, capabilities) => {
+const providerCatalogEntry = async (provider, capabilities) => {
const policy = normalizePersistentMindCapabilities(capabilities);
- const models = selectableModelIds(provider)
+ const models = (await selectableModelIds(provider))
.filter((model) => isPersistentMindTaskModelAllowed(capabilities, provider.id, model));
if ((policy.taskModelAllowlist.length > 0 || policy.taskModelAllowlistInvalid) && models.length === 0) return null;
return {
@@ -137,9 +177,9 @@ export async function readPersistentMindTaskCatalog({ allowedAppIds, includeAllA
// The tools settings page needs to see revoked apps so it can restore them;
// the model-facing catalog remains narrowed to the granted set.
apps: includeAllApps || !allowed ? appCatalog : appCatalog.filter((app) => allowed.has(app.id)),
- providers: candidates
+ providers: (await Promise.all(candidates
.filter((provider) => readiness[provider.id]?.status === 'ready')
- .map((provider) => providerCatalogEntry(provider, capabilities))
+ .map((provider) => providerCatalogEntry(provider, capabilities))))
.filter(Boolean),
providerReadiness: providerReadinessSummary(candidates, readiness),
};
@@ -246,7 +286,7 @@ const validateChoice = async (request, apps, providers, capabilities) => {
cwd: app.repoPath,
}))[provider.id];
if (providerReadiness?.status !== 'ready') return { error: readinessError(provider.id, providerReadiness) };
- const models = selectableModelIds(provider);
+ const models = await selectableModelIds(provider);
if (request.model && !models.includes(request.model)) {
return { error: `Model '${request.model}' is not configured for provider '${request.providerId}'` };
}
diff --git a/server/services/persistentMindTaskCapability.test.js b/server/services/persistentMindTaskCapability.test.js
index f3fa5b91b6..154f846523 100644
--- a/server/services/persistentMindTaskCapability.test.js
+++ b/server/services/persistentMindTaskCapability.test.js
@@ -13,6 +13,7 @@ const mocks = vi.hoisted(() => ({
getAppWorkTracker: vi.fn(),
resolveAppWorkTracker: vi.fn(),
getProviderPrerequisiteReadinessMap: vi.fn(),
+ listManagedBackendModels: vi.fn(),
workspacePreflight: vi.fn(),
assessWorkspaceReadiness: vi.fn(),
}));
@@ -27,6 +28,9 @@ vi.mock('./cosTaskStore.js', () => ({
getTaskById: (...args) => mocks.getTaskById(...args),
}));
vi.mock('./providers.js', () => ({ listProviders: vi.fn(async () => mocks.providers) }));
+vi.mock('./localLlm.js', () => ({
+ listManagedBackendModels: (...args) => mocks.listManagedBackendModels(...args),
+}));
vi.mock('./providerPrerequisites.js', () => ({
getProviderPrerequisiteReadinessMap: (...args) => mocks.getProviderPrerequisiteReadinessMap(...args),
}));
@@ -69,6 +73,7 @@ beforeEach(() => {
mocks.resolveAppWorkTracker.mockResolvedValue({ resolved: 'plan' });
mocks.getTaskById.mockImplementation(async () => mocks.existing);
mocks.addTask.mockResolvedValue({ id: 'sys-mind-stable', status: 'pending', autoApproved: true });
+ mocks.listManagedBackendModels.mockResolvedValue({ models: null, error: 'no daemon in tests' });
mocks.getProviderPrerequisiteReadinessMap.mockImplementation((providers) => Object.fromEntries(
providers.map((provider) => [provider.id, { status: 'ready', reasonCodes: [] }]),
));
@@ -145,6 +150,57 @@ describe('persistent mind CoS-task capability', () => {
expect(mocks.addTask).toHaveBeenCalledWith(expect.objectContaining({ model: 'gpt-5-mini' }), 'internal');
});
+ // A local provider's `models` array is a cached snapshot; the daemon on this
+ // machine is the authority, and every other model picker already offers what
+ // it reports. Building this catalog from the record rejects a model the user
+ // pulled after the record was last refreshed, as "not configured".
+ it('sources a local-runtime provider\'s models from the daemon, not its cached list', async () => {
+ mocks.providers = [{
+ id: 'grok-ollama', name: 'Grok (Ollama)', type: 'cli', enabled: true, command: 'grok',
+ ollamaBacked: true, models: ['qwen3-coder:30b'], defaultModel: 'qwen3-coder:30b',
+ }];
+ mocks.listManagedBackendModels.mockResolvedValue({
+ models: [{ id: 'qwen3-coder:30b' }, { id: 'gemma3:27b' }], error: null,
+ });
+
+ const catalog = await readPersistentMindTaskCatalog();
+ expect(catalog.providers[0].models.map((model) => model.id))
+ .toEqual(['qwen3-coder:30b', 'gemma3:27b']);
+ expect(mocks.listManagedBackendModels).toHaveBeenCalledWith('ollama');
+
+ const [result] = await executePersistentMindTaskRequests({
+ taskRequests: [taskRequest({ providerId: 'grok-ollama', model: 'gemma3:27b', effort: undefined })],
+ turnId: 'turn-daemon-model',
+ wake: { kind: 'message', message: { id: 'message-daemon-model' } },
+ });
+ expect(result).toMatchObject({ success: true });
+ expect(mocks.addTask).toHaveBeenCalledWith(expect.objectContaining({ model: 'gemma3:27b' }), 'internal');
+ });
+
+ // `null` (list unreadable) must not collapse to `[]` (nothing installed) — a
+ // daemon that is merely down would otherwise wipe the provider off the catalog.
+ it('keeps the record list when the daemon list cannot be read', async () => {
+ mocks.providers = [{
+ id: 'grok-ollama', name: 'Grok (Ollama)', type: 'cli', enabled: true, command: 'grok',
+ ollamaBacked: true, models: ['qwen3-coder:30b'], defaultModel: 'qwen3-coder:30b',
+ }];
+ mocks.listManagedBackendModels.mockResolvedValue({ models: [], error: 'daemon not running' });
+
+ const catalog = await readPersistentMindTaskCatalog();
+ expect(catalog.providers[0].models.map((model) => model.id)).toEqual(['qwen3-coder:30b']);
+ });
+
+ // A cloud provider enumerates its own catalog, so a retired id is still refused.
+ it('still refuses a retired model on a non-local provider', async () => {
+ const [result] = await executePersistentMindTaskRequests({
+ taskRequests: [taskRequest({ model: 'gpt-4' })],
+ turnId: 'turn-retired-model',
+ wake: { kind: 'message', message: { id: 'message-retired-model' } },
+ });
+ expect(result).toMatchObject({ success: false, error: expect.stringContaining('not configured') });
+ expect(mocks.addTask).not.toHaveBeenCalled();
+ });
+
it('filters the model-facing catalog while retaining all apps for the settings inventory', async () => {
mocks.apps.push({ id: 'second-app', name: 'Second App', repoPath: '/example/second-app' });