The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(provider): meine eigene Haertung von 0e740f60 hat einen Fall zerstoert
David1f7ef5e65297
diff --git a/src-tauri/src/commands/bg_tasks.rs b/src-tauri/src/commands/bg_tasks.rsindex 40852de5..fec51958 100644--- a/src-tauri/src/commands/bg_tasks.rs+++ b/src-tauri/src/commands/bg_tasks.rs@@ -1045,8 +1045,10 @@ mod cwd_default_tests {/// the model started "in the project" ran somewhere else.#[tokio::test]async fn a_task_without_an_explicit_cwd_lands_in_the_workspace() {- let ws = std::env::temp_dir().join(format!("lu-bg-ws-{}", std::process::id()));- std::fs::create_dir_all(&ws).unwrap();+ // `os_paths::test_dir` statt eines handgebauten `temp_dir().join(…)`:+ // das Aufräumen hängt am `Drop` und läuft auch dann, wenn das+ // `assert!` unten panickt — die letzte Zeile des Tests tat das nicht.+ let ws = crate::os_paths::test_dir("bg-ws");let start = shell_task_start_impl(&super::a_task_that_prints_its_directory(json!({"working_directory": ws.to_string_lossy(),@@ -1060,16 +1062,15 @@ mod cwd_default_tests {same_directory(&seen, &ws),"background task did not start in the workspace: reported {seen:?}, wanted {ws:?}",);- let _ = std::fs::remove_dir_all(&ws);}/// An explicit cwd from the caller still wins over the derived default.#[tokio::test]async fn an_explicit_cwd_still_wins() {- let a = std::env::temp_dir().join(format!("lu-bg-a-{}", std::process::id()));- let b = std::env::temp_dir().join(format!("lu-bg-b-{}", std::process::id()));- std::fs::create_dir_all(&a).unwrap();- std::fs::create_dir_all(&b).unwrap();+ // Siehe oben: beide Verzeichnisse räumen sich beim Verlassen selbst+ // ab, auch über die drei `assert!` hinweg.+ let a = crate::os_paths::test_dir("bg-a");+ let b = crate::os_paths::test_dir("bg-b");let start = shell_task_start_impl(&super::a_task_that_prints_its_directory(json!({"cwd": b.to_string_lossy(),@@ -1086,8 +1087,6 @@ mod cwd_default_tests {);// Negative control: the folder that must NOT have won.assert!(!same_directory(&seen, &a), "the task ran in the fallback {a:?}");- let _ = std::fs::remove_dir_all(&a);- let _ = std::fs::remove_dir_all(&b);}}diff --git a/src/api/providers/__tests__/anthropic-proxy-shapes.test.ts b/src/api/providers/__tests__/anthropic-proxy-shapes.test.tsindex 6f3d38a8..0ae5a9d7 100644--- a/src/api/providers/__tests__/anthropic-proxy-shapes.test.ts+++ b/src/api/providers/__tests__/anthropic-proxy-shapes.test.ts@@ -6,14 +6,27 @@* Namen. Anthropic selbst sendet beide Formen nicht; wer sie sieht, sitzt* hinter einer Zwischenstation, die das Protokoll nachbaut.*- * 1. `content_block_start` OHNE `index`.- * Vor 0e740f60 stand dort `toolUseBlocks.set(data.index!, …)`. Die- * Non-null-Assertion galt auf einem Feld, das dieselbe Datei als optional- * deklariert hatte: der Block landete unter dem Schluessel `undefined`,- * jedes `content_block_delta` suchte ihn unter seiner echten Zahl und fand- * nichts — und am Ende ging der Tool-Call mit `{}` raus. Ein `file_read`- * ohne `path`, an das Modell zurueckgemeldet als "Tool hat versagt", statt- * als das, was es war.+ * 1. Ein `tool_use`-Block, dessen Events kein `index` tragen.+ *+ * `index` ist der Schluessel, unter dem `content_block_start` den Block+ * anlegt und `content_block_delta` seine JSON-Fragmente nachschiebt. Drei+ * Formen kommen auf dieser Route an, und die Geschichte des Codes hat jede+ * einzelne davon schon einmal fallen lassen:+ *+ * (a) Start und Deltas beide MIT index — Anthropic selbst.+ * (b) Start OHNE, Deltas MIT — `set(data.index!)` legte den Block unter+ * `undefined` an, jedes Delta suchte unter `0` und fand nichts: der+ * Tool-Call ging mit `{}` raus. Ein `file_read` ohne `path`, das dem+ * Modell als "Tool hat versagt" zurueckgemeldet wurde.+ * (c) Start und Deltas beide OHNE — lief unter `set(data.index!)`+ * versehentlich RICHTIG, weil beide Seiten auf `undefined`+ * schluesselten. Der erste Reparaturversuch (Event ueberspringen,+ * wenn `index` fehlt) hat (b) geheilt und dabei (c) zerbrochen: der+ * Tool-Call verschwand still, ohne Chunk und ohne Meldung.+ *+ * Deshalb stehen alle drei hier mit einem eigenen Fall. Die Regel dahinter+ * ist `keyForUnindexedBlock` in wire.ts — dieselbe, mit der der+ * OpenAI-Akkumulator seit jeher indexlose Deltas einsortiert.** 2. Eine 200er-Antwort OHNE `content`.* `const data: AnthropicResponse = await res.json()` behauptete das Feld@@ -27,7 +40,7 @@*/import { describe, it, expect, vi, afterEach } from 'vitest'import { AnthropicProvider } from '../anthropic-provider'-import type { ProviderConfig, ChatStreamChunk } from '../types'+import type { ProviderConfig, ChatStreamChunk, ToolCall } from '../types'// api.anthropic.com steht auf der gepinnten CSP-Liste, nimmt also den// direkten `fetch` — den, den `vi.stubGlobal` hier ersetzt. Die Form der@@ -52,68 +65,139 @@ async function drain(gen: AsyncGenerator<ChatStreamChunk>): Promise<ChatStreamChreturn out}+/** Den Stream einmal durchlaufen lassen und die Chunks einsammeln. */+async function chunksOf(events: string[]): Promise<ChatStreamChunk[]> {+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(sse(events)))+ return drain(new AnthropicProvider(config())+ .chatStream('claude-sonnet-4-20250514', [{ role: 'user', content: 'read it' }]))+}++async function toolCallsOf(events: string[]): Promise<ToolCall[]> {+ return (await chunksOf(events)).flatMap(c => c.toolCalls ?? [])+}++// ── Die drei Event-Formen, gleicher Inhalt, unterschiedlich indiziert ──++const START_MESSAGE =+ 'event: message_start\ndata: {"type":"message_start","message":{"id":"m","usage":{"input_tokens":11,"output_tokens":0}}}\n\n'+const STOP =+ 'event: message_stop\ndata: {"type":"message_stop"}\n\n'++/** `content_block_start` fuer einen tool_use-Block, mit oder ohne `index`. */+function blockStart(id: string, name: string, index?: number): string {+ const idx = index === undefined ? '' : `"index":${index},`+ return `event: content_block_start\ndata: {"type":"content_block_start",${idx}"content_block":{"type":"tool_use","id":"${id}","name":"${name}"}}\n\n`+}++/** Ein `input_json_delta`-Fragment, mit oder ohne `index`. */+function jsonDelta(fragment: string, index?: number): string {+ const idx = index === undefined ? '' : `"index":${index},`+ return `event: content_block_delta\ndata: {"type":"content_block_delta",${idx}"delta":{"type":"input_json_delta","partial_json":${JSON.stringify(fragment)}}}\n\n`+}+afterEach(() => {vi.unstubAllGlobals()vi.restoreAllMocks()})-describe('a proxy that opens a tool_use block without an index', () => {- // Der Mitschnitt-Fall: `content_block_start` ohne `index`, die- // `input_json_delta`-Fragmente danach MIT `index`. Genau diese Mischung- // liess den Tool-Call mit leeren Argumenten rausgehen.- const PROXY_STREAM = [- 'event: message_start\ndata: {"type":"message_start","message":{"id":"m","usage":{"input_tokens":11,"output_tokens":0}}}\n\n',- 'event: content_block_start\ndata: {"type":"content_block_start","content_block":{"type":"tool_use","id":"toolu_1","name":"file_read"}}\n\n',- 'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\\"path\\":\\"README.md\\"}"}}\n\n',- 'event: message_stop\ndata: {"type":"message_stop"}\n\n',- ]-- it('never emits a tool call whose arguments the deltas could not reach', async () => {- vi.stubGlobal('fetch', vi.fn().mockResolvedValue(sse(PROXY_STREAM)))-- const chunks = await drain(new AnthropicProvider(config())- .chatStream('claude-sonnet-4-20250514', [{ role: 'user', content: 'read it' }]))-- const calls = chunks.flatMap(c => c.toolCalls ?? [])- // Der Schaden war nicht "ein Tool-Call fehlt", sondern "ein Tool-Call mit- // leeren Argumenten geht raus und wird ausgefuehrt". Beides wird hier- // benannt, damit ein spaeterer Umbau, der die Argumente wirklich- // einsammelt, diesen Test nicht falsch-positiv rot macht.- for (const call of calls) {- expect(Object.keys(call.function.arguments).length).toBeGreaterThan(0)+describe('a tool_use block arrives intact however the proxy numbers it', () => {+ // Alle drei Faelle tragen denselben Aufruf. Die Erwartung ist deshalb in+ // allen drei identisch — genau das ist die Aussage.+ const WANTED = { path: 'README.md' }+ const FRAGMENTS = ['{"path":', '"README.md"}']++ it('(a) start and deltas both carry an index — the shape Anthropic itself sends', async () => {+ const calls = await toolCallsOf([+ START_MESSAGE,+ blockStart('toolu_1', 'file_read', 0),+ jsonDelta(FRAGMENTS[0], 0),+ jsonDelta(FRAGMENTS[1], 0),+ STOP,+ ])++ expect(calls).toHaveLength(1)+ expect(calls[0].function.name).toBe('file_read')+ expect(calls[0].function.arguments).toEqual(WANTED)+ })++ it('(b) only the deltas carry one — the shape that used to go out with {}', async () => {+ const calls = await toolCallsOf([+ START_MESSAGE,+ blockStart('toolu_1', 'file_read'),+ jsonDelta(FRAGMENTS[0], 0),+ jsonDelta(FRAGMENTS[1], 0),+ STOP,+ ])++ expect(calls).toHaveLength(1)+ expect(calls[0].function.name).toBe('file_read')+ expect(calls[0].function.arguments).toEqual(WANTED)+ })++ it('(c) neither carries one — the shape the skip-guard silently dropped', async () => {+ const calls = await toolCallsOf([+ START_MESSAGE,+ blockStart('toolu_1', 'file_read'),+ jsonDelta(FRAGMENTS[0]),+ jsonDelta(FRAGMENTS[1]),+ STOP,+ ])++ expect(calls).toHaveLength(1)+ expect(calls[0].function.name).toBe('file_read')+ expect(calls[0].function.arguments).toEqual(WANTED)+ })++ it('never lets a tool call out with arguments the deltas could not reach', async () => {+ // Die Schadensform, unabhaengig von der Ursache: ein Aufruf mit leeren+ // Argumenten wird ausgefuehrt und scheitert am Tool, nicht am Provider.+ for (const startIndex of [0, undefined]) {+ for (const deltaIndex of [0, undefined]) {+ const calls = await toolCallsOf([+ blockStart('toolu_1', 'file_read', startIndex),+ jsonDelta('{"path":"README.md"}', deltaIndex),+ STOP,+ ])+ expect(+ calls.filter(c => Object.keys(c.function.arguments).length === 0),+ `start index ${startIndex}, delta index ${deltaIndex}`,+ ).toEqual([])+ }}- expect(calls.filter(c => Object.keys(c.function.arguments).length === 0)).toEqual([])})- it('still ends the turn cleanly instead of hanging on the orphaned block', async () => {- vi.stubGlobal('fetch', vi.fn().mockResolvedValue(sse(PROXY_STREAM)))+ it('keeps two unindexed tool blocks apart by their ids', async () => {+ // Der Grund, warum die Regel den `id` liest und nicht einfach hochzaehlt:+ // ein zweiter Start oeffnet einen zweiten Slot, seine Fragmente landen+ // dort und nicht im ersten.+ const calls = await toolCallsOf([+ blockStart('toolu_1', 'file_read'),+ jsonDelta('{"path":"a.md"}'),+ blockStart('toolu_2', 'file_write'),+ jsonDelta('{"path":"b.md"}'),+ STOP,+ ])++ expect(calls).toHaveLength(2)+ expect(calls.map(c => c.function.name)).toEqual(['file_read', 'file_write'])+ expect(calls.map(c => c.function.arguments)).toEqual([{ path: 'a.md' }, { path: 'b.md' }])+ })- const chunks = await drain(new AnthropicProvider(config())- .chatStream('claude-sonnet-4-20250514', [{ role: 'user', content: 'read it' }]))+ it('ends the turn cleanly and passes the rest of the stream through', async () => {+ const chunks = await chunksOf([+ START_MESSAGE,+ blockStart('toolu_1', 'file_read'),+ jsonDelta('{"path":"README.md"}', 0),+ STOP,+ ])const done = chunks.filter(c => c.done)expect(done).toHaveLength(1)expect(done[0].finishReason).toBe('stop')- // Die uebrigen Felder des Streams kommen unveraendert durch — der Guard- // sitzt am Tool-Block, nicht am Event.+ // Die uebrigen Felder kommen unveraendert durch — die Regel sitzt am+ // Tool-Block, nicht am Event.expect(done[0].promptEvalCount).toBe(11)})-- it('leaves the well-formed case alone — an indexed block still carries its arguments', async () => {- vi.stubGlobal('fetch', vi.fn().mockResolvedValue(sse([- 'event: content_block_start\ndata: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_1","name":"file_read"}}\n\n',- 'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\\"path\\":\\"README.md\\"}"}}\n\n',- 'event: message_stop\ndata: {"type":"message_stop"}\n\n',- ])))-- const calls = (await drain(new AnthropicProvider(config())- .chatStream('claude-sonnet-4-20250514', [{ role: 'user', content: 'read it' }])))- .flatMap(c => c.toolCalls ?? [])-- expect(calls).toHaveLength(1)- expect(calls[0].function.name).toBe('file_read')- expect(calls[0].function.arguments).toEqual({ path: 'README.md' })- })})describe('a 200 response whose body carries no content array', () => {diff --git a/src/api/providers/__tests__/ollama-ndjson-boundary.test.ts b/src/api/providers/__tests__/ollama-ndjson-boundary.test.tsnew file mode 100644index 00000000..8e61603c--- /dev/null+++ b/src/api/providers/__tests__/ollama-ndjson-boundary.test.ts@@ -0,0 +1,118 @@+/**+ * Die NDJSON-Grenze von `/api/chat` ist eine Grenze, keine Zusage.+ *+ * `parseNDJSONStream<T>` macht aus jedem `JSON.parse` ein `T` — per+ * Typzusicherung, ohne irgendetwas zu pruefen. Der Streaming-Pfad des+ * Ollama-Providers benannte dort eine handgeschriebene `OllamaChatChunk`-Form+ * und las danach `chunk.message?.tool_calls?.map(...)`. Auf dieser Route+ * antwortet aber nicht nur Ollama: llama.cpp-basierte Server, LiteLLM und+ * jeder selbstgebaute Proxy bedienen sie auch. Schickt einer davon+ * `tool_calls` als Objekt statt als Liste, ist `.map` keine Funktion und die+ * ganze Stream-Schleife reisst mit einem `TypeError` ab — mitten im Turn, mit+ * einer Meldung, die weder den Provider noch den Grund nennt.+ *+ * `parseOllamaChatChunk` in wire.ts gab es zu dem Zeitpunkt schon; es wurde+ * nur nirgends aufgerufen. Jetzt schon.+ *+ * Run: npx vitest run src/api/providers/__tests__/ollama-ndjson-boundary.test.ts+ */+import { describe, it, expect, vi, beforeEach } from 'vitest'+import type { ProviderConfig, ChatStreamChunk } from '../types'++vi.mock('../../backend', () => ({+ isTauri: () => false,+ localFetch: vi.fn(),+ localFetchStream: vi.fn(),+ ollamaUrl: (path: string) => `/api${path}`,+}))++import { OllamaProvider } from '../ollama-provider'+import { localFetchStream } from '../../backend'++const mockLocalFetchStream = localFetchStream as ReturnType<typeof vi.fn>++const config: ProviderConfig = {+ id: 'ollama', name: 'Ollama', enabled: true,+ baseUrl: 'http://localhost:11434', apiKey: '', isLocal: true,+}++/** Die NDJSON-Zeilen einmal durch den Provider laufen lassen. */+async function stream(lines: string[]): Promise<ChatStreamChunk[]> {+ mockLocalFetchStream.mockResolvedValueOnce(new Response(lines.join('\n') + '\n', { status: 200 }))+ const out: ChatStreamChunk[] = []+ for await (const c of new OllamaProvider(config)+ .chatStream('qwen2.5-coder:14b', [{ role: 'user', content: 'hi' }])) {+ out.push(c)+ }+ return out+}++beforeEach(() => {+ vi.clearAllMocks()+})++describe('a foreign /api/chat body cannot tear down the stream loop', () => {+ it('survives a tool_calls field that is not an array', async () => {+ const chunks = await stream([+ '{"message":{"content":"one moment","tool_calls":{"function":{"name":"file_read"}}},"done":false}',+ '{"message":{"content":""},"done":true,"done_reason":"stop"}',+ ])++ // Der Inhalt kommt an, der Turn endet sauber, und aus der unbrauchbaren+ // Form wird kein Tool-Call erfunden.+ expect(chunks.map(c => c.content).join('')).toBe('one moment')+ expect(chunks.flatMap(c => c.toolCalls ?? [])).toEqual([])+ expect(chunks.filter(c => c.done)).toHaveLength(1)+ })++ it('survives a message that is not an object', async () => {+ const chunks = await stream([+ '{"message":"just a string","done":false}',+ '{"message":{"content":"ok"},"done":true,"done_reason":"stop"}',+ ])++ expect(chunks.map(c => c.content).join('')).toBe('ok')+ expect(chunks.filter(c => c.done)).toHaveLength(1)+ })++ it('reports done as a real boolean, whatever the server put there', async () => {+ const chunks = await stream([+ '{"message":{"content":"hi"},"done":"true"}',+ ])++ // Frueher ging der String `"true"` als `done` durch den ChatStreamChunk —+ // typisiert als `boolean`, und jede `=== true`-Pruefung weiter oben las+ // ihn falsch. Ein Feld, das nicht das ist, was es zu sein behauptet,+ // beendet den Turn jetzt nicht mehr; der Abbruch faellt als+ // 'disconnect' auf, statt still als sauberes Ende durchzugehen.+ for (const c of chunks) expect(typeof c.done).toBe('boolean')+ expect(chunks[chunks.length - 1].finishReason).toBe('disconnect')+ })++ it('reports the server metrics as numbers, not as whatever arrived', async () => {+ const chunks = await stream([+ '{"message":{"content":"hi"},"done":true,"eval_count":"12","prompt_eval_count":7}',+ ])++ const last = chunks[chunks.length - 1]+ expect(last.evalCount).toBeUndefined()+ expect(last.promptEvalCount).toBe(7)+ })++ it('leaves a well-formed stream exactly as it was', async () => {+ const chunks = await stream([+ '{"message":{"content":"hel","thinking":"hm"},"done":false}',+ '{"message":{"content":"lo"},"done":false}',+ '{"message":{"content":""},"done":true,"done_reason":"stop","eval_count":3,"prompt_eval_count":9,"eval_duration":2000000}',+ ])++ expect(chunks.map(c => c.content).join('')).toBe('hello')+ expect(chunks.find(c => c.thinking)?.thinking).toBe('hm')+ const last = chunks[chunks.length - 1]+ expect(last.done).toBe(true)+ expect(last.finishReason).toBe('stop')+ expect(last.evalCount).toBe(3)+ expect(last.promptEvalCount).toBe(9)+ expect(last.evalDurationMs).toBe(2)+ })+})diff --git a/src/api/providers/__tests__/tool-arguments-stay-objects.test.ts b/src/api/providers/__tests__/tool-arguments-stay-objects.test.tsindex 5a2437f1..6ae4d57b 100644--- a/src/api/providers/__tests__/tool-arguments-stay-objects.test.ts+++ b/src/api/providers/__tests__/tool-arguments-stay-objects.test.ts@@ -1,8 +1,8 @@/*** Ein Tool-Call traegt seine `arguments` als JSON-TEXT ueber die Leitung, und* geschrieben hat den Text ein Sprachmodell. `JSON.parse` liefert darum nicht- * zwingend ein Objekt: `"null"` und `"42"` sind gueltiges JSON und beide kein- * `Record<string, …>`.+ * zwingend ein Objekt: `"null"`, `"42"` und `"[1,2]"` sind alle gueltiges JSON+ * und alle drei kein `Record<string, …>`.** Vor 0e740f60 prueften beide Provider das nur im REPARATURZWEIG. Der* Erfolgszweig gab zurueck, was `JSON.parse` produziert hatte, unter einer@@ -121,6 +121,20 @@ describe('openai-provider hands on an object even when the model sent none', ()expect(args).toEqual({})})+ // `typeof [] === 'object'`: der erste Anlauf des Fixes pruefte genau das und+ // liess ein Array durch — der Fall, den sein eigener Kommentar als abgedeckt+ // benannte. `isRecord` weist Arrays und `null` ab.+ it('turns a "[1,2]" arguments payload into an empty object', async () => {+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(openAIToolCallResponse('[1,2]')))++ const result = await new OpenAIProvider(openAIConfig())+ .chatWithTools('gpt-4o', [{ role: 'user', content: 'read it' }], [])++ const args = onlyCall(result.toolCalls).function.arguments+ expectPlainObject(args)+ expect(args).toEqual({})+ })+it('still passes a real object through untouched', async () => {vi.stubGlobal('fetch', vi.fn().mockResolvedValue(openAIToolCallResponse('{"path":"README.md"}'),@@ -195,6 +209,21 @@ describe('anthropic-provider hands on an object even when the model sent none',expect(args).toEqual({})})+ it('turns tool input that decodes to an array into an empty object', async () => {+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(sse([+ 'event: content_block_start\ndata: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_1","name":"file_read"}}\n\n',+ 'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"[1,2]"}}\n\n',+ 'event: message_stop\ndata: {"type":"message_stop"}\n\n',+ ])))++ const chunks = await drain(new AnthropicProvider(anthropicConfig())+ .chatStream('claude-sonnet-4-20250514', [{ role: 'user', content: 'read it' }]))++ const args = onlyCall(chunks.flatMap(c => c.toolCalls ?? [])).function.arguments+ expectPlainObject(args)+ expect(args).toEqual({})+ })+it('still assembles a real object out of its fragments', async () => {vi.stubGlobal('fetch', vi.fn().mockResolvedValue(sse(['event: content_block_start\ndata: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_1","name":"file_read"}}\n\n',diff --git a/src/api/providers/anthropic-provider.ts b/src/api/providers/anthropic-provider.tsindex df9a2eb4..1e5b73da 100644--- a/src/api/providers/anthropic-provider.ts+++ b/src/api/providers/anthropic-provider.ts@@ -22,7 +22,8 @@ import {hostnameOf, ensureProxyAllowsHost,} from '../backend'import {- parseAnthropicStreamEvent, parseAnthropicMessageResponse, isRecord, prop, asString,+ parseAnthropicStreamEvent, parseAnthropicMessageResponse, keyForUnindexedBlock,+ isRecord, prop, asString,} from './wire'// ── Anthropic API Types ────────────────────────────────────────@@ -403,13 +404,20 @@ export class AnthropicProvider implements ProviderClient {case 'content_block_start': {// `index` keys the accumulator that content_block_delta later// appends to. It used to be read through a non-null assertion, so- // an event without one silently opened a block under the key- // `undefined` — and every delta then looked it up under a real- // number and found nothing, dropping the whole tool call. Skipping- // the block is the same outcome the lookup already produced, minus- // the poisoned map entry.- if (data.content_block?.type === 'tool_use' && data.index !== undefined) {- toolUseBlocks.set(data.index, {+ // an event without one opened a block under the key `undefined`,+ // and a delta that DID carry an index found nothing there — the+ // tool call went out with `{}` arguments.+ //+ // Proxies that omit the field are the reason this provider needs a+ // rule rather than an assertion (see messagesUrl). Skipping the+ // block was not that rule: it fixed the mixed stream and broke the+ // consistent one, where start and deltas BOTH leave the index out+ // and the old code — accidentally, both sides keyed on `undefined`+ // — got the call through intact. `keyForUnindexedBlock` is the+ // rule, and it is the same one the OpenAI accumulator uses.+ if (data.content_block?.type === 'tool_use') {+ const key = data.index ?? keyForUnindexedBlock(toolUseBlocks, data.content_block.id)+ toolUseBlocks.set(key, {id: data.content_block.id || '',name: data.content_block.name || '',input: '',@@ -427,8 +435,11 @@ export class AnthropicProvider implements ProviderClient {// Claude Extended Thinking stream — route to `thinking` so the// ThinkingBlock UI picks it up (same field as Ollama's native).yield { content: '', thinking: delta.thinking, done: false }- } else if (dtype === 'input_json_delta' && delta?.partial_json && data.index !== undefined) {- const block = toolUseBlocks.get(data.index)+ } else if (dtype === 'input_json_delta' && delta?.partial_json) {+ // Ohne `index` ist es das Fragment des Blocks, der gerade+ // gefuellt wird — dieselbe Regel wie oben, dieselbe Funktion.+ const key = data.index ?? keyForUnindexedBlock(toolUseBlocks)+ const block = toolUseBlocks.get(key)if (block) block.input += delta.partial_json}break@@ -690,11 +701,13 @@ export class AnthropicProvider implements ProviderClient {// `input` is JSON text assembled from input_json_delta fragments. It can// decode to a non-object (a truncated stream, or a model that emitted// `null`) — the old annotation promised a Record and would have handed- // `null` straight to the tool dispatcher.+ // `null` straight to the tool dispatcher. `isRecord` and not a bare+ // `typeof … === 'object'`: that one is true for an array too, so `[1,2]`+ // would still have arrived as "the arguments".let args: Record<string, unknown> = {}try {const parsed: unknown = JSON.parse(block.input)- if (parsed && typeof parsed === 'object') args = parsed as Record<string, unknown>+ if (isRecord(parsed)) args = parsed} catch { /* empty */ }calls.push({diff --git a/src/api/providers/ollama-provider.ts b/src/api/providers/ollama-provider.tsindex 850cd540..db4c1c36 100644--- a/src/api/providers/ollama-provider.ts+++ b/src/api/providers/ollama-provider.ts@@ -15,8 +15,7 @@ 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'-import type { OllamaWireToolCall } from './wire'-import { isRecord, prop, asString, asNumber, asRecordArray } from './wire'+import { parseOllamaChatChunk, isRecord, prop, asString, asNumber, asRecordArray } from './wire'// ── Ollama-specific types ──────────────────────────────────────@@ -52,20 +51,14 @@ export interface OllamaChatRequest {think?: boolean}-interface OllamaChatChunk {- message?: { content?: string; thinking?: string; tool_calls?: OllamaWireToolCall[] }- done?: boolean- // Why generation ended ('stop' | 'length' | 'load' | …), final chunk only.- done_reason?: string- // Server-reported timing in the final done:true chunk (Bug M v2.4.7).- // Ollama returns nanoseconds; we convert to ms before yielding upstream.- eval_count?: number // tokens the model produced- eval_duration?: number // generation phase in nanoseconds- prompt_eval_count?: number // tokens in the prompt (unused for tps)- prompt_eval_duration?: number- total_duration?: number- load_duration?: number-}+// Was auf dieser Route ZURUECKKOMMT, liegt als `OllamaChatChunk` in ./wire,+// hinter `parseOllamaChatChunk`. Hier stand dieselbe Form ein zweites Mal —+// als Typargument an `parseNDJSONStream`, also als BEHAUPTUNG ueber+// `JSON.parse`, mit drei Feldern (`prompt_eval_duration`, `total_duration`,+// `load_duration`), die diese Datei nie gelesen hat. Die sieben, die sie+// liest, kommen jetzt geprueft aus dem Parser. Dass das ueberhaupt auffiel:+// `tool_calls` wurde direkt `.map`-t, ein Server, der dort kein Array+// schickt, riss die ganze Stream-Schleife mit einem TypeError auf.interface OllamaModelEntry {name: string@@ -218,18 +211,20 @@ export class OllamaProvider implements ProviderClient {})try {- for await (const chunk of parseNDJSONStream<OllamaChatChunk>(res, {+ for await (const raw of parseNDJSONStream<unknown>(res, {idleMs: STREAM_IDLE_TIMEOUT_MS,onIdle: guard.abort,})) {if (options?.signal?.aborted) break+ const chunk = parseOllamaChatChunk(raw)// 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}`)+ // chat turn (rikki Discord 2026-06-10, Win11 proxy path). `error`+ // kommt als `string | undefined` aus dem Parser, der `typeof`-Test+ // von frueher sass auf einem `unknown` aus einer Typzusicherung.+ if (chunk.error) {+ throw new Error(`Ollama: ${chunk.error}`)}// `arguments` arrives as `unknown` from the wire because Ollama isdiff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.tsindex d834f3e4..444eb93e 100644--- a/src/api/providers/openai-provider.ts+++ b/src/api/providers/openai-provider.ts@@ -24,8 +24,8 @@ import { localFetch, localFetchStream, isPrivateOrLanHost, isDirectFetchAllowed,import { ensureBuiltinEngineAlive, explainDeadEngine, explainEngineTransportMessage, isManagedBuiltinSlot } from '../builtin-ensure'import { applyTemplateContract } from './normalize-system'import {- parseOpenAIStreamChunk, parseOpenAIChatResponse,- prop, asString, asNumber, asBoolean, asRecordArray,+ parseOpenAIStreamChunk, parseOpenAIChatResponse, keyForUnindexedBlock,+ isRecord, prop, asString, asNumber, asBoolean, asRecordArray,} from './wire'// Transport routing lives in the `useLocalProxy` getter (below) plus the shared@@ -41,7 +41,7 @@ import {// declared here as two hand-rolled interfaces asserted onto `JSON.parse` and// `res.json()`, and both said things the code itself knew to be false: the// tool-call delta declared `index: number` as required while the accumulator-// right below it falls back to `keyForUnindexedDelta` precisely because+// right below it falls back to `keyForUnindexedBlock` precisely because// servers omit it, and `choices` was typed as a one-element tuple./**@@ -220,25 +220,6 @@ 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.- * A delta carrying a fresh id opens the next slot; anything else continues the- * call currently being filled.- */-function keyForUnindexedDelta(- accum: Map<number, { id: string; name: string; args: string }>,- id?: string,-): number {- if (id) {- for (const [key, call] of accum) {- if (call.id === id) return key- }- return accum.size- }- return Math.max(0, accum.size - 1)-}-/*** Flat token cost charged for one inline image during prompt estimation.*@@ -752,7 +733,7 @@ export class OpenAIProvider implements ProviderClient {// Accumulate streamed tool callsif (choice.delta?.tool_calls) {for (const tc of choice.delta.tool_calls) {- const key = tc.index ?? keyForUnindexedDelta(toolCallAccum, tc.id)+ const key = tc.index ?? keyForUnindexedBlock(toolCallAccum, tc.id)const existing = toolCallAccum.get(key)if (existing) {// id and name do NOT always arrive in the first delta — several@@ -1257,22 +1238,27 @@ export class OpenAIProvider implements ProviderClient {/*** A tool call's `arguments` is a JSON *string* on the wire and the caller is- * a language model, so nothing guarantees it decodes to an object. The- * happy path used to return whatever JSON.parse produced under a+ * a language model, so nothing guarantees it decodes to an object. The happy+ * path used to return whatever JSON.parse produced under a* `Record<string, any>` annotation — `"null"` therefore handed `null` to- * every downstream `args.foo` read, and `"[1,2]"` / `"42"` handed on a- * value with none of the promised keys. Both branches now apply the same- * object check the repair branch always had.+ * every downstream `args.foo` read, and `"[1,2]"` / `"42"` handed on a value+ * with none of the promised keys.+ *+ * Both branches now go through `isRecord`, and that is deliberately NOT the+ * check the repair branch used to have: `typeof [] === 'object'`, so+ * `parsed && typeof parsed === 'object'` let an ARRAY through — the very+ * `"[1,2]"` this comment named as covered while it was not. Arrays and null+ * are rejected here; only something indexable by name leaves.*/private safeParseArgs(args: string): Record<string, unknown> {try {const parsed: unknown = JSON.parse(args)- if (parsed && typeof parsed === 'object') return parsed as Record<string, unknown>+ if (isRecord(parsed)) return parsed} catch {// fall through to the repair path below}const repaired: unknown = repairJson(args)- return repaired && typeof repaired === 'object' ? repaired as Record<string, unknown> : {}+ return isRecord(repaired) ? repaired : {}}// ── Error parsing ────────────────────────────────────────────diff --git a/src/api/providers/wire.ts b/src/api/providers/wire.tsindex f430a574..c158a84f 100644--- a/src/api/providers/wire.ts+++ b/src/api/providers/wire.ts@@ -57,6 +57,46 @@ export function asStringArray(v: unknown): string[] {return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []}+// ── Streamed tool-call accumulators ────────────────────────────++/**+ * Which accumulator slot a streamed tool-call block belongs to when the server+ * left out the `index` that is supposed to identify it.+ *+ * Both streaming protocols in this file number their tool-call blocks, and+ * both are served by things that do not: OpenAI-compatible servers omit+ * `index` on a tool_call delta, Anthropic-compatible proxies (LiteLLM,+ * claude-relay-server) omit it on `content_block_start`. The rule is the same+ * on both, which is why this lives here and not twice in two providers:+ *+ * an event carrying an id → the slot already holding that id, else a new one+ * an event carrying none → the slot currently being filled+ *+ * It maps onto both wire formats because both put the id on the event that+ * OPENS a call and leave it off the ones that continue it — OpenAI on the+ * first delta, Anthropic on `content_block_start`.+ *+ * Reading a missing index as an assertion instead was a real outage on both+ * sides: `set(undefined)` opened a block under a key no lookup would ever+ * produce, and the whole tool call went out with `{}` arguments.+ *+ * Limit, and the same one on both providers: a stream that omits BOTH the+ * index and the id can only be read as one call at a time. A second block+ * opened that way continues the first instead of starting its own.+ */+export function keyForUnindexedBlock<T extends { id: string }>(+ accum: ReadonlyMap<number, T>,+ id?: string,+): number {+ if (id) {+ for (const [key, call] of accum) {+ if (call.id === id) return key+ }+ return accum.size+ }+ return Math.max(0, accum.size - 1)+}+// ── Ollama: /api/chat ──────────────────────────────────────────/**