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
feat(local-llm): inline "Upgrade Ollama & Retry" prompt on 412 pull errors
[._.]/ Adam Eivyf0cc05271da8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 808452c4ff..0506523039 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -11,6 +11,7 @@ TBD- **Unified Story Builder** (`/story-builder`): a new guided page that walks a story from idea → universe aesthetic → plot arc → reader map → characters → issues → production as one linear flow. Each step is LLM-assisted with an AI-refinement affordance and ends with an explicit lock before the next unlocks; going back to revise an earlier step soft-flags the downstream locked steps as "stale" (integrity gate) so nothing silently drifts — without destroying their content. The builder is a thin conductor over the existing Universe / Series / Issue records (no data duplication); heavy per-issue production hands off to the existing Pipeline issue page. Reachable from the sidebar (Create → Story Builder), ⌘K, and voice. The intro screen supports two intake modes: **start from a seed idea**, or **import a finished work** (comic script / screenplay / novel / short story) — the importer reverse-engineers it into a universe, arc, characters, and issues, then drops you into the wizard to review and lock each stage. An **AI provider/model picker** at the top of the builder (and the import tab) drives every operation — idea expand, aesthetic, arc, reader map, character refine, and the import analysis — persisted on the session so one selection applies throughout. The **characters step generates a styled preview image per character** (world style fused with the character descriptor, via the same render path as the Universe Builder) and shows it alongside each character so you can eyeball that the world and character styles read correctly together.- **Base style image (style probe)** on a universe: generate a canonical image from the raw style guide alone — style notes + the embrace/avoid influences as the positive/negative prompt, with no character or subject — to preview the world's base visual emphasis. Triggerable from both the Universe Builder (under the style/influences editor) and the Story Builder's Universe Aesthetic step; the result persists on the universe (`styleImageRefs`) so both surfaces share it.- **Reader Map** on a series arc (`series.arc.readerMap`): a distinct audience-experience roadmap — hooks, payoffs, emotional beats, and cliffhangers across the arc — built on top of the Vonnegut story shape, separate from the protagonist arc. Generated and refined via the new Story Builder reader-map step (also preserved by arc regeneration).+- Local LLMs: when an Ollama model pull fails with `412: requires a newer version of Ollama`, PortOS now offers an inline "Upgrade Ollama & Retry" prompt instead of surfacing the raw error. Runs `brew upgrade ollama` on macOS / re-runs the official Ollama install script on Linux, restarts the Ollama service so the new binary is actually serving requests, and automatically retries the original model download.## Changeddiff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsxindex e8ece80167..4cb8d29d7d 100644--- a/client/src/components/settings/LocalLlmTab.jsx+++ b/client/src/components/settings/LocalLlmTab.jsx@@ -5,7 +5,7 @@ import BrailleSpinner from '../BrailleSpinner';import { formatBytes, timeAgo } from '../../utils/formatters';import {getLocalLlmStatus, getLocalLlmCatalog, getLocalLlmHuggingFaceSearch, installLocalLlmModel,- deleteLocalLlmModel, switchLocalLlmBackend, migrateLocalLlmBackend, installLocalLlmBackend, controlOllamaService+ deleteLocalLlmModel, switchLocalLlmBackend, migrateLocalLlmBackend, installLocalLlmBackend, upgradeLocalLlmBackend, controlOllamaService} from '../../services/api';import socket from '../../services/socket';@@ -304,8 +304,9 @@ export function LocalLlmTab() {};}, [loadStatus, loadCatalog, selected, query, catalogSource, activeCategory]);- const runAction = useCallback((key, fn, successMsg) => {- setConfirmAction(null);+ const runAction = useCallback((key, fn, successMsg, options = {}) => {+ const { onError, clearConfirm = true } = options;+ if (clearConfirm) setConfirmAction(null);setActionInProgress(key);return fn().then((result) => {@@ -322,8 +323,15 @@ export function LocalLlmTab() {}loadStatus();loadCatalog(selected, query, catalogSource, activeCategory);+ return result;+ })+ .catch((err) => {+ // Caller-handled errors (e.g. OLLAMA_OUTDATED → offer to upgrade) ask us+ // to skip the default toast and run their own handler instead. The error+ // toast from apiCore has already fired unless the caller passed {silent}+ // through fn — onError just gets to consume the structured code/context.+ if (typeof onError === 'function') onError(err);})- .catch(() => { /* request() surfaces API errors as a toast */ }).finally(() => setActionInProgress(null));}, [loadStatus, loadCatalog, selected, query, catalogSource, activeCategory]);@@ -354,11 +362,46 @@ export function LocalLlmTab() {}, [activeCategory, catalog, catalogCategories, catalogSource]);// LM Studio's REST fallback returns { pending: true } — the download was only- // queued, not finished — so don't claim "installed" in that case.- const install = (modelId) => runAction(`install-${modelId}`, () => installLocalLlmModel(selected, modelId),- (r) => r?.pending ? `${modelId} download started` : `${modelId} installed`);+ // queued, not finished — so don't claim "installed" in that case. Install is+ // silent so an OLLAMA_OUTDATED failure replaces the default toast with an+ // inline confirm row offering to auto-upgrade Ollama and retry.+ const install = (modelId) => runAction(+ `install-${modelId}`,+ () => installLocalLlmModel(selected, modelId, { silent: true }),+ (r) => r?.pending ? `${modelId} download started` : `${modelId} installed`,+ {+ onError: (err) => {+ if (err?.code === 'OLLAMA_OUTDATED' && selected === 'ollama') {+ setConfirmAction({+ type: 'upgrade-ollama',+ modelId,+ label: 'Ollama is out of date for this model.',+ detail: `${modelId} needs a newer Ollama than the one installed. PortOS can upgrade Ollama in place (Homebrew on macOS, the official Ollama installer on Linux), restart the service, and retry the download.`+ });+ } else {+ // Any other failure: restore the default toast we suppressed.+ toast.error(err?.message || 'Install failed');+ }+ },+ clearConfirm: false+ }+ );const remove = (modelId) => runAction(`delete-${modelId}`, () => deleteLocalLlmModel(selected, modelId), `${modelId} deleted`);+ const upgradeOllamaAndRetry = (modelId) => {+ setConfirmAction(null);+ // runAction resolves with the server result on success and undefined when+ // its internal catch consumed the error — gate the retry on a truthy+ // result so a failed upgrade doesn't loop straight back into the same 412.+ runAction(+ 'upgrade-ollama',+ () => upgradeLocalLlmBackend('ollama'),+ (r) => r?.note ? `Ollama upgraded — ${r.note}` : 'Ollama upgraded'+ ).then((r) => {+ if (r?.success && modelId) install(modelId);+ });+ };+return (<div className="space-y-4">{/* Backends — status + switch/migrate */}@@ -399,24 +442,38 @@ export function LocalLlmTab() {<p className="text-sm text-white">{confirmAction.label}</p>{confirmAction.detail && <p className="text-xs text-gray-400">{confirmAction.detail}</p>}<div className="flex items-center gap-2 flex-wrap">- <button- onClick={() => runAction(`migrate-${confirmAction.to}-link`, () => migrateLocalLlmBackend(confirmAction.to, 'link'), summarizeMigrate)}- disabled={busy}- className="flex items-center gap-2 px-3 py-1.5 text-sm font-medium rounded-lg transition-colors disabled:opacity-50 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent"- title="Hardlink each GGUF so both backends share one file on disk (no extra space; falls back to a copy across filesystems)"- >- {actionInProgress === `migrate-${confirmAction.to}-link` ? <BrailleSpinner /> : <Link2 size={14} />}- Link (share disk)- </button>- <button- onClick={() => runAction(`migrate-${confirmAction.to}-copy`, () => migrateLocalLlmBackend(confirmAction.to, 'copy'), summarizeMigrate)}- disabled={busy}- className="flex items-center gap-2 px-3 py-1.5 text-sm font-medium rounded-lg transition-colors disabled:opacity-50 bg-port-border hover:bg-port-border/70 text-white"- title="Make an independent duplicate on the target (uses extra disk; survives deleting the source backend's copy)"- >- {actionInProgress === `migrate-${confirmAction.to}-copy` ? <BrailleSpinner /> : <Copy size={14} />}- Copy (independent)- </button>+ {confirmAction.type === 'upgrade-ollama' ? (+ <button+ onClick={() => upgradeOllamaAndRetry(confirmAction.modelId)}+ disabled={busy}+ className="flex items-center gap-2 px-3 py-1.5 text-sm font-medium rounded-lg transition-colors disabled:opacity-50 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent"+ title="Run brew upgrade ollama (macOS) or the official Ollama install script (Linux), then retry the model download"+ >+ {actionInProgress === 'upgrade-ollama' ? <BrailleSpinner /> : <Download size={14} />}+ Upgrade Ollama & Retry+ </button>+ ) : (+ <>+ <button+ onClick={() => runAction(`migrate-${confirmAction.to}-link`, () => migrateLocalLlmBackend(confirmAction.to, 'link'), summarizeMigrate)}+ disabled={busy}+ className="flex items-center gap-2 px-3 py-1.5 text-sm font-medium rounded-lg transition-colors disabled:opacity-50 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent"+ title="Hardlink each GGUF so both backends share one file on disk (no extra space; falls back to a copy across filesystems)"+ >+ {actionInProgress === `migrate-${confirmAction.to}-link` ? <BrailleSpinner /> : <Link2 size={14} />}+ Link (share disk)+ </button>+ <button+ onClick={() => runAction(`migrate-${confirmAction.to}-copy`, () => migrateLocalLlmBackend(confirmAction.to, 'copy'), summarizeMigrate)}+ disabled={busy}+ className="flex items-center gap-2 px-3 py-1.5 text-sm font-medium rounded-lg transition-colors disabled:opacity-50 bg-port-border hover:bg-port-border/70 text-white"+ title="Make an independent duplicate on the target (uses extra disk; survives deleting the source backend's copy)"+ >+ {actionInProgress === `migrate-${confirmAction.to}-copy` ? <BrailleSpinner /> : <Copy size={14} />}+ Copy (independent)+ </button>+ </>+ )}<button onClick={() => setConfirmAction(null)} className="px-3 py-1.5 text-sm text-gray-400 hover:text-white transition-colors">Cancel</button>diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.jsindex 0d2b2958d1..8acc39dbbb 100644--- a/client/src/services/apiLocalLlm.js+++ b/client/src/services/apiLocalLlm.js@@ -10,8 +10,11 @@ export const getLocalLlmCatalog = (backend, q = '') =>export const getLocalLlmHuggingFaceSearch = (backend, q = '', category = 'all', limit = 12) =>request(`/local-llm/huggingface-search?backend=${encodeURIComponent(backend)}&category=${encodeURIComponent(category)}&limit=${encodeURIComponent(limit)}${q ? `&q=${encodeURIComponent(q)}` : ''}`);-export const installLocalLlmModel = (backend, modelId) =>- request('/local-llm/install', { method: 'POST', body: JSON.stringify({ backend, modelId }) });+// `options` lets callers opt into `{ silent: true }` so structured failure codes+// (e.g. OLLAMA_OUTDATED → offer to upgrade in place) can be handled by the UI+// without the default error toast firing first and stacking with the prompt.+export const installLocalLlmModel = (backend, modelId, options) =>+ request('/local-llm/install', { method: 'POST', body: JSON.stringify({ backend, modelId }), ...options });export const deleteLocalLlmModel = (backend, modelId) =>request('/local-llm/delete', { method: 'POST', body: JSON.stringify({ backend, modelId }) });@@ -19,6 +22,12 @@ export const deleteLocalLlmModel = (backend, modelId) =>export const installLocalLlmBackend = (backend) =>request('/local-llm/install-backend', { method: 'POST', body: JSON.stringify({ backend }) });+// Upgrade an already-installed backend in place (Homebrew on macOS, official+// Ollama script on Linux). The pull-model path uses this on the OLLAMA_OUTDATED+// recovery flow so a stale binary doesn't keep the user from installing new models.+export const upgradeLocalLlmBackend = (backend) =>+ request('/local-llm/upgrade-backend', { method: 'POST', body: JSON.stringify({ backend }) });+export const controlOllamaService = (action) =>request('/local-llm/ollama-service', { method: 'POST', body: JSON.stringify({ action }) });diff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex 509cfe34c1..5b0264935a 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -23,7 +23,7 @@ import {import { getCatalog, searchCatalog, isBackend } from '../lib/localLlmCatalog.js'import { searchHuggingFaceModels } from '../services/huggingFaceCatalog.js'import {- getStatus, listModels, installModel, deleteModel, switchBackend, migrateBackend, installBackend, controlOllamaServer+ getStatus, listModels, installModel, deleteModel, switchBackend, migrateBackend, installBackend, upgradeBackend, controlOllamaServer} from '../services/localLlm.js'const router = Router()@@ -120,7 +120,10 @@ router.post('/install', asyncHandler(async (req, res) => {})if (!result.success) {emit('error', result.error || 'Install failed')- return res.status(502).json({ error: result.error || 'Install failed', modelId })+ // Forward structured `code` (e.g. OLLAMA_OUTDATED) so the client can offer+ // a recovery action — like prompting to upgrade Ollama — instead of just+ // surfacing the raw error string in a toast.+ return res.status(502).json({ error: result.error || 'Install failed', modelId, ...(result.code ? { code: result.code } : {}) })}emit('complete', result.pending? `${modelId} download started in LM Studio — it'll finish in the background`@@ -128,6 +131,25 @@ router.post('/install', asyncHandler(async (req, res) => {res.json({ success: true, ...result })}))+// POST /api/local-llm/upgrade-backend — upgrade an existing backend install+// (Homebrew on macOS, official script for Ollama on Linux). Streams progress+// over the same `localLlm:progress` socket event the install/pull paths use.+router.post('/upgrade-backend', asyncHandler(async (req, res) => {+ const { backend } = validateRequest(localLlmInstallBackendSchema, req.body)+ const emit = emitter(req)+ const result = await upgradeBackend(backend, ({ event, message }) => emit(event, message))+ .catch((err) => {+ emit('error', `Upgrade failed: ${err.message}`)+ throw err+ })+ if (!result.success) {+ emit('error', result.error || 'Upgrade failed')+ return res.status(502).json({ error: result.error || 'Upgrade failed', backend })+ }+ emit('complete', `${backend === 'ollama' ? 'Ollama' : 'LM Studio'} upgraded${result.note ? ` — ${result.note}` : ''}`)+ res.json(result)+}))+// POST /api/local-llm/delete — remove an installed modelrouter.post('/delete', asyncHandler(async (req, res) => {const { backend, modelId } = validateRequest(localLlmDeleteSchema, req.body)diff --git a/server/services/localLlm.js b/server/services/localLlm.jsindex c7b7e87688..5555ca3925 100644--- a/server/services/localLlm.js+++ b/server/services/localLlm.js@@ -237,6 +237,62 @@ export async function installBackend(backend, onProgress = () => {}) {}}+/**+ * Upgrade an already-installed backend in place. Used when a model pull returns+ * Ollama's 412 "requires a newer version of Ollama" error — instead of telling+ * the user to download a new binary, we run the same package manager that put+ * it there. macOS: `brew upgrade ollama` / `brew upgrade --cask lm-studio`.+ * Linux Ollama: re-run the official install script (it's idempotent and acts as+ * an upgrade). Windows / Linux-LM-Studio fall back to the download URL.+ *+ * @param {string} backend - 'ollama' | 'lmstudio'+ * @param {(p: { event: string, message: string }) => void} [onProgress]+ */+export async function upgradeBackend(backend, onProgress = () => {}) {+ if (!isBackend(backend)) return { success: false, error: `Unknown backend: ${backend}` }+ const emit = (message) => onProgress({ event: 'start', message })+ const downloadHint = `Download the latest version from ${DOWNLOAD_URL[backend]}.`++ if (!canAutoInstall(backend)) {+ return { success: false, error: `Automatic upgrade isn't supported on this platform. ${downloadHint}` }+ }++ // Linux Ollama: the official install script is also the upgrade path.+ if (process.platform === 'linux') {+ emit('Upgrading Ollama via the official install script…')+ const r = await runStreaming('bash', ['-c', 'curl -fsSL https://ollama.com/install.sh | sh'], emit, BACKEND_INSTALL_TIMEOUT_MS)+ if (!r.success) return { success: false, error: `Ollama upgrade failed: ${r.error}. ${downloadHint}` }+ console.log('⬆️ Upgraded Ollama (linux script)')+ return { success: true, backend }+ }++ // macOS: Homebrew.+ if (!(await commandExists('brew', ['--version']))) {+ return { success: false, error: `Homebrew not found — install it from https://brew.sh first, or ${downloadHint.toLowerCase()}` }+ }+ const label = backend === 'ollama' ? 'Ollama' : 'LM Studio'+ const args = backend === 'ollama' ? ['upgrade', 'ollama'] : ['upgrade', '--cask', 'lm-studio']+ emit(`Upgrading ${label} via Homebrew (this can take a few minutes)…`)+ const r = await runStreaming('brew', args, emit, BACKEND_INSTALL_TIMEOUT_MS)+ // brew exits non-zero with "already up-to-date" only on some versions; the+ // common "Warning: ollama X.Y.Z already installed" path is exit 0. If we did+ // get a real failure, surface it.+ if (!r.success) return { success: false, error: `Homebrew upgrade failed: ${r.error}` }+ console.log(`🍺 Upgraded ${label} via Homebrew`)+ if (backend === 'ollama') {+ // Restart the service so the new binary is actually running — `brew upgrade`+ // doesn't bounce running services. Best-effort; report it in `note` either+ // way so the user knows whether to restart Ollama themselves.+ const stop = await ollamaManager.stopPersistentService().catch((err) => ({ success: false, error: err.message }))+ const restart = await ollamaManager.startPersistentService().catch((err) => ({ success: false, error: err.message }))+ const note = restart.success+ ? 'Restarted Ollama service so the new binary is now serving requests.'+ : `Upgraded, but PortOS could not restart the Ollama service (${restart.error || stop.error}). Restart it from the Local LLMs tab.`+ return { success: true, backend, note }+ }+ return { success: true, backend, note: 'Restart LM Studio so the new binary is loaded.' }+}+/*** Start/stop the Ollama HTTP server from the UI. LM Studio is app-controlled,* so keep this intentionally narrow instead of inventing unreliable app-launchdiff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.jsindex 2ffc7f821f..603fc4f61e 100644--- a/server/services/ollamaManager.js+++ b/server/services/ollamaManager.js@@ -444,7 +444,25 @@ async function pullModel(modelId, onProgress) {}console.error(`⚠️ Ollama pull failed for ${modelId}: ${lastError}`)- return { success: false, error: lastError, modelId }+ const code = isOllamaOutdatedError(lastError) ? 'OLLAMA_OUTDATED' : undefined+ return { success: false, error: lastError, modelId, ...(code ? { code } : {}) }+}++/**+ * Detect Ollama's "model requires a newer version" 412 response surfaced in the+ * NDJSON stream. The registry returns it when a new model format (e.g. a fresh+ * GGUF feature) lands before the local Ollama binary supports it; the fix is to+ * upgrade the Ollama install. The error string we see looks like:+ * "pull model manifest: 412: The model you are attempting to pull requires+ * a newer version of Ollama. Please download the latest version at: …"+ * Match on the "newer version of Ollama" phrase plus the 412 status code so a+ * benign 412 from an unrelated path can't slip through.+ * @param {string|null|undefined} error+ */+function isOllamaOutdatedError(error) {+ if (!error) return false+ const str = String(error)+ return /\b412\b/.test(str) && /newer version of ollama/i.test(str)}/**diff --git a/server/services/ollamaManager.test.js b/server/services/ollamaManager.test.jsindex dfbb3568a3..7836771ca2 100644--- a/server/services/ollamaManager.test.js+++ b/server/services/ollamaManager.test.js@@ -154,4 +154,17 @@ describe('ollamaManager.pullModel transient-error retry', () => {expect(onProgress).toHaveBeenCalledWith(expect.objectContaining({ retrying: true }))})++ it('tags a 412 "newer version of Ollama" error with code OLLAMA_OUTDATED', async () => {+ const pullModel = await loadPullModel()+ const { pullUrls } = stubFetch([+ makeStreamResponse([{ error: 'pull model manifest: 412: The model you are attempting to pull requires a newer version of Ollama. Please download the latest version at: https://ollama.com/download' }])+ ])++ const { result } = await runPull(pullModel, 'qwen3:8b')++ expect(result.success).toBe(false)+ expect(result.code).toBe('OLLAMA_OUTDATED')+ expect(pullUrls).toHaveLength(1) // not retried — outdated binary won't fix itself+ })})