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

Make voice model provisioning provider-agnostic and default to Ollama

Adam Eivy88c79863e1bd
diff --git a/scripts/migrations/392-voice-llm-pin-lmstudio-default.js b/scripts/migrations/392-voice-llm-pin-lmstudio-default.js
new file mode 100644
index 0000000000..54761a04cb
--- /dev/null
+++ b/scripts/migrations/392-voice-llm-pin-lmstudio-default.js
@@ -0,0 +1,46 @@
+/**
+ * Pin `voice.llm.provider: 'lmstudio'` for installs that were relying on it
+ * being the default.
+ *
+ * `VOICE_DEFAULTS.llm.provider` changes from 'lmstudio' to 'ollama' in this
+ * release. Voice config is stored as a sparse patch merged over the defaults
+ * (`getVoiceConfig` → `deepMerge(VOICE_DEFAULTS, settings.voice)`), so an
+ * install that configured voice without ever touching the provider field would
+ * silently switch backends on upgrade — pointing at an Ollama daemon that may
+ * not be running, and re-provisioning models it already has in LM Studio.
+ *
+ * Only an install that has ALREADY configured voice is pinned. A `settings.json`
+ * with no `voice` key has expressed no preference and is exactly who the new
+ * default is for, so it is deliberately left alone rather than pinned to the
+ * outgoing backend.
+ *
+ * Gates on the presence of its INPUT (a stored `voice` object without an
+ * explicit `llm.provider`), never on the absence of its output — per the
+ * migration rule in AGENTS.md. Re-running is a no-op because the first run
+ * writes the very field the gate checks for.
+ */
+
+import { readFile } from 'node:fs/promises';
+import { join } from 'node:path';
+import { writeJsonAtomic } from './_lib.js';
+
+export default {
+ async up({ rootDir }) {
+ const path = join(rootDir, 'data', 'settings.json');
+ const raw = await readFile(path, 'utf8').catch(error => {
+ if (error.code === 'ENOENT') return null;
+ throw error;
+ });
+ if (raw === null) return;
+
+ const settings = JSON.parse(raw);
+ // No stored voice config at all — never configured, so the new default applies.
+ if (!settings.voice || typeof settings.voice !== 'object') return;
+ // Already explicit (either backend, or a remote provider) — respect it.
+ if (typeof settings.voice.llm?.provider === 'string' && settings.voice.llm.provider) return;
+
+ settings.voice.llm = { ...(settings.voice.llm || {}), provider: 'lmstudio' };
+ await writeJsonAtomic(path, settings);
+ console.log('🎙️ Voice: pinned llm.provider=lmstudio (the default is now ollama; change it in Settings → Voice)');
+ },
+};
diff --git a/scripts/migrations/392-voice-llm-pin-lmstudio-default.test.js b/scripts/migrations/392-voice-llm-pin-lmstudio-default.test.js
new file mode 100644
index 0000000000..f39914a2d6
--- /dev/null
+++ b/scripts/migrations/392-voice-llm-pin-lmstudio-default.test.js
@@ -0,0 +1,72 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import migration from './392-voice-llm-pin-lmstudio-default.js';
+
+const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');
+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));
+
+describe('migration 392 — pin the outgoing voice LLM default', () => {
+ let rootDir;
+ let settingsPath;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-392-'));
+ mkdirSync(join(rootDir, 'data'), { recursive: true });
+ settingsPath = join(rootDir, 'data/settings.json');
+ });
+
+ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));
+
+ // The whole point: voice config is a sparse patch merged over VOICE_DEFAULTS,
+ // so an install that configured voice but never touched the provider field
+ // would silently switch backends when the default changed.
+ it('pins lmstudio for an install that configured voice without naming a provider', async () => {
+ writeJson(settingsPath, { voice: { enabled: true, llm: { model: 'auto' } } });
+ await migration.up({ rootDir });
+ const settings = readJson(settingsPath);
+ expect(settings.voice.llm.provider).toBe('lmstudio');
+ expect(settings.voice.llm.model).toBe('auto');
+ expect(settings.voice.enabled).toBe(true);
+ });
+
+ it('pins lmstudio when voice is configured with no llm block at all', async () => {
+ writeJson(settingsPath, { voice: { enabled: true } });
+ await migration.up({ rootDir });
+ expect(readJson(settingsPath).voice.llm.provider).toBe('lmstudio');
+ });
+
+ it('leaves an explicitly chosen provider alone', async () => {
+ for (const provider of ['ollama', 'lmstudio', 'openai']) {
+ writeJson(settingsPath, { voice: { llm: { provider } } });
+ await migration.up({ rootDir });
+ expect(readJson(settingsPath).voice.llm.provider).toBe(provider);
+ }
+ });
+
+ // An install with no stored voice config has expressed no preference and is
+ // exactly who the NEW default is for — pinning it to the outgoing backend
+ // would deny every fresh install the change.
+ it('leaves an install that never configured voice on the new default', async () => {
+ writeJson(settingsPath, { theme: 'dark' });
+ await migration.up({ rootDir });
+ expect(readJson(settingsPath).voice).toBeUndefined();
+ });
+
+ it('is a no-op with no settings file', async () => {
+ await expect(migration.up({ rootDir })).resolves.toBeUndefined();
+ expect(existsSync(settingsPath)).toBe(false);
+ });
+
+ // Gates on the presence of its INPUT, so a second run finds the field it
+ // wrote and changes nothing.
+ it('is idempotent across repeated runs', async () => {
+ writeJson(settingsPath, { voice: { enabled: true } });
+ await migration.up({ rootDir });
+ const first = readFileSync(settingsPath, 'utf-8');
+ await migration.up({ rootDir });
+ expect(readFileSync(settingsPath, 'utf-8')).toBe(first);
+ });
+});
diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.js
index 07a4ad99f8..32e7a6f90b 100644
--- a/server/services/ollamaManager.js
+++ b/server/services/ollamaManager.js
@@ -1360,6 +1360,33 @@ async function unloadModel(modelName) {
return { unloaded: true, model: modelName }
}
+/**
+ * Make `modelName` resident so the next request doesn't pay a cold load.
+ * The inverse of `unloadModel`: an empty-prompt `/api/generate` with a
+ * non-zero `keep_alive` loads the weights and returns without generating
+ * tokens (Ollama answers with `done_reason: "load"`).
+ *
+ * Unlike the unload path there is deliberately NO "already resident" guard
+ * here — the caller checks `/api/ps` first because re-warming is merely
+ * wasteful, whereas an unguarded UNLOAD-shaped request against a cold model
+ * would load many GB just to evict it.
+ * @returns {Promise<{ warmed: true, model: string } | { warmed: false, reason: string }>}
+ */
+async function warmModel(modelName, keepAlive = '30m') {
+ if (typeof modelName !== 'string' || modelName.length === 0) {
+ return { warmed: false, reason: 'missing model name' }
+ }
+ if (!(await checkOllamaAvailable())) {
+ return { warmed: false, reason: 'Ollama unreachable' }
+ }
+ const body = JSON.stringify({ model: modelName, prompt: '', keep_alive: keepAlive, stream: false })
+ const result = await ollamaRequest('/api/generate', { method: 'POST', body }).catch((err) => ({ _err: err }))
+ if (result && result._err) {
+ return { warmed: false, reason: result._err.message || 'request failed' }
+ }
+ return { warmed: true, model: modelName }
+}
+
/**
* Pull a model, streaming progress. Resolves once the pull finishes.
* Non-percent frames carry a reason flag so the UI can show why the banner is
@@ -2001,6 +2028,7 @@ export {
getLastInstalledModelsError,
getLastLoadedModelsError,
unloadModel,
+ warmModel,
pullModel,
importModelFromHfSafetensors,
deleteModel,
diff --git a/server/services/voice/bootstrap.js b/server/services/voice/bootstrap.js
index bf042f45e4..32552af2b4 100644
--- a/server/services/voice/bootstrap.js
+++ b/server/services/voice/bootstrap.js
@@ -9,7 +9,10 @@ import { createServer } from 'net';
import { PATHS } from '../../lib/fileUtils.js';
import { execPm2, getAppStatus } from '../pm2.js';
import { expandPath, piperVoiceTildePath, voiceHome, IS_WIN, PIPER_BIN_NAME } from './config.js';
-import { isToolCapable, isReasoningModel } from './llm.js';
+import { isReasoningModel } from './llm.js';
+import {
+ getVoiceProvisioner, DEFAULT_VOICE_BACKEND, sortPreferred, sizeOf, FAST_VOICE_MODEL_MAX_B,
+} from './modelProvisioners.js';
import { getProviderById } from '../providers.js';
import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';
import { whichFirst } from '../../lib/processEnv.js';
@@ -209,228 +212,160 @@ export const stopWhisper = async () => {
return { stopped: true };
};
-// Default tool-capable model to auto-install via `lms get` when the user has
-// voice.enabled + tools.enabled + model='auto' but LM Studio has no model that
-// speaks OpenAI structured tool_calls. We try a small list in order — first
-// one resolved successfully wins. Picks favor: small (≤8B), explicitly
-// non-reasoning ("instruct"/"2507" non-thinking variants), and currently
-// available in the LM Studio Hub catalog under the un-gated
-// `lmstudio-community/...-GGUF` form (`lms get` needs an actual fetchable HF
-// repo; gated repos like `meta-llama/*` and MLX-only ids fail silently).
-// Ids mirror the curated catalog in `server/lib/localLlmCatalog.js` so the
-// "recommended installs" UI stays consistent with what voice auto-installs.
-// Override the entire chain with PORTOS_VOICE_DEFAULT_TOOL_MODEL (single id).
-const DEFAULT_TOOL_MODEL_CHAIN = () => {
- const override = process.env.PORTOS_VOICE_DEFAULT_TOOL_MODEL;
- if (override) return [override];
- return [
- 'lmstudio-community/Qwen2.5-3B-Instruct-GGUF', // 3B, ~2 GB, no thinking phase at all
- 'lmstudio-community/functiongemma-270m-it-GGUF', // 270M, ~300 MB, function-calling specialist
- 'lmstudio-community/granite-4.1-8b-GGUF', // 8B, ~5.3 GB, tools without a thinking mode
- 'lmstudio-community/Ministral-3-8B-Instruct-2512-GGUF', // 8B, ~6 GB, Instruct (not the Reasoning build)
- ];
+/**
+ * The first model in `ids` that is fast, non-reasoning and tool-capable.
+ *
+ * Sequential on purpose. The capability check can be a per-model HTTP probe
+ * (Ollama's /api/show), and we only need the FIRST match — a `Promise.all`
+ * here would probe every installed model on an install with dozens of them to
+ * answer a question the first hit already settles.
+ */
+const firstFastCapable = async (backend, ids) => {
+ for (const id of ids) {
+ if (isReasoningModel(id) || sizeOf(id) > FAST_VOICE_MODEL_MAX_B) continue;
+ if (await backend.isToolCapable(id)) return id;
+ }
+ return null;
};
-const LMS_BASE = () => (process.env.LM_STUDIO_URL || 'http://localhost:1234')
- .replace(/\/+$/, '').replace(/\/v1$/, '');
-
-// The auto-install + preload paths only know how to talk to LM Studio
-// (`lms get`, `lms load`, `/v1/models`). Mirror `resolveLlmEndpoint` in
-// `llm.js`: voice falls back to LM Studio whenever the configured provider
-// is missing, not api-type, or has no endpoint — so we still want to
-// provision in those cases. Only skip when the configured provider really
-// resolves to a usable non-lmstudio backend (e.g. a working Ollama).
-const isEffectiveLmStudioVoiceProvider = async (cfg) => {
- const providerId = cfg?.llm?.provider || 'lmstudio';
- if (providerId === 'lmstudio') return true;
+/**
+ * The local backend voice should PROVISION models against for `cfg`, or null
+ * when this provider needs no provisioning.
+ *
+ * Mirrors `resolveLlmEndpoint` in llm.js: voice falls back to the default
+ * backend whenever the configured provider is missing, not api-type, or has no
+ * endpoint — so a half-configured install still gets a working local model.
+ * A provider that DOES resolve to a usable api-type endpoint serves its own
+ * models (OpenAI, Groq, a remote vLLM), so there is nothing to install or
+ * pre-warm and we return null rather than provisioning the wrong backend.
+ */
+const resolveVoiceProvisioner = async (cfg) => {
+ const providerId = cfg?.llm?.provider || DEFAULT_VOICE_BACKEND;
+ const local = getVoiceProvisioner(providerId);
+ if (local) return local;
const provider = await getProviderById(providerId).catch(() => null);
- return !(provider && provider.type === 'api' && provider.endpoint);
-};
-
-// Sentinel + validate: `null` = the API server could not be reached or
-// answered with a non-OK status (we could not ask); `[]` = it answered with
-// zero models (we asked, legitimately empty). Callers must branch on `null`
-// explicitly rather than on `.length` — see AGENTS.md "Sentinel + validate".
-export const listLmStudioModels = async () => {
- const res = await fetch(`${LMS_BASE()}/v1/models`, { signal: AbortSignal.timeout(5000) }).catch(() => null);
- if (!res?.ok) return null;
- const body = await res.json().catch(() => null);
- // A 200 with a body that doesn't match the OpenAI-compatible `{data: [...]}`
- // shape (truncated response, a gateway returning HTML) means we still
- // couldn't actually ask — treat it the same as unreachable, not "0 models".
- if (!Array.isArray(body?.data)) return null;
- return body.data.map((m) => m?.id).filter(Boolean);
+ // A usable remote provider needs no local provisioning.
+ if (provider && provider.type === 'api' && provider.endpoint) return null;
+ return getVoiceProvisioner(DEFAULT_VOICE_BACKEND);
};
-// Matches the `lms` CLI's own message when the LM Studio API server itself
-// is unreachable — distinct from a model-specific failure (404, gated repo,
-// bad id). Detecting this lets the install chain abort immediately instead
-// of repeating the identical failure for every remaining entry.
-const isLmStudioConnectError = (message) => /failed to (?:start or )?connect to\b.*lm studio/i.test(String(message || ''));
-
-// Approximate parameter count from id, mirroring `sizeRank` in llm.js but
-// hoisted here so bootstrap doesn't need to import it. Returns Infinity for
-// model ids without a `<n>B` suffix (utility models, embeddings, etc.).
-const sizeOf = (id) => {
- const n = String(id).toLowerCase();
- const moe = n.match(/(\d+(?:\.\d+)?)\s*x\s*(\d+(?:\.\d+)?)\s*b\b/);
- if (moe) return parseFloat(moe[1]) * parseFloat(moe[2]);
- const m = n.match(/(\d+(?:\.\d+)?)\s*b\b/);
- return m ? parseFloat(m[1]) : Infinity;
-};
-
-// Above this rough parameter count (in B), a model is too heavy for a
-// snappy single-user voice agent on Apple Silicon — TTFT balloons and
-// it competes for VRAM with anything else loaded. We treat "tool-capable
-// but huge" as effectively missing and install a small one alongside.
-const FAST_VOICE_MODEL_MAX_B = 10;
-
+/**
+ * Ensure a fast, tool-capable model exists on the configured local backend,
+ * installing one from the catalog-derived chain when none does.
+ *
+ * Only intervenes when the user opted in: voice on, tools on AND model is
+ * 'auto'. An explicit model id means they know what they want — respect it
+ * even if incompatible.
+ *
+ * The `enabled` gate is deliberately duplicated from `reconcile`'s early
+ * return rather than left to the caller: this function downloads multi-GB
+ * weights, so an install with voice OFF must never reach it even if a future
+ * caller forgets the gate. `preloadModel` guards itself the same way.
+ */
export const ensureToolCapableModel = async (cfg) => {
- // Only intervene when the user opted in: voice on, tools on AND model is
- // 'auto'. An explicit model id means they know what they want — respect it
- // even if incompatible.
- //
- // The `enabled` gate is deliberately duplicated from `reconcile`'s early
- // return rather than left to the caller: this function shells out to
- // `lms get`, a multi-GB download the user never asked for, so an install
- // with voice OFF must never reach it even if a future caller forgets the
- // gate. `preloadModel` guards itself the same way for the same reason.
if (!cfg?.enabled) return { skipped: 'voice-disabled' };
if (!cfg?.llm?.tools?.enabled) return { skipped: 'tools-disabled' };
if (cfg?.llm?.model && cfg.llm.model !== 'auto') return { skipped: 'explicit-model' };
- if (!(await isEffectiveLmStudioVoiceProvider(cfg))) return { skipped: 'non-lmstudio-provider', provider: cfg?.llm?.provider };
- const installed = await listLmStudioModels();
+ const backend = await resolveVoiceProvisioner(cfg);
+ if (!backend) return { skipped: 'remote-provider', provider: cfg?.llm?.provider };
+
+ const installed = await backend.listModels();
+ // `null` = the backend could not be reached. Every entry in the install
+ // chain would fail for that one shared reason, so say so ONCE and stop —
+ // walking the chain here is what spawned four futile multi-GB downloads on
+ // every boot of a machine whose local server simply wasn't running.
if (installed === null) {
- console.warn(`🎙️ voice: LM Studio API server unreachable at ${LMS_BASE()} — start LM Studio (or set voice.llm.provider) before voice can install a tool-capable model`);
- return { skipped: 'lmstudio-unreachable' };
- }
- // Tool-capable AND non-reasoning AND under the size cap. The size cap is
- // important: a user with only `mistral-small-24B` installed gets a model
- // that thrashes VRAM on every turn; we'd rather download Qwen2.5-7B and
- // give them snappy responses out of the box.
- const fastCapable = installed.find(
- (id) => isToolCapable(id) && !isReasoningModel(id) && sizeOf(id) <= FAST_VOICE_MODEL_MAX_B
- );
- if (fastCapable) {
- return { skipped: 'already-capable', model: fastCapable };
+ console.warn(`🎙️ voice: ${backend.label} is not reachable — ${backend.remedy}`);
+ return { skipped: 'backend-unreachable', backend: backend.id };
}
- const lms = await which('lms');
- if (!lms) {
- console.warn(`🎙️ voice: no fast tool-capable model installed and 'lms' CLI not on PATH — install LM Studio CLI or set voice.llm.model explicitly.`);
- return { skipped: 'no-lms-cli' };
+ // Tool-capable AND non-reasoning AND under the size cap. The size cap
+ // matters: a user with only `mistral-small-24B` installed gets a model that
+ // thrashes VRAM on every turn; we'd rather pull a small one and give them
+ // snappy responses out of the box.
+ const fastCapable = await firstFastCapable(backend, installed);
+ if (fastCapable) return { skipped: 'already-capable', model: fastCapable };
+
+ // Snapshot the model set BEFORE install so we can detect which id the
+ // backend actually registered the download under (ids get case-normalized or
+ // gain a quant suffix). Without this snapshot we mis-attributed success to
+ // whichever existing tool-capable model happened to match — including the
+ // slow reasoning model we were trying to escape.
+ const before = new Set(installed);
+ const chain = backend.chain();
+ if (!chain.length) {
+ console.warn(`🎙️ voice: no catalog model with tool support is installable on ${backend.label} — set voice.llm.model explicitly in Settings`);
+ return { skipped: 'no-install-target', backend: backend.id };
}
- // Snapshot the model set BEFORE install so we can detect which id LM Studio
- // actually registered the new download under (LM Studio sometimes
- // normalizes case or appends quant suffix). Without this snapshot we
- // mis-attributed success to whichever existing tool-capable model
- // happened to match — including the slow 14B reasoning model we were
- // trying to escape.
- const before = new Set(installed);
- const chain = DEFAULT_TOOL_MODEL_CHAIN();
- // Pick the last non-empty line from stderr (LM Studio CLI trails newlines)
- // so the warning is actionable instead of an empty `()`. Combine with
- // stdout when stderr is empty — `lms` sometimes routes errors to stdout.
- const lastMeaningfulLine = (s) => String(s || '').split('\n').map((l) => l.trim()).filter(Boolean).pop() || '';
for (const target of chain) {
- console.log(`🎙️ voice: installing fast tool-capable model ${target} via lms get (this may take a few minutes)`);
- const { stdout, stderr } = await pexec(lms, ['get', '-y', target], {
- maxBuffer: 64 * 1024 * 1024,
- timeout: 30 * 60 * 1000,
- }).catch((err) => ({ stdout: '', stderr: err?.message || String(err) }));
- const reason = lastMeaningfulLine(stderr) || lastMeaningfulLine(stdout) || 'unknown';
- // The API server going unreachable mid-chain is a shared cause every
- // remaining entry would hit identically — abort instead of repeating it.
- if (isLmStudioConnectError(reason)) {
- console.warn(`🎙️ voice: LM Studio API server unreachable at ${LMS_BASE()} — aborting install chain (${target} failed: ${reason.slice(0, 160)})`);
- return { skipped: 'lmstudio-unreachable' };
- }
- const after = await listLmStudioModels();
+ console.log(`🎙️ voice: installing fast tool-capable model ${target} via ${backend.label} (this may take a few minutes)`);
+ const outcome = await backend.install(target);
+ const after = await backend.listModels();
+ // The backend going away mid-chain is the same shared cause as above —
+ // stop rather than retrying every remaining entry against a dead server.
if (after === null) {
- console.warn(`🎙️ voice: LM Studio API server unreachable at ${LMS_BASE()} — aborting install chain (lost contact after attempting ${target})`);
- return { skipped: 'lmstudio-unreachable' };
+ console.warn(`🎙️ voice: ${backend.label} became unreachable during install — ${backend.remedy}`);
+ return { skipped: 'backend-unreachable', backend: backend.id };
}
- const newOnes = after.filter((id) => !before.has(id));
- const fastNew = newOnes.find(
- (id) => isToolCapable(id) && !isReasoningModel(id) && sizeOf(id) <= FAST_VOICE_MODEL_MAX_B
- );
+ const fastNew = await firstFastCapable(backend, after.filter((id) => !before.has(id)));
if (fastNew) {
console.log(`🎙️ voice: fast tool-capable model ready — ${fastNew}`);
return { installed: fastNew };
}
- console.warn(`🎙️ voice: ${target} unavailable (${reason.slice(0, 160)}) — trying next`);
+ console.warn(`🎙️ voice: ${target} unavailable (${String(outcome?.reason || 'unknown').slice(0, 160)}) — trying next`);
}
- console.warn(`🎙️ voice: exhausted install chain ${chain.join(', ')} — set voice.llm.model explicitly in Settings`);
+ console.warn(`🎙️ voice: exhausted ${backend.label} install chain ${chain.join(', ')} — set voice.llm.model explicitly in Settings`);
return { failed: chain };
};
-// Returns the set of model keys currently loaded in LM Studio (per `lms ps`).
-// `lms load` is NOT idempotent in practice — re-loading an already-loaded
-// model spawns a SECOND instance of it, doubling VRAM. Worse, when VRAM is
-// full the second load fails with "Model loading was stopped due to
-// insufficient system resources" and our preload reports as failed even
-// though the original instance is fine. Always check `lms ps` first.
-const listLoadedModelKeys = async () => {
- const lms = await which('lms');
- if (!lms) return new Set();
- const { stdout } = await pexec(lms, ['ps', '--json'], { timeout: 10_000 })
- .catch(() => ({ stdout: '' }));
- try {
- const arr = JSON.parse(stdout || '[]');
- return new Set(arr.map((m) => m.modelKey).filter(Boolean));
- } catch {
- return new Set();
- }
-};
-
// Pre-warm the model that 'auto' will pick on the first turn so the user
-// doesn't pay a 5–30 s cold-load on their first question. Skip when the
-// chosen model is already loaded — see `listLoadedModelKeys` for why "skip
-// if loaded" matters more than just being efficient.
+// doesn't pay a 5–30 s cold-load on their first question. Skip when the chosen
+// model is already resident: on LM Studio a second `lms load` spawns another
+// INSTANCE of the same model (3 copies of qwen3-4b reported in the wild),
+// eating multiples of its VRAM and producing "Model loading was stopped due to
+// insufficient system resources" when nothing is actually wrong.
export const preloadModel = async (cfg) => {
if (!cfg?.enabled) return { skipped: 'voice-disabled' };
if (cfg?.llm?.model && cfg.llm.model !== 'auto') return { skipped: 'explicit-model' };
- if (!(await isEffectiveLmStudioVoiceProvider(cfg))) return { skipped: 'non-lmstudio-provider', provider: cfg?.llm?.provider };
- const lms = await which('lms');
- if (!lms) return { skipped: 'no-lms-cli' };
- const installed = await listLmStudioModels();
- if (installed === null) return { skipped: 'lmstudio-unreachable' };
- if (!installed.length) return { skipped: 'no-models' };
-
- const sortPreferred = (list) => list.slice().sort((a, b) => {
- const ar = isReasoningModel(a) ? 1 : 0;
- const br = isReasoningModel(b) ? 1 : 0;
- if (ar !== br) return ar - br;
- return sizeOf(a) - sizeOf(b);
- });
- const wantsTools = !!cfg.llm?.tools?.enabled;
- const candidates = wantsTools ? installed.filter(isToolCapable) : installed;
- const target = sortPreferred(candidates)[0] || sortPreferred(installed)[0];
+ const backend = await resolveVoiceProvisioner(cfg);
+ if (!backend) return { skipped: 'remote-provider', provider: cfg?.llm?.provider };
+
+ const installed = await backend.listModels();
+ if (installed === null) return { skipped: 'backend-unreachable', backend: backend.id };
+ if (!installed.length) return { skipped: 'no-models', backend: backend.id };
+
+ // Rank first, then walk — so the tool-capability probe runs on the models we
+ // would actually pick and stops at the winner, rather than on every model.
+ const ranked = sortPreferred(installed);
+ let target = ranked[0] || null;
+ if (cfg.llm?.tools?.enabled) {
+ for (const id of ranked) {
+ if (await backend.isToolCapable(id)) { target = id; break; }
+ }
+ }
if (!target) return { skipped: 'no-candidate' };
- // CRITICAL: skip the load if the model is already in `lms ps`. Otherwise
- // every server restart spawns another instance of the same model in
- // LM Studio (3 copies of qwen3-4b reported in the wild), eating multiples
- // of its VRAM and causing OOM-style "Model loading was stopped due to
- // insufficient system resources" errors when nothing is actually wrong.
- const loaded = await listLoadedModelKeys();
+ const loaded = await backend.loadedModels();
if (loaded.has(target)) {
console.log(`🎙️ voice: ${target} already loaded — skipping preload`);
return { skipped: 'already-loaded', model: target };
}
- // `lms load` blocks until ready (5-30s cold). Run as fire-and-forget so
+ // The load blocks until ready (5–30 s cold). Run fire-and-forget so
// reconcile returns immediately; whisper/TTS can come up in parallel.
console.log(`🎙️ voice: preloading ${target} (warming GPU/cache for first turn)`);
- pexec(lms, ['load', target], { timeout: 5 * 60 * 1000 })
- .then(() => console.log(`🎙️ voice: ${target} loaded and ready`))
+ backend.load(target)
+ .then((result) => (result?.ok
+ ? console.log(`🎙️ voice: ${target} loaded and ready`)
+ : console.warn(`🎙️ voice: preload ${target} failed: ${result?.reason || 'unknown'}`)))
.catch((err) => console.warn(`🎙️ voice: preload ${target} failed: ${err.message}`));
return { preloading: target };
};
+
/**
* Reconcile PM2 state with desired voice.enabled. Called from
* PUT /api/voice/config and at server boot.
diff --git a/server/services/voice/bootstrap.lmStudioUnreachable.test.js b/server/services/voice/bootstrap.lmStudioUnreachable.test.js
index 946ccc71d2..1c4869a523 100644
--- a/server/services/voice/bootstrap.lmStudioUnreachable.test.js
+++ b/server/services/voice/bootstrap.lmStudioUnreachable.test.js
@@ -1,3 +1,13 @@
+// Every case here arrived with the LM-Studio-only fix for #7541 and is kept
+// verbatim in intent after the provisioning layer became provider-agnostic.
+// It now drives the REAL LM Studio provisioner through bootstrap (rather than
+// bootstrap's own former `listLmStudioModels`), so it still pins the same
+// behaviour end to end: an unreachable local API server must cost one message,
+// not one multi-GB `lms get` attempt per entry in the install chain.
+//
+// The unreachable verdict is now `{ skipped: 'backend-unreachable', backend }`
+// — the same state, named for the backend that reported it rather than for
+// LM Studio specifically.
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
vi.mock('fs', () => ({ existsSync: vi.fn(() => false) }));
@@ -9,11 +19,24 @@ vi.mock('./llm.js', () => ({ isToolCapable: vi.fn(() => false), isReasoningModel
vi.mock('../providers.js', () => ({ getProviderById: vi.fn() }));
vi.mock('../../lib/childProcess.js', () => ({ execFile: vi.fn() }));
vi.mock('../settings.js', () => ({ getSettings: vi.fn(), updateSettings: vi.fn() }));
+vi.mock('../ollamaManager.js', () => ({
+ getInstalledModels: vi.fn(async () => []),
+ getLastInstalledModelsError: vi.fn(() => null),
+ getModelCapabilities: vi.fn(async () => null),
+ getLoadedModels: vi.fn(async () => []),
+ pullModel: vi.fn(),
+ ensureRunning: vi.fn(),
+ warmModel: vi.fn(),
+}));
const { whichFirst } = await import('../../lib/processEnv.js');
const { execFile } = await import('../../lib/childProcess.js');
const { VOICE_DEFAULTS } = await import('./config.js');
-const { ensureToolCapableModel, preloadModel, listLmStudioModels } = await import('./bootstrap.js');
+const { getVoiceProvisioner } = await import('./modelProvisioners.js');
+const { ensureToolCapableModel, preloadModel } = await import('./bootstrap.js');
+
+const listLmStudioModels = () => getVoiceProvisioner('lmstudio').listModels();
+const UNREACHABLE = { skipped: 'backend-unreachable', backend: 'lmstudio' };
const toolCfg = () => ({
...VOICE_DEFAULTS,
@@ -26,10 +49,11 @@ const toolCfg = () => ({
},
});
-// `execFile` is promisified in bootstrap.js. Node's real child_process.execFile
-// carries a promisify-custom symbol that resolves to a single `{stdout, stderr}`
-// object; mimic that here (rather than the generic multi-arg-callback array
-// behavior `util.promisify` falls back to) so the mock matches production shape.
+// `execFile` is promisified in the provisioner. Node's real
+// child_process.execFile carries a promisify-custom symbol that resolves to a
+// single `{stdout, stderr}` object; mimic that here (rather than the generic
+// multi-arg-callback array behavior `util.promisify` falls back to) so the
+// mock matches production shape.
const respondWith = (stderr) => execFile.mockImplementation((...args) => {
const callback = args[args.length - 1];
callback(null, { stdout: '', stderr });
@@ -54,6 +78,11 @@ it('listLmStudioModels returns null when the API server answers non-OK', async (
await expect(listLmStudioModels()).resolves.toBeNull();
});
+it('listLmStudioModels returns null on a 200 whose body is not the OpenAI shape', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => '<html>gateway</html>' })));
+ await expect(listLmStudioModels()).resolves.toBeNull();
+});
+
it('listLmStudioModels returns [] on a 200 with an empty data array', async () => {
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => ({ data: [] }) })));
await expect(listLmStudioModels()).resolves.toEqual([]);
@@ -63,39 +92,46 @@ it('ensureToolCapableModel invokes no lms get when LM Studio is unreachable', as
vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('ECONNREFUSED'); }));
whichFirst.mockImplementation(async (bin) => (bin === 'lms' ? '/usr/local/bin/lms' : null));
const result = await ensureToolCapableModel(toolCfg());
- expect(result).toEqual({ skipped: 'lmstudio-unreachable' });
+ expect(result).toEqual(UNREACHABLE);
expect(execFile).not.toHaveBeenCalled();
});
-it('preloadModel reports lmstudio-unreachable distinctly from no-models', async () => {
+it('preloadModel reports an unreachable backend distinctly from no-models', async () => {
vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('ECONNREFUSED'); }));
whichFirst.mockImplementation(async (bin) => (bin === 'lms' ? '/usr/local/bin/lms' : null));
const result = await preloadModel(toolCfg());
- expect(result).toEqual({ skipped: 'lmstudio-unreachable' });
+ expect(result).toEqual(UNREACHABLE);
});
-it('ensureToolCapableModel aborts the remaining install chain on a connect-class lms get failure', async () => {
- vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => ({ data: [] }) })));
+it('ensureToolCapableModel aborts the chain when the post-install health check loses contact', async () => {
+ // The pre-loop snapshot succeeds (reachable, empty); `lms get` reports a
+ // model-specific failure; the post-install re-check then fails to reach the
+ // API server at all. The original `after ?? []` coercion silently treated
+ // that as "0 new models" and kept trying the rest of the chain against a
+ // dead server — one attempt, then stop, is the contract.
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce({ ok: true, json: async () => ({ data: [] }) })
+ .mockRejectedValueOnce(new Error('ECONNREFUSED'));
+ vi.stubGlobal('fetch', fetchMock);
whichFirst.mockImplementation(async (bin) => (bin === 'lms' ? '/usr/local/bin/lms' : null));
- respondWith('Error: Failed to start or connect to local LM Studio API server.');
+ respondWith('Error: model not found on hub');
const result = await ensureToolCapableModel(toolCfg());
- expect(result).toEqual({ skipped: 'lmstudio-unreachable' });
+ expect(result).toEqual(UNREACHABLE);
expect(execFile).toHaveBeenCalledTimes(1);
});
-it('ensureToolCapableModel aborts the chain when the post-install health check loses contact with LM Studio', async () => {
- // The pre-loop snapshot succeeds (reachable, empty); `lms get` itself
- // reports an unrelated model-specific failure (no connect-error text);
- // the post-install re-check then fails to reach the API server at all.
- // The prior `after ?? []` coercion silently treated that as "0 new
- // models" and kept trying the rest of the chain against a dead server.
+// The connect-class `lms get` failure that motivated the original fix. The
+// provider-agnostic orchestrator detects it through the post-install re-list
+// (which returns null for exactly this cause) rather than regex-matching
+// LM Studio's wording, so the guard also covers a backend with other phrasing.
+it('ensureToolCapableModel aborts on a connect-class lms get failure', async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce({ ok: true, json: async () => ({ data: [] }) })
- .mockRejectedValueOnce(new Error('ECONNREFUSED'));
+ .mockRejectedValue(new Error('ECONNREFUSED'));
vi.stubGlobal('fetch', fetchMock);
whichFirst.mockImplementation(async (bin) => (bin === 'lms' ? '/usr/local/bin/lms' : null));
- respondWith('Error: model not found on hub');
+ respondWith('Error: Failed to start or connect to local LM Studio API server.');
const result = await ensureToolCapableModel(toolCfg());
- expect(result).toEqual({ skipped: 'lmstudio-unreachable' });
+ expect(result).toEqual(UNREACHABLE);
expect(execFile).toHaveBeenCalledTimes(1);
});
diff --git a/server/services/voice/bootstrap.retirement.test.js b/server/services/voice/bootstrap.retirement.test.js
index 76fd5806ec..0ee32d0008 100644
--- a/server/services/voice/bootstrap.retirement.test.js
+++ b/server/services/voice/bootstrap.retirement.test.js
@@ -14,6 +14,10 @@ vi.mock('net', () => ({ createServer: () => {
return server;
} }));
vi.mock('./llm.js', () => ({ isToolCapable: vi.fn(), isReasoningModel: vi.fn() }));
+vi.mock('./modelProvisioners.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, getVoiceProvisioner: vi.fn() };
+});
vi.mock('../providers.js', () => ({ getProviderById: vi.fn() }));
vi.mock('../../lib/childProcess.js', () => ({ execFile: vi.fn() }));
vi.mock('../settings.js', () => ({ getSettings: vi.fn(), updateSettings: vi.fn() }));
@@ -24,7 +28,26 @@ const { execPm2 } = await import('../pm2.js');
const { execFile } = await import('../../lib/childProcess.js');
const { getProviderById } = await import('../providers.js');
const { VOICE_DEFAULTS } = await import('./config.js');
-const { reconcile, ensureToolCapableModel } = await import('./bootstrap.js');
+const { getVoiceProvisioner } = await import('./modelProvisioners.js');
+const { reconcile, ensureToolCapableModel, preloadModel } = await import('./bootstrap.js');
+
+// A provisioner double: every primitive is a spy so a test can assert that an
+// unreachable backend short-circuits BEFORE any install is attempted.
+const fakeBackend = (overrides = {}) => ({
+ id: 'ollama', label: 'Ollama', remedy: 'start Ollama',
+ listModels: vi.fn(async () => []),
+ isToolCapable: vi.fn(async () => false),
+ chain: vi.fn(() => ['small:1b', 'bigger:3b']),
+ install: vi.fn(async () => ({ ok: true, reason: '' })),
+ loadedModels: vi.fn(async () => new Set()),
+ load: vi.fn(async () => ({ ok: true, reason: '' })),
+ ...overrides,
+});
+
+const toolsOn = (cfg = {}) => ({
+ ...VOICE_DEFAULTS, enabled: true, ...cfg,
+ llm: { ...VOICE_DEFAULTS.llm, model: 'auto', tools: { enabled: true }, ...(cfg.llm || {}) },
+});
it('does not download or preload anything when an upgraded install boots before Piper setup', async () => {
const cfg = { ...VOICE_DEFAULTS, enabled: true, tts: { ...VOICE_DEFAULTS.tts, retiredEngine: 'kokoro' } };
@@ -58,3 +81,66 @@ it('does not probe or download a tool-capable model when voice is disabled', asy
expect(execFile).not.toHaveBeenCalled();
expect(getProviderById).not.toHaveBeenCalled();
});
+
+// #7541: an unreachable backend is ONE shared cause. Walking the whole install
+// chain against it spawned four futile multi-GB downloads on every boot.
+it('stops at one message instead of walking the chain when the backend is unreachable', async () => {
+ vi.clearAllMocks();
+ const backend = fakeBackend({ listModels: vi.fn(async () => null) });
+ getVoiceProvisioner.mockReturnValue(backend);
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ await expect(ensureToolCapableModel(toolsOn())).resolves.toEqual({ skipped: 'backend-unreachable', backend: 'ollama' });
+
+ expect(backend.install).not.toHaveBeenCalled();
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(warn.mock.calls[0][0]).toContain('not reachable');
+ warn.mockRestore();
+});
+
+it('installs from the chain when the backend is reachable with nothing capable', async () => {
+ vi.clearAllMocks();
+ const backend = fakeBackend({
+ listModels: vi.fn().mockResolvedValueOnce([]).mockResolvedValue(['small:1b']),
+ isToolCapable: vi.fn(async () => true),
+ });
+ getVoiceProvisioner.mockReturnValue(backend);
+ await expect(ensureToolCapableModel(toolsOn())).resolves.toEqual({ installed: 'small:1b' });
+ expect(backend.install).toHaveBeenCalledWith('small:1b');
+});
+
+it('aborts the chain when the backend disappears mid-install', async () => {
+ vi.clearAllMocks();
+ const backend = fakeBackend({
+ listModels: vi.fn().mockResolvedValueOnce([]).mockResolvedValue(null),
+ });
+ getVoiceProvisioner.mockReturnValue(backend);
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ await expect(ensureToolCapableModel(toolsOn())).resolves.toEqual({ skipped: 'backend-unreachable', backend: 'ollama' });
+ // One attempt, then stop — not one per remaining chain entry.
+ expect(backend.install).toHaveBeenCalledTimes(1);
+ vi.restoreAllMocks();
+});
+
+// A remote OpenAI-compatible provider serves its own models: nothing to pull,
+// nothing to pre-warm, and certainly nothing to provision on a local daemon.
+it('provisions nothing for a remote API provider', async () => {
+ vi.clearAllMocks();
+ getVoiceProvisioner.mockReturnValue(null);
+ getProviderById.mockResolvedValue({ id: 'openai', type: 'api', endpoint: 'https://api.openai.com/v1' });
+ const cfg = toolsOn({ llm: { provider: 'openai' } });
+ await expect(ensureToolCapableModel(cfg)).resolves.toEqual({ skipped: 'remote-provider', provider: 'openai' });
+ await expect(preloadModel(cfg)).resolves.toEqual({ skipped: 'remote-provider', provider: 'openai' });
+});
+
+it('skips the preload when the chosen model is already resident', async () => {
+ vi.clearAllMocks();
+ const backend = fakeBackend({
+ listModels: vi.fn(async () => ['small:1b']),
+ isToolCapable: vi.fn(async () => true),
+ loadedModels: vi.fn(async () => new Set(['small:1b'])),
+ });
+ getVoiceProvisioner.mockReturnValue(backend);
+ await expect(preloadModel(toolsOn())).resolves.toEqual({ skipped: 'already-loaded', model: 'small:1b' });
+ expect(backend.load).not.toHaveBeenCalled();
+});
diff --git a/server/services/voice/config.js b/server/services/voice/config.js
index 1552a0dc5c..4ab9957fac 100644
--- a/server/services/voice/config.js
+++ b/server/services/voice/config.js
@@ -12,6 +12,21 @@ import { PORTS } from '../../lib/ports.js';
const VOICE_HOME = join(homedir(), '.portos', 'voice');
+/**
+ * The local LLM backend voice uses when nothing else is configured.
+ *
+ * Ollama is the default: it ships a daemon PortOS can start and probe itself
+ * (`ollamaManager.ensureRunning`), reports per-model tool capability from
+ * /api/show rather than leaving it to an id guess, and needs no separate GUI
+ * running. LM Studio remains fully supported — set `voice.llm.provider` to
+ * 'lmstudio', which migration 392 pins for every install that was relying on
+ * the previous default.
+ *
+ * Lives here rather than in modelProvisioners.js so both that module and
+ * llm.js can read it without an import cycle (modelProvisioners imports llm).
+ */
+export const DEFAULT_VOICE_BACKEND = 'ollama';
+
export const VOICE_DEFAULTS = Object.freeze({
enabled: false,
trigger: 'push-to-talk',
@@ -79,7 +94,7 @@ export const VOICE_DEFAULTS = Object.freeze({
},
llm: {
- provider: 'lmstudio',
+ provider: DEFAULT_VOICE_BACKEND,
model: 'auto',
visionModel: 'auto',
// Legacy free-form system prompt. Overridden by `personality` + tool
diff --git a/server/services/voice/llm.js b/server/services/voice/llm.js
index 3899ad23d9..fa26989017 100644
--- a/server/services/voice/llm.js
+++ b/server/services/voice/llm.js
@@ -7,20 +7,37 @@
// provider is missing, not API-type, or the toolkit hasn't warmed yet.
import { getProviderById } from '../providers.js';
+import { DEFAULT_VOICE_BACKEND } from './config.js';
+import { normalizeOpenAiBaseUrl } from '../../lib/localProviderRuntime.js';
import { assertSecretEndpoint } from '../../lib/aiToolkit/endpointGuard.js';
// Legacy env-based LM Studio default. Returns the OpenAI-compatible API base
// INCLUDING the version path, so callers append `/models` / `/chat/completions`.
-const LM_STUDIO_API_BASE = () => `${(process.env.LM_STUDIO_URL || 'http://localhost:1234')
- .replace(/\/+$/, '').replace(/\/v1$/, '')}/v1`;
+const LM_STUDIO_API_BASE = () => normalizeOpenAiBaseUrl(process.env.LM_STUDIO_URL || 'http://localhost:1234');
+
+// Ollama's OpenAI-compatible surface. `OLLAMA_HOST` is conventionally a BARE
+// `host:port` with no scheme (that is how .env.example documents it), so this
+// must go through the shared normalizer rather than string-concatenating
+// `/v1` onto it — `localhost:11434/v1` is not a fetchable URL.
+const OLLAMA_API_BASE = () => normalizeOpenAiBaseUrl(
+ process.env.OLLAMA_URL || process.env.OLLAMA_HOST || 'http://localhost:11434'
+);
+
+// Last-resort endpoints when the configured provider resolves to nothing
+// usable. Keyed by the built-in local backends so the fallback follows
+// `DEFAULT_VOICE_BACKEND` instead of being pinned to one vendor.
+const LOCAL_FALLBACKS = {
+ ollama: () => ({ apiBase: OLLAMA_API_BASE(), providerName: 'Ollama' }),
+ lmstudio: () => ({ apiBase: LM_STUDIO_API_BASE(), providerName: 'LM Studio' }),
+};
/**
* Resolve the OpenAI-compatible endpoint for the voice text LLM.
- * @param {string} [providerId='lmstudio']
+ * @param {string} [providerId=DEFAULT_VOICE_BACKEND]
* @returns {Promise<{ apiBase: string, apiKey: string, defaultModel: string|null, providerName: string }>}
*/
-export const resolveLlmEndpoint = async (providerId = 'lmstudio') => {
- const provider = await getProviderById(providerId || 'lmstudio').catch(() => null);
+export const resolveLlmEndpoint = async (providerId = DEFAULT_VOICE_BACKEND) => {
+ const provider = await getProviderById(providerId || DEFAULT_VOICE_BACKEND).catch(() => null);
if (provider && provider.type === 'api' && provider.endpoint) {
// Back-compat: the LM_STUDIO_URL env override still wins for the built-in
// lmstudio provider, so installs that pointed it at another host keep
@@ -47,8 +64,12 @@ export const resolveLlmEndpoint = async (providerId = 'lmstudio') => {
};
}
// No usable API provider (CLI/TUI, missing, or toolkit not warmed) — fall
- // back to the env-based LM Studio default so voice still works out of the box.
- return { apiBase: LM_STUDIO_API_BASE(), apiKey: '', defaultModel: null, providerName: 'LM Studio' };
+ // back to the env-based local default so voice still works out of the box.
+ // Falls back to the backend the user NAMED when that is a known local one,
+ // so a `provider: 'lmstudio'` install whose provider record is missing still
+ // lands on LM Studio rather than being silently redirected to Ollama.
+ const fallback = (LOCAL_FALLBACKS[providerId] || LOCAL_FALLBACKS[DEFAULT_VOICE_BACKEND])();
+ return { apiBase: fallback.apiBase, apiKey: '', defaultModel: null, providerName: fallback.providerName };
};
export const authHeaders = (apiKey) => (apiKey ? { Authorization: `Bearer ${apiKey}` } : {});
diff --git a/server/services/voice/llm.test.js b/server/services/voice/llm.test.js
index 96847f528d..4f8d68162b 100644
--- a/server/services/voice/llm.test.js
+++ b/server/services/voice/llm.test.js
@@ -217,14 +217,25 @@ describe('resolveLlmEndpoint', () => {
expect(ep.apiBase).toBe('http://localhost:11434/v1');
});
- it('falls back to the env LM Studio default for CLI/TUI providers', async () => {
+ it('falls back to the default local backend for CLI/TUI providers', async () => {
getProviderById.mockResolvedValue({ id: 'claude-code', type: 'cli', command: 'claude' });
const ep = await resolveLlmEndpoint('claude-code');
- expect(ep.apiBase).toBe('http://localhost:1234/v1');
+ expect(ep.apiBase).toBe('http://localhost:11434/v1');
+ expect(ep.providerName).toBe('Ollama');
expect(ep.apiKey).toBe('');
expect(ep.defaultModel).toBeNull();
});
+ // A named local backend must not be silently redirected to the default one:
+ // an install that pinned lmstudio and whose provider record went missing has
+ // to keep landing on LM Studio, or voice quietly talks to the wrong daemon.
+ it('falls back to the NAMED local backend rather than the default one', async () => {
+ getProviderById.mockResolvedValue(null);
+ const ep = await resolveLlmEndpoint('lmstudio');
+ expect(ep.apiBase).toBe('http://localhost:1234/v1');
+ expect(ep.providerName).toBe('LM Studio');
+ });
+
it('falls back when the provider is missing or the lookup throws', async () => {
getProviderById.mockRejectedValue(Object.assign(new Error('not ready'), { code: 'AI_TOOLKIT_NOT_INITIALIZED' }));
const ep = await resolveLlmEndpoint('lmstudio');
@@ -261,11 +272,11 @@ describe('resolveLlmEndpoint', () => {
expect(ep.apiBase).toBe('http://localhost:11434/v1');
});
- it('defaults to lmstudio when no provider id is passed', async () => {
+ it('defaults to ollama when no provider id is passed', async () => {
getProviderById.mockResolvedValue(null);
const ep = await resolveLlmEndpoint();
- expect(getProviderById).toHaveBeenCalledWith('lmstudio');
- expect(ep.apiBase).toBe('http://localhost:1234/v1');
+ expect(getProviderById).toHaveBeenCalledWith('ollama');
+ expect(ep.apiBase).toBe('http://localhost:11434/v1');
});
});
diff --git a/server/services/voice/modelProvisioners.js b/server/services/voice/modelProvisioners.js
new file mode 100644
index 0000000000..4f05e7ced4
--- /dev/null
+++ b/server/services/voice/modelProvisioners.js
@@ -0,0 +1,232 @@
+// Backend-specific model provisioning for voice.
+//
+// Voice's RUNTIME chat path is already provider-agnostic: `resolveLlmEndpoint`
+// in llm.js speaks OpenAI-compatible HTTP to any `type: 'api'` provider with an
+// endpoint. What is NOT portable is the work of getting a tool-capable model
+// onto the machine and warm before the first turn — listing what is installed,
+// pulling one that is not, and pre-loading it so the user doesn't pay a cold
+// start. Each local backend does that its own way, so it lives behind this
+// registry instead of being hardcoded to LM Studio in bootstrap.js.
+//
+// A provisioner is intentionally the SMALL surface bootstrap needs. Anything a
+// backend cannot do degrades to a skip, never a throw — provisioning is a
+// convenience on top of a stack that must still come up without it.
+//
+// **The `listModels` sentinel is load-bearing.** `null` means "we could not
+// ask" (daemon down, CLI missing, HTTP error); `[]` means "we asked and the
+// backend has nothing installed". Collapsing the two is what made voice chase
+// a four-entry install chain on every boot against an unreachable LM Studio.
+// Callers MUST branch on `null` explicitly and never on `.length` alone — see
+// the "Sentinel + validate" rule in AGENTS.md.
+
+import { promisify } from 'util';
+import { execFile } from '../../lib/childProcess.js';
+import { whichFirst } from '../../lib/processEnv.js';
+import { isToolCapable, isReasoningModel } from './llm.js';
+import { DEFAULT_VOICE_BACKEND } from './config.js';
+import { LOCAL_LLM_CATALOG } from '../../lib/localLlmCatalog.js';
+import { normalizeOpenAiBaseUrl } from '../../lib/localProviderRuntime.js';
+import * as ollamaManager from '../ollamaManager.js';
+
+const pexec = promisify(execFile);
+
+// Above this rough parameter count (in B), a model is too heavy for a snappy
+// single-user voice agent on Apple Silicon — TTFT balloons and it competes for
+// VRAM with anything else loaded. We treat "tool-capable but huge" as
+// effectively missing and install a small one alongside.
+export const FAST_VOICE_MODEL_MAX_B = 10;
+
+// Approximate parameter count from a model id. Returns Infinity for ids with
+// no `<n>B` suffix (utility models, embeddings) so they sort last rather than
+// silently winning a tie.
+export const sizeOf = (id) => {
+ const n = String(id).toLowerCase();
+ const moe = n.match(/(\d+(?:\.\d+)?)\s*x\s*(\d+(?:\.\d+)?)\s*b\b/);
+ if (moe) return parseFloat(moe[1]) * parseFloat(moe[2]);
+ const m = n.match(/(\d+(?:\.\d+)?)\s*b\b/);
+ return m ? parseFloat(m[1]) : Infinity;
+};
+
+/**
+ * A catalog entry's `params` string ("7B", "270M", "3.8B") as a number of
+ * billions.
+ *
+ * Distinct from `sizeOf`, which parses a model ID and only understands a `B`
+ * suffix. A sub-billion entry writes its size in MILLIONS, so running ids
+ * through `sizeOf` scores `270M` as Infinity and sorts the smallest,
+ * fastest function-calling specialist in the catalog LAST in the install
+ * chain — the opposite of what the chain is for.
+ */
+export const paramsToB = (params) => {
+ const m = String(params).trim().match(/^(\d+(?:\.\d+)?)\s*([bm])\b/i);
+ if (!m) return Infinity;
+ return m[2].toLowerCase() === 'm' ? parseFloat(m[1]) / 1000 : parseFloat(m[1]);
+};
+
+/**
+ * Install targets for `backend`, derived from the curated catalog rather than
+ * a second hardcoded list: small, tool-capable, non-reasoning, smallest first.
+ *
+ * The previous LM Studio chain was a hand-maintained copy of catalog ids with
+ * a comment asking the next editor to keep the two in sync. Deriving it means
+ * adding a small tool model to the catalog arms it for voice on every backend
+ * that has an id for it, and a retired id can't linger here.
+ *
+ * `PORTOS_VOICE_DEFAULT_TOOL_MODEL` still overrides the whole chain with one id.
+ */
+export const CHAIN_ENTRIES = (backend) => LOCAL_LLM_CATALOG
+ .filter(entry => entry?.capabilities?.includes('tools')
+ && !entry.capabilities.includes('reasoning')
+ && typeof entry[backend] === 'string'
+ && paramsToB(entry.params || '') <= FAST_VOICE_MODEL_MAX_B)
+ .sort((a, b) => paramsToB(a.params || '') - paramsToB(b.params || ''));
+
+export const defaultToolModelChain = (backend) => {
+ const override = process.env.PORTOS_VOICE_DEFAULT_TOOL_MODEL;
+ if (override) return [override];
+ return CHAIN_ENTRIES(backend).map(entry => entry[backend]);
+};
+
+// ---------------------------------------------------------------------------
+// Ollama
+// ---------------------------------------------------------------------------
+
+// Ollama reports a model's capability set (`["completion","tools","vision"]`)
+// from /api/show, so tool support is a FACT here rather than the id-substring
+// guess `isToolCapable` has to make for LM Studio. `getModelCapabilities`
+// returns null when the per-model probe fails — treat that as "unknown", and
+// fall back to the id heuristic rather than declaring a model tool-less.
+const ollamaToolCapable = async (id) => {
+ const capabilities = await ollamaManager.getModelCapabilities(id).catch(() => null);
+ return capabilities === null ? isToolCapable(id) : capabilities.includes('tools');
+};
+
+const ollamaProvisioner = {
+ id: 'ollama',
+ label: 'Ollama',
+ remedy: 'start Ollama (`ollama serve`) or set voice.llm.provider to another backend',
+ listModels: async () => {
+ const models = await ollamaManager.getInstalledModels().catch(() => null);
+ // getInstalledModels returns [] both for "daemon down" and "no models", but
+ // it records WHY in getLastInstalledModelsError — a non-null error with an
+ // empty list means we could not ask, which is this layer's `null`.
+ if (!Array.isArray(models)) return null;
+ if (!models.length && ollamaManager.getLastInstalledModelsError()) return null;
+ return models.map(m => m.id || m.name).filter(Boolean);
+ },
+ isToolCapable: ollamaToolCapable,
+ chain: () => defaultToolModelChain('ollama'),
+ install: async (target) => {
+ const result = await ollamaManager.pullModel(target).catch(err => ({ success: false, error: err?.message }));
+ return { ok: result?.success === true, reason: result?.error || 'unknown' };
+ },
+ loadedModels: async () => {
+ const loaded = await ollamaManager.getLoadedModels().catch(() => []);
+ return new Set((loaded || []).map(m => m.id || m.name).filter(Boolean));
+ },
+ // Ollama has no separate "load" verb — an empty-prompt generate with a
+ // non-zero keep_alive is the documented way to make a model resident
+ // (`ollamaManager.warmModel`). Keeping the warm-up behind the provisioner is
+ // what lets bootstrap stay backend-agnostic.
+ load: async (model) => {
+ const started = await ollamaManager.ensureRunning().catch(() => null);
+ if (started && started.success === false) {
+ return { ok: false, reason: started.error || 'Ollama is not running' };
+ }
+ const result = await ollamaManager.warmModel(model);
+ return { ok: result.warmed === true, reason: result.reason || '' };
+ },
+};
+
+// ---------------------------------------------------------------------------
+// LM Studio
+// ---------------------------------------------------------------------------
+
+// `/v1` is appended per-call below, so strip it here. Goes through the shared
+// normalizer so a scheme-less host from the env is still a fetchable URL.
+const LMS_BASE = () => normalizeOpenAiBaseUrl(process.env.LM_STUDIO_URL || 'http://localhost:1234')
+ .replace(/\/v1$/, '');
+
+// Pick the last non-empty line (the `lms` CLI trails newlines) so a failure
+// reason is actionable instead of an empty `()`. Combine with stdout when
+// stderr is empty — `lms` sometimes routes errors to stdout.
+const lastMeaningfulLine = (s) => String(s || '').split('\n').map(l => l.trim()).filter(Boolean).pop() || '';
+
+const lmStudioProvisioner = {
+ id: 'lmstudio',
+ label: 'LM Studio',
+ remedy: 'start the LM Studio local server, or set voice.llm.provider to another backend',
+ listModels: async () => {
+ const res = await fetch(`${LMS_BASE()}/v1/models`, { signal: AbortSignal.timeout(5000) }).catch(() => null);
+ // `null`, not `[]`: an unreachable server is "could not ask", and the
+ // caller must not read it as "no models installed, go download one".
+ if (!res?.ok) return null;
+ const body = await res.json().catch(() => null);
+ // A 200 whose body doesn't match the OpenAI-compatible `{data: [...]}`
+ // shape (truncated response, a gateway returning HTML) means we still
+ // could not actually ask — same as unreachable, not "0 models".
+ if (!Array.isArray(body?.data)) return null;
+ return body.data.map(m => m?.id).filter(Boolean);
+ },
+ // LM Studio's OpenAI-compatible /v1/models carries no capability field, so
+ // tool support stays an id heuristic here.
+ isToolCapable: async (id) => isToolCapable(id),
+ chain: () => defaultToolModelChain('lmstudio'),
+ install: async (target) => {
+ const lms = await whichFirst('lms');
+ if (!lms) return { ok: false, reason: "'lms' CLI not on PATH" };
+ const { stdout, stderr } = await pexec(lms, ['get', '-y', target], {
+ maxBuffer: 64 * 1024 * 1024,
+ timeout: 30 * 60 * 1000,
+ }).catch(err => ({ stdout: '', stderr: err?.message || String(err) }));
+ const reason = lastMeaningfulLine(stderr) || lastMeaningfulLine(stdout) || 'unknown';
+ // `lms get` exit status is not a reliable success signal; the caller
+ // re-lists and diffs against a pre-install snapshot instead.
+ return { ok: true, reason };
+ },
+ // `lms load` is NOT idempotent — re-loading an already-loaded model spawns a
+ // SECOND instance, doubling VRAM. Worse, when VRAM is full the second load
+ // fails with "Model loading was stopped due to insufficient system
+ // resources" and preload reports failure though the original is fine.
+ loadedModels: async () => {
+ const lms = await whichFirst('lms');
+ if (!lms) return new Set();
+ const { stdout } = await pexec(lms, ['ps', '--json'], { timeout: 10_000 }).catch(() => ({ stdout: '' }));
+ const parsed = (() => { try { return JSON.parse(stdout || '[]'); } catch { return []; } })();
+ return new Set(parsed.map(m => m.modelKey).filter(Boolean));
+ },
+ load: async (model) => {
+ const lms = await whichFirst('lms');
+ if (!lms) return { ok: false, reason: "'lms' CLI not on PATH" };
+ // `lms load` blocks until ready (5–30s cold). The caller runs this
+ // fire-and-forget so reconcile returns immediately.
+ await pexec(lms, ['load', model], { timeout: 5 * 60 * 1000 });
+ return { ok: true, reason: '' };
+ },
+};
+
+const PROVISIONERS = {
+ [ollamaProvisioner.id]: ollamaProvisioner,
+ [lmStudioProvisioner.id]: lmStudioProvisioner,
+};
+
+/**
+ * The provisioner for `providerId`, or `null` when that provider needs no
+ * local provisioning.
+ *
+ * A remote OpenAI-compatible provider (OpenAI, Groq, a self-hosted vLLM) serves
+ * its own models — there is nothing to pull or pre-warm, so returning `null` is
+ * the correct answer rather than an error. `sortPreferred` / the chat path
+ * still work against it through `resolveLlmEndpoint`.
+ */
+export { DEFAULT_VOICE_BACKEND };
+
+export const getVoiceProvisioner = (providerId) => PROVISIONERS[providerId] || null;
+
+/** Rank installed models the way voice's `auto` picks: fast and non-reasoning first. */
+export const sortPreferred = (ids) => ids.slice().sort((a, b) => {
+ const ar = isReasoningModel(a) ? 1 : 0;
+ const br = isReasoningModel(b) ? 1 : 0;
+ if (ar !== br) return ar - br;
+ return sizeOf(a) - sizeOf(b);
+});
diff --git a/server/services/voice/modelProvisioners.test.js b/server/services/voice/modelProvisioners.test.js
new file mode 100644
index 0000000000..8fe8ba0d7c
--- /dev/null
+++ b/server/services/voice/modelProvisioners.test.js
@@ -0,0 +1,136 @@
+import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
+
+vi.mock('../ollamaManager.js', () => ({
+ getInstalledModels: vi.fn(),
+ getLastInstalledModelsError: vi.fn(() => null),
+ getModelCapabilities: vi.fn(),
+ getLoadedModels: vi.fn(),
+ pullModel: vi.fn(),
+ ensureRunning: vi.fn(),
+ warmModel: vi.fn(),
+}));
+
+const ollamaManager = await import('../ollamaManager.js');
+const { getVoiceProvisioner, defaultToolModelChain, sizeOf, paramsToB, CHAIN_ENTRIES } = await import('./modelProvisioners.js');
+
+const ollama = getVoiceProvisioner('ollama');
+const lmstudio = getVoiceProvisioner('lmstudio');
+
+beforeEach(() => vi.clearAllMocks());
+
+describe('getVoiceProvisioner', () => {
+ it('serves both built-in local backends and nothing for a remote provider', () => {
+ expect(ollama.id).toBe('ollama');
+ expect(lmstudio.id).toBe('lmstudio');
+ // A remote OpenAI-compatible provider serves its own models — there is
+ // nothing to install or pre-warm, so `null` is the answer, not an error.
+ expect(getVoiceProvisioner('openai')).toBeNull();
+ });
+});
+
+// The sentinel is the whole point of this module: `null` = "could not ask",
+// `[]` = "asked, nothing installed". Collapsing them is what made voice chase
+// a four-entry install chain on every boot against a backend that was down.
+describe('listModels sentinel', () => {
+ it('reports an unreachable Ollama as null, not an empty list', async () => {
+ ollamaManager.getInstalledModels.mockResolvedValue([]);
+ ollamaManager.getLastInstalledModelsError.mockReturnValue('Ollama is unavailable');
+ expect(await ollama.listModels()).toBeNull();
+ });
+
+ it('reports a reachable but empty Ollama as an empty list', async () => {
+ ollamaManager.getInstalledModels.mockResolvedValue([]);
+ ollamaManager.getLastInstalledModelsError.mockReturnValue(null);
+ expect(await ollama.listModels()).toEqual([]);
+ });
+
+ it('maps installed Ollama models to their ids', async () => {
+ ollamaManager.getInstalledModels.mockResolvedValue([{ id: 'qwen2.5:7b-instruct' }, { name: 'granite4.1:3b' }]);
+ ollamaManager.getLastInstalledModelsError.mockReturnValue(null);
+ expect(await ollama.listModels()).toEqual(['qwen2.5:7b-instruct', 'granite4.1:3b']);
+ });
+
+ it('reports an unreachable LM Studio as null, not an empty list', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('ECONNREFUSED'); }));
+ expect(await lmstudio.listModels()).toBeNull();
+ vi.unstubAllGlobals();
+ });
+
+ it('reports a reachable but empty LM Studio as an empty list', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => ({ data: [] }) })));
+ expect(await lmstudio.listModels()).toEqual([]);
+ vi.unstubAllGlobals();
+ });
+});
+
+describe('tool capability', () => {
+ it('trusts Ollama /api/show capabilities over the id heuristic', async () => {
+ // `granite4.1:3b` carries no tool-ish token in its id, so the LM Studio
+ // heuristic would miss it — Ollama reports the fact directly.
+ ollamaManager.getModelCapabilities.mockResolvedValue(['completion', 'tools']);
+ expect(await ollama.isToolCapable('granite4.1:3b')).toBe(true);
+
+ ollamaManager.getModelCapabilities.mockResolvedValue(['completion']);
+ expect(await ollama.isToolCapable('qwen2.5:7b-instruct')).toBe(false);
+ });
+
+ it('falls back to the id heuristic when the capability probe fails', async () => {
+ // null = the probe failed. "Unknown" must not read as "no tools".
+ ollamaManager.getModelCapabilities.mockResolvedValue(null);
+ expect(await ollama.isToolCapable('qwen2.5-7b-instruct')).toBe(true);
+ });
+});
+
+describe('defaultToolModelChain', () => {
+ it('derives small non-reasoning tool models from the shared catalog, smallest first', () => {
+ const chain = defaultToolModelChain('ollama');
+ expect(chain.length).toBeGreaterThan(0);
+ const sizes = CHAIN_ENTRIES('ollama').map(e => paramsToB(e.params));
+ expect([...sizes].sort((a, b) => a - b)).toEqual(sizes);
+ expect(sizes.every(s => s <= 10)).toBe(true);
+ // Every entry must be a real install target, not an unparseable size that
+ // slipped through the cap because Infinity <= 10 is false but NaN isn't.
+ expect(sizes.every(Number.isFinite)).toBe(true);
+ });
+
+ // Regression: `params` below a billion is written in MILLIONS. Ranking the
+ // chain with the id-based `sizeOf` scored "270M" as Infinity and sorted the
+ // smallest, fastest function-calling model LAST.
+ it('ranks a sub-billion model ahead of a multi-billion one', () => {
+ expect(paramsToB('270M')).toBeCloseTo(0.27);
+ expect(paramsToB('7B')).toBe(7);
+ expect(paramsToB('3.8B')).toBe(3.8);
+ expect(paramsToB('')).toBe(Infinity);
+ expect(sizeOf('functiongemma:270m')).toBe(Infinity);
+ expect(paramsToB('270M')).toBeLessThan(paramsToB('3B'));
+ });
+
+ it('produces backend-native ids per backend', () => {
+ // The same catalog entry has a different install id per backend; a chain
+ // must never hand LM Studio repo ids to `ollama pull`.
+ expect(defaultToolModelChain('ollama')).not.toEqual(defaultToolModelChain('lmstudio'));
+ });
+
+ it('honours the single-id env override', () => {
+ process.env.PORTOS_VOICE_DEFAULT_TOOL_MODEL = 'custom/model:tag';
+ expect(defaultToolModelChain('ollama')).toEqual(['custom/model:tag']);
+ delete process.env.PORTOS_VOICE_DEFAULT_TOOL_MODEL;
+ });
+});
+
+describe('ollama load', () => {
+ afterEach(() => vi.clearAllMocks());
+
+ it('warms the model once the daemon is confirmed running', async () => {
+ ollamaManager.ensureRunning.mockResolvedValue({ success: true, running: true });
+ ollamaManager.warmModel.mockResolvedValue({ warmed: true, model: 'granite4.1:3b' });
+ expect(await ollama.load('granite4.1:3b')).toEqual({ ok: true, reason: '' });
+ expect(ollamaManager.warmModel).toHaveBeenCalledWith('granite4.1:3b');
+ });
+
+ it('does not attempt a warm when the daemon could not be started', async () => {
+ ollamaManager.ensureRunning.mockResolvedValue({ success: false, error: 'port in use' });
+ expect(await ollama.load('granite4.1:3b')).toEqual({ ok: false, reason: 'port in use' });
+ expect(ollamaManager.warmModel).not.toHaveBeenCalled();
+ });
+});