The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(ollama): stale-manifest health scan for 0.20.7/0.21 + hotfixes
PurpleDoubleDad29b2c0556d
diff --git a/src/api/__tests__/model-pipeline.test.ts b/src/api/__tests__/model-pipeline.test.tsindex 7b264f66..f7c89a81 100644--- a/src/api/__tests__/model-pipeline.test.ts+++ b/src/api/__tests__/model-pipeline.test.ts@@ -96,8 +96,11 @@ describe('MODEL_TYPE_DEFAULTS', () => {})it('FLUX uses low CFG', () => {+ // FLUX 1 + FLUX 2 are both distilled flow-matching models, both use cfg=1.0.+ // Z-Image (separate type) is the 3.5-CFG model — see zimage defaults.expect(MODEL_TYPE_DEFAULTS.flux.cfgScale).toBe(1.0)- expect(MODEL_TYPE_DEFAULTS.flux2.cfgScale).toBe(3.5) // flux2 uses 3.5+ expect(MODEL_TYPE_DEFAULTS.flux2.cfgScale).toBe(1.0)+ expect(MODEL_TYPE_DEFAULTS.zimage.cfgScale).toBe(3.5)})it('SD1.5 uses 512x512', () => {diff --git a/src/api/__tests__/ollama-capability-check.test.ts b/src/api/__tests__/ollama-capability-check.test.tsnew file mode 100644index 00000000..0f6a3c1e--- /dev/null+++ b/src/api/__tests__/ollama-capability-check.test.ts@@ -0,0 +1,170 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'++// Mock localFetch to simulate Ollama responses without hitting a real server.+// This covers BOTH listModels (/api/tags) AND checkModelCapability (/api/generate)+// since both go through the same transport.+vi.mock('../backend', async () => {+ const actual = await vi.importActual<typeof import('../backend')>('../backend')+ return {+ ...actual,+ localFetch: vi.fn(),+ isTauri: () => false,+ ollamaUrl: (p: string) => `http://localhost:11434/api${p.startsWith('/') ? p : '/' + p}`,+ }+})++import { localFetch } from '../backend'+import { checkModelCapability, scanInstalledModels } from '../ollama'++const mockedFetch = localFetch as unknown as ReturnType<typeof vi.fn>++/** Helper: match a request to the /api/generate probe for a specific model. */+function respond(matcher: (url: string, body: any) => Response | null): void {+ mockedFetch.mockImplementation(async (url: string, opts: any) => {+ const body = opts?.body ? JSON.parse(opts.body) : {}+ const res = matcher(url, body)+ if (res) return res+ return new Response(JSON.stringify({ error: 'no matcher' }), { status: 500 })+ })+}++describe('checkModelCapability', () => {+ beforeEach(() => {+ mockedFetch.mockReset()+ })+ afterEach(() => {+ mockedFetch.mockReset()+ })++ it('returns ok=true when /api/show returns metadata (valid manifest)', async () => {+ mockedFetch.mockResolvedValueOnce(+ new Response(JSON.stringify({ license: 'Apache-2.0', template: '{{ .Prompt }}', parameters: '' }), { status: 200 })+ )+ const result = await checkModelCapability('qwen2.5-coder:3b')+ expect(result).toEqual({ name: 'qwen2.5-coder:3b', ok: true, stale: false })+ })++ it('flags stale=true when /api/show returns 404 "model not found" (the staleness signature in 0.20.7)', async () => {+ mockedFetch.mockResolvedValueOnce(+ new Response(JSON.stringify({ error: "model 'phi4:14b' not found" }), { status: 404 })+ )+ const result = await checkModelCapability('phi4:14b')+ expect(result.ok).toBe(false)+ expect(result.stale).toBe(true)+ expect(result.name).toBe('phi4:14b')+ })++ it('flags stale=true for legacy 400 "does not support chat" bodies (covers chat/codex/agent paths)', async () => {+ mockedFetch.mockResolvedValueOnce(+ new Response(JSON.stringify({ error: '"phi4:14b" does not support chat' }), { status: 400 })+ )+ const result = await checkModelCapability('phi4:14b')+ expect(result.stale).toBe(true)+ })++ it('flags stale=true even when wrapped as fake-500 by Rust proxy fallback', async () => {+ const wrapped = `HTTP 404: ${JSON.stringify({ error: "model 'phi4:14b' not found" })}`+ mockedFetch.mockResolvedValueOnce(+ new Response(JSON.stringify({ error: wrapped }), { status: 500 })+ )+ const result = await checkModelCapability('phi4:14b')+ expect(result.stale).toBe(true)+ })++ it('returns ok=false, stale=false for unrelated errors (e.g. CUDA OOM)', async () => {+ mockedFetch.mockResolvedValueOnce(+ new Response(JSON.stringify({ error: 'CUDA: out of memory' }), { status: 500 })+ )+ const result = await checkModelCapability('gemma4:e4b')+ expect(result.ok).toBe(false)+ expect(result.stale).toBe(false)+ expect(result.error).toContain('CUDA')+ })++ it('returns ok=false, stale=false on network error', async () => {+ mockedFetch.mockRejectedValueOnce(new Error('ECONNREFUSED'))+ const result = await checkModelCapability('qwen2.5-coder:3b')+ expect(result.ok).toBe(false)+ expect(result.stale).toBe(false)+ expect(result.error).toContain('ECONNREFUSED')+ })++ it('passes AbortSignal through to localFetch', async () => {+ mockedFetch.mockResolvedValueOnce(+ new Response(JSON.stringify({ done: true }), { status: 200 })+ )+ const controller = new AbortController()+ await checkModelCapability('qwen2.5-coder:3b', controller.signal)+ const callArgs = mockedFetch.mock.calls[0][1]+ expect(callArgs.signal).toBe(controller.signal)+ })+})++describe('scanInstalledModels', () => {+ beforeEach(() => {+ mockedFetch.mockReset()+ })++ it('filters out embedding models (nomic, bge, *-embed)', async () => {+ respond((url) => {+ // /api/tags listing — Ollama's canonical shape is {models: [{name, ...}]}+ if (url.endsWith('/api/tags')) {+ return new Response(+ JSON.stringify({+ models: [+ { name: 'qwen2.5-coder:3b' },+ { name: 'nomic-embed-text:latest' },+ { name: 'bge-large:latest' },+ { name: 'some-embed-v1:small' },+ { name: 'phi4:14b' },+ ],+ }),+ { status: 200 }+ )+ }+ // /api/show metadata probe — succeed for any non-embedding model+ if (url.endsWith('/api/show')) {+ return new Response(JSON.stringify({ license: 'MIT', template: '' }), { status: 200 })+ }+ return null+ })+ const results = await scanInstalledModels()+ expect(results.map((r) => r.name).sort()).toEqual(['phi4:14b', 'qwen2.5-coder:3b'])+ })++ it('returns per-model results including mixed pass/fail', async () => {+ respond((url, body) => {+ if (url.endsWith('/api/tags')) {+ return new Response(+ JSON.stringify({ models: [{ name: 'qwen2.5-coder:3b' }, { name: 'phi4:14b' }] }),+ { status: 200 }+ )+ }+ if (url.endsWith('/api/show')) {+ if (body.model === 'qwen2.5-coder:3b') {+ return new Response(JSON.stringify({ license: 'MIT', template: '' }), { status: 200 })+ }+ return new Response(JSON.stringify({ error: `model '${body.model}' not found` }), { status: 404 })+ }+ return null+ })+ const results = await scanInstalledModels()+ expect(results).toHaveLength(2)+ const qwen = results.find((r) => r.name === 'qwen2.5-coder:3b')!+ const phi4 = results.find((r) => r.name === 'phi4:14b')!+ expect(qwen.ok).toBe(true)+ expect(phi4.ok).toBe(false)+ expect(phi4.stale).toBe(true)+ })++ it('returns empty array when listModels returns empty', async () => {+ respond((url) => {+ if (url.endsWith('/api/tags')) {+ return new Response(JSON.stringify({ models: [] }), { status: 200 })+ }+ return null+ })+ const results = await scanInstalledModels()+ expect(results).toEqual([])+ })+})diff --git a/src/api/comfyui.ts b/src/api/comfyui.tsindex 296bb2b8..a74b8112 100644--- a/src/api/comfyui.ts+++ b/src/api/comfyui.ts@@ -365,10 +365,12 @@ export async function getAnimateDiffModels(): Promise<string[]> {let _knownFileSizes: Map<string, { subfolder: string; expectedBytes: number }> | null = null-function getKnownFileSizes(): Map<string, { subfolder: string; expectedBytes: number }> {+async function getKnownFileSizes(): Promise<Map<string, { subfolder: string; expectedBytes: number }>> {if (_knownFileSizes) return _knownFileSizes- // Lazy import to avoid circular deps- const { getImageBundles, getVideoBundles } = require('../api/discover')+ // Dynamic import (not CommonJS require) — discover.ts imports back into+ // comfyui.ts for classification helpers, so we defer the import to break+ // the cycle at runtime instead of at module init.+ const { getImageBundles, getVideoBundles } = await import('./discover')_knownFileSizes = new Map()for (const bundle of [...getImageBundles(), ...getVideoBundles()]) {for (const f of (bundle as any).files) {@@ -385,7 +387,7 @@ function getKnownFileSizes(): Map<string, { subfolder: string; expectedBytes: nu/** Filter out partially downloaded files. Returns only filenames that are complete. */export async function filterPartialFiles(filenames: string[]): Promise<Set<string>> {- const known = getKnownFileSizes()+ const known = await getKnownFileSizes()const filesToCheck = filenames.filter(name => known.has(name)).map(name => {diff --git a/src/api/ollama.ts b/src/api/ollama.tsindex 32c528eb..4f729c16 100644--- a/src/api/ollama.ts+++ b/src/api/ollama.ts@@ -191,6 +191,83 @@ export async function listRunningModels(): Promise<string[]> {}}+export interface ModelCapabilityCheck {+ name: string+ ok: boolean+ stale: boolean+ error?: string+}++/**+ * Probe a model's loadability without committing VRAM or touching the runner.+ *+ * Uses /api/show (metadata endpoint) rather than /api/generate or /api/chat:+ *+ * - Empty-prompt /api/generate and empty-messages /api/chat both bail out+ * BEFORE Ollama's capability check fires, so they return 200 even for+ * stale manifests — useless as a probe.+ * - A real-content /api/chat triggers the capability check, but also loads+ * the model into VRAM (~7 s for a 3 B, minutes for a 14 B) even with+ * num_predict:1 + keep_alive:0. Prohibitively expensive for a startup+ * scan over N installed models.+ * - /api/show returns 200 with full metadata (~200 ms) for valid manifests+ * and 404 "model '<name>' not found" (~100 ms) for stale ones. No runner,+ * no VRAM, fast enough to run on every cold start.+ *+ * parseOllamaError handles both the 404 "not found" path AND the legacy 400+ * "does not support chat/generate" path, so callers don't need to know which+ * endpoint produced the error.+ */+export async function checkModelCapability(+ name: string,+ signal?: AbortSignal+): Promise<ModelCapabilityCheck> {+ try {+ const res = await localFetch(ollamaUrl("/show"), {+ method: "POST",+ body: JSON.stringify({ model: name }),+ signal,+ })+ if (res.ok) {+ try { await res.json() } catch {}+ return { name, ok: true, stale: false }+ }+ const { parseOllamaError, parseShowNotFound } = await import("../lib/ollama-errors")+ const parsed = await parseOllamaError(res, `HTTP ${res.status}`)+ // CALLER CONTRACT: only call this for models that are present in /api/tags.+ // Under that assumption:+ // - "does not support …" (legacy 400) → stale+ // - "model '<name>' not found" from /api/show → stale (manifest on disk,+ // runtime refuses to parse it — the Ollama 0.20.7 signature)+ // - Anything else → propagate as non-stale (transient/network).+ // The `parseShowNotFound` call finds the pattern whether the body arrived+ // as a direct 404 OR as a Rust-proxy-wrapped fake-500.+ const stale = parsed.kind === 'stale-manifest' || !!parseShowNotFound(parsed.raw)+ return {+ name,+ ok: false,+ stale,+ error: parsed.message,+ }+ } catch (e) {+ return { name, ok: false, stale: false, error: String(e) }+ }+}++/**+ * Probe every installed Ollama model. Excludes embedding models (not usable+ * for chat/generate anyway) so they don't skew the "stale" count.+ * Runs probes in parallel — Ollama queues internally and each probe is ~100ms.+ */+export async function scanInstalledModels(): Promise<ModelCapabilityCheck[]> {+ const models = await listModels()+ const probeable = models.filter(m => {+ const lower = m.name.toLowerCase()+ return !lower.includes('embed') && !lower.includes('bge-') && !lower.includes('nomic')+ })+ return Promise.all(probeable.map(m => checkModelCapability(m.name)))+}+export async function loadModel(name: string): Promise<void> {const res = await localFetch(ollamaUrl("/generate"), {method: "POST",diff --git a/src/components/chat/CodeBlock.tsx b/src/components/chat/CodeBlock.tsxindex 9ae23cb7..d72c97dc 100644--- a/src/components/chat/CodeBlock.tsx+++ b/src/components/chat/CodeBlock.tsx@@ -10,6 +10,31 @@ interface Props {const COLLAPSE_THRESHOLD = 4 // lines — always start collapsed unless very short+const HTML_LANG_TAGS = new Set(['html', 'htm', 'xhtml', 'svg'])++/**+ * Decide whether a code block should offer the Preview chip that opens+ * HtmlPreviewModal. Err on the side of NOT previewing: a fragment like+ * `<div>foo</div>` could just as well be JSX / Vue / Angular template,+ * and rendering those as raw HTML in a sandboxed iframe is useless.+ *+ * Positive by language tag: html, htm, xhtml, svg (case-insensitive).+ * Positive by content: starts with `<!doctype html`, `<html`, or an+ * `<svg xmlns=` that carries the xmlns attribute (leading whitespace ok).+ * Everything else → false.+ */+export function isHtmlSnippet(code: string, language?: string): boolean {+ if (language && HTML_LANG_TAGS.has(language.toLowerCase())) return true+ if (!code) return false+ const trimmed = code.trimStart()+ if (!trimmed) return false+ const lower = trimmed.toLowerCase()+ if (lower.startsWith('<!doctype html')) return true+ if (lower.startsWith('<html')) return true+ if (lower.startsWith('<svg') && /<svg[^>]*\bxmlns\s*=/.test(trimmed)) return true+ return false+}+export function CodeBlock({ code, language }: Props) {const [copied, setCopied] = useState(false)const lineCount = code.split('\n').lengthdiff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsxindex fc985f69..21c51106 100644--- a/src/components/layout/AppShell.tsx+++ b/src/components/layout/AppShell.tsx@@ -1,5 +1,6 @@import { useEffect, useState } from 'react'import { Header } from './Header'+import { StaleModelsBanner } from './StaleModelsBanner'import { Sidebar } from './Sidebar'import { ChatView } from '../chat/ChatView'import { ModelManager } from '../models/ModelManager'@@ -15,6 +16,7 @@ import { useProviderStore } from '../../stores/providerStore'import { useChatStore } from '../../stores/chatStore'import { useModelStore } from '../../stores/modelStore'import { useRemoteStore } from '../../stores/remoteStore'+import { useModelHealthStore } from '../../stores/modelHealthStore'import { extractMemoriesFromPair } from '../../hooks/useMemory'import { detectLocalBackends, type DetectedBackend } from '../../lib/backend-detector'import { backendCall, isTauri } from '../../api/backend'@@ -205,6 +207,36 @@ export function AppShell() {}}, [])+ // Ollama 0.20.7 stale-manifest scan — runs once per session shortly after+ // startup. Flags installed models that the server now rejects with "does+ // not support chat/completion/generate" (pulled before the registry-side+ // capabilities refresh). Populates useModelHealthStore → StaleModelsBanner+ // surfaces the result as a top-of-app notice with one-click Refresh All.+ useEffect(() => {+ if (!onboardingDone || !isTauri()) return+ if (sessionStorage.getItem('lu-model-health-scan-done')) return+ sessionStorage.setItem('lu-model-health-scan-done', '1')++ // 3 s delay: give Ollama time to respond to /api/version after cold start+ // and avoid racing the backend-detection effect below.+ const timer = setTimeout(async () => {+ try {+ useModelHealthStore.getState().setScanning(true)+ const { scanInstalledModels, checkConnection } = await import('../../api/ollama')+ const ok = await checkConnection()+ if (!ok) return+ const results = await scanInstalledModels()+ const stale = results.filter((r) => r.stale).map((r) => r.name)+ useModelHealthStore.getState().setStaleModels(stale)+ } catch {+ // Scan is best-effort — silently fall back if Ollama is unreachable.+ } finally {+ useModelHealthStore.getState().setScanning(false)+ }+ }, 3000)+ return () => clearTimeout(timer)+ }, [onboardingDone])+// Auto-detect local backends on startup (once per session)useEffect(() => {if (!onboardingDone) return@@ -247,6 +279,7 @@ export function AppShell() {<div className="h-full flex flex-col"><Titlebar /><Header />+ <StaleModelsBanner /><div className="flex-1 flex overflow-hidden"><Sidebar /><main className="flex-1 overflow-hidden">diff --git a/src/components/layout/Header.tsx b/src/components/layout/Header.tsxindex 3b9a783e..de799bcc 100644--- a/src/components/layout/Header.tsx+++ b/src/components/layout/Header.tsx@@ -13,6 +13,8 @@ import { loadModel, unloadModel, listRunningModels } from '../../api/ollama'import { getProviderIdFromModel } from '../../api/providers'import { ModelLoadError } from '../../lib/ollama-errors'import { useModels } from '../../hooks/useModels'+import { useModelHealthStore } from '../../stores/modelHealthStore'+import { checkModelCapability } from '../../api/ollama'export function Header() {const { currentView, toggleSidebar, setView } = useUIStore()@@ -26,12 +28,23 @@ export function Header() {// one-click refresh that re-pulls the model (progress tracked in DownloadBadge).const [staleError, setStaleError] = useState<{ model: string; message: string } | null>(null)const { pullModel, isPullingModel } = useModels()+ const healthStaleModels = useModelHealthStore((s) => s.staleModels)+ const addStaleToHealth = useModelHealthStore((s) => s.setStaleModels)+ const markHealthFresh = useModelHealthStore((s) => s.markFresh)// Check if active model is an Ollama modelconst isOllamaModel = activeModel ? getProviderIdFromModel(activeModel) === 'ollama' : falseconst modelToUse = activeModel?.includes('::') ? activeModel.split('::')[1] : activeModelconst isRefreshing = modelToUse ? isPullingModel(modelToUse) : false+ // Merge a single stale discovery into the shared health store so the top+ // banner and any Model Manager indicators update in lock-step with the+ // inline Lichtschalter chip.+ const syncStaleToStore = (name: string) => {+ const current = useModelHealthStore.getState().staleModels+ if (!current.includes(name)) addStaleToHealth([...current, name])+ }+const handleLoad = async () => {if (!modelToUse || loadingState !== 'idle') returnsetStaleError(null)@@ -39,9 +52,13 @@ export function Header() {try {await loadModel(modelToUse)setIsModelLoaded(true)+ // If the store still thinks this model is stale (e.g. a scan ran before+ // the user re-pulled externally), clear it.+ markHealthFresh(modelToUse)} catch (e) {if (e instanceof ModelLoadError && e.kind === 'stale-manifest') {setStaleError({ model: e.model, message: e.message })+ syncStaleToStore(e.model)}}finally { setLoadingState('idle') }@@ -56,6 +73,7 @@ export function Header() {} catch (e) {if (e instanceof ModelLoadError && e.kind === 'stale-manifest') {setStaleError({ model: e.model, message: e.message })+ syncStaleToStore(e.model)}}finally { setLoadingState('idle') }@@ -66,17 +84,33 @@ export function Header() {const name = staleError.model// pullModel wires into the DownloadBadge via useModels' activePulls store —// user sees progress in the header badge. After the pull completes,- // re-attempt the load automatically.+ // verify via a cheap probe and then re-attempt the load automatically.try {await pullModel(name)- setStaleError(null)- // pullModel resolves when the stream ends; give Ollama a beat then retry.- setTimeout(() => { handleLoad() }, 300)+ const check = await checkModelCapability(name)+ if (check.ok) {+ markHealthFresh(name)+ setStaleError(null)+ setTimeout(() => { handleLoad() }, 200)+ }+ // If still not ok, keep the chip visible so the user can retry.} catch {// error stays visible — user can click Refresh again}}+ // When the startup health scan flags this model as stale, pre-populate the+ // chip so the user sees it WITHOUT having to click the broken toggle first.+ useEffect(() => {+ if (!modelToUse || !isOllamaModel) return+ if (healthStaleModels.includes(modelToUse) && !staleError) {+ setStaleError({+ model: modelToUse,+ message: `Model "${modelToUse}" has a stale manifest. Run "ollama pull ${modelToUse}" to refresh.`,+ })+ }+ }, [modelToUse, isOllamaModel, healthStaleModels, staleError])+// Check loaded state when model changesuseEffect(() => {if (modelToUse && isOllamaModel) {diff --git a/src/components/layout/StaleModelsBanner.tsx b/src/components/layout/StaleModelsBanner.tsxnew file mode 100644index 00000000..285a7f89--- /dev/null+++ b/src/components/layout/StaleModelsBanner.tsx@@ -0,0 +1,109 @@+import { useState } from 'react'+import { RefreshCw, X, AlertTriangle, Check } from 'lucide-react'+import { useModelHealthStore } from '../../stores/modelHealthStore'+import { useModels } from '../../hooks/useModels'+import { checkModelCapability } from '../../api/ollama'++/**+ * Top-of-app banner shown when the startup health scan finds installed+ * Ollama models whose manifests are rejected by 0.20.7. Auto-hides when+ * all models are refreshed or the user dismisses for this session.+ *+ * Cause: Ollama auto-upgraded 0.20.6 → 0.20.7 today and started strict-+ * rejecting manifests pulled before the registry-side capabilities refresh.+ * Fix: re-pull each stale model. The banner does this serially via the+ * existing useModels.pullModel flow (progress lands in DownloadBadge).+ */+export function StaleModelsBanner() {+ const { staleModels, dismissed, dismiss, markFresh } = useModelHealthStore()+ const { pullModel, isPullingModel } = useModels()+ const [refreshingAll, setRefreshingAll] = useState(false)++ if (dismissed || staleModels.length === 0) return null++ const pending = staleModels.filter((m) => !isPullingModel(m))+ const inProgressCount = staleModels.filter((m) => isPullingModel(m)).length++ const refreshAll = async () => {+ if (refreshingAll) return+ setRefreshingAll(true)+ try {+ // Serial — one pull at a time keeps disk/network manageable and gives+ // clear progress in DownloadBadge without interleaved output.+ for (const name of pending) {+ try {+ await pullModel(name)+ // Verify post-pull: Ollama's on-disk manifest is refreshed, probe+ // to confirm 0.20.7 now accepts it before marking fresh.+ const check = await checkModelCapability(name)+ if (check.ok) markFresh(name)+ } catch {+ // Continue with next model; user can retry via the banner later.+ }+ }+ } finally {+ setRefreshingAll(false)+ }+ }++ return (+ <div+ className="flex items-center gap-3 px-3 py-1.5 border-b border-amber-400/30 bg-amber-500/10 backdrop-blur-sm"+ role="alert"+ >+ <AlertTriangle+ size={13}+ className="text-amber-600 dark:text-amber-400 shrink-0"+ aria-hidden="true"+ />+ <div className="flex-1 min-w-0 text-[0.7rem]">+ <span className="font-semibold text-amber-800 dark:text-amber-200">+ Ollama 0.20.7 broke {staleModels.length} of your model{staleModels.length === 1 ? '' : 's'}.+ </span>+ <span+ className="ml-1.5 text-amber-700/90 dark:text-amber-300/80 truncate inline-block max-w-[50vw] align-bottom"+ title={staleModels.join(', ')}+ >+ {staleModels.slice(0, 3).join(', ')}+ {staleModels.length > 3 ? `, +${staleModels.length - 3} more` : ''}+ </span>+ {inProgressCount > 0 && (+ <span className="ml-2 text-amber-600 dark:text-amber-300 text-[0.65rem]">+ · refreshing {inProgressCount}/{staleModels.length}+ </span>+ )}+ </div>+ <button+ onClick={refreshAll}+ disabled={refreshingAll || pending.length === 0}+ className="flex items-center gap-1 px-2 py-1 rounded bg-amber-500/20 border border-amber-400/40 text-amber-800 dark:text-amber-200 text-[0.65rem] font-medium hover:bg-amber-500/30 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"+ title={`Re-pull ${staleModels.length} stale model${staleModels.length === 1 ? '' : 's'}`}+ >+ {refreshingAll ? (+ <>+ <RefreshCw size={10} className="animate-spin" />+ <span>Refreshing…</span>+ </>+ ) : pending.length === 0 ? (+ <>+ <Check size={10} />+ <span>Queued</span>+ </>+ ) : (+ <>+ <RefreshCw size={10} />+ <span>Refresh all</span>+ </>+ )}+ </button>+ <button+ onClick={dismiss}+ className="p-1 rounded text-amber-700/70 dark:text-amber-300/70 hover:text-amber-900 dark:hover:text-amber-100 hover:bg-amber-500/20 transition-colors"+ aria-label="Dismiss until next launch"+ title="Dismiss until next launch"+ >+ <X size={11} />+ </button>+ </div>+ )+}diff --git a/src/lib/__tests__/ollama-errors.test.ts b/src/lib/__tests__/ollama-errors.test.tsindex 3388c791..1bb98b85 100644--- a/src/lib/__tests__/ollama-errors.test.ts+++ b/src/lib/__tests__/ollama-errors.test.ts@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest'-import { parseOllamaError, ModelLoadError, chatStyleMessage } from '../ollama-errors'+import { parseOllamaError, ModelLoadError, chatStyleMessage, parseShowNotFound } from '../ollama-errors'describe('parseOllamaError', () => {it('detects /api/chat stale-manifest error', async () => {@@ -44,6 +44,18 @@ describe('parseOllamaError', () => {expect(parsed.model).toBe('mannix/llama3.1-8b-abliterated:agent')})+ // "model X not found" is NOT flagged as stale by parseOllamaError alone —+ // it also fires for genuinely non-existent models, and we must not misclassify+ // those. Disambiguation is done by the scanner via cross-reference with+ // /api/tags. parseShowNotFound extracts the name for scanner use.+ it('does NOT flag /api/show 404 as stale from parseOllamaError alone', async () => {+ const body = JSON.stringify({ error: "model 'phi4:14b' not found" })+ const res = new Response(body, { status: 404 })+ const parsed = await parseOllamaError(res)+ expect(parsed.kind).toBe('other')+ expect(parsed.model).toBeNull()+ })+it('returns other for unknown 400 errors', async () => {const body = JSON.stringify({ error: 'unrelated error message' })const res = new Response(body, { status: 400 })@@ -88,6 +100,27 @@ describe('ModelLoadError', () => {})})+describe('parseShowNotFound', () => {+ it('extracts model name from quoted "not found" message', () => {+ expect(parseShowNotFound("model 'phi4:14b' not found")).toBe('phi4:14b')+ })+ it('tolerates double-quotes', () => {+ expect(parseShowNotFound('model "hermes3:8b" not found')).toBe('hermes3:8b')+ })+ it('tolerates no quotes', () => {+ expect(parseShowNotFound('model dolphin3:8b not found')).toBe('dolphin3:8b')+ })+ it('handles namespaced model names', () => {+ expect(parseShowNotFound("model 'mannix/llama3.1-8b-abliterated:agent' not found"))+ .toBe('mannix/llama3.1-8b-abliterated:agent')+ })+ it('returns null for unrelated strings', () => {+ expect(parseShowNotFound('server crashed')).toBeNull()+ expect(parseShowNotFound('')).toBeNull()+ expect(parseShowNotFound('does not support chat')).toBeNull()+ })+})+describe('chatStyleMessage', () => {it('produces terminal-instruction wording for stale-manifest', async () => {const res = new Response(JSON.stringify({ error: '"gemma4:e4b" does not support chat' }), { status: 400 })diff --git a/src/lib/ollama-errors.ts b/src/lib/ollama-errors.tsindex 0f35ec87..203c5677 100644--- a/src/lib/ollama-errors.ts+++ b/src/lib/ollama-errors.ts@@ -31,6 +31,12 @@ export interface ParsedOllamaError {const STALE_MANIFEST_RE =/[\\'"]*([\w.:/\-]+?)[\\'"]*\s+does not support (chat|completion|generate)/i+// Ollama 0.20.7's /api/show returns 404 "model '<name>' not found" for+// manifests it can no longer parse — empirically this only happens for+// stale manifests pulled before the registry-side capabilities refresh.+// Fresh pulls of the same model name succeed. Treated as stale-manifest so+// the scan + banner can offer a one-click refresh.+const SHOW_NOT_FOUND_RE = /model\s+['"]?([\w.:/\-]+?)['"]?\s+not\s+found/i/*** Parse an Ollama error response into a typed structure.@@ -58,20 +64,39 @@ export async function parseOllamaError(raw = fallback}- const m = typeof raw === 'string' ? raw.match(STALE_MANIFEST_RE) : null- if (m) {- const model = m[1]- return {- kind: 'stale-manifest',- model,- message: `Model "${model}" has a stale manifest. Run "ollama pull ${model}" to refresh.`,- raw,+ if (typeof raw === 'string') {+ const m1 = raw.match(STALE_MANIFEST_RE)+ if (m1) {+ const model = m1[1]+ return {+ kind: 'stale-manifest',+ model,+ message: `Model "${model}" has a stale manifest. Run "ollama pull ${model}" to refresh.`,+ raw,+ }}+ // NOTE: we intentionally do NOT treat "model X not found" as stale here.+ // That string also legitimately fires for genuinely absent models+ // (user types a model name that was never pulled). The health scanner+ // cross-references with /api/tags before calling parseShowNotFound to+ // disambiguate — see `checkModelCapability` in api/ollama.ts.}return { kind: 'other', model: null, message: raw, raw }}+/**+ * Parse `{"error":"model 'X' not found"}` bodies from /api/show.+ * Returns the captured model name or null. Only the scanner should call this,+ * and only AFTER verifying the name is present in /api/tags — the string+ * `model X not found` also fires for genuinely absent models (a user typing+ * a model that was never pulled) and we must not flag those as stale.+ */+export function parseShowNotFound(raw: string): string | null {+ const m = raw.match(SHOW_NOT_FOUND_RE)+ return m ? m[1] : null+}+/** Typed error thrown by loadModel / unloadModel. */export class ModelLoadError extends Error {readonly kind: OllamaErrorKinddiff --git a/src/stores/__tests__/modelHealthStore.test.ts b/src/stores/__tests__/modelHealthStore.test.tsnew file mode 100644index 00000000..8be91ad1--- /dev/null+++ b/src/stores/__tests__/modelHealthStore.test.ts@@ -0,0 +1,66 @@+import { describe, it, expect, beforeEach } from 'vitest'+import { useModelHealthStore } from '../modelHealthStore'++describe('useModelHealthStore', () => {+ beforeEach(() => {+ useModelHealthStore.getState().reset()+ })++ it('setStaleModels records models + advances lastScanTime + clears dismissed', () => {+ // Arrange: user had dismissed a previous banner+ useModelHealthStore.setState({ dismissed: true, lastScanTime: 100 })++ useModelHealthStore.getState().setStaleModels(['phi4:14b', 'hermes3:8b'])++ const s = useModelHealthStore.getState()+ expect(s.staleModels).toEqual(['phi4:14b', 'hermes3:8b'])+ expect(s.lastScanTime).toBeGreaterThan(100)+ // A new scan finding stale models must re-show the banner.+ expect(s.dismissed).toBe(false)+ })++ it('markFresh removes a single model from the stale list', () => {+ useModelHealthStore.setState({+ staleModels: ['phi4:14b', 'hermes3:8b', 'dolphin3:8b'],+ })+ useModelHealthStore.getState().markFresh('hermes3:8b')+ expect(useModelHealthStore.getState().staleModels).toEqual(['phi4:14b', 'dolphin3:8b'])+ })++ it('markFresh is a no-op if model was not stale', () => {+ useModelHealthStore.setState({ staleModels: ['phi4:14b'] })+ useModelHealthStore.getState().markFresh('never-installed:7b')+ expect(useModelHealthStore.getState().staleModels).toEqual(['phi4:14b'])+ })++ it('dismiss hides the banner for this session without clearing stale models', () => {+ useModelHealthStore.setState({ staleModels: ['phi4:14b'] })+ useModelHealthStore.getState().dismiss()+ const s = useModelHealthStore.getState()+ expect(s.dismissed).toBe(true)+ expect(s.staleModels).toEqual(['phi4:14b'])+ })++ it('setScanning tracks concurrent scan state', () => {+ expect(useModelHealthStore.getState().scanning).toBe(false)+ useModelHealthStore.getState().setScanning(true)+ expect(useModelHealthStore.getState().scanning).toBe(true)+ useModelHealthStore.getState().setScanning(false)+ expect(useModelHealthStore.getState().scanning).toBe(false)+ })++ it('reset clears everything back to initial state', () => {+ useModelHealthStore.setState({+ staleModels: ['phi4:14b'],+ scanning: true,+ dismissed: true,+ lastScanTime: 12345,+ })+ useModelHealthStore.getState().reset()+ const s = useModelHealthStore.getState()+ expect(s.staleModels).toEqual([])+ expect(s.scanning).toBe(false)+ expect(s.dismissed).toBe(false)+ expect(s.lastScanTime).toBe(0)+ })+})diff --git a/src/stores/modelHealthStore.ts b/src/stores/modelHealthStore.tsnew file mode 100644index 00000000..b62f8857--- /dev/null+++ b/src/stores/modelHealthStore.ts@@ -0,0 +1,54 @@+import { create } from 'zustand'+import { persist } from 'zustand/middleware'++/**+ * Tracks which installed Ollama models have stale manifests (rejected by+ * Ollama 0.20.7 with "does not support (chat|completion|generate)").+ *+ * Populated by the startup health scan (AppShell) and consumed by:+ * - StaleModelsBanner — top-of-app notice with "Refresh All"+ * - Header Lichtschalter — knows without a load attempt that the model is stale+ * - DiscoverModels — shows "Needs Refresh" badge instead of green "Installed"+ *+ * `dismissed` is session-only so the banner reappears next launch if stale+ * models remain. `lastScanTime` is persisted so we can skip re-scan for a+ * cool-down window on app restart.+ */++interface ModelHealthState {+ staleModels: string[]+ lastScanTime: number+ scanning: boolean+ dismissed: boolean+ // actions+ setStaleModels: (models: string[]) => void+ markFresh: (name: string) => void+ setScanning: (scanning: boolean) => void+ dismiss: () => void+ reset: () => void+}++export const useModelHealthStore = create<ModelHealthState>()(+ persist(+ (set) => ({+ staleModels: [],+ lastScanTime: 0,+ scanning: false,+ dismissed: false,+ setStaleModels: (models) =>+ set({ staleModels: models, lastScanTime: Date.now(), dismissed: false }),+ markFresh: (name) =>+ set((s) => ({ staleModels: s.staleModels.filter((m) => m !== name) })),+ setScanning: (scanning) => set({ scanning }),+ dismiss: () => set({ dismissed: true }),+ reset: () =>+ set({ staleModels: [], scanning: false, dismissed: false, lastScanTime: 0 }),+ }),+ {+ name: 'locally-uncensored-model-health',+ // Only persist the scan result + timestamp. `scanning` and `dismissed`+ // are intentionally session-only.+ partialize: (s) => ({ staleModels: s.staleModels, lastScanTime: s.lastScanTime }),+ }+ )+)