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.

tech(Streaming): ein Idle-Wächter für alle Pfade, Ollama endet terminal, Anthropic-Thinking funktioniert überhaupt

David9c7243a1f34f
diff --git a/src/api/__tests__/provider-anthropic.test.ts b/src/api/__tests__/provider-anthropic.test.ts
index b4e45b0e..92901f67 100644
--- a/src/api/__tests__/provider-anthropic.test.ts
+++ b/src/api/__tests__/provider-anthropic.test.ts
@@ -208,8 +208,12 @@ describe('AnthropicProvider', () => {
it('429 → rate_limit error', async () => {
const provider = new AnthropicProvider(makeConfig())
- vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
- new Response('', { status: 429 })
+ // Every attempt, not just the first: a throttle is now retried with
+ // backoff (providers/retry.ts), so a single mocked answer would let the
+ // second attempt escape to the real network. The assertion is on what
+ // the user finally sees once the retries are spent.
+ vi.spyOn(globalThis, 'fetch').mockImplementation(
+ async () => new Response('', { status: 429 })
)
try {
await provider.chatWithTools('claude-sonnet-4-20250514', [{ role: 'user', content: 'hi' }], [])
diff --git a/src/api/__tests__/provider-maxtokens-guard.test.ts b/src/api/__tests__/provider-maxtokens-guard.test.ts
index ca295737..e561a227 100644
--- a/src/api/__tests__/provider-maxtokens-guard.test.ts
+++ b/src/api/__tests__/provider-maxtokens-guard.test.ts
@@ -16,7 +16,11 @@ vi.mock('../backend', () => ({
localFetch: vi.fn(),
localFetchStream: (...a: any[]) => localFetchStream(...(a as [])),
ollamaUrl: (path: string) => `http://localhost:11434/api${path}`,
- isPrivateOrLanHost: () => true,
+ // Honest transport answers: api.anthropic.com is a public host the CSP
+ // allows, so the Anthropic provider takes its direct fetch and the stubbed
+ // global fetch below is what it hits. Blanket-true `isPrivateOrLanHost` used
+ // to be harmless because the provider never asked; now it does.
+ isPrivateOrLanHost: () => false,
isDirectFetchAllowed: () => true,
hostnameOf: (u: string) => { try { return new URL(u).hostname } catch { return '' } },
ensureProxyAllowsHost: async () => {},
diff --git a/src/api/__tests__/provider-ollama-terminal-chunk.test.ts b/src/api/__tests__/provider-ollama-terminal-chunk.test.ts
new file mode 100644
index 00000000..cc64f8c6
--- /dev/null
+++ b/src/api/__tests__/provider-ollama-terminal-chunk.test.ts
@@ -0,0 +1,160 @@
+/**
+ * Ollama always ends its turn — audit finding "no terminal done-chunk on a
+ * truncated NDJSON stream".
+ *
+ * Ollama marks the end of a turn with a `"done":true` line, and nothing
+ * guarantees it arrives: a runner OOM, VRAM eviction by an image job,
+ * `ollama stop`, a proxy or LAN cut all end the NDJSON mid-line. The generator
+ * then simply returned, and the chat layer — which only explains a turn it was
+ * handed a finishReason for — left a permanently empty assistant bubble with
+ * no hint whatsoever. Ollama is the most-used local backend and every one of
+ * those triggers is an ordinary Tuesday.
+ *
+ * The OpenAI provider has ended its stream with an explicit terminal chunk for
+ * several releases; this pulls the same semantics over.
+ *
+ * Run: npx vitest run src/api/__tests__/provider-ollama-terminal-chunk.test.ts
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import type { ProviderConfig, ChatStreamChunk } from '../providers/types'
+
+vi.mock('../backend', () => ({
+ isTauri: () => false,
+ localFetch: vi.fn(),
+ localFetchStream: vi.fn(),
+ ollamaUrl: (path: string) => `http://localhost:11434/api${path}`,
+}))
+
+import { OllamaProvider } from '../providers/ollama-provider'
+import { localFetchStream } from '../backend'
+import { STREAM_IDLE_TIMEOUT_MS } from '../stream-idle'
+
+const mockStream = localFetchStream as ReturnType<typeof vi.fn>
+
+const config: ProviderConfig = {
+ id: 'ollama', name: 'Ollama', enabled: true,
+ baseUrl: 'http://localhost:11434', apiKey: '', isLocal: true,
+}
+
+/** NDJSON that stops mid-turn without ever closing — a dropped LAN link. */
+function stalling(lines: string[]): Response {
+ const enc = new TextEncoder()
+ return new Response(new ReadableStream<Uint8Array>({
+ start(c) { for (const l of lines) c.enqueue(enc.encode(l)) },
+ }), { status: 200 })
+}
+
+async function drain(gen: AsyncGenerator<ChatStreamChunk>): Promise<ChatStreamChunk[]> {
+ const out: ChatStreamChunk[] = []
+ for await (const c of gen) out.push(c)
+ return out
+}
+
+beforeEach(() => { vi.clearAllMocks() })
+afterEach(() => { vi.useRealTimers() })
+
+describe('OllamaProvider.chatStream — the turn always ends', () => {
+ it('a truncated stream ends terminally instead of leaving an empty bubble', async () => {
+ // Two content lines, then the connection dies. No done:true ever arrives.
+ mockStream.mockResolvedValueOnce(new Response(
+ '{"message":{"content":"Once upon"},"done":false}\n' +
+ '{"message":{"content":" a ti',
+ { status: 200 },
+ ))
+
+ const chunks = await drain(new OllamaProvider(config)
+ .chatStream('llama3', [{ role: 'user', content: 'hi' }]))
+
+ const terminal = chunks.filter(c => c.done)
+ expect(terminal).toHaveLength(1)
+ expect(terminal[0].finishReason).toBe('disconnect')
+ // The partial text the model DID produce is still delivered.
+ expect(chunks.map(c => c.content).join('')).toBe('Once upon')
+ })
+
+ it('an empty truncated stream still says why, rather than nothing at all', async () => {
+ mockStream.mockResolvedValueOnce(new Response('', { status: 200 }))
+
+ const chunks = await drain(new OllamaProvider(config)
+ .chatStream('llama3', [{ role: 'user', content: 'hi' }]))
+
+ expect(chunks).toHaveLength(1)
+ expect(chunks[0]).toMatchObject({ done: true, finishReason: 'disconnect' })
+ })
+
+ it('does not add a second terminal chunk to a healthy turn', async () => {
+ mockStream.mockResolvedValueOnce(new Response(
+ '{"message":{"content":"hello"},"done":false}\n' +
+ '{"message":{"content":""},"done":true,"done_reason":"stop","eval_count":3}\n',
+ { status: 200 },
+ ))
+
+ const chunks = await drain(new OllamaProvider(config)
+ .chatStream('llama3', [{ role: 'user', content: 'hi' }]))
+
+ const terminal = chunks.filter(c => c.done)
+ expect(terminal).toHaveLength(1)
+ expect(terminal[0].finishReason).toBe('stop')
+ expect(terminal[0].evalCount).toBe(3)
+ })
+
+ it('a user Stop is not a disconnect and gets no terminal chunk', async () => {
+ const abort = new AbortController()
+ mockStream.mockResolvedValueOnce(new Response(
+ '{"message":{"content":"a"},"done":false}\n' +
+ '{"message":{"content":"b"},"done":false}\n',
+ { status: 200 },
+ ))
+
+ const chunks: ChatStreamChunk[] = []
+ for await (const c of new OllamaProvider(config)
+ .chatStream('llama3', [{ role: 'user', content: 'hi' }], { signal: abort.signal })) {
+ chunks.push(c)
+ abort.abort()
+ }
+ expect(chunks.every(c => !c.done)).toBe(true)
+ })
+
+ it('a mid-stream error line still throws — silence is not the failure mode there', async () => {
+ mockStream.mockResolvedValueOnce(new Response(
+ '{"error":"llama runner process has terminated: signal: killed"}\n',
+ { status: 200 },
+ ))
+ await expect(drain(new OllamaProvider(config)
+ .chatStream('llama3', [{ role: 'user', content: 'hi' }])))
+ .rejects.toThrow(/llama runner process has terminated/)
+ })
+})
+
+describe('OllamaProvider.chatStream — the idle watchdog reaches this path too', () => {
+ it('a stream that goes silent ends as a disconnect, not as a dead spinner', async () => {
+ vi.useFakeTimers()
+ mockStream.mockResolvedValueOnce(stalling(['{"message":{"content":"Hi"},"done":false}\n']))
+
+ const stream = new OllamaProvider(config)
+ .chatStream('llama3', [{ role: 'user', content: 'hi' }])
+
+ expect((await stream.next()).value).toMatchObject({ content: 'Hi', done: false })
+
+ const pending = stream.next()
+ await vi.advanceTimersByTimeAsync(STREAM_IDLE_TIMEOUT_MS + 1)
+ expect((await pending).value).toMatchObject({ done: true, finishReason: 'disconnect' })
+ expect((await stream.next()).done).toBe(true)
+ })
+
+ it('passes the guard signal, not the raw one, so the watchdog can abort', async () => {
+ mockStream.mockResolvedValueOnce(stalling(['{"message":{"content":"Hi"},"done":false}\n']))
+ const abort = new AbortController()
+ const stream = new OllamaProvider(config)
+ .chatStream('llama3', [{ role: 'user', content: 'hi' }], { signal: abort.signal })
+ await stream.next()
+
+ const sent: AbortSignal = mockStream.mock.calls[0][1].signal
+ expect(sent).toBeInstanceOf(AbortSignal)
+ // A provider is only ever handed a signal, so the watchdog needs its own
+ // controller — and Stop must still reach through it while the stream lives.
+ expect(sent).not.toBe(abort.signal)
+ abort.abort()
+ expect(sent.aborted).toBe(true)
+ })
+})
diff --git a/src/api/__tests__/sse-parser.test.ts b/src/api/__tests__/sse-parser.test.ts
index 2feeaa5d..14e7514c 100644
--- a/src/api/__tests__/sse-parser.test.ts
+++ b/src/api/__tests__/sse-parser.test.ts
@@ -5,7 +5,9 @@
* Run: npx vitest run src/api/__tests__/sse-parser.test.ts
*/
import { describe, it, expect } from 'vitest'
-import { parseSSEStream, parseSSEJsonStream, parseSSEWithEvents } from '../sse'
+import {
+ parseSSEStream, parseSSEJsonStream, parseSSEWithEvents, SSEMalformedDataError,
+} from '../sse'
// Helper: create a Response from a string
function mockResponse(text: string): Response {
@@ -127,6 +129,57 @@ describe('parseSSEStream', () => {
expect(events[0].data).toBe('{"a":1}')
})
+ // Regression fence for the idle-watchdog rework: the byte reader moved into
+ // stream-idle.ts, and the terminator handling — CRLF, lone CR, a terminator
+ // torn across two reads — has to come through it unchanged. Most SSE clients
+ // get this wrong; this is the part that must not be lost.
+ describe('line terminators survive the byte reader', () => {
+ it('holds a lone CR that turns out to be a separator in the next read', async () => {
+ const res = mockChunkedResponse(['data: {"a":1}\r', '\rdata: {"a":2}\r\r'])
+ const events = []
+ for await (const event of parseSSEStream(res)) {
+ events.push(event)
+ }
+ expect(events.map(e => e.data)).toEqual(['{"a":1}', '{"a":2}'])
+ })
+
+ it('parses a CRLF stream delivered one byte at a time', async () => {
+ const wire = 'data: {"a":1}\r\n\r\ndata: {"a":2}\r\n\r\n'
+ const res = mockChunkedResponse(wire.split(''))
+ const events = []
+ for await (const event of parseSSEStream(res)) {
+ events.push(event)
+ }
+ expect(events.map(e => e.data)).toEqual(['{"a":1}', '{"a":2}'])
+ })
+
+ it('keeps a multi-byte character whole across a read boundary', async () => {
+ // '€' is three bytes; the decoder must still be streaming.
+ const bytes = new TextEncoder().encode('data: {"t":"€"}\r\n\r\n')
+ const res = new Response(new ReadableStream<Uint8Array>({
+ start(c) {
+ c.enqueue(bytes.slice(0, 12))
+ c.enqueue(bytes.slice(12))
+ c.close()
+ },
+ }))
+ const events = []
+ for await (const event of parseSSEStream(res)) {
+ events.push(event)
+ }
+ expect(events.map(e => e.data)).toEqual(['{"t":"€"}'])
+ })
+
+ it('still flushes a trailing event that never got its terminator', async () => {
+ const res = mockResponse('data: {"a":1}\r\n\r\ndata: {"a":2}')
+ const events = []
+ for await (const event of parseSSEStream(res)) {
+ events.push(event)
+ }
+ expect(events.map(e => e.data)).toEqual(['{"a":1}', '{"a":2}'])
+ })
+ })
+
it('ignores comment lines', async () => {
const res = mockResponse(': this is a comment\ndata: {"a":1}\n\n')
const events = []
@@ -150,15 +203,40 @@ describe('parseSSEJsonStream', () => {
expect(items[1].id).toBe(2)
})
- it('skips malformed JSON', async () => {
+ // Was "skips malformed JSON". The skip WAS the bug: the payload that lands
+ // here is a provider error object in an unexpected shape (a relay's HTML
+ // error page, a gateway's bare string), and swallowing it left the user an
+ // empty bubble with nothing to look at. Everything valid before it is still
+ // delivered; the junk itself is now named.
+ it('surfaces malformed JSON instead of swallowing it', async () => {
const res = mockResponse('data: {"valid":true}\n\ndata: not-json\n\ndata: {"also":true}\n\n')
- const items = []
- for await (const item of parseSSEJsonStream<any>(res)) {
- items.push(item)
+ const items: any[] = []
+ let caught: any
+ try {
+ for await (const item of parseSSEJsonStream<any>(res)) {
+ items.push(item)
+ }
+ } catch (e) {
+ caught = e
}
- expect(items).toHaveLength(2)
+ expect(items).toHaveLength(1)
expect(items[0].valid).toBe(true)
- expect(items[1].also).toBe(true)
+ expect(caught).toBeInstanceOf(SSEMalformedDataError)
+ expect(caught.raw).toBe('not-json')
+ expect(caught.message).toContain('not-json')
+ })
+
+ it('names the event a malformed payload arrived under', async () => {
+ const res = mockResponse('event: error\ndata: <html>502 Bad Gateway</html>\n\n')
+ let caught: any
+ try {
+ for await (const _ of parseSSEJsonStream<any>(res)) { /* drain */ }
+ } catch (e) {
+ caught = e
+ }
+ expect(caught).toBeInstanceOf(SSEMalformedDataError)
+ expect(caught.event).toBe('error')
+ expect(caught.code).toBe('sse_malformed_data')
})
it('stops at [DONE]', async () => {
diff --git a/src/api/__tests__/stream-idle-watchdog.test.ts b/src/api/__tests__/stream-idle-watchdog.test.ts
new file mode 100644
index 00000000..ae05ba36
--- /dev/null
+++ b/src/api/__tests__/stream-idle-watchdog.test.ts
@@ -0,0 +1,237 @@
+/**
+ * Idle watchdog — Zeitbombe 4.
+ *
+ * Before this, the only bound on a chat stream was the Rust proxy's 7200 s
+ * TOTAL timeout, and the direct-fetch paths (cloud providers, macOS/Linux,
+ * browser dev mode) had none at all. A laptop that sleeps or Wi-Fi that drops
+ * without a FIN leaves the socket half-open: `reader.read()` never settles and
+ * the spinner runs until the user presses Stop.
+ *
+ * What is asserted here:
+ * - silence past the budget ends the read, and aborts the request first
+ * - the FIRST chunk gets a much longer grace (a cold model load is silent and
+ * healthy) — a 60 s cap there would abort every large local model
+ * - the budget is opt-in for NDJSON, because `ollama pull` is legitimately
+ * silent for minutes while it verifies a blob
+ * - both SSE providers turn the timeout into ONE terminal 'disconnect' chunk
+ * - and exactly one, also when the stream is closed from the other side
+ * (which is what the Rust-side idle timeout in proxy.rs looks like from
+ * here) — the two must not each contribute a terminal chunk
+ *
+ * Run: npx vitest run src/api/__tests__/stream-idle-watchdog.test.ts
+ */
+import { describe, it, expect, vi, afterEach } from 'vitest'
+import {
+ readChunks, StreamIdleTimeoutError, isStreamIdleTimeout,
+ STREAM_IDLE_TIMEOUT_MS, STREAM_FIRST_CHUNK_TIMEOUT_MS, idleAbortGuard,
+} from '../stream-idle'
+import { OpenAIProvider } from '../providers/openai-provider'
+import { AnthropicProvider } from '../providers/anthropic-provider'
+import type { ProviderConfig } from '../providers/types'
+
+/** A body that delivers `chunks` and then goes silent WITHOUT closing — the
+ * half-open connection a sleeping laptop leaves behind. */
+function stalling(chunks: string[]): Response {
+ const enc = new TextEncoder()
+ return new Response(new ReadableStream<Uint8Array>({
+ start(c) { for (const ch of chunks) c.enqueue(enc.encode(ch)) },
+ // deliberately never close()
+ }))
+}
+
+/** A body that delivers `chunks` and then closes cleanly — what a proxy-side
+ * idle timeout (or any tidy upstream cut) looks like to this side. */
+function cleanCut(chunks: string[]): Response {
+ const enc = new TextEncoder()
+ return new Response(new ReadableStream<Uint8Array>({
+ start(c) {
+ for (const ch of chunks) c.enqueue(enc.encode(ch))
+ c.close()
+ },
+ }))
+}
+
+/** Watch a promise without consuming it, so "has not settled yet" is testable. */
+function watch<T>(p: Promise<T>): () => boolean {
+ let done = false
+ p.then(() => { done = true }, () => { done = true })
+ return () => done
+}
+
+afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+})
+
+describe('readChunks — the watchdog itself', () => {
+ it('ends the read after the budget and aborts the request first', async () => {
+ vi.useFakeTimers()
+ const onIdle = vi.fn()
+ const gen = readChunks(stalling(['hello']), { idleMs: 1000, firstChunkMs: 1000, onIdle })
+
+ expect(new TextDecoder().decode((await gen.next()).value)).toBe('hello')
+
+ const pending = gen.next()
+ const settled = watch(pending)
+ await vi.advanceTimersByTimeAsync(999)
+ expect(settled()).toBe(false)
+
+ await vi.advanceTimersByTimeAsync(2)
+ await expect(pending).rejects.toBeInstanceOf(StreamIdleTimeoutError)
+ // The abort has to happen BEFORE the throw: only that stops the upstream
+ // (and, on the Tauri path, fires cancel_proxy_stream).
+ expect(onIdle).toHaveBeenCalledTimes(1)
+ })
+
+ it('gives the first chunk a much longer grace than the stream', async () => {
+ vi.useFakeTimers()
+ const gen = readChunks(stalling([]), { idleMs: STREAM_IDLE_TIMEOUT_MS })
+
+ const pending = gen.next()
+ const settled = watch(pending)
+ // A cold 30 GB model loading into VRAM is silent and perfectly healthy.
+ await vi.advanceTimersByTimeAsync(STREAM_IDLE_TIMEOUT_MS + 1000)
+ expect(settled()).toBe(false)
+
+ await vi.advanceTimersByTimeAsync(STREAM_FIRST_CHUNK_TIMEOUT_MS)
+ await expect(pending).rejects.toBeInstanceOf(StreamIdleTimeoutError)
+ })
+
+ it('stays off unless asked — `ollama pull` is silent for minutes on purpose', async () => {
+ vi.useFakeTimers()
+ const enc = new TextEncoder()
+ let ctrl!: ReadableStreamDefaultController<Uint8Array>
+ const res = new Response(new ReadableStream<Uint8Array>({
+ start(c) { ctrl = c; c.enqueue(enc.encode('{"status":"verifying sha256"}\n')) },
+ }))
+
+ const gen = readChunks(res)
+ await gen.next()
+
+ const pending = gen.next()
+ const settled = watch(pending)
+ await vi.advanceTimersByTimeAsync(STREAM_FIRST_CHUNK_TIMEOUT_MS * 2)
+ expect(settled()).toBe(false)
+
+ // Let the generator finish so it does not outlive the test suspended in a
+ // read (an async generator parked on an `await` cannot be .return()ed).
+ ctrl.close()
+ await pending
+ })
+
+ it('tags its error so a provider can tell silence from failure', () => {
+ expect(isStreamIdleTimeout(new StreamIdleTimeoutError(60_000, 'stream'))).toBe(true)
+ expect(isStreamIdleTimeout(new Error('boom'))).toBe(false)
+ expect(new StreamIdleTimeoutError(60_000, 'stream').message).toMatch(/60s/)
+ })
+})
+
+describe('idleAbortGuard', () => {
+ it('passes the caller Stop inward, so the guard signal is the only one needed', () => {
+ const outer = new AbortController()
+ const guard = idleAbortGuard(outer.signal)
+ expect(guard.signal.aborted).toBe(false)
+ outer.abort()
+ expect(guard.signal.aborted).toBe(true)
+ guard.release()
+ })
+
+ it('lets the watchdog abort without the caller knowing', () => {
+ const outer = new AbortController()
+ const guard = idleAbortGuard(outer.signal)
+ guard.abort()
+ expect(guard.signal.aborted).toBe(true)
+ expect(outer.signal.aborted).toBe(false)
+ guard.release()
+ })
+
+ it('drops its listener on release, so a long session cannot pile them up', () => {
+ const outer = new AbortController()
+ const remove = vi.spyOn(outer.signal, 'removeEventListener')
+ const guard = idleAbortGuard(outer.signal)
+ guard.release()
+ expect(remove).toHaveBeenCalled()
+ })
+
+ it('is already aborted when the caller was', () => {
+ const outer = new AbortController()
+ outer.abort()
+ expect(idleAbortGuard(outer.signal).signal.aborted).toBe(true)
+ })
+})
+
+// ── Provider level: the timeout becomes a terminal chunk ───────
+
+function openAIConfig(): ProviderConfig {
+ return {
+ id: 'openai', name: 'TestProvider', enabled: true,
+ baseUrl: 'https://api.test.com/v1', apiKey: 'k', isLocal: false,
+ }
+}
+
+function anthropicConfig(): ProviderConfig {
+ return {
+ id: 'anthropic', name: 'Anthropic', enabled: true,
+ baseUrl: 'https://api.anthropic.com', apiKey: 'sk-ant-test', isLocal: false,
+ }
+}
+
+describe('OpenAI-compatible stream that goes silent', () => {
+ it('ends with one terminal disconnect chunk instead of an endless spinner', async () => {
+ vi.useFakeTimers()
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async () =>
+ stalling(['data: {"choices":[{"delta":{"content":"Hi"}}]}\n\n']))
+
+ const stream = new OpenAIProvider(openAIConfig())
+ .chatStream('gpt-4o', [{ role: 'user', content: 'hi' }])
+
+ expect((await stream.next()).value).toMatchObject({ content: 'Hi', done: false })
+
+ const pending = stream.next()
+ const settled = watch(pending)
+ await vi.advanceTimersByTimeAsync(STREAM_IDLE_TIMEOUT_MS - 1)
+ expect(settled()).toBe(false)
+
+ await vi.advanceTimersByTimeAsync(2)
+ expect((await pending).value).toMatchObject({ done: true, finishReason: 'disconnect' })
+ // ONE terminal chunk, not two — the end-of-stream fallback must not fire
+ // on top of the watchdog's.
+ expect((await stream.next()).done).toBe(true)
+ })
+
+ it('still emits exactly one when the OTHER side closes the stream', async () => {
+ // What the Rust-side idle timeout in proxy.rs looks like from here: a
+ // clean EOF. The watchdog's timer is cleared by the read that comes back
+ // done, so the two never both contribute a chunk.
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async () =>
+ cleanCut(['data: {"choices":[{"delta":{"content":"Hi"}}]}\n\n']))
+
+ const chunks = []
+ for await (const c of new OpenAIProvider(openAIConfig())
+ .chatStream('gpt-4o', [{ role: 'user', content: 'hi' }])) {
+ chunks.push(c)
+ }
+ const terminal = chunks.filter(c => c.done)
+ expect(terminal).toHaveLength(1)
+ expect(terminal[0].finishReason).toBe('disconnect')
+ })
+})
+
+describe('Anthropic stream that goes silent', () => {
+ it('ends with one terminal disconnect chunk', async () => {
+ vi.useFakeTimers()
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async () => stalling([
+ 'event: content_block_delta\ndata: {"type":"content_block_delta","delta":{"type":"text_delta","text":"Hi"}}\n\n',
+ ]))
+
+ const stream = new AnthropicProvider(anthropicConfig())
+ .chatStream('claude-sonnet-4-20250514', [{ role: 'user', content: 'hi' }])
+
+ expect((await stream.next()).value).toMatchObject({ content: 'Hi', done: false })
+
+ const pending = stream.next()
+ await vi.advanceTimersByTimeAsync(STREAM_IDLE_TIMEOUT_MS + 1)
+ expect((await pending).value).toMatchObject({ done: true, finishReason: 'disconnect' })
+ expect((await stream.next()).done).toBe(true)
+ })
+})
diff --git a/src/api/providers/__tests__/anthropic-thinking-and-errors.test.ts b/src/api/providers/__tests__/anthropic-thinking-and-errors.test.ts
new file mode 100644
index 00000000..0bb57129
--- /dev/null
+++ b/src/api/providers/__tests__/anthropic-thinking-and-errors.test.ts
@@ -0,0 +1,288 @@
+/**
+ * Three Anthropic audit findings that all end the same way — a turn that
+ * cannot work, or a failure the user never gets told about.
+ *
+ * 1. Extended Thinking could only ever produce a 400. `budget_tokens: 5000`
+ * was sent against the `max_tokens: 4096` default (the API carves the
+ * budget OUT of max_tokens, so it must be strictly smaller), and
+ * temperature/top_p/top_k rode along, which the API forbids together with
+ * thinking. The 400-retry then dropped `thinking` and succeeded — which is
+ * exactly why nobody noticed: Extended Thinking has never once run, and
+ * every Anthropic turn quietly paid for a whole extra request first.
+ * (useChat injects a `<think>` prompt for non-Ollama models, so a thinking
+ * block still appeared in the UI.)
+ *
+ * 2. An `error` event on an HTTP-200 stream — overloaded_error, api_error —
+ * hit a switch with no arm for it and was dropped. The stream then ended
+ * without message_stop, so Anthropic's own outage reached the user as an
+ * empty bubble blaming their network.
+ *
+ * 3. The custom/relay baseUrl this provider goes out of its way to support
+ * (see messagesUrl) was issued as a raw webview fetch, which the pinned CSP
+ * kills in the packaged app before it reaches the network.
+ *
+ * Run: npx vitest run src/api/providers/__tests__/anthropic-thinking-and-errors.test.ts
+ */
+import { describe, it, expect, vi, afterEach } from 'vitest'
+
+const localFetch = vi.fn()
+const localFetchStream = vi.fn()
+const ensureProxyAllowsHost = vi.fn(async () => {})
+
+vi.mock('../../backend', async () => {
+ const actual = await vi.importActual<typeof import('../../backend')>('../../backend')
+ return {
+ ...actual,
+ isTauri: () => false,
+ localFetch: (...a: any[]) => localFetch(...a),
+ localFetchStream: (...a: any[]) => localFetchStream(...a),
+ ensureProxyAllowsHost: (...a: any[]) => ensureProxyAllowsHost(...(a as [])),
+ }
+})
+
+import { AnthropicProvider } from '../anthropic-provider'
+import { ProviderError } from '../types'
+import type { ProviderConfig, ChatStreamChunk } from '../types'
+
+function config(overrides: Partial<ProviderConfig> = {}): ProviderConfig {
+ return {
+ id: 'anthropic', name: 'Anthropic', enabled: true,
+ baseUrl: 'https://api.anthropic.com', apiKey: 'sk-ant-test', isLocal: false,
+ ...overrides,
+ }
+}
+
+function sse(events: string[]): Response {
+ return new Response(events.join(''), {
+ status: 200, headers: { 'Content-Type': 'text/event-stream' },
+ })
+}
+
+const STOP = 'event: message_stop\ndata: {"type":"message_stop"}\n\n'
+
+function sentBody(mock: { mock: { calls: any[][] } }, call = 0): any {
+ return JSON.parse(String(mock.mock.calls[call]?.[1]?.body ?? '{}'))
+}
+
+async function drain(gen: AsyncGenerator<ChatStreamChunk>): Promise<ChatStreamChunk[]> {
+ const out: ChatStreamChunk[] = []
+ for await (const c of gen) out.push(c)
+ return out
+}
+
+afterEach(() => {
+ vi.restoreAllMocks()
+ localFetch.mockReset()
+ localFetchStream.mockReset()
+ ensureProxyAllowsHost.mockReset()
+})
+
+describe('Extended Thinking sends a body the API can accept', () => {
+ it('keeps max_tokens strictly above budget_tokens', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(sse([STOP]))
+ vi.stubGlobal('fetch', fetchMock)
+
+ await drain(new AnthropicProvider(config())
+ .chatStream('claude-sonnet-4-20250514', [{ role: 'user', content: 'hi' }], { thinking: true }))
+
+ const body = sentBody(fetchMock)
+ expect(body.thinking).toEqual({ type: 'enabled', budget_tokens: expect.any(Number) })
+ expect(body.max_tokens).toBeGreaterThan(body.thinking.budget_tokens)
+ // The API's own floor for a reasoning budget.
+ expect(body.thinking.budget_tokens).toBeGreaterThanOrEqual(1024)
+ })
+
+ it('drops temperature / top_p / top_k, which thinking forbids', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(sse([STOP]))
+ vi.stubGlobal('fetch', fetchMock)
+
+ await drain(new AnthropicProvider(config()).chatStream(
+ 'claude-sonnet-4-20250514',
+ [{ role: 'user', content: 'hi' }],
+ { thinking: true, temperature: 0.7, topP: 0.9, topK: 40 },
+ ))
+
+ const body = sentBody(fetchMock)
+ expect(body).not.toHaveProperty('temperature')
+ expect(body).not.toHaveProperty('top_p')
+ expect(body).not.toHaveProperty('top_k')
+ })
+
+ it('never needs the drop-thinking retry any more — one request, not two', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(sse([STOP]))
+ vi.stubGlobal('fetch', fetchMock)
+
+ await drain(new AnthropicProvider(config())
+ .chatStream('claude-sonnet-4-20250514', [{ role: 'user', content: 'hi' }], { thinking: true }))
+
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ })
+
+ it('still leaves the sampling knobs alone when thinking is off', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(sse([STOP]))
+ vi.stubGlobal('fetch', fetchMock)
+
+ await drain(new AnthropicProvider(config()).chatStream(
+ 'claude-sonnet-4-20250514',
+ [{ role: 'user', content: 'hi' }],
+ { temperature: 0.7, topP: 0.9 },
+ ))
+
+ const body = sentBody(fetchMock)
+ expect(body.temperature).toBe(0.7)
+ expect(body.top_p).toBe(0.9)
+ expect(body).not.toHaveProperty('thinking')
+ })
+
+ it('respects a lowered Max Tokens instead of eating it whole', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(sse([STOP]))
+ vi.stubGlobal('fetch', fetchMock)
+
+ await drain(new AnthropicProvider(config()).chatStream(
+ 'claude-sonnet-4-20250514',
+ [{ role: 'user', content: 'hi' }],
+ { thinking: true, maxTokens: 20000 },
+ ))
+
+ const body = sentBody(fetchMock)
+ expect(body.max_tokens).toBe(20000)
+ expect(body.thinking.budget_tokens).toBeLessThanOrEqual(10000)
+ expect(body.max_tokens).toBeGreaterThan(body.thinking.budget_tokens)
+ })
+
+ it('applies to the non-streaming tool path as well', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({ content: [{ type: 'text', text: 'ok' }] }), { status: 200 }),
+ )
+ vi.stubGlobal('fetch', fetchMock)
+
+ await new AnthropicProvider(config()).chatWithTools(
+ 'claude-sonnet-4-20250514',
+ [{ role: 'user', content: 'hi' }],
+ [],
+ { thinking: true, temperature: 0.5 },
+ )
+
+ const body = sentBody(fetchMock)
+ expect(body.max_tokens).toBeGreaterThan(body.thinking.budget_tokens)
+ expect(body).not.toHaveProperty('temperature')
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ })
+})
+
+describe('a mid-stream error event is no longer swallowed', () => {
+ it('raises the overload instead of an empty disconnect bubble', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(sse([
+ 'event: message_start\ndata: {"type":"message_start","message":{"id":"m","usage":{"input_tokens":9,"output_tokens":0}}}\n\n',
+ 'event: error\ndata: {"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}\n\n',
+ ])))
+
+ const err = await drain(new AnthropicProvider(config())
+ .chatStream('claude-sonnet-4-20250514', [{ role: 'user', content: 'hi' }]))
+ .then(() => null, (e: unknown) => e as ProviderError)
+
+ expect(err).toBeInstanceOf(ProviderError)
+ expect(err!.message).toBe('Overloaded')
+ expect(err!.code).toBe('overloaded')
+ expect(err!.status).toBe(529)
+ })
+
+ it('maps a mid-stream rate limit onto a retryable status', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(sse([
+ 'event: error\ndata: {"type":"error","error":{"type":"rate_limit_error","message":"Slow down"}}\n\n',
+ ])))
+
+ const err = await drain(new AnthropicProvider(config())
+ .chatStream('claude-sonnet-4-20250514', [{ role: 'user', content: 'hi' }]))
+ .then(() => null, (e: unknown) => e as ProviderError)
+
+ expect(err!.code).toBe('rate_limit')
+ expect(err!.status).toBe(429)
+ })
+
+ it('names an api_error even when the payload carries no message', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(sse([
+ 'event: error\ndata: {"type":"error","error":{"type":"api_error"}}\n\n',
+ ])))
+
+ const err = await drain(new AnthropicProvider(config())
+ .chatStream('claude-sonnet-4-20250514', [{ role: 'user', content: 'hi' }]))
+ .then(() => null, (e: unknown) => e as ProviderError)
+
+ expect(err!.message).toMatch(/api_error/)
+ expect(err!.provider).toBe('anthropic')
+ })
+
+ it('a healthy stream is untouched', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(sse([
+ 'event: content_block_delta\ndata: {"type":"content_block_delta","delta":{"type":"text_delta","text":"Hi"}}\n\n',
+ STOP,
+ ])))
+
+ const chunks = await drain(new AnthropicProvider(config())
+ .chatStream('claude-sonnet-4-20250514', [{ role: 'user', content: 'hi' }]))
+
+ expect(chunks.map(c => c.content).join('')).toBe('Hi')
+ expect(chunks.filter(c => c.done)).toHaveLength(1)
+ expect(chunks[chunks.length - 1].finishReason).toBe('stop')
+ })
+})
+
+describe('a custom relay baseUrl reaches the network at all', () => {
+ it('takes the Rust proxy, because the pinned CSP would kill a direct fetch', async () => {
+ const fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+ localFetchStream.mockResolvedValue(sse([STOP]))
+
+ await drain(new AnthropicProvider(config({ baseUrl: 'https://claude-relay.example.com/v1' }))
+ .chatStream('claude-sonnet-4-20250514', [{ role: 'user', content: 'hi' }]))
+
+ expect(localFetchStream).toHaveBeenCalledTimes(1)
+ expect(fetchMock).not.toHaveBeenCalled()
+ // …and the host is registered with the proxy allow-list first, or the
+ // proxy would refuse to forward to it.
+ expect(ensureProxyAllowsHost).toHaveBeenCalledWith('https://claude-relay.example.com/v1')
+ // The /v1 de-duplication survives the transport change.
+ expect(localFetchStream.mock.calls[0][0]).toBe('https://claude-relay.example.com/v1/messages')
+ // The API key still travels — the proxy path forwards caller headers.
+ expect(localFetchStream.mock.calls[0][1].headers['x-api-key']).toBe('sk-ant-test')
+ })
+
+ it('a LAN relay takes the proxy too', async () => {
+ const fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+ localFetchStream.mockResolvedValue(sse([STOP]))
+
+ await drain(new AnthropicProvider(config({ baseUrl: 'http://192.168.1.50:8082' }))
+ .chatStream('claude-sonnet-4-20250514', [{ role: 'user', content: 'hi' }]))
+
+ expect(localFetchStream).toHaveBeenCalledTimes(1)
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+
+ it('api.anthropic.com keeps its direct fetch — the CSP names it', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(sse([STOP]))
+ vi.stubGlobal('fetch', fetchMock)
+
+ await drain(new AnthropicProvider(config())
+ .chatStream('claude-sonnet-4-20250514', [{ role: 'user', content: 'hi' }]))
+
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ expect(localFetchStream).not.toHaveBeenCalled()
+ })
+
+ it('the non-streaming path routes the same way', async () => {
+ const fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+ localFetch.mockResolvedValue(
+ new Response(JSON.stringify({ content: [{ type: 'text', text: 'ok' }] }), { status: 200 }),
+ )
+
+ const out = await new AnthropicProvider(config({ baseUrl: 'https://relay.example.com' }))
+ .chatWithTools('claude-sonnet-4-20250514', [{ role: 'user', content: 'hi' }], [])
+
+ expect(out.content).toBe('ok')
+ expect(localFetch).toHaveBeenCalledTimes(1)
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/api/providers/__tests__/openai-probe-guards.test.ts b/src/api/providers/__tests__/openai-probe-guards.test.ts
new file mode 100644
index 00000000..88128be5
--- /dev/null
+++ b/src/api/providers/__tests__/openai-probe-guards.test.ts
@@ -0,0 +1,105 @@
+/**
+ * The context probe is an optimisation, not a gate — audit finding
+ * "probeContextFromServer without signal and timeout".
+ *
+ * applyMaxTokens runs on EVERY send, and on a LAN backend without a catalogue
+ * entry it reaches two HTTP probes. Both went out with neither an AbortSignal
+ * nor a timeout, so a backend that accepts the TCP connection and then says
+ * nothing — a wedged LM Studio, a half-suspended NAS — held the user's message
+ * for the proxy's full default, twice over, with Stop unable to cut in. All the
+ * probe buys is a better `max_tokens` estimate; the cascade already has a
+ * heuristic for when it fails.
+ *
+ * Run: npx vitest run src/api/providers/__tests__/openai-probe-guards.test.ts
+ */
+import { describe, it, expect, vi, afterEach } from 'vitest'
+
+const localFetch = vi.fn()
+const localFetchStream = vi.fn()
+
+vi.mock('../../backend', async () => {
+ const actual = await vi.importActual<typeof import('../../backend')>('../../backend')
+ return {
+ ...actual,
+ isTauri: () => false,
+ localFetch: (...a: any[]) => localFetch(...a),
+ localFetchStream: (...a: any[]) => localFetchStream(...a),
+ ensureProxyAllowsHost: async () => {},
+ }
+})
+
+import { OpenAIProvider } from '../openai-provider'
+import type { ProviderConfig, ChatStreamChunk } from '../types'
+
+function lanConfig(port: number): ProviderConfig {
+ return {
+ id: 'openai', name: 'LM Studio', enabled: true,
+ baseUrl: `http://192.168.1.44:${port}/v1`, apiKey: '', isLocal: true,
+ }
+}
+
+async function drain(gen: AsyncGenerator<ChatStreamChunk>): Promise<ChatStreamChunk[]> {
+ const out: ChatStreamChunk[] = []
+ for await (const c of gen) out.push(c)
+ return out
+}
+
+afterEach(() => {
+ vi.restoreAllMocks()
+ localFetch.mockReset()
+ localFetchStream.mockReset()
+})
+
+describe('the side probes on the send path are bounded and cancellable', () => {
+ it('every probe carries a timeout and the request signal', async () => {
+ // A distinct port keeps this out of the module-level probe cache.
+ const provider = new OpenAIProvider(lanConfig(1301))
+ localFetch.mockResolvedValue(new Response('{}', { status: 404 }))
+ localFetchStream.mockResolvedValue(new Response('data: [DONE]\n\n', { status: 200 }))
+ const abort = new AbortController()
+
+ await drain(provider.chatStream(
+ 'some-unknown-local-model-a',
+ [{ role: 'user', content: 'hi' }],
+ { signal: abort.signal },
+ ))
+
+ expect(localFetch.mock.calls.length).toBeGreaterThan(0)
+ for (const [url, init] of localFetch.mock.calls) {
+ expect(typeof init?.timeoutMs, `${url} has no timeout`).toBe('number')
+ expect(init.timeoutMs).toBeGreaterThan(0)
+ expect(init.timeoutMs).toBeLessThanOrEqual(10_000)
+ // Stop has to be able to cut the probe short; the guard signal chained
+ // onto the caller's is what the request carries.
+ expect(init.signal, `${url} runs without a signal`).toBeInstanceOf(AbortSignal)
+ }
+ })
+
+ it('a probe that times out just falls back — the message still goes out', async () => {
+ const provider = new OpenAIProvider(lanConfig(1302))
+ // localFetch rejects the way an aborted timeout does.
+ localFetch.mockRejectedValue(Object.assign(new Error('Aborted'), { name: 'AbortError' }))
+ localFetchStream.mockResolvedValue(new Response(
+ 'data: {"choices":[{"delta":{"content":"Hi"}}]}\n\ndata: [DONE]\n\n',
+ { status: 200 },
+ ))
+
+ const chunks = await drain(provider.chatStream(
+ 'some-unknown-local-model-b',
+ [{ role: 'user', content: 'hi' }],
+ ))
+
+ expect(chunks.map(c => c.content).join('')).toBe('Hi')
+ // The heuristic still produced a usable budget instead of nothing.
+ const body = JSON.parse(String(localFetchStream.mock.calls[0][1].body))
+ expect(body.max_tokens).toBeGreaterThan(0)
+ })
+
+ it('a probed window still wins over the name heuristic', async () => {
+ const provider = new OpenAIProvider(lanConfig(1303))
+ localFetch.mockResolvedValue(
+ new Response(JSON.stringify({ max_context_length: 32768 }), { status: 200 }),
+ )
+ expect(await provider.getContextLength('some-unknown-local-model-c')).toBe(32768)
+ })
+})
diff --git a/src/api/providers/__tests__/transient-retry.test.ts b/src/api/providers/__tests__/transient-retry.test.ts
new file mode 100644
index 00000000..2ba80b27
--- /dev/null
+++ b/src/api/providers/__tests__/transient-retry.test.ts
@@ -0,0 +1,221 @@
+/**
+ * Retry on 429/503 — the Sanierungspfad item.
+ *
+ * A throttle or a gateway hiccup says nothing about the request, and it used
+ * to reach the user as the raw status line. The rules this has to keep while
+ * fixing that are the interesting part, and each one has a test below:
+ *
+ * - only transient statuses; a deterministic 4xx surfaces at once
+ * - `Retry-After` beats the local ladder, because a fixed-window limiter
+ * refuses again for the whole window
+ * - an empty wallet also answers 429 and no wait fixes it (credits_exhausted)
+ * - abortable: Stop must not queue behind a backoff
+ * - a small number of attempts, and never around a stream already running
+ *
+ * Run: npx vitest run src/api/providers/__tests__/transient-retry.test.ts
+ */
+import { describe, it, expect, vi, afterEach } from 'vitest'
+import {
+ sendWithTransientRetry, MAX_TRANSIENT_ATTEMPTS, MAX_SILENT_RETRY_WAIT_MS,
+} from '../retry'
+import { OpenAIProvider } from '../openai-provider'
+import type { ProviderConfig, ChatStreamChunk } from '../types'
+
+/** Records every backoff instead of sleeping it. */
+function recorder() {
+ const waited: number[] = []
+ return {
+ waited,
+ wait: async (ms: number) => { waited.push(ms) },
+ }
+}
+
+function res(status: number, body = '', headers: Record<string, string> = {}): Response {
+ return new Response(body, { status, headers })
+}
+
+afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+})
+
+describe('sendWithTransientRetry', () => {
+ it('retries a 429 with a growing backoff and returns the first good answer', async () => {
+ const clock = recorder()
+ const send = vi.fn()
+ .mockResolvedValueOnce(res(429))
+ .mockResolvedValueOnce(res(200, 'ok'))
+
+ const out = await sendWithTransientRetry(send, { wait: clock.wait })
+
+ expect(out.status).toBe(200)
+ expect(send).toHaveBeenCalledTimes(2)
+ expect(clock.waited).toEqual([500])
+ })
+
+ it('backs off exponentially across attempts', async () => {
+ const clock = recorder()
+ const send = vi.fn().mockResolvedValue(res(503))
+
+ const out = await sendWithTransientRetry(send, { wait: clock.wait })
+
+ expect(out.status).toBe(503)
+ expect(send).toHaveBeenCalledTimes(MAX_TRANSIENT_ATTEMPTS)
+ expect(clock.waited).toEqual([500, 1000])
+ })
+
+ it('honours Retry-After over its own ladder', async () => {
+ const clock = recorder()
+ const send = vi.fn()
+ .mockResolvedValueOnce(res(429, '', { 'retry-after': '3' }))
+ .mockResolvedValueOnce(res(200, 'ok'))
+
+ await sendWithTransientRetry(send, { wait: clock.wait })
+
+ expect(clock.waited).toEqual([3000])
+ })
+
+ it('does not sit out a wait it cannot announce', async () => {
+ // A minute of frozen composer is worse than the honest rate-limit error;
+ // the agent loop has its own ANNOUNCED ladder for windows that long.
+ const clock = recorder()
+ const send = vi.fn().mockResolvedValue(res(429, '', { 'retry-after': '120' }))
+
+ const out = await sendWithTransientRetry(send, { wait: clock.wait })
+
+ expect(out.status).toBe(429)
+ expect(send).toHaveBeenCalledTimes(1)
+ expect(clock.waited).toEqual([])
+ expect(MAX_SILENT_RETRY_WAIT_MS).toBeLessThan(120_000)
+ })
+
+ it('leaves a deterministic 4xx alone', async () => {
+ const clock = recorder()
+ for (const status of [400, 401, 403, 404, 422]) {
+ const send = vi.fn().mockResolvedValue(res(status))
+ const out = await sendWithTransientRetry(send, { wait: clock.wait })
+ expect(out.status).toBe(status)
+ expect(send).toHaveBeenCalledTimes(1)
+ }
+ expect(clock.waited).toEqual([])
+ })
+
+ it('does not retry an empty wallet, which answers 429 too', async () => {
+ const clock = recorder()
+ const send = vi.fn().mockResolvedValue(
+ res(429, JSON.stringify({ error: { code: 'credits_exhausted', message: 'no credits' } })),
+ )
+
+ const out = await sendWithTransientRetry(send, { wait: clock.wait })
+
+ expect(send).toHaveBeenCalledTimes(1)
+ expect(clock.waited).toEqual([])
+ // The body the caller still has to read must be untouched by the peek.
+ expect(await out.text()).toContain('credits_exhausted')
+ })
+
+ it('stops on abort instead of queueing Stop behind a backoff', async () => {
+ const abort = new AbortController()
+ const send = vi.fn().mockResolvedValue(res(503))
+ const wait = vi.fn(async () => { abort.abort() })
+
+ const out = await sendWithTransientRetry(send, { signal: abort.signal, wait })
+
+ expect(out.status).toBe(503)
+ expect(send).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not start at all once the caller has already aborted', async () => {
+ const abort = new AbortController()
+ abort.abort()
+ const clock = recorder()
+ const send = vi.fn().mockResolvedValue(res(429))
+
+ await sendWithTransientRetry(send, { signal: abort.signal, wait: clock.wait })
+
+ expect(send).toHaveBeenCalledTimes(1)
+ expect(clock.waited).toEqual([])
+ })
+
+ it('really sleeps when no clock is injected, and the sleep is abortable', async () => {
+ vi.useFakeTimers()
+ const abort = new AbortController()
+ const send = vi.fn().mockResolvedValue(res(503))
+
+ const running = sendWithTransientRetry(send, { signal: abort.signal })
+ await vi.advanceTimersByTimeAsync(10)
+ expect(send).toHaveBeenCalledTimes(1)
+
+ abort.abort()
+ await vi.advanceTimersByTimeAsync(1)
+ expect((await running).status).toBe(503)
+ expect(send).toHaveBeenCalledTimes(1)
+ })
+})
+
+// ── Through the provider, on the real send path ───────────────
+
+function openAIConfig(): ProviderConfig {
+ return {
+ id: 'openai', name: 'TestProvider', enabled: true,
+ baseUrl: 'https://api.test.com/v1', apiKey: 'k', isLocal: false,
+ }
+}
+
+async function drain(gen: AsyncGenerator<ChatStreamChunk>): Promise<ChatStreamChunk[]> {
+ const out: ChatStreamChunk[] = []
+ for await (const c of gen) out.push(c)
+ return out
+}
+
+describe('the chat send path retries a throttle', () => {
+ it('a 429 followed by a good answer produces the answer, not the error', async () => {
+ vi.useFakeTimers()
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(res(429, JSON.stringify({ error: { message: 'slow down' } })))
+ .mockResolvedValueOnce(new Response(
+ 'data: {"choices":[{"delta":{"content":"Hi"}}]}\n\ndata: [DONE]\n\n',
+ { status: 200 },
+ ))
+ vi.stubGlobal('fetch', fetchMock)
+
+ const running = drain(new OpenAIProvider(openAIConfig())
+ .chatStream('gpt-4o', [{ role: 'user', content: 'hi' }]))
+ await vi.advanceTimersByTimeAsync(1000)
+ const chunks = await running
+
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ expect(chunks.map(c => c.content).join('')).toBe('Hi')
+ })
+
+ it('a throttle that never lifts still ends as the honest rate-limit error', async () => {
+ vi.useFakeTimers()
+ const fetchMock = vi.fn().mockImplementation(async () =>
+ res(429, JSON.stringify({ error: { message: 'slow down' } })))
+ vi.stubGlobal('fetch', fetchMock)
+
+ const running = drain(new OpenAIProvider(openAIConfig())
+ .chatStream('gpt-4o', [{ role: 'user', content: 'hi' }])).then(() => null, (e: any) => e)
+ await vi.advanceTimersByTimeAsync(5000)
+ const err = await running
+
+ expect(fetchMock).toHaveBeenCalledTimes(MAX_TRANSIENT_ATTEMPTS)
+ expect(err.code).toBe('rate_limit')
+ })
+
+ it('never retries once the stream has started — a cut mid-answer is terminal', async () => {
+ // The body is already partly delivered, so a re-post would replay half an
+ // answer. The truncated stream ends with its terminal chunk instead.
+ const fetchMock = vi.fn().mockResolvedValueOnce(new Response(
+ 'data: {"choices":[{"delta":{"content":"Hi"}}]}\n\n',
+ { status: 200 },
+ ))
+ vi.stubGlobal('fetch', fetchMock)
+
+ const chunks = await drain(new OpenAIProvider(openAIConfig())
+ .chatStream('gpt-4o', [{ role: 'user', content: 'hi' }]))
+
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ expect(chunks[chunks.length - 1]).toMatchObject({ done: true, finishReason: 'disconnect' })
+ })
+})
diff --git a/src/api/providers/anthropic-provider.ts b/src/api/providers/anthropic-provider.ts
index fd03e0e7..954fbbb7 100644
--- a/src/api/providers/anthropic-provider.ts
+++ b/src/api/providers/anthropic-provider.ts
@@ -14,6 +14,13 @@ import type {
} from './types'
import { ProviderError } from './types'
import { parseSSEWithEvents } from '../sse'
+import { idleAbortGuard, isStreamIdleTimeout } from '../stream-idle'
+import { sendWithTransientRetry } from './retry'
+import { parseRetryAfter } from '../../lib/http-status'
+import {
+ localFetch, localFetchStream, isPrivateOrLanHost, isDirectFetchAllowed,
+ hostnameOf, ensureProxyAllowsHost,
+} from '../backend'
// ── Anthropic API Types ────────────────────────────────────────
@@ -25,6 +32,10 @@ interface AnthropicStreamEvent {
message?: { id: string; usage?: { input_tokens: number; output_tokens: number } }
// message_delta events carry cumulative output usage at the event top level.
usage?: { input_tokens?: number; output_tokens?: number }
+ // `event: error` on an otherwise healthy HTTP-200 stream. Anthropic sends it
+ // for overloaded_error / api_error when the failure happens AFTER the
+ // response headers are out.
+ error?: { type?: string; message?: string }
}
interface AnthropicResponse {
@@ -68,8 +79,28 @@ const CLAUDE_MODELS: ProviderModel[] = [
// write a fresh entry on every step and never read one back, because A1
// decay and A3 compaction still rewrite the tail of the history.
+/** A /v1/messages body under construction. The wire mixes strings, numbers,
+ * nested objects and content-block arrays, so the value type stays open —
+ * named once here rather than restated on every signature. */
+type MessagesBody = Record<string, any>
+
+/** The init every transport in this file accepts: plain `fetch`, and the two
+ * proxy-aware helpers in backend.ts. */
+interface MessagesRequestInit {
+ method: string
+ headers: Record<string, string>
+ body: string
+ signal?: AbortSignal
+}
+
const CACHE_CONTROL = { type: 'ephemeral' } as const
+// ── Extended Thinking budget ───────────────────────────────────
+/** Upper bound for the reasoning budget. The model may use less. */
+const DEFAULT_THINKING_BUDGET = 5000
+/** Room the answer itself keeps on top of the reasoning budget. */
+const MIN_ANSWER_TOKENS = 2048
+
/** A message content as blocks, so a marker has something to ride on. */
function asContentBlocks(content: string | Record<string, any>[]): Record<string, any>[] {
return typeof content === 'string' ? [{ type: 'text', text: content }] : content
@@ -80,7 +111,7 @@ function asContentBlocks(content: string | Record<string, any>[]): Record<string
* from both request paths (chatStream and chatWithTools) after the body is
* fully built, so vision, tool and plain-text variants all carry the markers.
*/
-function applyCacheControl(body: Record<string, any>): void {
+function applyCacheControl(body: MessagesBody): void {
if (Array.isArray(body.tools) && body.tools.length > 0) {
body.tools[body.tools.length - 1].cache_control = { ...CACHE_CONTROL }
}
@@ -134,6 +165,80 @@ export class AnthropicProvider implements ProviderClient {
}
}
+ /**
+ * Transport decision, same rule the OpenAI provider uses.
+ *
+ * This provider explicitly supports a custom baseUrl (claude-relay-server,
+ * LiteLLM, opencode-zen — see messagesUrl above), and then always issued a
+ * raw webview fetch. In the packaged app that request never leaves the
+ * webview: the pinned CSP lists api.anthropic.com and nothing else, and a
+ * self-hosted relay adds CORS on top. So the one configuration the code went
+ * out of its way to support was the one that could not work. Anything the CSP
+ * does not name — and every LAN address — takes the Rust proxy instead;
+ * api.anthropic.com itself keeps its direct fetch, unchanged.
+ */
+ private get useLocalProxy(): boolean {
+ const host = hostnameOf(this.baseUrl)
+ return this.config.isLocal === true
+ || isPrivateOrLanHost(host)
+ || !isDirectFetchAllowed(host)
+ }
+
+ /**
+ * One POST to /v1/messages, over whichever transport this endpoint needs,
+ * with the throttle retry around it (providers/retry.ts — request only,
+ * never around a stream that has already started).
+ */
+ private async send(
+ body: MessagesBody,
+ signal: AbortSignal | undefined,
+ streaming: boolean,
+ ): Promise<Response> {
+ const proxied = this.useLocalProxy
+ if (proxied) await ensureProxyAllowsHost(this.baseUrl)
+ const fetcher: (url: string, init: MessagesRequestInit) => Promise<Response> =
+ proxied ? (streaming ? localFetchStream : localFetch) : fetch
+ return sendWithTransientRetry(
+ () => fetcher(this.messagesUrl(), {
+ method: 'POST',
+ headers: this.headers,
+ body: JSON.stringify(body),
+ signal,
+ }),
+ { signal },
+ )
+ }
+
+ /**
+ * Extended Thinking, built to the API's constraints instead of against them.
+ *
+ * Two of them were violated at once, so this feature could only ever produce
+ * a 400: `budget_tokens` has to be strictly SMALLER than `max_tokens` (the
+ * budget is carved out of it), and 5000 was sent against a 4096 default; and
+ * `temperature` / `top_p` / `top_k` may not be sent at all while thinking is
+ * on, which the sampling defaults above did on every turn. The retry below
+ * then dropped `thinking` and succeeded, which is why nobody saw a failure —
+ * it just meant Extended Thinking has never once run, at the price of a full
+ * extra request per Anthropic turn. (useChat injects a `<think>` prompt for
+ * non-Ollama models, so the UI still showed a thinking block.)
+ *
+ * The budget stays under half the ceiling so a user who lowered Max Tokens
+ * still gets an answer and not only reasoning, and never drops below the
+ * 1024 the API requires.
+ */
+ private applyThinking(body: MessagesBody, options?: ChatOptions): void {
+ if (options?.thinking !== true) return
+
+ const ceiling: number = body.max_tokens
+ const budget = Math.max(1024, Math.min(DEFAULT_THINKING_BUDGET, Math.floor(ceiling / 2)))
+ body.thinking = { type: 'enabled', budget_tokens: budget }
+ // max_tokens covers thinking AND the answer, so it must have room for both.
+ body.max_tokens = Math.max(ceiling, budget + MIN_ANSWER_TOKENS)
+ delete body.temperature
+ delete body.top_p
+ delete body.top_k
+ }
+
async *chatStream(
model: string,
messages: ChatMessage[],
@@ -141,7 +246,7 @@ export class AnthropicProvider implements ProviderClient {
): AsyncGenerator<ChatStreamChunk> {
const { system, anthropicMessages } = this.convertMessages(messages)
- const body: Record<string, any> = {
+ const body: MessagesBody = {
model,
messages: anthropicMessages,
max_tokens: options?.maxTokens && options.maxTokens > 0 ? options.maxTokens : 4096,
@@ -154,11 +259,9 @@ export class AnthropicProvider implements ProviderClient {
if (options?.topK !== undefined) body.top_k = options.topK
// Claude Extended Thinking (Sonnet 3.7+, Opus 4). Opt-in: only when the
// user actually toggled Thinking ON. Default stays OFF, so toggle OFF
- // simply omits the field. 5000 tokens is a sensible default budget —
- // the model may produce less, but won't exceed it.
- if (options?.thinking === true) {
- body.thinking = { type: 'enabled', budget_tokens: 5000 }
- }
+ // simply omits the field. See applyThinking for the API constraints it
+ // has to satisfy — and used to violate.
+ this.applyThinking(body, options)
// Streaming tool turn (same conversion as chatWithTools below). The
// stream parser already accumulates tool_use blocks via input_json_delta
@@ -173,27 +276,30 @@ export class AnthropicProvider implements ProviderClient {
applyCacheControl(body)
- let res = await fetch(this.messagesUrl(), {
- method: 'POST',
- headers: this.headers,
- body: JSON.stringify(body),
- signal: options?.signal,
- })
-
- // Retry without extended thinking if the model rejects it (e.g. older
- // Claude versions don't support `thinking`).
- if (!res.ok && res.status === 400 && 'thinking' in body) {
- delete body.thinking
- res = await fetch(this.messagesUrl(), {
- method: 'POST',
- headers: this.headers,
- body: JSON.stringify(body),
- signal: options?.signal,
- })
- }
+ // Zeitbombe 4 — the idle watchdog needs a controller to abort, and a
+ // provider only ever receives a signal. This chains one onto the caller's:
+ // Stop still propagates inward, and a stream that goes silent can cancel
+ // its own request instead of leaving reader.read() pending forever.
+ const guard = idleAbortGuard(options?.signal)
+ let res: Response
+ try {
+ res = await this.send(body, guard.signal, true)
+
+ // Retry without extended thinking if the model rejects it (e.g. older
+ // Claude versions don't support `thinking`). With applyThinking building
+ // an API-conform body this is a genuine fallback again rather than the
+ // request that always ran.
+ if (!res.ok && res.status === 400 && 'thinking' in body) {
+ delete body.thinking
+ res = await this.send(body, guard.signal, true)
+ }
- if (!res.ok) {
- throw await this.parseError(res)
+ if (!res.ok) throw await this.parseError(res)
+ } catch (err) {
+ // Nothing to watch — drop the listener on the caller's signal here, the
+ // stream loop's `finally` below is never reached on this path.
+ guard.release()
+ throw err
}
// Track tool use blocks being built
@@ -204,69 +310,110 @@ export class AnthropicProvider implements ProviderClient {
let inputTokens = 0
let outputTokens = 0
- for await (const { data } of parseSSEWithEvents<AnthropicStreamEvent>(res)) {
- if (options?.signal?.aborted) break
+ try {
+ for await (const { data } of parseSSEWithEvents<AnthropicStreamEvent>(res, { onIdle: guard.abort })) {
+ if (options?.signal?.aborted) break
+
+ switch (data.type) {
+ case 'error': {
+ // Anthropic reports a failure that happened AFTER the response
+ // headers went out as an `error` EVENT on a healthy HTTP 200 —
+ // overloaded_error when the fleet is saturated, api_error for an
+ // internal fault. The switch had no arm for it, so the event was
+ // dropped, the stream then ended without message_stop, and the user
+ // got an empty 'disconnect' bubble that blamed their network for
+ // the provider's outage. Surface the real thing, with the status
+ // the retry policy in lib/http-status expects for it.
+ const kind = data.error?.type
+ const code = kind === 'overloaded_error' ? 'overloaded'
+ : kind === 'rate_limit_error' ? 'rate_limit'
+ : kind === 'authentication_error' ? 'auth'
+ : 'network'
+ const status = kind === 'overloaded_error' ? 529
+ : kind === 'rate_limit_error' ? 429
+ : kind === 'authentication_error' ? 401
+ : 500
+ throw new ProviderError(
+ data.error?.message || `Anthropic stream error${kind ? ` (${kind})` : ''}`,
+ 'anthropic',
+ code,
+ status,
+ )
+ }
- switch (data.type) {
- case 'message_start': {
- const u = data.message?.usage
- if (u?.input_tokens) inputTokens = u.input_tokens
- break
- }
+ case 'message_start': {
+ const u = data.message?.usage
+ if (u?.input_tokens) inputTokens = u.input_tokens
+ break
+ }
- case 'content_block_start': {
- if (data.content_block?.type === 'tool_use') {
- toolUseBlocks.set(data.index!, {
- id: data.content_block.id || '',
- name: data.content_block.name || '',
- input: '',
- })
+ case 'content_block_start': {
+ if (data.content_block?.type === 'tool_use') {
+ toolUseBlocks.set(data.index!, {
+ id: data.content_block.id || '',
+ name: data.content_block.name || '',
+ input: '',
+ })
+ }
+ break
}
- break
- }
- case 'content_block_delta': {
- const dtype = (data.delta as any)?.type
- if (dtype === 'text_delta' && (data.delta as any).text) {
- yield { content: (data.delta as any).text, done: false }
- } else if (dtype === 'thinking_delta' && (data.delta as any).thinking) {
- // Claude Extended Thinking stream — route to `thinking` so the
- // ThinkingBlock UI picks it up (same field as Ollama's native).
- yield { content: '', thinking: (data.delta as any).thinking, done: false }
- } else if (dtype === 'input_json_delta' && (data.delta as any).partial_json) {
- const block = toolUseBlocks.get(data.index!)
- if (block) block.input += (data.delta as any).partial_json
+ case 'content_block_delta': {
+ const dtype = (data.delta as any)?.type
+ if (dtype === 'text_delta' && (data.delta as any).text) {
+ yield { content: (data.delta as any).text, done: false }
+ } else if (dtype === 'thinking_delta' && (data.delta as any).thinking) {
+ // Claude Extended Thinking stream — route to `thinking` so the
+ // ThinkingBlock UI picks it up (same field as Ollama's native).
+ yield { content: '', thinking: (data.delta as any).thinking, done: false }
+ } else if (dtype === 'input_json_delta' && (data.delta as any).partial_json) {
+ const block = toolUseBlocks.get(data.index!)
+ if (block) block.input += (data.delta as any).partial_json
+ }
+ break
}
- break
- }
- case 'message_delta': {
- // End of message — flush tool calls. Map Anthropic's stop_reason
- // onto the unified finishReason ('max_tokens' → 'length', the key
- // the chat layer uses to explain thought-only/truncated turns).
- const stopReason = (data.delta as any)?.stop_reason as string | undefined
- if (data.usage?.output_tokens) outputTokens = data.usage.output_tokens
- const toolCalls = this.flushToolUseBlocks(toolUseBlocks)
- yield {
- content: '',
- toolCalls: toolCalls.length ? toolCalls : undefined,
- done: true,
- finishReason: stopReason === 'max_tokens' ? 'length' : (stopReason || 'stop'),
- promptEvalCount: inputTokens || undefined,
- evalCount: outputTokens || undefined,
+ case 'message_delta': {
+ // End of message — flush tool calls. Map Anthropic's stop_reason
+ // onto the unified finishReason ('max_tokens' → 'length', the key
+ // the chat layer uses to explain thought-only/truncated turns).
+ const stopReason = (data.delta as any)?.stop_reason as string | undefined
+ if (data.usage?.output_tokens) outputTokens = data.usage.output_tokens
+ const toolCalls = this.flushToolUseBlocks(toolUseBlocks)
+ yield {
+ content: '',
+ toolCalls: toolCalls.length ? toolCalls : undefined,
+ done: true,
+ finishReason: stopReason === 'max_tokens' ? 'length' : (stopReason || 'stop'),
+ promptEvalCount: inputTokens || undefined,
+ evalCount: outputTokens || undefined,
+ }
+ return
}
- return
- }
- case 'message_stop': {
- const toolCalls2 = this.flushToolUseBlocks(toolUseBlocks)
- yield {
- content: '', toolCalls: toolCalls2.length ? toolCalls2 : undefined, done: true, finishReason: 'stop',
- promptEvalCount: inputTokens || undefined, evalCount: outputTokens || undefined,
+ case 'message_stop': {
+ const toolCalls2 = this.flushToolUseBlocks(toolUseBlocks)
+ yield {
+ content: '', toolCalls: toolCalls2.length ? toolCalls2 : undefined, done: true, finishReason: 'stop',
+ promptEvalCount: inputTokens || undefined, evalCount: outputTokens || undefined,
+ }
+ return
}
- return
}
}
+ } catch (err) {
+ // The watchdog fired: the stream did not fail, it went quiet. Terminal
+ // chunk, same as a clean cut, instead of a raw error.
+ if (isStreamIdleTimeout(err)) {
+ yield {
+ content: '', done: true, finishReason: 'disconnect',
+ promptEvalCount: inputTokens || undefined, evalCount: outputTokens || undefined,
+ }
+ return
+ }
+ throw err
+ } finally {
+ guard.release()
}
// Stream ended without an explicit message_delta/message_stop — the
@@ -287,7 +434,7 @@ export class AnthropicProvider implements ProviderClient {
): Promise<{ content: string; toolCalls: ToolCall[]; promptEvalCount?: number; evalCount?: number }> {
const { system, anthropicMessages } = this.convertMessages(messages)
- const body: Record<string, any> = {
+ const body: MessagesBody = {
model,
messages: anthropicMessages,
max_tokens: options?.maxTokens && options.maxTokens > 0 ? options.maxTokens : 4096,
@@ -298,9 +445,7 @@ export class AnthropicProvider implements ProviderClient {
if (options?.topP !== undefined) body.top_p = options.topP
if (options?.topK !== undefined) body.top_k = options.topK
// Same extended-thinking gate as chatStream.
- if (options?.thinking === true) {
- body.thinking = { type: 'enabled', budget_tokens: 5000 }
- }
+ this.applyThinking(body, options)
// Convert OpenAI tool format to Anthropic format
if (tools.length > 0) {
@@ -313,22 +458,12 @@ export class AnthropicProvider implements ProviderClient {
applyCacheControl(body)
- let res = await fetch(this.messagesUrl(), {
- method: 'POST',
- headers: this.headers,
- body: JSON.stringify(body),
- signal: options?.signal,
- })
+ let res = await this.send(body, options?.signal, false)
// Retry without extended thinking if the model rejects it.
if (!res.ok && res.status === 400 && 'thinking' in body) {
delete body.thinking
- res = await fetch(this.messagesUrl(), {
- method: 'POST',
- headers: this.headers,
- body: JSON.stringify(body),
- signal: options?.signal,
- })
+ res = await this.send(body, options?.signal, false)
}
if (!res.ok) {
@@ -374,15 +509,11 @@ export class AnthropicProvider implements ProviderClient {
try {
// Send a minimal request to verify the API key
- const res = await fetch(this.messagesUrl(), {
- method: 'POST',
- headers: this.headers,
- body: JSON.stringify({
- model: 'claude-haiku-4-5-20251001',
- max_tokens: 1,
- messages: [{ role: 'user', content: 'hi' }],
- }),
- })
+ const res = await this.send({
+ model: 'claude-haiku-4-5-20251001',
+ max_tokens: 1,
+ messages: [{ role: 'user', content: 'hi' }],
+ }, undefined, false)
// 200 or 400 (bad request but auth worked) both mean the key is valid
return res.status !== 401 && res.status !== 403
} catch {
@@ -525,6 +656,8 @@ export class AnthropicProvider implements ProviderClient {
message = 'Anthropic API is overloaded. Try again in a few seconds.'
}
- return new ProviderError(message, 'anthropic', code, res.status)
+ // The throttle's own number, so the agent's retry ladder waits out the real
+ // window instead of its 1.5 s guess (lib/http-status retryDelayMs).
+ return new ProviderError(message, 'anthropic', code, res.status, undefined, parseRetryAfter(res))
}
}
diff --git a/src/api/providers/ollama-provider.ts b/src/api/providers/ollama-provider.ts
index c38d1515..dd5a3a65 100644
--- a/src/api/providers/ollama-provider.ts
+++ b/src/api/providers/ollama-provider.ts
@@ -12,6 +12,7 @@ import type {
import { ProviderError } from './types'
import { localFetch, localFetchStream, ollamaUrl } from '../backend'
import { parseNDJSONStream } from '../stream'
+import { idleAbortGuard, isStreamIdleTimeout, STREAM_IDLE_TIMEOUT_MS } from '../stream-idle'
import { repairToolCallArgs, extractToolCallsFromContent } from '../../lib/tool-call-repair'
import { applyTemplateContract } from './normalize-system'
@@ -134,57 +135,102 @@ export class OllamaProvider implements ProviderClient {
if (options?.thinking === true) body.think = true
else if (options?.thinking === false) body.think = false
- let res = await localFetchStream(this.apiUrl('/chat'), {
- method: 'POST',
- body: JSON.stringify(body),
- signal: options?.signal,
- })
-
- // Older Ollama builds / non-thinking models reject ANY `think` field
- // with HTTP 400. Retry once without it so the user's request still
- // succeeds — we just fall back to model-default behaviour.
- if (!res.ok && res.status === 400 && 'think' in body) {
- delete body.think
- res = await localFetchStream(this.apiUrl('/chat'), {
+ // Zeitbombe 4 — the idle watchdog needs something to abort, and a provider
+ // only ever gets a signal, never the controller behind it. This chains one
+ // onto the caller's: Stop still propagates inward, and a stream that goes
+ // silent can now cancel its own request (which on the Tauri path is what
+ // fires cancel_proxy_stream, so Ollama actually stops generating).
+ const guard = idleAbortGuard(options?.signal)
+ try {
+ let res = await localFetchStream(this.apiUrl('/chat'), {
method: 'POST',
body: JSON.stringify(body),
- signal: options?.signal,
+ signal: guard.signal,
})
- }
- if (!res.ok) {
- throw await this.buildError(res, 'Chat failed', model)
- }
+ // Older Ollama builds / non-thinking models reject ANY `think` field
+ // with HTTP 400. Retry once without it so the user's request still
+ // succeeds — we just fall back to model-default behaviour.
+ if (!res.ok && res.status === 400 && 'think' in body) {
+ delete body.think
+ res = await localFetchStream(this.apiUrl('/chat'), {
+ method: 'POST',
+ body: JSON.stringify(body),
+ signal: guard.signal,
+ })
+ }
- for await (const chunk of parseNDJSONStream<OllamaChatChunk>(res)) {
- if (options?.signal?.aborted) break
+ if (!res.ok) {
+ throw await this.buildError(res, 'Chat failed', model)
+ }
- // 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}`)
+ // Ollama marks the end of a turn with a `"done":true` line. Nothing
+ // guarantees it arrives: a runner OOM, VRAM eviction, `ollama stop`, a
+ // proxy or LAN cut all end the NDJSON mid-line. Without the guarantee
+ // below the generator simply returned and the chat layer, which only
+ // explains a turn it was given a finishReason for, left a permanently
+ // empty assistant bubble with no hint at all. openai-provider.ts has
+ // ended its stream with an explicit terminal chunk for several releases
+ // (see its end-of-stream 'disconnect' path); this is the same semantics.
+ let sawDone = false
+ const terminal = (reason: string): ChatStreamChunk => ({
+ content: '', done: true, finishReason: reason,
+ })
+
+ try {
+ for await (const chunk of parseNDJSONStream<OllamaChatChunk>(res, {
+ idleMs: STREAM_IDLE_TIMEOUT_MS,
+ onIdle: guard.abort,
+ })) {
+ 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 },
+ }))
+
+ if (chunk.done) sawDone = true
+
+ yield {
+ content: chunk.message?.content || '',
+ thinking: chunk.message?.thinking || undefined,
+ toolCalls: toolCalls?.length ? toolCalls : undefined,
+ done: chunk.done || false,
+ finishReason: chunk.done_reason || undefined,
+ // Bug M v2.4.7 — pass through server-side generation metrics so the
+ // benchmark can report Ollama's own measurement instead of trusting
+ // client-side TTFT, which WebView2 release-mode buffers into
+ // uselessness for fast small models.
+ evalCount: chunk.eval_count,
+ promptEvalCount: chunk.prompt_eval_count,
+ evalDurationMs: chunk.eval_duration !== undefined ? chunk.eval_duration / 1_000_000 : undefined,
+ }
+ }
+ } catch (err) {
+ // The watchdog fired: the stream did not fail, it went quiet. That is
+ // a disconnect, not an error to throw at the user.
+ if (isStreamIdleTimeout(err)) {
+ yield terminal('disconnect')
+ return
+ }
+ throw err
}
- const toolCalls: ToolCall[] | undefined = chunk.message?.tool_calls?.map(tc => ({
- function: { name: tc.function.name, arguments: tc.function.arguments },
- }))
-
- yield {
- content: chunk.message?.content || '',
- thinking: chunk.message?.thinking || undefined,
- toolCalls: toolCalls?.length ? toolCalls : undefined,
- done: chunk.done || false,
- finishReason: chunk.done_reason || undefined,
- // Bug M v2.4.7 — pass through server-side generation metrics so the
- // benchmark can report Ollama's own measurement instead of trusting
- // client-side TTFT, which WebView2 release-mode buffers into
- // uselessness for fast small models.
- evalCount: chunk.eval_count,
- promptEvalCount: chunk.prompt_eval_count,
- evalDurationMs: chunk.eval_duration !== undefined ? chunk.eval_duration / 1_000_000 : undefined,
+ // Truncated NDJSON — no done:true ever arrived. A user-pressed Stop is
+ // not a disconnect, so it gets no terminal chunk (the chat layer has
+ // already stopped reading by then anyway).
+ if (!sawDone && !options?.signal?.aborted) {
+ yield terminal('disconnect')
}
+ } finally {
+ guard.release()
}
}
diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.ts
index 4b21ea01..6326beac 100644
--- a/src/api/providers/openai-provider.ts
+++ b/src/api/providers/openai-provider.ts
@@ -15,6 +15,8 @@ import type {
} from './types'
import { ProviderError } from './types'
import { parseSSEStream } from '../sse'
+import { idleAbortGuard, isStreamIdleTimeout } from '../stream-idle'
+import { sendWithTransientRetry } from './retry'
import { repairJson } from '../../lib/tool-call-repair'
import { signalCreditsExhausted } from '../../lib/credits-exhausted'
import { parseRetryAfter } from '../../lib/http-status'
@@ -153,6 +155,9 @@ function guessContextFromName(model: string): number {
// applyMaxTokens and getContextLength read it through another.
const catalogContext = new Map<string, number>()
+/** Ceiling for the optional metadata probes — see `probeInit`. */
+const CONTEXT_PROBE_TIMEOUT_MS = 2500
+
/**
* Which accumulator slot a tool-call delta without an `index` belongs to. The
* field is required by the OpenAI spec but several compatible servers omit it.
@@ -398,12 +403,19 @@ export class OpenAIProvider implements ProviderClient {
signal: AbortSignal | undefined,
fetcher: (url: string, init: any) => Promise<Response>,
): Promise<Response> {
- const post = () => fetcher(`${this.baseUrl}/chat/completions`, {
- method: 'POST',
- headers: this.headers,
- body: JSON.stringify(body),
- signal,
- })
+ // Sanierungspfad: a throttle or a gateway hiccup is not the request's
+ // fault, and the user used to read the raw status line for it. The retry
+ // sits HERE, around the request, so it can never replay a stream that has
+ // already started — see providers/retry.ts for the rules.
+ const post = () => sendWithTransientRetry(
+ () => fetcher(`${this.baseUrl}/chat/completions`, {
+ method: 'POST',
+ headers: this.headers,
+ body: JSON.stringify(body),
+ signal,
+ }),
+ { signal },
+ )
const refused = (res: Response) => !res.ok && (res.status === 400 || res.status === 422)
const asked = body.reasoning_effort as string | undefined
@@ -466,6 +478,21 @@ export class OpenAIProvider implements ProviderClient {
return h
}
+ /**
+ * Request init for the optional side probes (context window, tool
+ * capabilities). Every one of them is an OPTIMISATION — a failure just means
+ * the cascade falls back to a heuristic — but they ran with neither a signal
+ * nor a timeout, so a LAN backend that accepts the TCP connection and then
+ * says nothing blocked the user's message for the proxy's full default
+ * (300 s, and applyMaxTokens can hit two of them) with Stop unable to cut in.
+ * A few seconds is already generous for a local metadata endpoint.
+ */
+ private probeInit(signal?: AbortSignal): {
+ headers: Record<string, string>; timeoutMs: number; signal?: AbortSignal
+ } {
+ return { headers: this.headers, timeoutMs: CONTEXT_PROBE_TIMEOUT_MS, signal }
+ }
+
/**
* Bound `max_tokens` so prompt + completion can never exceed the model's real
* context window. Some cloud backends (DeepInfra) otherwise default the
@@ -483,7 +510,12 @@ export class OpenAIProvider implements ProviderClient {
): Promise<void> {
const requested = options?.maxTokens && options.maxTokens > 0 ? options.maxTokens : 0
let ctxLen = 0
- try { ctxLen = await this.getContextLength(model) } catch { ctxLen = 0 }
+ // Audit: the probe behind this runs on the SEND path. Without the signal a
+ // Stop could not interrupt it, and without a timeout a hung LAN backend
+ // held the message hostage for the proxy's full 300 s (twice). Both are
+ // threaded through probeInit(); on a timeout the cascade just falls back to
+ // the heuristic, which is what an optional optimisation should do.
+ try { ctxLen = await this.getContextLength(model, options?.signal) } catch { ctxLen = 0 }
if (ctxLen <= 0) {
// No context info at all — honor an explicit request, else a safe default.
body.max_tokens = requested || 4096
@@ -557,10 +589,20 @@ export class OpenAIProvider implements ProviderClient {
if (this.useLocalProxy) await ensureProxyAllowsHost(this.baseUrl)
const fetcher = this.useLocalProxy ? localFetchStream : fetch
- const res = await this.sendChat(model, body, options?.signal, fetcher as any)
-
- if (!res.ok) {
- throw await this.parseError(res)
+ // Zeitbombe 4 — the idle watchdog needs a controller to abort, and a
+ // provider only ever receives a signal. This chains one onto the caller's:
+ // Stop still propagates inward, and a stream that goes silent can cancel
+ // its own request instead of leaving reader.read() pending forever.
+ const guard = idleAbortGuard(options?.signal)
+ let res: Response
+ try {
+ res = await this.sendChat(model, body, guard.signal, fetcher as any)
+ if (!res.ok) throw await this.parseError(res)
+ } catch (err) {
+ // Nothing to watch — drop the listener on the caller's signal here, the
+ // stream loop's `finally` below is never reached on this path.
+ guard.release()
+ throw err
}
// Accumulate tool call arguments across chunks (OpenAI streams them in pieces)
@@ -580,95 +622,108 @@ export class OpenAIProvider implements ProviderClient {
}
}
- for await (const event of parseSSEStream(res)) {
- if (event.data === '[DONE]') {
- yield doneChunk('stop')
- return
- }
+ try {
+ for await (const event of parseSSEStream(res, { onIdle: guard.abort })) {
+ if (event.data === '[DONE]') {
+ yield doneChunk('stop')
+ return
+ }
- let chunk: OpenAIStreamChunk
- try {
- chunk = JSON.parse(event.data)
- } catch {
- continue
- }
+ let chunk: OpenAIStreamChunk
+ try {
+ chunk = JSON.parse(event.data)
+ } catch {
+ continue
+ }
- // LM Studio (and some OpenAI-compat servers) report a mid-stream failure
- // as a 200 response carrying an SSE error chunk ({ error: { message } } or
- // a bare { error: "..." }) instead of a non-2xx status, so the !res.ok
- // guard above never fires. Such a chunk has no `choices`, so the old loop
- // just skipped it → the user got a SILENT EMPTY reply. Surface it as a
- // thrown error so the chat layer can map it to a friendly message (e.g.
- // the #67 image-on-text-model case). Verified live: LM Studio + image on a
- // text-only model returns `event: error` with HTTP 200 (2026-06-21).
- const streamErr = (chunk as { error?: { message?: string } | string }).error
- if (streamErr) {
- throw new Error(typeof streamErr === 'string' ? streamErr : (streamErr.message || 'Streaming error'))
- }
+ // LM Studio (and some OpenAI-compat servers) report a mid-stream failure
+ // as a 200 response carrying an SSE error chunk ({ error: { message } } or
+ // a bare { error: "..." }) instead of a non-2xx status, so the !res.ok
+ // guard above never fires. Such a chunk has no `choices`, so the old loop
+ // just skipped it → the user got a SILENT EMPTY reply. Surface it as a
+ // thrown error so the chat layer can map it to a friendly message (e.g.
+ // the #67 image-on-text-model case). Verified live: LM Studio + image on a
+ // text-only model returns `event: error` with HTTP 200 (2026-06-21).
+ const streamErr = (chunk as { error?: { message?: string } | string }).error
+ if (streamErr) {
+ throw new Error(typeof streamErr === 'string' ? streamErr : (streamErr.message || 'Streaming error'))
+ }
- // Real token usage — the include_usage final chunk carries `usage` with
- // an empty choices[], so capture it BEFORE the choice guard below.
- const u = (chunk as { usage?: { prompt_tokens?: number; completion_tokens?: number } }).usage
- if (u) {
- promptTokens = u.prompt_tokens || promptTokens
- completionTokens = u.completion_tokens || completionTokens
- }
+ // Real token usage — the include_usage final chunk carries `usage` with
+ // an empty choices[], so capture it BEFORE the choice guard below.
+ const u = (chunk as { usage?: { prompt_tokens?: number; completion_tokens?: number } }).usage
+ if (u) {
+ promptTokens = u.prompt_tokens || promptTokens
+ completionTokens = u.completion_tokens || completionTokens
+ }
- const choice = chunk.choices?.[0]
- if (!choice) continue
+ const choice = chunk.choices?.[0]
+ if (!choice) continue
- // Capture WHY the model stopped ('stop', 'length', 'content_filter').
- // 'length' with zero content is the reasoning-loop failure mode: the
- // whole token budget went into thinking and no answer was ever written
- // (David, cloud Qwen3.6, 2026-07-12) — the chat layer needs the reason
- // to explain the empty bubble.
- if (choice.finish_reason) finishReason = choice.finish_reason
+ // Capture WHY the model stopped ('stop', 'length', 'content_filter').
+ // 'length' with zero content is the reasoning-loop failure mode: the
+ // whole token budget went into thinking and no answer was ever written
+ // (David, cloud Qwen3.6, 2026-07-12) — the chat layer needs the reason
+ // to explain the empty bubble.
+ if (choice.finish_reason) finishReason = choice.finish_reason
- const content = choice.delta?.content || ''
+ const content = choice.delta?.content || ''
- // Yield native reasoning as `thinking` so the panel fills live —
- // without this the entire reasoning phase of a cloud reasoner is
- // silently dropped and the chat sits in dead air (uselu fc55c91).
- const reasoning = choice.delta?.reasoning_content ?? choice.delta?.reasoning ?? ''
- if (reasoning) {
- yield { content: '', thinking: reasoning, done: false }
- }
+ // Yield native reasoning as `thinking` so the panel fills live —
+ // without this the entire reasoning phase of a cloud reasoner is
+ // silently dropped and the chat sits in dead air (uselu fc55c91).
+ const reasoning = choice.delta?.reasoning_content ?? choice.delta?.reasoning ?? ''
+ if (reasoning) {
+ yield { content: '', thinking: reasoning, done: false }
+ }
- // Accumulate streamed tool calls
- if (choice.delta?.tool_calls) {
- for (const tc of choice.delta.tool_calls) {
- const key = tc.index ?? keyForUnindexedDelta(toolCallAccum, tc.id)
- const existing = toolCallAccum.get(key)
- if (existing) {
- // id and name do NOT always arrive in the first delta — several
- // OpenAI-compat servers send the id one chunk later, or open with a
- // bare index. Ignoring them left a call with an empty name (dispatch
- // fails on "") or an empty tool_call_id, which 422s the follow-up
- // turn — the exact break the server-side normalizer had to heal.
- // Set-if-empty, not append: servers that repeat the full name in
- // every delta are far more common than ones that stream it in parts.
- if (tc.id && !existing.id) existing.id = tc.id
- if (tc.function?.name && !existing.name) existing.name = tc.function.name
- if (tc.function?.arguments) existing.args += tc.function.arguments
- } else {
- toolCallAccum.set(key, {
- id: tc.id || '',
- name: tc.function?.name || '',
- args: tc.function?.arguments || '',
- })
+ // Accumulate streamed tool calls
+ if (choice.delta?.tool_calls) {
+ for (const tc of choice.delta.tool_calls) {
+ const key = tc.index ?? keyForUnindexedDelta(toolCallAccum, tc.id)
+ const existing = toolCallAccum.get(key)
+ if (existing) {
+ // id and name do NOT always arrive in the first delta — several
+ // OpenAI-compat servers send the id one chunk later, or open with a
+ // bare index. Ignoring them left a call with an empty name (dispatch
+ // fails on "") or an empty tool_call_id, which 422s the follow-up
+ // turn — the exact break the server-side normalizer had to heal.
+ // Set-if-empty, not append: servers that repeat the full name in
+ // every delta are far more common than ones that stream it in parts.
+ if (tc.id && !existing.id) existing.id = tc.id
+ if (tc.function?.name && !existing.name) existing.name = tc.function.name
+ if (tc.function?.arguments) existing.args += tc.function.arguments
+ } else {
+ toolCallAccum.set(key, {
+ id: tc.id || '',
+ name: tc.function?.name || '',
+ args: tc.function?.arguments || '',
+ })
+ }
}
}
- }
- if (content) {
- yield { content, done: false }
- }
+ if (content) {
+ yield { content, done: false }
+ }
- // NB: we intentionally do NOT early-return on finish_reason. With
- // stream_options.include_usage the server sends the usage chunk AFTER
- // the finish_reason chunk — returning early would discard it. The [DONE]
- // sentinel (or the end-of-stream fallback below) emits the single done
- // chunk, which now carries the captured usage.
+ // NB: we intentionally do NOT early-return on finish_reason. With
+ // stream_options.include_usage the server sends the usage chunk AFTER
+ // the finish_reason chunk — returning early would discard it. The [DONE]
+ // sentinel (or the end-of-stream fallback below) emits the single done
+ // chunk, which now carries the captured usage.
+ }
+ } catch (err) {
+ // The watchdog fired: the stream did not fail, it went quiet. Same
+ // terminal chunk as a clean cut, so the chat layer explains it the same
+ // way instead of throwing a raw error at the user.
+ if (isStreamIdleTimeout(err)) {
+ yield doneChunk('disconnect')
+ return
+ }
+ throw err
+ } finally {
+ guard.release()
}
// Stream ended without an explicit [DONE] sentinel. If the server also
@@ -836,7 +891,7 @@ export class OpenAIProvider implements ProviderClient {
*
* Returnt `null` wenn nichts gefunden, damit Callers cascaden koennen.
*/
- private async probeContextFromServer(model: string): Promise<number | null> {
+ private async probeContextFromServer(model: string, signal?: AbortSignal): Promise<number | null> {
if (!this.isLanBackend) return null
// Probe cache (audit E5): applyMaxTokens calls getContextLength on EVERY
@@ -861,7 +916,7 @@ export class OpenAIProvider implements ProviderClient {
const lmStudioBase = this.baseUrl.replace(/\/v1\/?$/, '/api/v0')
const lmsRes = await localFetch(
`${lmStudioBase}/models/${encodeURIComponent(model)}`,
- { headers: this.headers } as any,
+ this.probeInit(signal),
)
if (lmsRes.ok) {
const data = await lmsRes.json()
@@ -875,7 +930,7 @@ export class OpenAIProvider implements ProviderClient {
try {
const res = await localFetch(
`${this.baseUrl}/models/${encodeURIComponent(model)}`,
- { headers: this.headers } as any,
+ this.probeInit(signal),
)
if (res.ok) {
const data = await res.json()
@@ -904,7 +959,7 @@ export class OpenAIProvider implements ProviderClient {
const enhancedBase = this.baseUrl.replace(/\/v1\/?$/, '/api/v0')
if (enhancedBase === this.baseUrl) return map
try {
- const res = await localFetch(`${enhancedBase}/models`, { headers: this.headers } as any)
+ const res = await localFetch(`${enhancedBase}/models`, this.probeInit())
if (!res.ok) return map
const data = await res.json()
for (const m of (data?.data ?? [])) {
@@ -927,7 +982,7 @@ export class OpenAIProvider implements ProviderClient {
private async fetchServerToolCaps(): Promise<boolean | undefined> {
const propsUrl = this.baseUrl.replace(/\/v1\/?$/, '') + '/props'
try {
- const res = await localFetch(propsUrl, { headers: this.headers } as any)
+ const res = await localFetch(propsUrl, this.probeInit())
if (!res.ok) return undefined
const data = await res.json()
const flag = data?.chat_template_caps?.supports_tools
@@ -1041,7 +1096,7 @@ export class OpenAIProvider implements ProviderClient {
try {
const res = await localFetch(
`${lmStudioBase}/models/${encodeURIComponent(model)}`,
- { headers: this.headers } as any,
+ this.probeInit(),
)
if (!res.ok) return remember(null)
const data = await res.json()
@@ -1051,7 +1106,7 @@ export class OpenAIProvider implements ProviderClient {
return remember(null)
}
- async getContextLength(model: string): Promise<number> {
+ async getContextLength(model: string, signal?: AbortSignal): Promise<number> {
// Cascade:
// 1. Server-declared context_length from the /models catalogue (LU
// Cloud) — authoritative for the deployment, beats every heuristic
@@ -1062,7 +1117,7 @@ export class OpenAIProvider implements ProviderClient {
const catalog = catalogContext.get(this.catalogKey(model))
if (catalog && catalog > 0) return catalog
if (KNOWN_CONTEXT[model]) return KNOWN_CONTEXT[model]
- const probed = await this.probeContextFromServer(model)
+ const probed = await this.probeContextFromServer(model, signal)
if (probed) return probed
return guessContextFromName(model)
}
diff --git a/src/api/providers/retry.ts b/src/api/providers/retry.ts
new file mode 100644
index 00000000..4b2af515
--- /dev/null
+++ b/src/api/providers/retry.ts
@@ -0,0 +1,121 @@
+/**
+ * Retry for the one class of failure a second attempt actually fixes: the
+ * server said "not now".
+ *
+ * Today a 429 or a 503 reaches the user as the raw status line, even though
+ * nothing is wrong with the request — a burst limiter is holding the door for
+ * a second or a gateway is between upstreams. Retrying that is free; retrying
+ * anything else is not, so the rules are narrow on purpose:
+ *
+ * - Only the transient statuses below. A 4xx that describes the request is
+ * deterministic and must surface immediately.
+ * - Only around the REQUEST, never around a body loop. Once bytes are
+ * flowing a retry would replay half an answer, so this wraps the call that
+ * produces the Response and hands the untouched Response straight back the
+ * moment the status is not retryable. The stream is consumed by the caller,
+ * after this returns.
+ * - Abortable. Stop during a backoff ends the wait and the walk.
+ *
+ * Deliberately capped short: the agent loop already has its own retry ladder
+ * (lib/http-status retryDelayMs + useAgentChat's announceWait) which can sit
+ * out a full minute BECAUSE it tells the user it is waiting. Nothing here can
+ * say anything, so a wait longer than MAX_SILENT_RETRY_WAIT_MS is worse than
+ * the honest error — we return the refusal and let the layer that can speak
+ * decide.
+ */
+
+import { parseRetryAfter } from '../../lib/http-status'
+
+/** Throttles and gateway hiccups. Everything else is the server's verdict on
+ * the request itself and gets exactly one attempt. */
+const TRANSIENT_STATUS = new Set([429, 502, 503, 504])
+
+/** Total attempts, i.e. the first try plus two retries. */
+export const MAX_TRANSIENT_ATTEMPTS = 3
+
+/** Longest backoff a single send may sit through without being able to say so. */
+export const MAX_SILENT_RETRY_WAIT_MS = 10_000
+
+/** Backoff when the server named no `Retry-After`: 500 ms, then 1 s. */
+function backoffMs(attempt: number): number {
+ return 500 * 2 ** (attempt - 1)
+}
+
+/** Sleep that ends early when the caller aborts, so Stop is never queued
+ * behind a backoff. */
+function sleep(ms: number, signal?: AbortSignal): Promise<void> {
+ return new Promise<void>((resolve) => {
+ if (signal?.aborted) { resolve(); return }
+ let onAbort: (() => void) | null = null
+ const timer = setTimeout(() => { finish() }, ms)
+ const finish = () => {
+ clearTimeout(timer)
+ if (signal && onAbort) signal.removeEventListener('abort', onAbort)
+ resolve()
+ }
+ if (signal) {
+ onAbort = () => finish()
+ signal.addEventListener('abort', onAbort, { once: true })
+ }
+ })
+}
+
+/**
+ * An empty wallet also answers 429, and no amount of waiting refills it. The
+ * body says which one it is (`credits_exhausted`, see lib/http-status), and
+ * getting that wrong is what once made a dead run look like four more seconds
+ * of work. Peeked on a clone so the caller still gets an unread body.
+ */
+async function isPermanent429(res: Response): Promise<boolean> {
+ if (res.status !== 429) return false
+ try {
+ return /credits_exhausted/.test(await res.clone().text())
+ } catch {
+ return false
+ }
+}
+
+export interface TransientRetryOptions {
+ signal?: AbortSignal
+ /** Total attempts including the first. Defaults to MAX_TRANSIENT_ATTEMPTS. */
+ attempts?: number
+ /** Seam for tests — swapped for a fake clock so a retry test does not
+ * actually sleep. */
+ wait?: (ms: number, signal?: AbortSignal) => Promise<void>
+}
+
+/**
+ * Run `send` and retry it while the answer is a transient refusal.
+ *
+ * `send` must be idempotent — it is, for every call site: a chat completion
+ * that was refused produced nothing, so re-posting the identical body is the
+ * same request, not a second one.
+ */
+export async function sendWithTransientRetry(
+ send: () => Promise<Response>,
+ opts?: TransientRetryOptions,
+): Promise<Response> {
+ const attempts = opts?.attempts ?? MAX_TRANSIENT_ATTEMPTS
+ const wait = opts?.wait ?? sleep
+
+ let res = await send()
+
+ for (let attempt = 1; attempt < attempts; attempt++) {
+ if (!TRANSIENT_STATUS.has(res.status)) return res
+ if (opts?.signal?.aborted) return res
+ if (await isPermanent429(res)) return res
+
+ // The server's own number wins — a fixed-window limiter refuses again for
+ // the whole window, so guessing shorter just burns an attempt inside it.
+ const asked = parseRetryAfter(res)
+ const delay = asked ?? backoffMs(attempt)
+ if (delay > MAX_SILENT_RETRY_WAIT_MS) return res
+
+ await wait(delay, opts?.signal)
+ if (opts?.signal?.aborted) return res
+
+ res = await send()
+ }
+
+ return res
+}
diff --git a/src/api/sse.ts b/src/api/sse.ts
index 150d6688..4351f7de 100644
--- a/src/api/sse.ts
+++ b/src/api/sse.ts
@@ -13,11 +13,45 @@
* data: {"type":"content_block_delta","delta":{"text":"Hi"}}\n\n
*/
+import {
+ readChunks, STREAM_IDLE_TIMEOUT_MS, type StreamIdleOptions,
+} from './stream-idle'
+
+export type { StreamIdleOptions }
+
export interface SSEEvent {
event?: string // e.g. "content_block_delta", "message_stop"
data: string // raw JSON string (or "[DONE]")
}
+/**
+ * A `data:` line that is not JSON.
+ *
+ * It used to be swallowed without a trace, and the shape that hits this is
+ * precisely a provider error object in an unexpected form — a relay that
+ * answers with an HTML error page, a gateway that writes a bare string. The
+ * user got an empty bubble and there was nothing to look at. Structured and
+ * thrown beats silent: the chat layer already renders a thrown error.
+ */
+export class SSEMalformedDataError extends Error {
+ readonly code = 'sse_malformed_data'
+ /** The offending payload, truncated — enough to recognise, not enough to
+ * paste a whole HTML page into a chat bubble. */
+ readonly raw: string
+ /** The `event:` field it arrived under, when the server sent one. */
+ readonly event?: string
+
+ constructor(raw: string, event?: string) {
+ const shown = raw.length > 200 ? `${raw.slice(0, 200)}…` : raw
+ super(
+ `Stream sent data that is not JSON${event ? ` (event: ${event})` : ''}: ${shown}`,
+ )
+ this.name = 'SSEMalformedDataError'
+ this.raw = raw
+ this.event = event
+ }
+}
+
/**
* Parse an SSE stream into individual events.
* Handles multi-line data fields, event types, and the [DONE] sentinel.
@@ -44,58 +78,69 @@ function parseEventBlock(block: string): SSEEvent | null {
return data ? { event, data } : null
}
-export async function* parseSSEStream(response: Response): AsyncGenerator<SSEEvent> {
- const reader = response.body?.getReader()
- if (!reader) throw new Error('No response body')
+/** JSON out of one event's data, or a named error instead of silence. */
+function parseEventJson<T>(event: SSEEvent): T {
+ try {
+ return JSON.parse(event.data) as T
+ } catch {
+ throw new SSEMalformedDataError(event.data, event.event)
+ }
+}
+/**
+ * `opts` reaches the idle watchdog in stream-idle.ts. The budget defaults to
+ * ON here because every SSE stream in this app is a chat completion, i.e. the
+ * exact surface where an endless silent read strands the user; pass
+ * `{ idleMs: 0 }` to opt out.
+ */
+export async function* parseSSEStream(
+ response: Response,
+ opts?: StreamIdleOptions,
+): AsyncGenerator<SSEEvent> {
const decoder = new TextDecoder()
let buffer = ''
- try {
- while (true) {
- const { done, value } = await reader.read()
- if (done) break
-
- buffer += decoder.decode(value, { stream: true })
-
- // The SSE spec allows CRLF and lone CR as line terminators, and some
- // servers and proxies use them. Splitting on '\n\n' alone glued every
- // event of such a stream into one block whose JSON never parsed — the
- // whole answer came back silently empty.
- // A trailing '\r' may be the first half of a CRLF split across two reads,
- // so it waits in the buffer until we can see what follows it.
- const carry = buffer.endsWith('\r') ? '\r' : ''
- const normalized = (carry ? buffer.slice(0, -1) : buffer).replace(/\r\n?/g, '\n')
-
- // SSE events are separated by double newline
- const parts = normalized.split('\n\n')
- buffer = (parts.pop() || '') + carry
-
- for (const part of parts) {
- const parsed = parseEventBlock(part)
- if (parsed) yield parsed
- }
- }
+ for await (const value of readChunks(response, {
+ idleMs: opts?.idleMs ?? STREAM_IDLE_TIMEOUT_MS,
+ firstChunkMs: opts?.firstChunkMs,
+ onIdle: opts?.onIdle,
+ })) {
+ buffer += decoder.decode(value, { stream: true })
+
+ // The SSE spec allows CRLF and lone CR as line terminators, and some
+ // servers and proxies use them. Splitting on '\n\n' alone glued every
+ // event of such a stream into one block whose JSON never parsed — the
+ // whole answer came back silently empty.
+ // A trailing '\r' may be the first half of a CRLF split across two reads,
+ // so it waits in the buffer until we can see what follows it.
+ const carry = buffer.endsWith('\r') ? '\r' : ''
+ const normalized = (carry ? buffer.slice(0, -1) : buffer).replace(/\r\n?/g, '\n')
- // Process any remaining buffer
- const tail = parseEventBlock(buffer.replace(/\r\n?/g, '\n'))
- if (tail) yield tail
- } finally {
- reader.releaseLock()
+ // SSE events are separated by double newline
+ const parts = normalized.split('\n\n')
+ buffer = (parts.pop() || '') + carry
+
+ for (const part of parts) {
+ const parsed = parseEventBlock(part)
+ if (parsed) yield parsed
+ }
}
+
+ // Process any remaining buffer
+ const tail = parseEventBlock(buffer.replace(/\r\n?/g, '\n'))
+ if (tail) yield tail
}
/**
* Parse SSE stream and yield parsed JSON objects, skipping [DONE].
*/
-export async function* parseSSEJsonStream<T>(response: Response): AsyncGenerator<T> {
- for await (const event of parseSSEStream(response)) {
+export async function* parseSSEJsonStream<T>(
+ response: Response,
+ opts?: StreamIdleOptions,
+): AsyncGenerator<T> {
+ for await (const event of parseSSEStream(response, opts)) {
if (event.data === '[DONE]') return
- try {
- yield JSON.parse(event.data) as T
- } catch {
- // Skip malformed JSON
- }
+ yield parseEventJson<T>(event)
}
}
@@ -103,13 +148,12 @@ export async function* parseSSEJsonStream<T>(response: Response): AsyncGenerator
* Parse SSE stream with event types (Anthropic format).
* Yields both the event type and parsed data.
*/
-export async function* parseSSEWithEvents<T>(response: Response): AsyncGenerator<{ event?: string; data: T }> {
- for await (const event of parseSSEStream(response)) {
+export async function* parseSSEWithEvents<T>(
+ response: Response,
+ opts?: StreamIdleOptions,
+): AsyncGenerator<{ event?: string; data: T }> {
+ for await (const event of parseSSEStream(response, opts)) {
if (event.data === '[DONE]') return
- try {
- yield { event: event.event, data: JSON.parse(event.data) as T }
- } catch {
- // Skip malformed JSON
- }
+ yield { event: event.event, data: parseEventJson<T>(event) }
}
}
diff --git a/src/api/stream-idle.ts b/src/api/stream-idle.ts
new file mode 100644
index 00000000..16fd2a7e
--- /dev/null
+++ b/src/api/stream-idle.ts
@@ -0,0 +1,183 @@
+/**
+ * Idle watchdog for streamed HTTP bodies — the one place every provider's
+ * bytes pass through.
+ *
+ * Constraint: a chat stream has no client-side deadline it can rely on. The
+ * only bound the app had was the Rust proxy's 7200 s TOTAL timeout, and the
+ * direct-fetch paths (cloud providers, macOS/Linux, browser dev mode) had none
+ * at all. When a laptop sleeps or Wi-Fi drops without a FIN the TCP connection
+ * stays half-open: `reader.read()` never settles, the spinner runs forever and
+ * only "Stop" ends it. Every laptop lid triggers it.
+ *
+ * So the bound is on SILENCE, not on total duration — a stream still producing
+ * tokens after an hour is healthy, one that produced nothing for a minute is
+ * not. Both stream parsers (sse.ts for OpenAI/Anthropic, stream.ts for Ollama
+ * NDJSON) read through `readChunks` below, so the watchdog exists once instead
+ * of once per provider.
+ *
+ * Relation to the Rust-side idle timeout (proxy.rs): the two do not double up.
+ * Whichever fires first ends the body. Rust closing the channel makes the
+ * parser see a clean EOF, which the providers already turn into their single
+ * terminal 'disconnect' chunk, and the timer here is cleared by the read that
+ * comes back done. This side exists because the direct-fetch paths never reach
+ * Rust at all, so it must work on its own.
+ */
+
+/** No chunk for this long, once the stream has started → treat it as dead. */
+export const STREAM_IDLE_TIMEOUT_MS = 60_000
+
+/**
+ * Grace for the FIRST chunk. A cold local model is loaded only when the
+ * request arrives: Ollama answers the headers immediately and then sends
+ * nothing at all while it pulls tens of gigabytes off disk into VRAM, and
+ * llama.cpp behaves the same on a long prompt. Holding that to the 60 s
+ * between-chunk budget would abort exactly the legitimate slow start the UI
+ * already shows as "loading model". Five minutes is past any load this app
+ * survives and still far short of the endless hang.
+ */
+export const STREAM_FIRST_CHUNK_TIMEOUT_MS = 300_000
+
+/** Thrown by the parsers when the watchdog fires. Providers catch it and end
+ * the turn with a terminal 'disconnect' chunk rather than letting it bubble
+ * up as a raw error — the stream did not fail, it went quiet. */
+export class StreamIdleTimeoutError extends Error {
+ readonly code = 'stream_idle_timeout'
+ /** The budget that elapsed, in ms — the readable cause for the log line. */
+ readonly idleMs: number
+
+ constructor(idleMs: number, phase: 'first chunk' | 'stream') {
+ super(`No data on the ${phase} for ${Math.round(idleMs / 1000)}s — connection went silent`)
+ this.name = 'StreamIdleTimeoutError'
+ this.idleMs = idleMs
+ }
+}
+
+export function isStreamIdleTimeout(err: unknown): err is StreamIdleTimeoutError {
+ return !!err && typeof err === 'object'
+ && (err as { code?: unknown }).code === 'stream_idle_timeout'
+}
+
+export interface StreamIdleOptions {
+ /** Silence budget between chunks, ms. `0` or negative disables the watchdog. */
+ idleMs?: number
+ /** Silence budget before the first chunk, ms. Independent of `idleMs` and
+ * much larger by default — see STREAM_FIRST_CHUNK_TIMEOUT_MS for why. Only
+ * consulted when `idleMs` enables the watchdog at all. */
+ firstChunkMs?: number
+ /**
+ * Fired once, before the error is thrown, so the caller can abort the request
+ * itself. That is what actually stops the upstream generation — and on the
+ * Tauri proxy path it is what fires `cancel_proxy_stream`. Cancelling only
+ * this reader would leave Rust happily pulling from the backend.
+ */
+ onIdle?: () => void
+}
+
+/**
+ * Read a response body chunk by chunk, abandoning it when it goes silent for
+ * longer than the budget. Yields the raw bytes; decoding and framing stay with
+ * the parser that called us, so the SSE line-terminator handling in sse.ts is
+ * untouched by this.
+ */
+export async function* readChunks(
+ response: Response,
+ opts?: StreamIdleOptions,
+): AsyncGenerator<Uint8Array> {
+ const reader = response.body?.getReader()
+ if (!reader) throw new Error('No response body')
+
+ const idleMs = opts?.idleMs ?? 0
+ const firstChunkMs = opts?.firstChunkMs ?? STREAM_FIRST_CHUNK_TIMEOUT_MS
+ let first = true
+ let timedOut = false
+
+ try {
+ for (;;) {
+ const budget = first ? firstChunkMs : idleMs
+ let result: ReadableStreamReadResult<Uint8Array>
+
+ if (idleMs > 0 && budget > 0) {
+ let timer: ReturnType<typeof setTimeout> | undefined
+ const silent = new Promise<never>((_, reject) => {
+ timer = setTimeout(() => {
+ timedOut = true
+ // Abort BEFORE rejecting: the reject only unblocks this loop, the
+ // caller's abort is what tears the request down.
+ try { opts?.onIdle?.() } catch { /* best effort, never mask the timeout */ }
+ reject(new StreamIdleTimeoutError(budget, first ? 'first chunk' : 'stream'))
+ }, budget)
+ })
+ try {
+ // Promise.race leaves a reaction on the pending read, so the abort's
+ // later rejection is handled and never surfaces as an unhandled one.
+ result = await Promise.race([reader.read(), silent])
+ } finally {
+ if (timer) clearTimeout(timer)
+ }
+ } else {
+ result = await reader.read()
+ }
+
+ if (result.done) break
+ if (result.value) {
+ first = false
+ yield result.value
+ }
+ }
+ } finally {
+ if (timedOut) {
+ // A read is still outstanding. Cancel so the body is not left dangling;
+ // both the cancel and the release can reject/throw on a stream the abort
+ // already killed, and neither is worth reporting.
+ try { void Promise.resolve(reader.cancel()).catch(() => { /* already dead */ }) } catch { /* no cancel */ }
+ }
+ try { reader.releaseLock() } catch { /* outstanding read after an idle abort */ }
+ }
+}
+
+/** A controller the watchdog may abort, chained to the caller's own signal. */
+export interface IdleAbortGuard {
+ /** Hand THIS to fetch / localFetchStream instead of the caller's signal. */
+ readonly signal: AbortSignal
+ /** Abort the request. Wired to `StreamIdleOptions.onIdle`. */
+ readonly abort: () => void
+ /** Drop the listener on the caller's signal — always call it in a `finally`,
+ * a long chat session would otherwise pile up listeners on a shared signal. */
+ readonly release: () => void
+}
+
+/**
+ * Chain a fresh AbortController onto the caller's signal.
+ *
+ * The provider only ever receives an AbortSignal, never the controller behind
+ * it, so it has nothing to abort when the watchdog fires. This gives it one:
+ * Stop still propagates (caller → ours), and the watchdog can now cancel the
+ * request without the caller knowing.
+ *
+ * Deliberately not `AbortSignal.any()`: that landed in Chrome 116 / Safari
+ * 17.4, and this ships inside whatever WebView the user's OS provides.
+ */
+export function idleAbortGuard(outer?: AbortSignal): IdleAbortGuard {
+ const ctl = new AbortController()
+ let onOuterAbort: (() => void) | null = null
+
+ if (outer) {
+ if (outer.aborted) {
+ ctl.abort()
+ } else {
+ onOuterAbort = () => ctl.abort()
+ outer.addEventListener('abort', onOuterAbort, { once: true })
+ }
+ }
+
+ return {
+ signal: ctl.signal,
+ abort: () => { if (!ctl.signal.aborted) ctl.abort() },
+ release: () => {
+ if (outer && onOuterAbort) {
+ outer.removeEventListener('abort', onOuterAbort)
+ onOuterAbort = null
+ }
+ },
+ }
+}
diff --git a/src/api/stream.ts b/src/api/stream.ts
index a728b512..a4d87067 100644
--- a/src/api/stream.ts
+++ b/src/api/stream.ts
@@ -1,38 +1,47 @@
-export async function* parseNDJSONStream<T>(response: Response): AsyncGenerator<T> {
- const reader = response.body?.getReader()
- if (!reader) throw new Error('No response body')
+import { readChunks, type StreamIdleOptions } from './stream-idle'
+/**
+ * Ollama's NDJSON wire format: one JSON object per line.
+ *
+ * `opts` reaches the shared idle watchdog in stream-idle.ts and is OFF by
+ * default here — unlike the SSE parser, this generator also carries
+ * `ollama pull` progress, where minutes of silence during checksum
+ * verification of a multi-gigabyte blob is normal and healthy. The chat path
+ * (providers/ollama-provider.ts) opts in explicitly.
+ *
+ * A malformed line stays skipped on purpose. Ollama's own mid-stream failure
+ * is a perfectly VALID JSON line (`{"error":"llama runner ... killed"}`) which
+ * the provider raises on, so silence is not the failure mode here the way it
+ * is for SSE.
+ */
+export async function* parseNDJSONStream<T>(
+ response: Response,
+ opts?: StreamIdleOptions,
+): AsyncGenerator<T> {
const decoder = new TextDecoder()
let buffer = ''
- try {
- while (true) {
- const { done, value } = await reader.read()
- if (done) break
+ for await (const value of readChunks(response, opts)) {
+ buffer += decoder.decode(value, { stream: true })
+ const lines = buffer.split('\n')
+ buffer = lines.pop() || ''
- buffer += decoder.decode(value, { stream: true })
- const lines = buffer.split('\n')
- buffer = lines.pop() || ''
-
- for (const line of lines) {
- const trimmed = line.trim()
- if (!trimmed) continue
- try {
- yield JSON.parse(trimmed) as T
- } catch {
- // skip malformed lines
- }
- }
- }
-
- if (buffer.trim()) {
+ for (const line of lines) {
+ const trimmed = line.trim()
+ if (!trimmed) continue
try {
- yield JSON.parse(buffer.trim()) as T
+ yield JSON.parse(trimmed) as T
} catch {
- // skip
+ // skip malformed lines
}
}
- } finally {
- reader.releaseLock()
+ }
+
+ if (buffer.trim()) {
+ try {
+ yield JSON.parse(buffer.trim()) as T
+ } catch {
+ // skip
+ }
}
}