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

address review: local-llm robustness + copilot threads

Adam Eivy672742f83f91
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsx
index d786260f35..c9c7d9eceb 100644
--- a/client/src/components/settings/LocalLlmTab.jsx
+++ b/client/src/components/settings/LocalLlmTab.jsx
@@ -240,20 +240,22 @@ export function LocalLlmTab() {
<div className="flex flex-col sm:flex-row gap-2">
<div className="flex-1 flex items-center gap-2 bg-port-bg border border-port-border rounded-lg px-3">
<Search size={14} className="text-gray-500" />
+ <label htmlFor="llm-catalog-search" className="sr-only">{`Search the ${labelFor(selected)} model catalog`}</label>
<input
+ id="llm-catalog-search"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={`Search the ${labelFor(selected)} catalog…`}
- aria-label={`Search the ${labelFor(selected)} model catalog`}
className="flex-1 bg-transparent py-2 text-sm text-white placeholder-gray-600 focus:outline-none"
/>
</div>
<div className="flex items-center gap-2">
+ <label htmlFor="llm-manual-install" className="sr-only">{`Install a ${labelFor(selected)} model by id`}</label>
<input
+ id="llm-manual-install"
value={manualId}
onChange={(e) => setManualId(e.target.value)}
placeholder={selected === 'ollama' ? 'pull by name e.g. llama3.2' : 'publisher/Model-GGUF'}
- aria-label={`Install a ${labelFor(selected)} model by id`}
className="flex-1 sm:w-56 bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-port-accent"
/>
<button
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 5bfc185d7b..1ba00a262a 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1047,7 +1047,7 @@ export const localLlmBackendSchema = z.enum(['ollama', 'lmstudio']);
// a leading dash (would be parsed as a flag) and control chars (NUL / newline).
export const localLlmModelIdSchema = z.string().min(1).max(256)
.refine((v) => !v.startsWith('-'), { message: 'modelId may not start with "-"' })
- .refine((v) => !/[\r\n]/.test(v), { message: 'modelId may not contain control characters' });
+ .refine((v) => !/[\0\r\n]/.test(v), { message: 'modelId may not contain control characters (NUL, CR, LF)' });
export const localLlmInstallSchema = z.object({
backend: localLlmBackendSchema,
modelId: localLlmModelIdSchema,
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index ecf31adc30..ab4630a0c5 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -54,14 +54,22 @@ router.post('/install', asyncHandler(async (req, res) => {
const { backend, modelId } = validateRequest(localLlmInstallSchema, req.body)
const emit = emitter(req)
emit('start', `Installing ${modelId} on ${backend}…`)
+ // A thrown rejection (e.g. the pull stream dropping mid-download) would 500
+ // via asyncHandler but never emit a terminal progress frame, leaving the
+ // client's progress banner stuck on the last 'start'. Surface it as 'error'.
const result = await installModel(backend, modelId, (p) => {
if (p?.percent != null) emit('start', `${modelId}: ${p.status || 'downloading'} ${p.percent}%`)
+ }).catch((err) => {
+ emit('error', `Install failed: ${err.message}`)
+ throw err
})
if (!result.success) {
emit('error', result.error || 'Install failed')
return res.status(502).json({ error: result.error || 'Install failed', modelId })
}
- emit('complete', `${modelId} installed on ${backend}`)
+ emit('complete', result.pending
+ ? `${modelId} download started in LM Studio — it'll finish in the background`
+ : `${modelId} installed on ${backend}`)
res.json({ success: true, ...result })
}))
diff --git a/server/services/localLlm.js b/server/services/localLlm.js
index b99fa2e440..309e8d8d37 100644
--- a/server/services/localLlm.js
+++ b/server/services/localLlm.js
@@ -27,6 +27,11 @@ const execFileAsync = promisify(execFile)
const ENV_PATH = join(PATHS.root, '.env')
const DEFAULT_BACKEND = 'ollama'
+// `lms get` blocks until the download finishes — generous but finite so a
+// stalled connection (or an unexpected interactive prompt) can't hang the
+// request forever. Large models on a slow link still fit comfortably.
+const LMS_INSTALL_TIMEOUT_MS = 60 * 60 * 1000
+
// aiToolkit provider id that pairs with each backend.
const PROVIDER_ID = { ollama: 'ollama', lmstudio: 'lmstudio' }
@@ -109,11 +114,17 @@ function normalizeModels(backend, models) {
}))
}
-/** Installed models for a backend, normalized. */
-export async function listModels(backend) {
+/**
+ * Installed models for a backend, normalized.
+ * @param {boolean} [forceRefresh] - bypass the Ollama installed-models cache.
+ * Default false so the catalog-overlay path (hit on every debounced keystroke)
+ * reuses the cache instead of spamming `/api/tags`. The cache is busted on
+ * pull/delete, so it stays accurate; force only for explicit refresh/migrate.
+ */
+export async function listModels(backend, forceRefresh = false) {
if (!isBackend(backend)) return []
const raw = backend === 'ollama'
- ? await ollamaManager.getInstalledModels(true)
+ ? await ollamaManager.getInstalledModels(forceRefresh)
: await lmStudioManager.getAvailableModels()
return normalizeModels(backend, raw)
}
@@ -127,7 +138,9 @@ export async function getStatus() {
commandExists('ollama', ['--version']),
lmStudioManager.getStatus(),
commandExists('lms', ['version']),
- listModels('lmstudio').catch(() => []) // already normalized
+ // already normalized; capture (don't swallow) a list failure so the UI can
+ // distinguish "no models" from "couldn't read the model list".
+ listModels('lmstudio').then((models) => ({ models, error: null })).catch((err) => ({ models: [], error: err.message }))
])
return {
@@ -145,8 +158,9 @@ export async function getStatus() {
available: lmStudioStatus.available,
hasCli: lmsCli,
baseUrl: lmStudioStatus.baseUrl,
- modelCount: lmStudioModels.length,
- models: lmStudioModels
+ modelCount: lmStudioModels.models.length,
+ models: lmStudioModels.models,
+ modelsError: lmStudioModels.error
}
}
}
@@ -162,18 +176,23 @@ export async function installModel(backend, modelId, onProgress) {
if (backend === 'ollama') {
return ollamaManager.pullModel(modelId, onProgress)
}
- // LM Studio: prefer the `lms` CLI (real download), fall back to the REST hook.
+ // LM Studio: prefer the `lms` CLI (real, blocking download), fall back to the
+ // REST hook.
if (await commandExists('lms', ['version'])) {
// `lms get` streams substantial progress to stdout; the default 1MB
// maxBuffer overflows and surfaces as a false install failure (see
// voice/bootstrap.js which uses the same 64MB ceiling for `lms get`).
- const r = await execFileAsync('lms', ['get', '-y', modelId], { timeout: 0, maxBuffer: 64 * 1024 * 1024 })
+ const r = await execFileAsync('lms', ['get', '-y', modelId], { timeout: LMS_INSTALL_TIMEOUT_MS, maxBuffer: 64 * 1024 * 1024 })
.then(() => ({ ok: true })).catch((err) => ({ _err: err.stderr || err.message }))
if (r._err) return { success: false, error: r._err, modelId }
lmStudioManager.resetCache()
return { success: true, modelId }
}
- return lmStudioManager.downloadModel(modelId)
+ // REST fallback only *queues* the download — LM Studio pulls it in the
+ // background and the call returns immediately. Flag it `pending` so callers
+ // don't claim the model is installed before it actually is.
+ const r = await lmStudioManager.downloadModel(modelId)
+ return r.success ? { ...r, pending: true } : r
}
/**
@@ -218,10 +237,15 @@ export async function switchBackend(to) {
*/
export async function migrateBackend(to, onProgress = () => {}) {
if (!isBackend(to)) return { success: false, error: `Unknown backend: ${to}` }
- const from = to === 'ollama' ? 'lmstudio' : 'ollama'
+ // Source is whatever's active now — we're moving away from it. Migrating to
+ // the already-active backend is a no-op, not "re-provision from the other".
+ const from = getBackend()
+ if (from === to) {
+ return { success: false, error: `${to} is already the active backend — nothing to migrate.` }
+ }
onProgress({ event: 'start', message: `Reading models installed on ${from}…` })
- const sourceModels = await listModels(from)
+ const sourceModels = await listModels(from, true) // fresh source list for an accurate migration
const results = []
for (const model of sourceModels) {
@@ -235,15 +259,21 @@ export async function migrateBackend(to, onProgress = () => {}) {
const r = await installModel(to, targetId, (p) => {
if (p?.percent != null) onProgress({ event: 'start', message: `Pulling ${targetId}: ${p.percent}%` })
})
- results.push({ source: model.id, target: targetId, status: r.success ? 'installed' : 'failed', reason: r.error })
+ // `pending` (LM Studio REST fallback) means the download was queued, not
+ // finished — don't report it as a completed install.
+ const status = r.success ? (r.pending ? 'started' : 'installed') : 'failed'
+ results.push({ source: model.id, target: targetId, status, reason: r.error })
}
writeBackend(to)
await ensureBackendProvider(to)
const installed = results.filter((r) => r.status === 'installed').length
+ const started = results.filter((r) => r.status === 'started').length
const failed = results.filter((r) => r.status === 'failed').length
- onProgress({ event: 'complete', message: `Migrated to ${to} — ${installed} installed, ${failed} failed, ${results.length - installed - failed} skipped` })
+ const skipped = results.length - installed - started - failed
+ const startedNote = started ? `, ${started} downloading` : ''
+ onProgress({ event: 'complete', message: `Migrated to ${to} — ${installed} installed${startedNote}, ${failed} failed, ${skipped} skipped` })
console.log(`🔀 Migrated local LLM backend → ${to} (${installed} installed, ${failed} failed)`)
return { success: true, backend: to, results }
}
diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.js
index e32f44d834..b60ce81edc 100644
--- a/server/services/localLlm.test.js
+++ b/server/services/localLlm.test.js
@@ -122,5 +122,15 @@ describe('localLlm', () => {
expect(r.results.find((x) => x.source === 'custom-unlisted:latest').status).toBe('skipped');
expect(mocks.lmstudio.downloadModel).not.toHaveBeenCalled();
});
+
+ it('rejects migrating to the already-active backend (no-op)', async () => {
+ writeEnv('LLM_BACKEND=ollama\n');
+ const r = await svc.migrateBackend('ollama');
+ expect(r.success).toBe(false);
+ expect(r.error).toMatch(/already the active backend/);
+ // No source read, no installs attempted.
+ expect(mocks.ollama.getInstalledModels).not.toHaveBeenCalled();
+ expect(mocks.lmstudio.getAvailableModels).not.toHaveBeenCalled();
+ });
});
});
diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.js
index ea2bece332..c336fcf021 100644
--- a/server/services/ollamaManager.js
+++ b/server/services/ollamaManager.js
@@ -137,6 +137,20 @@ async function pullModel(modelId, onProgress) {
let buffer = ''
let lastError = null
+ const handleFrame = (line) => {
+ const trimmed = line.trim()
+ if (!trimmed) return
+ const frame = safeParse(trimmed)
+ if (!frame) return
+ if (frame.error) lastError = frame.error
+ if (typeof onProgress === 'function') {
+ const percent = frame.total > 0 && frame.completed >= 0
+ ? Math.round((frame.completed / frame.total) * 100)
+ : null
+ onProgress({ status: frame.status || '', percent, completed: frame.completed, total: frame.total })
+ }
+ }
+
// Ollama streams newline-delimited JSON progress frames. Read via getReader()
// to match the rest of the codebase's streaming-fetch convention. try/finally
// releases the reader even if a read rejects mid-pull (avoids leaking the
@@ -148,20 +162,15 @@ async function pullModel(modelId, onProgress) {
buffer += decoder.decode(value, { stream: true })
let nl
while ((nl = buffer.indexOf('\n')) !== -1) {
- const line = buffer.slice(0, nl).trim()
+ handleFrame(buffer.slice(0, nl))
buffer = buffer.slice(nl + 1)
- if (!line) continue
- const frame = safeParse(line)
- if (!frame) continue
- if (frame.error) lastError = frame.error
- if (typeof onProgress === 'function') {
- const percent = frame.total > 0 && frame.completed >= 0
- ? Math.round((frame.completed / frame.total) * 100)
- : null
- onProgress({ status: frame.status || '', percent, completed: frame.completed, total: frame.total })
- }
}
}
+ // Flush the decoder and process any final frame that wasn't newline-
+ // terminated — otherwise a terminal `{"error":...}` (or "success") frame
+ // would be dropped and a failed pull silently reported as success.
+ buffer += decoder.decode()
+ handleFrame(buffer)
} finally {
reader.releaseLock()
}