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(lmstudio): auto-load a model on "No models loaded" 400

Adam Eivy9227ec66288d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index d85cab1dd9..92760a7ef9 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,7 @@
## Fixed
+- **LM Studio auto-loads a model on "No models loaded" 400.** Any caller of `callProviderAISimple` (taste questionnaire, identity, autobiography, insights, jiraReports, goalCheckIn) that hit a cold LM Studio used to error out with `Provider returned 400: { ... "No models loaded" ... }`. Now on that specific error pattern, the helper lists LM Studio's downloaded LLMs via `/api/v0/models`, picks one (preferring `provider.defaultModel`, then any id in `provider.models` that's downloaded, else the first downloaded LLM), loads it via `POST /api/v1/models/load`, and retries the chat-completion. Mirrors the existing pattern in `services/memoryClassifier.js` but driven from the provider config so every API caller benefits. File: `server/lib/aiProvider.js`.
- **Stop showing the same error toast 3-4 times.** A single failing API call could surface its error message multiple times because three independent channels all toasted the same payload: `apiCore.request` toasts on every non-OK response, the server emits both `io.emit('error:occurred')` (broadcast) and `errorEvents → broadcastToErrors('error:notified')` (subscriber) for the same error, and `useErrorNotifications` listened to *both* socket events with the same handler. Two changes: (1) `useErrorNotifications` now subscribes to the targeted `error:notified` channel only — `error:occurred` was the duplicate broadcast leg — and (2) the Toast layer added a content-based dedup window (1.5s) so any duplicate from any source is silently dropped. Explicit-`id` toasts (loading→success swaps) skip dedup so progress toasts still update in place. Files: `client/src/components/ui/Toast.jsx`, `client/src/hooks/useErrorNotifications.js`.
- **Media Gen Video defaults to the smallest model.** The macOS default was LTX-2 Unified (~42 GB). New default is LTX-2.3 Distilled Q4 (~22 GB) so a fresh install fits on smaller machines without a manual override. File: `server/services/videoGen/local.js`.
- **Taste questionnaire falls back to a configured API provider.** The Digital Twin → Taste tab was auto-selecting the first enabled provider for `Generate Summary` / `Go Deeper`. When that happened to be a CLI provider (Claude Code, Codex, Gemini CLI), the request failed with a generic "requires an API-based provider" toast — three times, because both the API client and two socket subscribers re-toasted the same error. Now (1) the section provider picker filters to API-type providers only, (2) the server resolves any usable API provider when the requested one isn't compatible (requested → active → first enabled API) via a new `resolveAPIProvider` helper in `server/lib/aiProvider.js`, (3) the section-complete view shows an inline link to AI Providers when no compatible provider is configured instead of leaving the user with a wall of red toasts and no direction, and (4) the redundant component-level `toast.error` calls were removed (apiCore already toasts on non-OK responses). Files: `server/lib/aiProvider.js`, `server/services/taste-questionnaire.js`, `client/src/components/digital-twin/tabs/TasteTab.jsx`.
diff --git a/server/lib/aiProvider.js b/server/lib/aiProvider.js
index 45a0c1f420..b59d4c21a1 100644
--- a/server/lib/aiProvider.js
+++ b/server/lib/aiProvider.js
@@ -39,50 +39,135 @@ export async function resolveAPIProvider(requestedProviderId) {
return providers.find(isAPI) || null;
}
+// LM Studio's chat-completions endpoint returns this when no model is in
+// memory. The error is identical regardless of which model name the request
+// asked for, so retrying with a different name is pointless — we have to
+// actually load a model first via /api/v1/models/load.
+const LM_STUDIO_NO_MODEL_RE = /no models loaded/i;
+
+const lmStudioBaseFromEndpoint = (endpoint) =>
+ (endpoint || '').replace(/\/v1\/?$/, '').replace(/\/+$/, '');
+
+/**
+ * When LM Studio reports "No models loaded", list its downloaded LLMs and
+ * load the user's preferred one (provider.defaultModel → first id in
+ * provider.models that's downloaded → first downloaded LLM). Returns the
+ * id of a model that's now loaded, or null if we couldn't auto-load anything.
+ *
+ * Pattern mirrors `ensureLLMModelLoaded` in services/memoryClassifier.js but
+ * is provider-config-driven so any caller of callProviderAISimple gets the
+ * same auto-recovery on first-use cold starts.
+ */
+async function ensureLMStudioModelLoaded(provider) {
+ const baseUrl = lmStudioBaseFromEndpoint(provider.endpoint);
+ if (!baseUrl) return null;
+
+ const listCtl = new AbortController();
+ const listTimer = setTimeout(() => listCtl.abort(), 5000);
+ const listResp = await fetch(`${baseUrl}/api/v0/models`, {
+ method: 'GET',
+ signal: listCtl.signal
+ }).catch(() => null).finally(() => clearTimeout(listTimer));
+
+ if (!listResp?.ok) return null;
+ const payload = await listResp.json().catch(() => null);
+ const llms = (payload?.data || []).filter(m => m.type === 'llm');
+ if (llms.length === 0) {
+ console.warn('⚠️ LM Studio has no downloaded LLMs — auto-load impossible');
+ return null;
+ }
+
+ const findInList = (name) => name && llms.find(m => m.id === name || m.id.includes(name));
+ const preferences = [provider.defaultModel, ...(provider.models || [])].filter(Boolean);
+
+ // If something is already loaded, prefer the configured default if it's in
+ // memory, otherwise just use whatever LM Studio has loaded.
+ const alreadyLoaded = llms.filter(m => m.state === 'loaded');
+ if (alreadyLoaded.length > 0) {
+ const match = preferences.map(findInList).find(Boolean) || alreadyLoaded[0];
+ return alreadyLoaded.find(m => m.id === match.id)?.id || alreadyLoaded[0].id;
+ }
+
+ const target = preferences.map(findInList).find(Boolean) || llms[0];
+ console.log(`📦 LM Studio reported no models loaded — auto-loading: ${target.id}`);
+
+ const loadCtl = new AbortController();
+ const loadTimer = setTimeout(() => loadCtl.abort(), 120000);
+ const loadResp = await fetch(`${baseUrl}/api/v1/models/load`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ model: target.id }),
+ signal: loadCtl.signal
+ }).catch(err => ({ ok: false, _err: err.message })).finally(() => clearTimeout(loadTimer));
+
+ if (!loadResp.ok) {
+ const errText = loadResp._err || await loadResp.text?.().catch(() => 'unknown error') || 'unknown error';
+ console.error(`❌ Failed to auto-load LM Studio model ${target.id}: ${errText}`);
+ return null;
+ }
+
+ console.log(`✅ LM Studio model loaded: ${target.id}`);
+ return target.id;
+}
+
+async function postChatCompletion(provider, model, prompt, { temperature, max_tokens, timeout }) {
+ const headers = { 'Content-Type': 'application/json' };
+ if (provider.apiKey) headers['Authorization'] = `Bearer ${provider.apiKey}`;
+
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), timeout);
+
+ let response;
+ try {
+ response = await fetch(`${provider.endpoint}/chat/completions`, {
+ method: 'POST',
+ headers,
+ signal: controller.signal,
+ body: JSON.stringify({ model, messages: [{ role: 'user', content: prompt }], temperature, max_tokens })
+ });
+ } catch (err) {
+ clearTimeout(timer);
+ return { error: `Provider request failed: ${err.message}` };
+ }
+ clearTimeout(timer);
+
+ if (!response.ok) {
+ const errorText = await response.text().catch(() => 'Unknown error');
+ return { error: `Provider returned ${response.status}: ${errorText}`, status: response.status, body: errorText };
+ }
+
+ const data = await response.json();
+ return { text: data.choices?.[0]?.message?.content || '' };
+}
+
/**
* Call an API-based AI provider with a simple prompt.
* Returns { text } on success, { error } on failure.
+ *
+ * On an LM Studio "No models loaded" 400, this auto-loads a model from the
+ * provider's configured models list and retries once. The retry uses the
+ * actually-loaded model id rather than re-sending the original `model`,
+ * since LM Studio's model resolver is name-fuzzy and always returns the
+ * loaded one in chat-completion responses anyway.
*/
export async function callProviderAISimple(provider, model, prompt, { temperature = 0.3, max_tokens = 1000 } = {}) {
- const timeout = provider.timeout || 300000;
-
- if (provider.type === 'api') {
- const headers = { 'Content-Type': 'application/json' };
- if (provider.apiKey) headers['Authorization'] = `Bearer ${provider.apiKey}`;
-
- const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), timeout);
-
- let response;
- try {
- response = await fetch(`${provider.endpoint}/chat/completions`, {
- method: 'POST',
- headers,
- signal: controller.signal,
- body: JSON.stringify({
- model,
- messages: [{ role: 'user', content: prompt }],
- temperature,
- max_tokens
- })
- });
- } catch (err) {
- clearTimeout(timer);
- return { error: `Provider request failed: ${err.message}` };
- }
+ if (provider.type !== 'api') {
+ return { error: 'This operation requires an API-based provider' };
+ }
+ const opts = { temperature, max_tokens, timeout: provider.timeout || 300000 };
- clearTimeout(timer);
+ const first = await postChatCompletion(provider, model, prompt, opts);
+ if (!first.error) return { text: first.text };
- if (!response.ok) {
- const errorText = await response.text().catch(() => 'Unknown error');
- return { error: `Provider returned ${response.status}: ${errorText}` };
+ if (first.status === 400 && LM_STUDIO_NO_MODEL_RE.test(first.body || '')) {
+ const loaded = await ensureLMStudioModelLoaded(provider);
+ if (loaded) {
+ const retry = await postChatCompletion(provider, loaded, prompt, opts);
+ if (!retry.error) return { text: retry.text };
+ return { error: retry.error };
}
-
- const data = await response.json();
- return { text: data.choices?.[0]?.message?.content || '' };
}
-
- return { error: 'This operation requires an API-based provider' };
+ return { error: first.error };
}
/**