Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
address review (codex): detect LM Studio by capability, always report modelPresent
[._.]/ Adam Eivyc32896373b46
diff --git a/client/src/components/brain/tabs/ConfigTab.jsx b/client/src/components/brain/tabs/ConfigTab.jsxindex eec48f594a..2ceb8a2836 100644--- a/client/src/components/brain/tabs/ConfigTab.jsx+++ b/client/src/components/brain/tabs/ConfigTab.jsx@@ -293,9 +293,12 @@ export default function ConfigTab({ onRefresh }) {<h3 className="text-md font-semibold text-white">Embeddings (semantic search)</h3></div>- {/* Live backend status */}+ {/* Live backend status. Green requires a positive model-present signal+ (the backend always returns modelPresent now) — a reachable backend+ with no usable embedding model is a warning, not success, because+ embedding calls would silently return null. */}{embeddingStatus && (- embeddingStatus.available && embeddingStatus.modelPresent !== false ? (+ embeddingStatus.available && embeddingStatus.modelPresent === true ? (<div className="flex items-center gap-2 text-xs text-port-success"><CheckCircle size={14} /><span>Reachable — model <span className="font-mono">{embeddingStatus.embeddingModel || '—'}</span></span>@@ -305,7 +308,7 @@ export default function ConfigTab({ onRefresh }) {<AlertTriangle size={14} className="mt-0.5 flex-shrink-0" /><span>{embeddingStatus.available- ? `Backend reachable but model "${embeddingModel}" isn't available there — pick an installed model (e.g. nomic-embed-text on Ollama).`+ ? `Backend reachable but no usable embedding model ("${embeddingStatus.embeddingModel || embeddingModel}") — pick/install one (e.g. nomic-embed-text on Ollama) before reprocessing.`: `Embedding backend unreachable: ${embeddingStatus.error || 'unknown error'}`}</span></div>diff --git a/server/services/memoryEmbeddings.js b/server/services/memoryEmbeddings.jsindex 4f7b021aee..51eeef779a 100644--- a/server/services/memoryEmbeddings.js+++ b/server/services/memoryEmbeddings.js@@ -26,6 +26,28 @@ function getBaseUrl(config) {return config.embeddingEndpoint.replace(/\/v1\/embeddings$/, '');}+/**+ * Probe whether the configured endpoint is an LM Studio backend by hitting its+ * NATIVE `/api/v0/models` API (which lists every downloaded model + type ++ * load-state). Returns the parsed model list when it's LM Studio, or `null`+ * when the endpoint doesn't speak that API — i.e. any other OpenAI-compatible+ * backend (Ollama, llama.cpp, …), which serves only `/v1/*` and 404s this.+ *+ * Detecting by CAPABILITY rather than by provider id (`=== 'lmstudio'`) means a+ * renamed/custom provider id still pointing at LM Studio keeps its lazy-load+ * behavior, and a non-LM-Studio backend is recognized regardless of its id.+ */+async function probeLmStudioModels(config) {+ const baseUrl = getBaseUrl(config);+ const response = await fetchWithTimeout(`${baseUrl}/api/v0/models`, {}, MODEL_LIST_TIMEOUT_MS)+ .catch(() => null);+ if (!response || !response.ok) return null;+ const models = await readResponseJson(response);+ // A non-LM-Studio backend that happens to 200 this path won't carry the+ // native shape (array of { id, type, state }); guard on it.+ return Array.isArray(models?.data) ? models.data : null;+}+/*** Discover and auto-load an embedding model in LM Studio.* Uses the REST API to find downloaded embedding models and load one if needed.@@ -34,28 +56,21 @@ function getBaseUrl(config) {* native `/api/v0/models` + `/api/v1/models/load` API to discover and pin one.* Other OpenAI-compatible embedding backends (Ollama, etc.) serve* `/v1/embeddings` directly with no load step and don't implement those- * endpoints — so for them we skip the dance and trust the configured model id.- * Without this guard, an Ollama-backed config would 404 the LMS-only URLs on- * every call (modelEnsured never latches → repeated failed probes per embed).+ * endpoints — detected here by the native-API probe coming back empty, in which+ * case we skip the dance and trust the configured model id. Without this, an+ * Ollama-backed config would 404 the LMS-only URLs on every call (modelEnsured+ * never latches → repeated failed probes per embed).*/async function ensureEmbeddingModelLoaded(config) {if (modelEnsured) return;- // Only LM Studio needs (and implements) the discover-and-load dance.- if (config.embeddingProvider !== 'lmstudio') {+ const allModels = await probeLmStudioModels(config);+ // Not an LM Studio backend (Ollama, etc.) — no load step exists; trust config.+ if (allModels === null) {modelEnsured = true;return;}- const baseUrl = getBaseUrl(config);-- // Query LM Studio's native API for all downloaded models- const response = await fetchWithTimeout(`${baseUrl}/api/v0/models`, {}, MODEL_LIST_TIMEOUT_MS);-- if (!response.ok) return;-- const models = await readResponseJson(response);- const allModels = models.data || [];const embeddingModels = allModels.filter(m => m.type === 'embeddings');// Check if an embedding model is already loaded@@ -81,6 +96,7 @@ async function ensureEmbeddingModelLoaded(config) {const modelToLoad = candidates[0];console.log(`📦 Auto-loading embedding model: ${modelToLoad.id}`);+ const baseUrl = getBaseUrl(config);const loadResponse = await fetchWithTimeout(`${baseUrl}/api/v1/models/load`, {method: 'POST',headers: { 'Content-Type': 'application/json' },@@ -171,41 +187,38 @@ export async function checkAvailability() {const data = await readResponseJson(response);const models = data.data?.map(m => m.id) || [];- // For a non-LM-Studio provider (Ollama, etc.) the configured model id is- // authoritative — don't guess from `.includes('embed')` (it could latch onto- // the wrong listed model). Just confirm it's present; the load dance is a- // no-op for these backends.- if (config.embeddingProvider !== 'lmstudio') {+ // Is this an LM Studio backend? Detect by capability (native API), not id, so+ // a renamed provider still gets the load behavior.+ const lmsModels = await probeLmStudioModels(config);++ if (lmsModels === null) {+ // Non-LM-Studio (Ollama, etc.): the configured model id is authoritative —+ // don't guess from `.includes('embed')` (could latch onto the wrong model).+ // The load dance is a no-op for these backends.modelEnsured = true;const present = models.some(id => id === config.embeddingModel || id.startsWith(`${config.embeddingModel}:`));- return {- available: true,- models,- embeddingModel: config.embeddingModel,- modelPresent: present,- endpoint: config.embeddingEndpoint- };+ return { available: true, models, embeddingModel: config.embeddingModel, modelPresent: present, endpoint: config.embeddingEndpoint };}- // LM Studio: if no embedding model is loaded, try to auto-load one.- const hasEmbeddingModel = models.some(id => id.includes('embed'));- if (!hasEmbeddingModel) {+ // LM Studio: auto-load an embedding model if none is loaded, then report+ // whether one is actually loaded so the UI can't show green on an empty LMS.+ const loaded = lmsModels.find(m => m.type === 'embeddings' && m.state === 'loaded');+ if (loaded) {+ config.embeddingModel = loaded.id;+ modelEnsured = true;+ } else {await ensureEmbeddingModelLoaded(config).catch(err =>console.warn(`⚠️ Could not auto-load embedding model: ${err.message}`));- } else {- // Use the loaded embedding model's actual ID- const embeddingModelId = models.find(id => id.includes('embed'));- if (embeddingModelId) {- config.embeddingModel = embeddingModelId;- modelEnsured = true;- }}return {available: true,models,embeddingModel: config.embeddingModel,+ // `modelEnsured` latches true only once an embeddings model is loaded (here+ // or inside ensureEmbeddingModelLoaded) — the honest model-present signal.+ modelPresent: modelEnsured,endpoint: config.embeddingEndpoint};}diff --git a/server/services/memoryEmbeddings.test.js b/server/services/memoryEmbeddings.test.jsindex dcbd7f5e7b..2e816c1b6c 100644--- a/server/services/memoryEmbeddings.test.js+++ b/server/services/memoryEmbeddings.test.js@@ -32,23 +32,33 @@ afterEach(() => {// Build a fake `GET /v1/models` response. readResponseJson() reads the body via// `.text()` (it tolerates non-JSON), so the payload must be the JSON string.-const mockModelsResponse = (ids) => {- const body = JSON.stringify({ data: ids.map((id) => ({ id })) });+const okJson = (obj) => {+ const body = JSON.stringify(obj);return { ok: true, json: async () => JSON.parse(body), text: async () => body };};+const mockModelsResponse = (ids) => okJson({ data: ids.map((id) => ({ id })) });++// An Ollama-style backend: serves /v1/models but 404s LM Studio's native+// /api/v0/models capability probe. Route by URL so the probe is recognized as+// "not LM Studio".+const ollamaFetch = (v1ModelIds) => (url) => {+ if (String(url).includes('/api/v0/models')) {+ return Promise.resolve({ ok: false, status: 404, json: async () => ({}), text: async () => '' });+ }+ return Promise.resolve(mockModelsResponse(v1ModelIds));+};describe('memoryEmbeddings — provider-aware config (Ollama vs LM Studio)', () => {- it('uses the configured model for a non-LM-Studio provider and reports modelPresent', async () => {+ it('uses the configured model for a non-LM-Studio backend and reports modelPresent', async () => {getCosConfig.mockResolvedValue({ embeddingProviderId: 'ollama', embeddingModel: 'nomic-embed-text' });getProviderById.mockResolvedValue({ id: 'ollama', endpoint: 'http://localhost:11434/v1' });- // Ollama's /v1/models lists installed models tagged with :latest.- fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(- mockModelsResponse(['nomic-embed-text:latest', 'llama3.2:latest'])+ // /v1/models lists installed models tagged with :latest; /api/v0/models 404s.+ fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(+ ollamaFetch(['nomic-embed-text:latest', 'llama3.2:latest']));const status = await embeddings.checkAvailability();- // Probed /v1/models on the OLLAMA endpoint, not LM Studio's :1234.expect(fetchSpy).toHaveBeenCalledWith('http://localhost:11434/v1/models',expect.objectContaining({ method: 'GET' })@@ -60,12 +70,10 @@ describe('memoryEmbeddings — provider-aware config (Ollama vs LM Studio)', ()expect(status.modelPresent).toBe(true);});- it('flags modelPresent:false when the configured model is not installed on the provider', async () => {+ it('flags modelPresent:false when the configured model is not installed on the backend', async () => {getCosConfig.mockResolvedValue({ embeddingProviderId: 'ollama', embeddingModel: 'mxbai-embed-large' });getProviderById.mockResolvedValue({ id: 'ollama', endpoint: 'http://localhost:11434/v1' });- fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(- mockModelsResponse(['nomic-embed-text:latest'])- );+ fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(ollamaFetch(['nomic-embed-text:latest']));const status = await embeddings.checkAvailability();@@ -73,18 +81,43 @@ describe('memoryEmbeddings — provider-aware config (Ollama vs LM Studio)', ()expect(status.modelPresent).toBe(false);});- it('does NOT hit LM Studio model-load endpoints for a non-LM-Studio provider', async () => {+ it('does NOT POST the LM Studio load endpoint for a non-LM-Studio backend', async () => {getCosConfig.mockResolvedValue({ embeddingProviderId: 'ollama', embeddingModel: 'nomic-embed-text' });getProviderById.mockResolvedValue({ id: 'ollama', endpoint: 'http://localhost:11434/v1' });- fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(mockModelsResponse(['nomic-embed-text:latest']));+ fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(ollamaFetch(['nomic-embed-text:latest']));await embeddings.checkAvailability();- // The LM-Studio-only discover/load dance (/api/v0/models, /api/v1/models/load)- // must never be called for Ollama.- const urls = fetchSpy.mock.calls.map((c) => c[0]);- expect(urls.some((u) => u.includes('/api/v0/models'))).toBe(false);- expect(urls.some((u) => u.includes('/api/v1/models/load'))).toBe(false);+ // The native probe (/api/v0/models) may be attempted (it's how we DETECT+ // non-LMS — it 404s), but the model-LOAD POST must never fire for Ollama.+ const loadCalls = fetchSpy.mock.calls.filter((c) => String(c[0]).includes('/api/v1/models/load'));+ expect(loadCalls.length).toBe(0);+ });++ it('detects LM Studio by capability even under a renamed provider id, and only greens when a model is loaded', async () => {+ // Provider id is NOT "lmstudio" — but the endpoint serves the native API.+ getCosConfig.mockResolvedValue({ embeddingProviderId: 'my-local-lms', embeddingModel: '' });+ getProviderById.mockResolvedValue({ id: 'my-local-lms', endpoint: 'http://localhost:1234/v1' });+ fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation((url) => {+ if (String(url).includes('/api/v0/models')) {+ // LM Studio native API: a downloaded-but-NOT-loaded embedding model.+ return Promise.resolve(okJson({ data: [{ id: 'nomic-embed-v1.5', type: 'embeddings', state: 'not-loaded' }] }));+ }+ if (String(url).includes('/api/v1/models/load')) {+ return Promise.resolve({ ok: true, json: async () => ({}), text: async () => '' });+ }+ return Promise.resolve(mockModelsResponse(['some-chat-model'])); // /v1/models+ });++ const status = await embeddings.checkAvailability();++ expect(status.available).toBe(true);+ // It recognized LM Studio (renamed id) and ran the load dance.+ const loadCalls = fetchSpy.mock.calls.filter((c) => String(c[0]).includes('/api/v1/models/load'));+ expect(loadCalls.length).toBe(1);+ // After a successful load, modelPresent is true and the model id is set.+ expect(status.modelPresent).toBe(true);+ expect(status.embeddingModel).toContain('nomic-embed');});it('reports unreachable when the embedding backend GET fails', async () => {