Skip to content

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.

fix(transport): Win11 "agent error" — status-faithful proxy streaming, proxy-first loopback, surface mid-stream Ollama errors (rikki Discord 2026-06-10)

purple13e34a86ed3d
diff --git a/src/api/__tests__/backend-stream-status.test.ts b/src/api/__tests__/backend-stream-status.test.ts
new file mode 100644
index 00000000..09e37e5a
--- /dev/null
+++ b/src/api/__tests__/backend-stream-status.test.ts
@@ -0,0 +1,141 @@
+/**
+ * localFetchStream transport tests (rikki Discord 2026-06-10 — Win11 "agent error").
+ *
+ * The chunked Rust proxy rejects with the STRING "HTTP <status>: <body>" when
+ * the local backend answered non-2xx. These tests pin the three behaviours the
+ * fix introduced:
+ * 1. Tauri + loopback target → proxy-FIRST (no doomed direct fetch on WebView2)
+ * 2. invoke rejection with HTTP shape → faithful Response status/body
+ * (so `res.status === 400` think-downgrade logic behaves like on Linux)
+ * 3. invoke rejection without HTTP shape → 503 (retryable transport error)
+ * plus the EOF-marker semantics: chunks delivered AFTER the invoke promise
+ * resolves (WebView2 149 ordering) still reach the reader.
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+
+const invokeMock = vi.fn()
+class MockChannel<T = unknown> {
+ onmessage: (msg: T) => void = () => {}
+}
+vi.mock('@tauri-apps/api/core', () => ({
+ invoke: (...args: unknown[]) => invokeMock(...args),
+ Channel: MockChannel,
+}))
+
+import { localFetchStream, parseProxyHttpError } from '../backend'
+
+const fetchMock = vi.fn()
+
+function tauriMode(on: boolean) {
+ const w = ((globalThis as any).window = (globalThis as any).window || {})
+ if (on) w.__TAURI_INTERNALS__ = {}
+ else { delete w.__TAURI_INTERNALS__; delete w.__TAURI__ }
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ vi.stubGlobal('fetch', fetchMock)
+})
+
+afterEach(() => {
+ vi.unstubAllGlobals()
+ tauriMode(false)
+})
+
+describe('parseProxyHttpError', () => {
+ it('parses the bare Rust proxy shape', () => {
+ expect(parseProxyHttpError('HTTP 400: {"error":"x does not support tools"}'))
+ .toEqual({ status: 400, body: '{"error":"x does not support tools"}' })
+ })
+
+ it('parses a prefixed command shape', () => {
+ expect(parseProxyHttpError('pull_model_stream: HTTP 502: bad gateway'))
+ .toEqual({ status: 502, body: 'bad gateway' })
+ })
+
+ it('returns null for transport errors', () => {
+ expect(parseProxyHttpError('proxy_localhost_stream_chunked: error sending request: connection refused')).toBeNull()
+ expect(parseProxyHttpError('connection refused')).toBeNull()
+ })
+
+ it('rejects out-of-range status numbers', () => {
+ expect(parseProxyHttpError('HTTP 99: nope')).toBeNull()
+ })
+})
+
+describe('localFetchStream in Tauri mode (loopback → proxy-first)', () => {
+ it('does NOT attempt a direct fetch for loopback targets', async () => {
+ tauriMode(true)
+ invokeMock.mockImplementationOnce((_cmd: string, args: any) => {
+ // Immediately EOF an empty-but-successful stream.
+ queueMicrotask(() => args.onChunk.onmessage([]))
+ return new Promise(() => {}) // never resolves — EOF settles the Response
+ })
+
+ const res = await localFetchStream('http://localhost:11434/api/chat', { method: 'POST', body: '{}' })
+ expect(res.status).toBe(200)
+ expect(fetchMock).not.toHaveBeenCalled()
+ expect(invokeMock).toHaveBeenCalledTimes(1)
+ expect(invokeMock.mock.calls[0][0]).toBe('proxy_localhost_stream_chunked')
+ })
+
+ it('rebuilds a faithful Response when the backend answered non-2xx', async () => {
+ tauriMode(true)
+ invokeMock.mockRejectedValueOnce('HTTP 400: {"error":"registry.ollama.ai/library/foo does not support tools"}')
+
+ const res = await localFetchStream('http://127.0.0.1:11434/api/chat', { method: 'POST', body: '{}' })
+ expect(res.status).toBe(400)
+ expect(await res.text()).toContain('does not support tools')
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+
+ it('maps transport failures to a retryable 503', async () => {
+ tauriMode(true)
+ invokeMock.mockRejectedValueOnce('proxy_localhost_stream_chunked: error sending request for url (http://localhost:11434/api/chat): connection refused')
+
+ const res = await localFetchStream('http://localhost:11434/api/chat', { method: 'POST', body: '{}' })
+ expect(res.status).toBe(503)
+ expect(await res.text()).toContain('connection refused')
+ })
+
+ it('delivers chunks that arrive AFTER the invoke promise resolved (WebView2 149 ordering)', async () => {
+ tauriMode(true)
+ let channel!: MockChannel<number[]>
+ invokeMock.mockImplementationOnce((_cmd: string, args: any) => {
+ channel = args.onChunk
+ return Promise.resolve()
+ })
+
+ const res = await localFetchStream('http://localhost:11434/api/chat', { method: 'POST', body: '{}' })
+ expect(res.status).toBe(200)
+
+ const enc = new TextEncoder()
+ channel.onmessage(Array.from(enc.encode('{"message":{"content":"hel')))
+ channel.onmessage(Array.from(enc.encode('lo"}}\n')))
+ channel.onmessage([]) // Rust EOF marker
+
+ expect(await res.text()).toBe('{"message":{"content":"hello"}}\n')
+ })
+
+ it('keeps direct-fetch-first for non-loopback (LAN) targets', async () => {
+ tauriMode(true)
+ fetchMock.mockResolvedValueOnce(new Response('ok', { status: 200 }))
+
+ const res = await localFetchStream('http://192.168.1.50:1234/v1/chat/completions', { method: 'POST', body: '{}' })
+ expect(res.status).toBe(200)
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ expect(invokeMock).not.toHaveBeenCalled()
+ })
+})
+
+describe('localFetchStream in dev mode (no Tauri)', () => {
+ it('uses a plain direct fetch', async () => {
+ tauriMode(false)
+ fetchMock.mockResolvedValueOnce(new Response('ok', { status: 200 }))
+
+ const res = await localFetchStream('/api/chat', { method: 'POST', body: '{}' })
+ expect(res.status).toBe(200)
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ expect(invokeMock).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/api/__tests__/provider-ollama-stream-errors.test.ts b/src/api/__tests__/provider-ollama-stream-errors.test.ts
new file mode 100644
index 00000000..42976bfa
--- /dev/null
+++ b/src/api/__tests__/provider-ollama-stream-errors.test.ts
@@ -0,0 +1,72 @@
+/**
+ * OllamaProvider.chatStream error-line test (rikki Discord 2026-06-10).
+ *
+ * Plain chat shares the same Ollama NDJSON wire format as the agent path:
+ * a mid-stream `{"error":"..."}` line inside an HTTP-200 stream means the
+ * runner died. The stream loop must throw instead of yielding nothing.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import type { ProviderConfig } from '../providers/types'
+
+vi.mock('../backend', () => ({
+ isTauri: () => false,
+ localFetch: vi.fn(),
+ localFetchStream: vi.fn(),
+ ollamaUrl: (path: string) => `/api${path}`,
+}))
+
+import { OllamaProvider } from '../providers/ollama-provider'
+import { localFetchStream } from '../backend'
+
+const mockLocalFetchStream = localFetchStream as ReturnType<typeof vi.fn>
+
+const config: ProviderConfig = {
+ id: 'ollama',
+ name: 'Ollama',
+ enabled: true,
+ baseUrl: 'http://localhost:11434',
+ apiKey: '',
+ isLocal: true,
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+})
+
+describe('OllamaProvider.chatStream — mid-stream error lines', () => {
+ it('throws on {"error":...} instead of ending as a silent empty reply', async () => {
+ mockLocalFetchStream.mockResolvedValueOnce(new Response(
+ '{"message":{"content":"par"},"done":false}\n' +
+ '{"error":"llama runner process has terminated: signal: killed"}\n',
+ { status: 200 },
+ ))
+
+ const provider = new OllamaProvider(config)
+ const collect = async () => {
+ const chunks: string[] = []
+ for await (const c of provider.chatStream('m', [{ role: 'user', content: 'hi' }])) {
+ chunks.push(c.content)
+ }
+ return chunks
+ }
+ await expect(collect()).rejects.toThrow(/llama runner process has terminated/)
+ })
+
+ it('still yields normal chunks', async () => {
+ mockLocalFetchStream.mockResolvedValueOnce(new Response(
+ '{"message":{"content":"hello"},"done":false}\n' +
+ '{"message":{"content":""},"done":true,"eval_count":3}\n',
+ { status: 200 },
+ ))
+
+ const provider = new OllamaProvider(config)
+ const contents: string[] = []
+ let evalCount: number | undefined
+ for await (const c of provider.chatStream('m', [{ role: 'user', content: 'hi' }])) {
+ contents.push(c.content)
+ if (c.evalCount !== undefined) evalCount = c.evalCount
+ }
+ expect(contents.join('')).toBe('hello')
+ expect(evalCount).toBe(3)
+ })
+})
diff --git a/src/api/backend.ts b/src/api/backend.ts
index 37137ba9..c8304603 100644
--- a/src/api/backend.ts
+++ b/src/api/backend.ts
@@ -29,6 +29,23 @@ async function getInvoke() {
return _invoke;
}
+/**
+ * The Rust proxy commands reject with the STRING `"HTTP <status>: <body>"`
+ * when the local backend answered non-2xx (vs. a transport error like
+ * "connection refused" when it could not be reached at all). Parse that shape
+ * so the JS side can rebuild a faithful Response — callers check
+ * `res.status === 400` for the Ollama think-field downgrade and similar, and
+ * those checks must behave identically whether the bytes traveled through the
+ * proxy (Windows/WebView2) or a direct fetch (Linux/macOS/dev).
+ */
+export function parseProxyHttpError(msg: string): { status: number; body: string } | null {
+ const m = /(?:^|:\s*)HTTP (\d{3}):\s?([\s\S]*)$/.exec(msg)
+ if (!m) return null
+ const status = Number(m[1])
+ if (status < 100 || status > 599) return null
+ return { status, body: m[2] ?? '' }
+}
+
/**
* Fetch a localhost URL, bypassing CORS in Tauri mode.
* In dev mode: uses normal fetch().
@@ -97,6 +114,19 @@ export async function localFetch(
return new Response(text, { status: 200, headers: { "Content-Type": "application/json" } });
} catch (proxyErr) {
const proxyErrMsg = String(proxyErr)
+
+ // The Rust proxy DID reach the backend and the backend answered non-2xx
+ // (Err("HTTP <status>: <body>")). That is a real HTTP response, not a
+ // transport failure — surface it faithfully so callers' status checks
+ // (think-field 400 downgrade, buildError) behave exactly like a direct
+ // fetch does on Linux/macOS. Retrying via direct fetch would be pointless
+ // and on WebView2 149 just adds a second guaranteed failure (rikki
+ // Discord 2026-06-10: Win11 "agent error" while Kubuntu was fine).
+ const httpErr = parseProxyHttpError(proxyErrMsg)
+ if (httpErr) {
+ return new Response(httpErr.body, { status: httpErr.status })
+ }
+
log.warn('[localFetch] Proxy failed, trying direct fetch', { err: proxyErrMsg })
// Fallback: try direct fetch (works when ComfyUI has --enable-cors-header *)
@@ -147,44 +177,84 @@ export async function localFetchStream(
const body = options?.body;
const headers = body ? { "Content-Type": "application/json" } : undefined;
- // Direct fetch first — Ollama has CORS open on localhost, so this gives
- // us true chunked streaming. Works in both dev mode and Tauri .exe.
- try {
- const res = await fetch(url, {
- method,
- headers,
- body,
- signal: options?.signal,
- });
- // Guard: some Tauri WebView setups still reject — if the Response is
- // malformed (no body at all), fall through to the proxy.
- if (res.body || res.ok || res.status >= 400) {
- return res;
+ // Transport order (rikki Discord 2026-06-10, Win11 "agent error"):
+ // on WebView2 the direct fetch to a loopback backend is dead on arrival —
+ // Ollama's CORS rejects the tauri.localhost origin and WebView2 149 made
+ // the failure mode flaky instead of clean. Burning that attempt first cost
+ // latency and, worse, a direct fetch that dies MID-stream cannot fall back
+ // (the body is already partially consumed). So in Tauri, loopback targets
+ // go proxy-FIRST; the direct fetch remains as fallback. Dev mode and
+ // non-loopback (LAN) targets keep the old order.
+ const proxyFirst = isTauri() && isLoopbackHost(hostnameOf(url));
+
+ const tryDirect = async (): Promise<Response | null> => {
+ try {
+ const res = await fetch(url, { method, headers, body, signal: options?.signal });
+ // Guard: some Tauri WebView setups still reject — if the Response is
+ // malformed (no body at all), fall through to the proxy.
+ if (res.body || res.ok || res.status >= 400) return res;
+ return null;
+ } catch (directErr) {
+ if (options?.signal?.aborted) throw directErr;
+ log.warn('[localFetchStream] Direct fetch failed', { err: String(directErr) });
+ return null;
+ }
+ };
+
+ if (!proxyFirst) {
+ const direct = await tryDirect();
+ if (direct) return direct;
+ if (!isTauri()) {
+ // No proxy to fall back to in plain browser dev mode.
+ return new Response(JSON.stringify({ error: 'Network error' }), { status: 500 });
}
- } catch (directErr) {
- if (options?.signal?.aborted) throw directErr;
- log.warn('[localFetchStream] Direct fetch failed, trying Rust proxy', { err: String(directErr) });
}
- // Fallback in Tauri: route through the Rust proxy.
- if (!isTauri()) {
- // Re-throw the original direct-fetch error if we are not in Tauri,
- // since there is no proxy to fall back to.
- return new Response(JSON.stringify({ error: 'Network error' }), { status: 500 });
+ const proxied = await proxyStreamChunked(url, method, body);
+ if (proxied) return proxied;
+
+ // Proxy layer itself unavailable (invoke/Channel import died) — give the
+ // direct fetch one shot if we skipped it above.
+ if (proxyFirst) {
+ const direct = await tryDirect();
+ if (direct) return direct;
}
+ return new Response(JSON.stringify({ error: 'Local backend unreachable (proxy and direct fetch both failed)' }), { status: 503 });
+}
- const invoke = await getInvoke();
+/**
+ * STREAMING proxy (David 2026-06-02): a Tauri Channel forwards each chunk from
+ * Rust as it arrives, fed into a ReadableStream → real token-by-token streaming
+ * (the old buffered path produced NOTHING until the body was complete — the
+ * multi-minute "model loading" hang, dhasim Discord report).
+ *
+ * Status fidelity (rikki Discord 2026-06-10): the Rust command rejects with the
+ * string "HTTP <status>: <body>" when the backend answered non-2xx — BEFORE any
+ * chunk is sent. The old code turned that into a stream error with no
+ * statusCode, so callers' `res.status === 400` handling (Ollama think-field
+ * downgrade, "does not support tools") never ran on the proxy path — Windows
+ * behaved differently from Linux for the SAME backend answer. Now the Response
+ * is deferred until the first signal:
+ * - invoke rejects "HTTP <s>: <body>" → faithful Response(<s>, body)
+ * - invoke rejects otherwise → Response 503 (transport: retryable)
+ * - first chunk / EOF / invoke resolve → streaming Response 200
+ *
+ * Returns null when the invoke/Channel layer itself is unavailable so the
+ * caller can decide on a last-resort transport.
+ */
+async function proxyStreamChunked(url: string, method: string, body?: string): Promise<Response | null> {
+ let invoke: Awaited<ReturnType<typeof getInvoke>>;
+ let ChannelCtor: typeof import("@tauri-apps/api/core").Channel;
+ try {
+ invoke = await getInvoke();
+ ChannelCtor = (await import("@tauri-apps/api/core")).Channel;
+ } catch (err) {
+ log.warn('[localFetchStream] invoke/Channel unavailable', { err: String(err) });
+ return null;
+ }
- // STREAMING proxy (David 2026-06-02): the webview can't fetch Ollama directly
- // — its origin is `http://tauri.localhost` and Ollama's CORS rejects it
- // ("Failed to fetch"), so EVERY chat request lands here. The old path awaited
- // the whole body (`bytes` buffered), so a long/slow generation produced
- // NOTHING in the UI until fully done — a multi-minute "model loading" hang
- // (dhasim Discord report). A Tauri Channel now forwards each chunk from Rust
- // as it arrives, fed into a ReadableStream → real token-by-token streaming.
try {
- const { Channel } = await import("@tauri-apps/api/core");
- const channel = new Channel<number[]>();
+ const channel = new ChannelCtor<number[]>();
let ctrl: ReadableStreamDefaultController<Uint8Array> | null = null;
let closed = false;
const stream = new ReadableStream<Uint8Array>({
@@ -195,30 +265,58 @@ export async function localFetchStream(
closed = true;
try { ctrl?.close(); } catch { /* already closed */ }
};
+
+ let responseSettled = false;
+ let settle!: (res: Response) => void;
+ const settled = new Promise<Response>((resolve) => {
+ settle = (res) => { if (!responseSettled) { responseSettled = true; resolve(res) } };
+ });
+ const settleStreaming = () => {
+ if (responseSettled) return;
+ settle(new Response(stream, { status: 200, headers: { "Content-Type": "application/x-ndjson" } }));
+ };
+
channel.onmessage = (chunk: number[]) => {
if (closed) return;
// Empty chunk = Rust's explicit EOF marker (data chunks are never
// empty). Closing HERE instead of on the invoke result is the fix for
// the silent no-reply chats (live find 2026-06-11): WebView2 149
// delivers queued channel messages AFTER the invoke promise resolves,
- // so the old `.then(close)` raced ahead of the data and dropped every
+ // so closing on the result raced ahead of the data and dropped every
// chunk — the user message appeared, the reply never did.
if (!chunk || chunk.length === 0) {
+ settleStreaming();
closeStream();
return;
}
try { ctrl?.enqueue(new Uint8Array(chunk)); } catch { /* reader gone */ }
+ settleStreaming();
};
+
void invoke("proxy_localhost_stream_chunked", { url, method, body: body || null, onChunk: channel })
.then(() => {
// Do NOT close here — the EOF marker does that (it may arrive after
// this resolves; see above). Grace fallback so a lost EOF can't leak
// the stream forever: anything still open 15s after the command
// returned closes with whatever was delivered by then.
+ settleStreaming();
setTimeout(closeStream, 15_000);
})
- .catch((err: unknown) => { closed = true; try { ctrl?.error(err); } catch { /* already errored */ } });
- return new Response(stream, { status: 200, headers: { "Content-Type": "application/x-ndjson" } });
+ .catch((err: unknown) => {
+ const msg = String(err);
+ const httpErr = parseProxyHttpError(msg);
+ // Backend answered non-2xx (rejected before any chunk): faithful status.
+ // Transport failure (connection refused / validation): 503 so callers
+ // treat it as retryable instead of a deterministic 4xx.
+ settle(httpErr
+ ? new Response(httpErr.body, { status: httpErr.status })
+ : new Response(JSON.stringify({ error: msg }), { status: 503 }));
+ closed = true;
+ // If a reader is already consuming (mid-stream death), surface there too.
+ try { ctrl?.error(err instanceof Error ? err : new Error(msg)); } catch { /* no reader */ }
+ });
+
+ return await settled;
} catch (chanErr) {
// Channel unavailable → legacy buffered proxy (still works, just not streamed).
log.warn('[localFetchStream] Channel stream unavailable, buffering via proxy', { err: String(chanErr) });
@@ -231,7 +329,11 @@ export async function localFetchStream(
const uint8 = new Uint8Array(bytes);
return new Response(uint8, { status: 200, headers: { "Content-Type": "application/x-ndjson" } });
} catch (err) {
- return new Response(JSON.stringify({ error: String(err) }), { status: 500 });
+ const msg = String(err);
+ const httpErr = parseProxyHttpError(msg);
+ return httpErr
+ ? new Response(httpErr.body, { status: httpErr.status })
+ : new Response(JSON.stringify({ error: msg }), { status: 503 });
}
}
}
diff --git a/src/api/providers/ollama-provider.ts b/src/api/providers/ollama-provider.ts
index 19086b19..8048b5f6 100644
--- a/src/api/providers/ollama-provider.ts
+++ b/src/api/providers/ollama-provider.ts
@@ -142,6 +142,14 @@ export class OllamaProvider implements ProviderClient {
for await (const chunk of parseNDJSONStream<OllamaChatChunk>(res)) {
if (options?.signal?.aborted) break
+ // Mid-stream `{"error":"..."}` line (runner crash, OOM) inside an
+ // HTTP-200 stream — surface it instead of yielding a silent empty
+ // chat turn (rikki Discord 2026-06-10, Win11 proxy path).
+ const errLine = (chunk as { error?: unknown }).error
+ if (typeof errLine === 'string' && errLine) {
+ throw new Error(`Ollama: ${errLine}`)
+ }
+
const toolCalls: ToolCall[] | undefined = chunk.message?.tool_calls?.map(tc => ({
function: { name: tc.function.name, arguments: tc.function.arguments },
}))
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 1dbc5a85..f6c7fd17 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -1203,6 +1203,16 @@ export function useAgentChat() {
convId!, assistantMessage.id,
`This model does not support thinking mode. Disable the Think button or switch to a compatible model (Qwen 3, DeepSeek-R1, Gemma 4).`
)
+ } else if (/failed to fetch|connection refused|connection reset|error sending request|proxy_localhost|network ?error|timed out|timeout|tcp connect|llama runner process|backend unreachable|HTTP 5\d\d/i.test(errorMsg)) {
+ // Connection-class failure — after the transient retries above this
+ // means the backend really dropped mid-run (crashed, was killed, or
+ // is busy swapping models). A bare "Agent error: Connection failed"
+ // gave users nothing to act on (rikki Discord 2026-06-10, Win11).
+ useChatStore.getState().updateMessageContent(
+ convId!, assistantMessage.id,
+ (contentRef.current ? contentRef.current + '\n\n' : '') +
+ `Lost the connection to the local model backend mid-response — it may have crashed, been closed, or was busy swapping models. LU already retried automatically.\n\nCheck that Ollama / LM Studio is running (and the model still loads), then send the message again.\n\nDetails: ${errorMsg}`
+ )
} else {
useChatStore.getState().updateMessageContent(
convId!, assistantMessage.id,
diff --git a/src/lib/__tests__/ollama-stream-tools-errors.test.ts b/src/lib/__tests__/ollama-stream-tools-errors.test.ts
new file mode 100644
index 00000000..9a59bb0d
--- /dev/null
+++ b/src/lib/__tests__/ollama-stream-tools-errors.test.ts
@@ -0,0 +1,101 @@
+/**
+ * streamOllamaChatWithTools error-path tests (rikki Discord 2026-06-10).
+ *
+ * Ollama reports mid-stream failures (runner crash, OOM) as an NDJSON line
+ * `{"error":"..."}` inside an HTTP-200 stream. Before the fix the parser
+ * silently skipped those lines → EMPTY agent turn → bare "Agent error" with
+ * zero context. Also pins the 400 think-field downgrade, which only works on
+ * Windows now that the proxy path carries faithful HTTP statuses.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+vi.mock('../../api/backend', () => ({
+ ollamaUrl: (path: string) => `/api${path}`,
+ localFetchStream: vi.fn(),
+}))
+
+import { streamOllamaChatWithTools } from '../ollama-stream-tools'
+import { localFetchStream } from '../../api/backend'
+
+const mockStream = localFetchStream as ReturnType<typeof vi.fn>
+
+const run = () =>
+ streamOllamaChatWithTools(
+ 'test-model',
+ [{ role: 'user', content: 'hi' }],
+ [],
+ {},
+ () => {},
+ () => {},
+ )
+
+beforeEach(() => {
+ vi.clearAllMocks()
+})
+
+describe('streamOllamaChatWithTools — NDJSON error lines', () => {
+ it('throws on a mid-stream {"error":...} line instead of returning an empty turn', async () => {
+ mockStream.mockResolvedValueOnce(new Response(
+ '{"message":{"content":"thinking about it"}}\n' +
+ '{"error":"llama runner process has terminated: exit status 2"}\n',
+ { status: 200 },
+ ))
+ await expect(run()).rejects.toThrow(/llama runner process has terminated/)
+ })
+
+ it('throws on an error line sitting in the tail buffer (no trailing newline)', async () => {
+ mockStream.mockResolvedValueOnce(new Response('{"error":"model requires more system memory"}', { status: 200 }))
+ await expect(run()).rejects.toThrow(/more system memory/)
+ })
+
+ it('still parses content, tool calls and token counts on the happy path', async () => {
+ mockStream.mockResolvedValueOnce(new Response(
+ '{"message":{"content":"hi","tool_calls":[{"function":{"name":"web_search","arguments":{"query":"x"}}}]}}\n' +
+ '{"done":true,"prompt_eval_count":5,"eval_count":7}\n',
+ { status: 200 },
+ ))
+ const turn = await run()
+ expect(turn.content).toBe('hi')
+ expect(turn.toolCalls).toHaveLength(1)
+ expect(turn.toolCalls[0].function.name).toBe('web_search')
+ expect(turn.promptEvalCount).toBe(5)
+ expect(turn.evalCount).toBe(7)
+ })
+
+ it('skips partial JSON lines without dying', async () => {
+ mockStream.mockResolvedValueOnce(new Response(
+ '{"message":{"content":"ok"}}\n{"mess\n',
+ { status: 200 },
+ ))
+ const turn = await run()
+ expect(turn.content).toBe('ok')
+ })
+})
+
+describe('streamOllamaChatWithTools — think-field 400 downgrade', () => {
+ it('retries once without `think` when the server answers 400 (now status-faithful via proxy)', async () => {
+ mockStream
+ .mockResolvedValueOnce(new Response('{"error":"registry model does not support thinking"}', { status: 400 }))
+ .mockResolvedValueOnce(new Response('{"message":{"content":"ok"}}\n', { status: 200 }))
+
+ const turn = await streamOllamaChatWithTools(
+ 'test-model',
+ [{ role: 'user', content: 'hi' }],
+ [],
+ { thinking: true },
+ () => {},
+ () => {},
+ )
+ expect(turn.content).toBe('ok')
+ expect(mockStream).toHaveBeenCalledTimes(2)
+ const firstBody = JSON.parse(mockStream.mock.calls[0][1].body)
+ const secondBody = JSON.parse(mockStream.mock.calls[1][1].body)
+ expect(firstBody.think).toBe(true)
+ expect('think' in secondBody).toBe(false)
+ })
+
+ it('throws with the real status code on a non-think 400', async () => {
+ mockStream.mockResolvedValueOnce(new Response('{"error":"model does not support tools"}', { status: 400 }))
+ await expect(run()).rejects.toMatchObject({ statusCode: 400 })
+ })
+})
diff --git a/src/lib/ollama-stream-tools.ts b/src/lib/ollama-stream-tools.ts
index 9fad63ef..5d28b432 100644
--- a/src/lib/ollama-stream-tools.ts
+++ b/src/lib/ollama-stream-tools.ts
@@ -113,40 +113,60 @@ export async function streamOllamaChatWithTools(
for (const line of lines) {
const trimmed = line.trim()
if (!trimmed) continue
+ // Parse and process are separated on purpose: the catch only covers the
+ // JSON.parse (partial lines are normal in a chunked stream), while a
+ // real `{"error":...}` line must THROW past it.
+ let j: any
try {
- const j = JSON.parse(trimmed)
- if (j.message) {
- if (j.message.content) {
- content += j.message.content
- onContent(content)
- }
- if (j.message.thinking) {
- thinking += j.message.thinking
- onThinking(thinking)
- }
- if (j.message.tool_calls && Array.isArray(j.message.tool_calls)) {
- toolCalls = [
- ...toolCalls,
- ...j.message.tool_calls.map((tc: any) => ({
- function: {
- name: tc.function.name,
- arguments: repairToolCallArgs(tc.function.arguments),
- },
- })),
- ]
- }
- }
- if (typeof j.prompt_eval_count === 'number') promptEvalCount = j.prompt_eval_count
- if (typeof j.eval_count === 'number') evalCount = j.eval_count
+ j = JSON.parse(trimmed)
} catch {
- // partial JSON line — skip
+ continue // partial JSON line — skip
+ }
+ // Ollama reports mid-stream failures (runner crash, OOM, context
+ // overflow on some builds) as an NDJSON line `{"error":"..."}` inside
+ // an HTTP-200 stream. Swallowing it produced an EMPTY turn — the agent
+ // loop then surfaced a bare "Agent error" with zero context (rikki
+ // Discord 2026-06-10). Throw so the caller's retry/classify logic runs.
+ if (typeof j.error === 'string' && j.error) {
+ throw new Error(`Ollama: ${j.error}`)
+ }
+ if (j.message) {
+ if (j.message.content) {
+ content += j.message.content
+ onContent(content)
+ }
+ if (j.message.thinking) {
+ thinking += j.message.thinking
+ onThinking(thinking)
+ }
+ if (j.message.tool_calls && Array.isArray(j.message.tool_calls)) {
+ toolCalls = [
+ ...toolCalls,
+ ...j.message.tool_calls.map((tc: any) => ({
+ function: {
+ name: tc.function.name,
+ arguments: repairToolCallArgs(tc.function.arguments),
+ },
+ })),
+ ]
+ }
}
+ if (typeof j.prompt_eval_count === 'number') promptEvalCount = j.prompt_eval_count
+ if (typeof j.eval_count === 'number') evalCount = j.eval_count
}
}
if (buf.trim()) {
+ let j: any
try {
- const j = JSON.parse(buf.trim())
+ j = JSON.parse(buf.trim())
+ } catch {
+ j = null // ignore tail-buffer parse errors
+ }
+ if (j) {
+ if (typeof j.error === 'string' && j.error) {
+ throw new Error(`Ollama: ${j.error}`)
+ }
if (j.message?.tool_calls && Array.isArray(j.message.tool_calls)) {
toolCalls = [
...toolCalls,
@@ -168,8 +188,6 @@ export async function streamOllamaChatWithTools(
}
if (typeof j.prompt_eval_count === 'number') promptEvalCount = j.prompt_eval_count
if (typeof j.eval_count === 'number') evalCount = j.eval_count
- } catch {
- // ignore tail-buffer parse errors
}
}