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 detection on Lichtschalter (0.20.6→0.20.7 regression)
PurpleDoubleD708670300311
diff --git a/src/api/ollama.ts b/src/api/ollama.tsindex 5e5bd05f..32c528eb 100644--- a/src/api/ollama.ts+++ b/src/api/ollama.ts@@ -197,7 +197,10 @@ export async function loadModel(name: string): Promise<void> {body: JSON.stringify({ model: name, prompt: "", stream: false, keep_alive: "10m" }),})if (!res.ok) {- console.warn(`[ollama] failed to load model "${name}":`, res.status)+ const { parseOllamaError, ModelLoadError } = await import("../lib/ollama-errors")+ const parsed = await parseOllamaError(res, `HTTP ${res.status}`)+ console.warn(`[ollama] failed to load model "${name}":`, res.status, parsed.message)+ throw new ModelLoadError(parsed, name)}// Consume response to ensure model is fully loadedtry { await res.json() } catch {}@@ -209,7 +212,10 @@ export async function unloadModel(name: string): Promise<void> {body: JSON.stringify({ model: name, prompt: "", keep_alive: 0 }),})if (!res.ok) {- console.warn(`[ollama] failed to unload model "${name}":`, res.status)+ const { parseOllamaError, ModelLoadError } = await import("../lib/ollama-errors")+ const parsed = await parseOllamaError(res, `HTTP ${res.status}`)+ console.warn(`[ollama] failed to unload model "${name}":`, res.status, parsed.message)+ throw new ModelLoadError(parsed, name)}}diff --git a/src/api/providers/ollama-provider.ts b/src/api/providers/ollama-provider.tsindex 41bab9b0..812a34ff 100644--- a/src/api/providers/ollama-provider.ts+++ b/src/api/providers/ollama-provider.ts@@ -240,21 +240,12 @@ export class OllamaProvider implements ProviderClient {private async extractError(res: Response, fallback: string): Promise<string> {try {- const data = await res.json()- const raw = data.error || fallback- // Ollama 0.20+ strict-rejects models with stale `capabilities` metadata- // (pulled before Ollama 0.15). Give the user an actionable remediation- // instead of the cryptic "X does not support chat/completion".- // Regex is tolerant to prefixes (e.g. Rust proxy wraps as "HTTP 400: {...}")- // with embedded \"…\" escapes, and to the model name being quoted or not.- // The [\\'"]* classes swallow any combination of escape backslashes and- // JSON-encoded quotes around the model identifier.- const m = typeof raw === 'string' && raw.match(/[\\'"]*([\w.:/\-]+?)[\\'"]*\s+does not support (chat|completion)/i)- if (m) {- const name = m[1]- return `Ollama rejected "${name}" — its manifest is stale (pulled before Ollama 0.15). Open a terminal and run: ollama pull ${name} Then reload the model.`- }- return raw+ // Share the detection logic with loadModel / unloadModel via ollama-errors.+ // The regex there matches chat, completion, AND generate (the Lichtschalter+ // path uses /api/generate with an empty prompt for preload — same error class).+ const { parseOllamaError, chatStyleMessage } = await import('../../lib/ollama-errors')+ const parsed = await parseOllamaError(res, fallback)+ return chatStyleMessage(parsed)} catch {return fallback}diff --git a/src/components/layout/Header.tsx b/src/components/layout/Header.tsxindex 4dfc6b79..3b9a783e 100644--- a/src/components/layout/Header.tsx+++ b/src/components/layout/Header.tsx@@ -1,5 +1,5 @@import { useState, useEffect } from 'react'-import { Menu, Loader2, Power, Sun, Moon } from 'lucide-react'+import { Menu, Loader2, Power, Sun, Moon, RefreshCw, X } from 'lucide-react'import { useUIStore } from '../../stores/uiStore'import { useSettingsStore } from '../../stores/settingsStore'import { useChatStore } from '../../stores/chatStore'@@ -11,6 +11,8 @@ import { DownloadBadge } from './DownloadBadge'import { CreateTopControls } from '../create/CreateTopControls'import { loadModel, unloadModel, listRunningModels } from '../../api/ollama'import { getProviderIdFromModel } from '../../api/providers'+import { ModelLoadError } from '../../lib/ollama-errors'+import { useModels } from '../../hooks/useModels'export function Header() {const { currentView, toggleSidebar, setView } = useUIStore()@@ -19,18 +21,29 @@ export function Header() {const activeModel = useModelStore((s) => s.activeModel)const [loadingState, setLoadingState] = useState<'idle' | 'loading' | 'unloading'>('idle')const [isModelLoaded, setIsModelLoaded] = useState(false)+ // Stale-manifest notice shown next to the Lichtschalter when Ollama rejects+ // the model with "does not support (chat|completion|generate)". Offers a+ // 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()// Check if active model is an Ollama modelconst isOllamaModel = activeModel ? getProviderIdFromModel(activeModel) === 'ollama' : falseconst modelToUse = activeModel?.includes('::') ? activeModel.split('::')[1] : activeModel+ const isRefreshing = modelToUse ? isPullingModel(modelToUse) : falseconst handleLoad = async () => {if (!modelToUse || loadingState !== 'idle') return+ setStaleError(null)setLoadingState('loading')try {await loadModel(modelToUse)setIsModelLoaded(true)- } catch {}+ } catch (e) {+ if (e instanceof ModelLoadError && e.kind === 'stale-manifest') {+ setStaleError({ model: e.model, message: e.message })+ }+ }finally { setLoadingState('idle') }}@@ -40,10 +53,30 @@ export function Header() {try {await unloadModel(modelToUse)setIsModelLoaded(false)- } catch {}+ } catch (e) {+ if (e instanceof ModelLoadError && e.kind === 'stale-manifest') {+ setStaleError({ model: e.model, message: e.message })+ }+ }finally { setLoadingState('idle') }}+ const handleRefreshStale = async () => {+ if (!staleError) return+ 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.+ try {+ await pullModel(name)+ setStaleError(null)+ // pullModel resolves when the stream ends; give Ollama a beat then retry.+ setTimeout(() => { handleLoad() }, 300)+ } catch {+ // error stays visible — user can click Refresh again+ }+ }+// Check loaded state when model changesuseEffect(() => {if (modelToUse && isOllamaModel) {@@ -125,36 +158,44 @@ export function Header() {<ModelSelector />{isOllamaModel && ((() => {- const busy = loadingState !== 'idle'+ const busy = loadingState !== 'idle' || isRefreshing+ const hasStale = !!staleErrorconst onClick = () => {if (busy) return+ if (hasStale) return // user uses the Refresh chip insteadif (isModelLoaded) handleUnload()else handleLoad()}const title = busy- ? (loadingState === 'loading' ? 'Loading model…' : 'Unloading model…')- : (isModelLoaded ? 'Model loaded — click to unload' : 'Model not loaded — click to load into VRAM')+ ? (isRefreshing ? 'Refreshing model…' : loadingState === 'loading' ? 'Loading model…' : 'Unloading model…')+ : hasStale+ ? `Model "${staleError!.model}" has a stale manifest — click Refresh`+ : (isModelLoaded ? 'Model loaded — click to unload' : 'Model not loaded — click to load into VRAM')return (<buttononClick={onClick}- disabled={busy}+ disabled={busy || hasStale}title={title}aria-label={title}className={`relative flex items-center h-[18px] w-[34px] rounded-full transition-colors duration-200 ${busy? 'bg-amber-500/25 border border-amber-400/40'- : isModelLoaded- ? 'bg-green-500/25 border border-green-400/50'- : 'bg-red-500/20 border border-red-400/40 hover:bg-red-500/30'+ : hasStale+ ? 'bg-red-500/30 border border-red-400/60 animate-pulse'+ : isModelLoaded+ ? 'bg-green-500/25 border border-green-400/50'+ : 'bg-red-500/20 border border-red-400/40 hover:bg-red-500/30'}`}><spanclassName={`absolute top-[1px] flex items-center justify-center w-[14px] h-[14px] rounded-full shadow-sm transition-all duration-200 ${busy? 'left-[9px] bg-amber-400'- : isModelLoaded- ? 'left-[18px] bg-green-400'- : 'left-[1px] bg-red-400'+ : hasStale+ ? 'left-[1px] bg-red-500'+ : isModelLoaded+ ? 'left-[18px] bg-green-400'+ : 'left-[1px] bg-red-400'}`}>{busy ? (@@ -166,6 +207,37 @@ export function Header() {</button>)})()+ )}+ {isOllamaModel && staleError && (+ <div+ className="ml-1.5 flex items-center gap-1 px-1.5 py-[2px] rounded-md bg-amber-500/10 border border-amber-400/30 text-[0.6rem]"+ title={staleError.message}+ >+ <span className="text-amber-600 dark:text-amber-300 font-medium">+ stale — refresh?+ </span>+ <button+ onClick={handleRefreshStale}+ disabled={isRefreshing}+ className="flex items-center gap-0.5 px-1 py-[1px] rounded text-amber-700 dark:text-amber-200 hover:bg-amber-500/20 disabled:opacity-50 transition-colors"+ title={`Re-pull ${staleError.model}`}+ >+ {isRefreshing ? (+ <Loader2 size={9} className="animate-spin" />+ ) : (+ <RefreshCw size={9} />+ )}+ <span>Refresh</span>+ </button>+ <button+ onClick={() => setStaleError(null)}+ className="flex items-center p-[1px] rounded text-amber-600/70 hover:text-amber-800 hover:bg-amber-500/20 transition-colors"+ title="Dismiss"+ aria-label="Dismiss"+ >+ <X size={9} />+ </button>+ </div>)}</>)}diff --git a/src/lib/__tests__/ollama-errors.test.ts b/src/lib/__tests__/ollama-errors.test.tsnew file mode 100644index 00000000..3388c791--- /dev/null+++ b/src/lib/__tests__/ollama-errors.test.ts@@ -0,0 +1,105 @@+import { describe, it, expect } from 'vitest'+import { parseOllamaError, ModelLoadError, chatStyleMessage } from '../ollama-errors'++describe('parseOllamaError', () => {+ it('detects /api/chat stale-manifest error', async () => {+ const body = JSON.stringify({ error: '"hermes3:8b" does not support chat' })+ const res = new Response(body, { status: 400 })+ const parsed = await parseOllamaError(res)+ expect(parsed.kind).toBe('stale-manifest')+ expect(parsed.model).toBe('hermes3:8b')+ })++ it('detects /api/generate stale-manifest error (Lichtschalter path)', async () => {+ const body = JSON.stringify({ error: '"phi4:14b" does not support generate' })+ const res = new Response(body, { status: 400 })+ const parsed = await parseOllamaError(res)+ expect(parsed.kind).toBe('stale-manifest')+ expect(parsed.model).toBe('phi4:14b')+ })++ it('detects /api/chat stale-manifest for "completion" variant', async () => {+ const body = JSON.stringify({ error: '"foo:7b" does not support completion' })+ const res = new Response(body, { status: 400 })+ const parsed = await parseOllamaError(res)+ expect(parsed.kind).toBe('stale-manifest')+ expect(parsed.model).toBe('foo:7b')+ })++ it('detects Rust-proxy-wrapped stale-manifest (fake-500 from localFetch)', async () => {+ // localFetch wraps as: Response(JSON.stringify({error: "HTTP 400: {...}"}), {status:500})+ const wrapped = `HTTP 400: ${JSON.stringify({ error: '"phi4:14b" does not support generate' })}`+ const body = JSON.stringify({ error: wrapped })+ const res = new Response(body, { status: 500 })+ const parsed = await parseOllamaError(res)+ expect(parsed.kind).toBe('stale-manifest')+ expect(parsed.model).toBe('phi4:14b')+ })++ it('detects stale-manifest for namespaced models (mannix/llama3.1-8b-abliterated:agent)', async () => {+ const body = JSON.stringify({ error: '"mannix/llama3.1-8b-abliterated:agent" does not support generate' })+ const res = new Response(body, { status: 400 })+ const parsed = await parseOllamaError(res)+ expect(parsed.kind).toBe('stale-manifest')+ expect(parsed.model).toBe('mannix/llama3.1-8b-abliterated:agent')+ })++ it('returns other for unknown 400 errors', async () => {+ const body = JSON.stringify({ error: 'unrelated error message' })+ const res = new Response(body, { status: 400 })+ const parsed = await parseOllamaError(res)+ expect(parsed.kind).toBe('other')+ expect(parsed.model).toBeNull()+ expect(parsed.message).toBe('unrelated error message')+ })++ it('falls back to default when body is empty', async () => {+ const res = new Response('', { status: 503 })+ const parsed = await parseOllamaError(res, 'server unavailable')+ expect(parsed.kind).toBe('other')+ expect(parsed.message).toBe('server unavailable')+ })++ it('falls back to default when body is non-JSON text (HTML gateway page, etc.)', async () => {+ const res = new Response('<html>gateway timeout</html>', { status: 504 })+ const parsed = await parseOllamaError(res, 'request failed')+ expect(parsed.kind).toBe('other')+ expect(parsed.raw).toBe('request failed')+ })+})++describe('ModelLoadError', () => {+ it('carries kind + model + raw error for downstream handling', async () => {+ const res = new Response(JSON.stringify({ error: '"phi4:14b" does not support generate' }), { status: 400 })+ const parsed = await parseOllamaError(res)+ const err = new ModelLoadError(parsed, 'phi4:14b')+ expect(err.kind).toBe('stale-manifest')+ expect(err.model).toBe('phi4:14b')+ expect(err.name).toBe('ModelLoadError')+ expect(err.message).toContain('stale manifest')+ })++ it('falls back to callerModel when regex fails to capture', async () => {+ const res = new Response(JSON.stringify({ error: 'server crash' }), { status: 500 })+ const parsed = await parseOllamaError(res)+ const err = new ModelLoadError(parsed, 'phi4:14b')+ expect(err.kind).toBe('other')+ expect(err.model).toBe('phi4:14b') // caller-supplied fallback+ })+})++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 })+ const parsed = await parseOllamaError(res)+ const msg = chatStyleMessage(parsed)+ expect(msg).toContain('Ollama rejected')+ expect(msg).toContain('ollama pull gemma4:e4b')+ })++ it('returns raw message for non-stale errors', async () => {+ const res = new Response(JSON.stringify({ error: 'CUDA out of memory' }), { status: 500 })+ const parsed = await parseOllamaError(res)+ expect(chatStyleMessage(parsed)).toBe('CUDA out of memory')+ })+})diff --git a/src/lib/ollama-errors.ts b/src/lib/ollama-errors.tsnew file mode 100644index 00000000..0f35ec87--- /dev/null+++ b/src/lib/ollama-errors.ts@@ -0,0 +1,99 @@+/**+ * Ollama error detection + typed errors.+ *+ * Ollama 0.20.x strict-rejects models whose on-disk manifest lacks the+ * runtime `capabilities` field (either pulled before Ollama 0.15 or whose+ * registry entry has been re-published since the local pull). The server+ * returns HTTP 400 with `{"error":"\"<model>\" does not support (chat|completion|generate)"}`.+ *+ * Two additional wrapping layers matter in practice:+ * 1. Tauri `proxy_localhost` wraps any non-2xx as Rust `Err("HTTP 400: <body>")`.+ * The JS `localFetch` catches that, tries a direct fetch fallback, and+ * if that also fails returns a synthetic `Response` with status 500 and+ * body `{"error":"HTTP 400: {…}"}`.+ * 2. JSON encoding quotes the model name as `\"phi4:14b\"` when it's nested+ * inside an outer JSON string.+ *+ * The regex here is tolerant to both wrappings and to all three API verbs+ * that can trigger it (`/api/chat`, `/api/generate` via `prompt`/`completion`).+ */++export type OllamaErrorKind = 'stale-manifest' | 'connection' | 'other'++export interface ParsedOllamaError {+ kind: OllamaErrorKind+ model: string | null+ /** Human-readable, actionable message. */+ message: string+ /** Original raw error string (for logs). */+ raw: string+}++const STALE_MANIFEST_RE =+ /[\\'"]*([\w.:/\-]+?)[\\'"]*\s+does not support (chat|completion|generate)/i++/**+ * Parse an Ollama error response into a typed structure.+ * `res` must be a non-ok Response. Safe to call on already-consumed bodies+ * (will return an `other` with the fallback message).+ */+export async function parseOllamaError(+ res: Response,+ fallback = 'Ollama request failed'+): Promise<ParsedOllamaError> {+ let raw = fallback+ try {+ const text = await res.text()+ // Only surface JSON error bodies — non-JSON responses (HTML gateway pages,+ // empty bodies) collapse to the caller-supplied fallback to avoid leaking+ // framework noise into the UI. Matches the pre-refactor behaviour of+ // OllamaProvider.extractError so existing tests keep passing.+ try {+ const data = JSON.parse(text)+ raw = (data && typeof data.error === 'string' ? data.error : fallback) || fallback+ } catch {+ raw = fallback+ }+ } catch {+ 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,+ }+ }++ return { kind: 'other', model: null, message: raw, raw }+}++/** Typed error thrown by loadModel / unloadModel. */+export class ModelLoadError extends Error {+ readonly kind: OllamaErrorKind+ readonly model: string+ readonly raw: string+ constructor(parsed: ParsedOllamaError, model: string) {+ super(parsed.message)+ this.name = 'ModelLoadError'+ this.kind = parsed.kind+ this.model = parsed.model || model+ this.raw = parsed.raw+ }+}++/**+ * Produce the same user-facing message as the chat path's `extractError`.+ * Kept separate so the detection logic stays in one place; callers that+ * want the chat-style wording (terminal instructions) can use this.+ */+export function chatStyleMessage(parsed: ParsedOllamaError): string {+ if (parsed.kind === 'stale-manifest' && parsed.model) {+ return `Ollama rejected "${parsed.model}" — its manifest is stale. Open a terminal and run: ollama pull ${parsed.model} Then reload the model.`+ }+ return parsed.message+}