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.

test(M-any): die sieben Provider-Funde festnageln, jeder mit Mutationssonde

David972053753da8
diff --git a/src-tauri/src/commands/bg_tasks.rs b/src-tauri/src/commands/bg_tasks.rs
index 40bbf358..40852de5 100644
--- a/src-tauri/src/commands/bg_tasks.rs
+++ b/src-tauri/src/commands/bg_tasks.rs
@@ -1128,10 +1128,15 @@ mod foreground_parity_tests {
/// A directory both runs can start in, so neither path has to fall back to
/// the per-chat workspace and touch the user's home.
- fn a_directory() -> std::path::PathBuf {
- let d = std::env::temp_dir().join(format!("lu-parity-{}", std::process::id()));
- std::fs::create_dir_all(&d).expect("temp dir");
- d
+ ///
+ /// `os_paths::test_dir` statt eines selbstgebauten `temp_dir().join(…)`:
+ /// das Aufräumen hängt dort am `Drop` und läuft deshalb auch dann, wenn
+ /// eine der Assertions dazwischen scheitert — die letzte Zeile des Tests
+ /// tat das nicht, und genau im Fehlerfall blieb der Ordner liegen. Der
+ /// Name trägt zusätzlich die ThreadId, und unter Windows liegt er unter
+ /// `target/`, wo ein `cargo clean` ihn erwischt.
+ fn a_directory() -> crate::os_paths::TestDir {
+ crate::os_paths::test_dir("parity")
}
async fn what_the_foreground_printed(dir: &std::path::Path) -> (String, i64) {
@@ -1215,8 +1220,8 @@ mod foreground_parity_tests {
"the same command in the same shell came out differently on the two paths",
);
assert_eq!((fg_code, bg_code), (0, 0), "one of the two paths failed");
-
- let _ = std::fs::remove_dir_all(&dir);
+ // Kein `remove_dir_all` mehr: `dir` ist ein `TestDir` und räumt beim
+ // Verlassen selbst auf, auch wenn eine Assertion oben vorher panickt.
}
/// The structural half: this file must not grow a second copy of the
diff --git a/src/api/providers/__tests__/anthropic-proxy-shapes.test.ts b/src/api/providers/__tests__/anthropic-proxy-shapes.test.ts
new file mode 100644
index 00000000..6f3d38a8
--- /dev/null
+++ b/src/api/providers/__tests__/anthropic-proxy-shapes.test.ts
@@ -0,0 +1,173 @@
+/**
+ * Zwei Formen, die nur ein PROXY schickt — und genau Proxys unterstuetzt
+ * dieser Provider ausdruecklich: `messagesUrl()` raeumt fuer sie ein doppeltes
+ * `/v1` weg, `useLocalProxy` schickt sie ueber den Rust-Proxy, und der
+ * Cache-Kommentar nennt LiteLLM, claude-relay-server und opencode-zen beim
+ * 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.
+ *
+ * 2. Eine 200er-Antwort OHNE `content`.
+ * `const data: AnthropicResponse = await res.json()` behauptete das Feld
+ * und die Schleife darunter iterierte es sofort. Ein Proxy, der einen
+ * Fehler als HTTP 200 mit Fehler-Body durchreicht, brach damit als nackter
+ * `TypeError` aus dem Provider — ohne Provider-Namen, ohne Status, ohne
+ * irgendetwas, woran der Chat-Layer eine Erklaerung haette aufhaengen
+ * koennen.
+ *
+ * Run: npx vitest run src/api/providers/__tests__/anthropic-proxy-shapes.test.ts
+ */
+import { describe, it, expect, vi, afterEach } from 'vitest'
+import { AnthropicProvider } from '../anthropic-provider'
+import type { ProviderConfig, ChatStreamChunk } 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
+// ANTWORT ist das Proxy-Verhalten, das dieser Test beschreibt; ueber welchen
+// Transport sie kommt, ist dafuer unerheblich.
+function config(): ProviderConfig {
+ return {
+ id: 'anthropic', name: 'Anthropic', enabled: true,
+ baseUrl: 'https://api.anthropic.com', apiKey: 'sk-ant-test', isLocal: false,
+ }
+}
+
+function sse(events: string[]): Response {
+ return new Response(events.join(''), {
+ status: 200, headers: { 'Content-Type': 'text/event-stream' },
+ })
+}
+
+async function drain(gen: AsyncGenerator<ChatStreamChunk>): Promise<ChatStreamChunk[]> {
+ const out: ChatStreamChunk[] = []
+ for await (const c of gen) out.push(c)
+ return out
+}
+
+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)
+ }
+ 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)))
+
+ const chunks = await drain(new AnthropicProvider(config())
+ .chatStream('claude-sonnet-4-20250514', [{ role: 'user', content: 'read it' }]))
+
+ 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.
+ 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', () => {
+ it('yields an empty turn instead of throwing a bare TypeError', async () => {
+ // Die Form, die ein Relay durchreicht, wenn es upstream einen Fehler
+ // bekommt, aber selbst schon mit 200 geantwortet hat.
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(
+ JSON.stringify({ type: 'error', error: { type: 'api_error', message: 'upstream said no' } }),
+ { status: 200 },
+ )))
+
+ const result = await new AnthropicProvider(config()).chatWithTools(
+ 'claude-sonnet-4-20250514',
+ [{ role: 'user', content: 'hi' }],
+ [],
+ )
+
+ expect(result.content).toBe('')
+ expect(result.toolCalls).toEqual([])
+ })
+
+ it('does the same for a body that is not an object at all', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('null', { status: 200 })))
+
+ const result = await new AnthropicProvider(config()).chatWithTools(
+ 'claude-sonnet-4-20250514',
+ [{ role: 'user', content: 'hi' }],
+ [],
+ )
+
+ expect(result.content).toBe('')
+ expect(result.toolCalls).toEqual([])
+ })
+
+ it('a body WITH content is still read the way it always was', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({
+ content: [
+ { type: 'text', text: 'here you go' },
+ { type: 'tool_use', id: 'toolu_1', name: 'file_read', input: { path: 'README.md' } },
+ ],
+ usage: { input_tokens: 7, output_tokens: 3 },
+ }), { status: 200 })))
+
+ const result = await new AnthropicProvider(config()).chatWithTools(
+ 'claude-sonnet-4-20250514',
+ [{ role: 'user', content: 'hi' }],
+ [],
+ )
+
+ expect(result.content).toBe('here you go')
+ expect(result.toolCalls).toHaveLength(1)
+ expect(result.toolCalls[0].function).toEqual({
+ name: 'file_read', arguments: { path: 'README.md' },
+ })
+ expect(result.promptEvalCount).toBe(7)
+ })
+})
diff --git a/src/api/providers/__tests__/ollama-tool-args-parity.test.ts b/src/api/providers/__tests__/ollama-tool-args-parity.test.ts
new file mode 100644
index 00000000..b0b76b0b
--- /dev/null
+++ b/src/api/providers/__tests__/ollama-tool-args-parity.test.ts
@@ -0,0 +1,137 @@
+/**
+ * Ollamas zwei Tool-Pfade muessen aus derselben Antwort dasselbe machen.
+ *
+ * `chatWithTools` (nicht streamend) schickt `tc.function.arguments` seit
+ * jeher durch `repairToolCallArgs`. `chatStream` tat das nicht: es reichte
+ * den Wert roh durch, unter der Annotation `Record<string, any>`. Auf dieser
+ * Route antwortet aber nicht nur Ollama selbst — llama.cpp-basierte und
+ * vorgeschaltete Server schicken `arguments` als JSON-STRING, und ein Modell
+ * schickt auch mal ein Objekt mit Schleppkomma. Der eine Pfad reparierte das,
+ * der andere gab die Zeichenkette an den Tool-Dispatcher weiter.
+ *
+ * Deshalb ist das hier EIN Paritaetstest und nicht zwei Einzeltests: die
+ * Aussage ist nicht "chatStream repariert", sondern "welchen der beiden Wege
+ * ein Turn nimmt, darf am Ergebnis nichts aendern". Die Erwartung wird nicht
+ * hingeschrieben, sondern aus dem etablierten Pfad GEHOLT und mit dem anderen
+ * verglichen — waere `repairToolCallArgs` eines Tages etwas anderes, zoege der
+ * Test mit, ohne die Paritaet aufzugeben.
+ *
+ * Run: npx vitest run src/api/providers/__tests__/ollama-tool-args-parity.test.ts
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import type { ProviderConfig, ToolCall, ToolDefinition } from '../types'
+
+vi.mock('../../backend', () => ({
+ isTauri: () => false,
+ localFetch: vi.fn(),
+ localFetchStream: vi.fn(),
+ ollamaUrl: (path: string) => `/api${path}`,
+}))
+
+import { OllamaProvider } from '../ollama-provider'
+import { localFetch, localFetchStream } from '../../backend'
+
+const mockLocalFetch = localFetch as ReturnType<typeof vi.fn>
+const mockLocalFetchStream = localFetchStream as ReturnType<typeof vi.fn>
+
+const config: ProviderConfig = {
+ id: 'ollama', name: 'Ollama', enabled: true,
+ baseUrl: 'http://localhost:11434', apiKey: '', isLocal: true,
+}
+
+const TOOLS: ToolDefinition[] = [{
+ type: 'function',
+ function: {
+ name: 'file_read',
+ description: 'read a file',
+ parameters: { type: 'object', properties: { path: { type: 'string', description: 'path' } }, required: ['path'] },
+ },
+}]
+
+/** Der eine Tool-Call, oder ein lautes Scheitern statt eines `undefined`,
+ * das sich anschliessend mit einem zweiten `undefined` vergleichen liesse. */
+function onlyCall(calls: ToolCall[], path: string): ToolCall {
+ if (calls.length !== 1) {
+ throw new Error(`${path}: erwartet genau ein Tool-Call, bekommen ${calls.length}`)
+ }
+ return calls[0]
+}
+
+/** Was der STREAMENDE Pfad aus diesem `arguments`-Wert macht. */
+async function throughChatStream(rawArguments: unknown): Promise<ToolCall> {
+ mockLocalFetchStream.mockResolvedValueOnce(new Response(
+ JSON.stringify({
+ message: { content: '', tool_calls: [{ function: { name: 'file_read', arguments: rawArguments } }] },
+ done: false,
+ }) + '\n' +
+ JSON.stringify({ message: { content: '' }, done: true, done_reason: 'stop' }) + '\n',
+ { status: 200 },
+ ))
+
+ const calls: ToolCall[] = []
+ for await (const chunk of new OllamaProvider(config)
+ .chatStream('qwen2.5-coder:14b', [{ role: 'user', content: 'read it' }])) {
+ if (chunk.toolCalls) calls.push(...chunk.toolCalls)
+ }
+ return onlyCall(calls, 'chatStream')
+}
+
+/** Was der NICHT-streamende Pfad aus demselben Wert macht. */
+async function throughChatWithTools(rawArguments: unknown): Promise<ToolCall> {
+ mockLocalFetch.mockResolvedValueOnce(new Response(JSON.stringify({
+ message: { content: '', tool_calls: [{ function: { name: 'file_read', arguments: rawArguments } }] },
+ done: true,
+ }), { status: 200 }))
+
+ const result = await new OllamaProvider(config)
+ .chatWithTools('qwen2.5-coder:14b', [{ role: 'user', content: 'read it' }], TOOLS)
+ return onlyCall(result.toolCalls, 'chatWithTools')
+}
+
+/**
+ * Die eigentliche Aussage: ein und derselbe Wert, beide Pfade, ein Ergebnis.
+ * Der Vergleich laeuft ueber `toEqual`, damit ein String und ein Objekt mit
+ * demselben Text NICHT als gleich durchgehen.
+ */
+async function bothPathsAgree(rawArguments: unknown): Promise<Record<string, unknown>> {
+ const streamed = await throughChatStream(rawArguments)
+ const direct = await throughChatWithTools(rawArguments)
+
+ expect(streamed.function.name).toBe(direct.function.name)
+ expect(streamed.function.arguments).toEqual(direct.function.arguments)
+ return direct.function.arguments
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+})
+
+describe('the streaming and the non-streaming Ollama tool path agree', () => {
+ it('agrees on arguments that arrived as a JSON string instead of an object', async () => {
+ const args = await bothPathsAgree('{"path":"notes.md"}')
+ // Und zwar auf dem geparsten Objekt — nicht darauf, dass beide dieselbe
+ // Zeichenkette durchreichen. Ohne diese Zeile bestuende der Test auch,
+ // wenn BEIDE Pfade kaputt waeren.
+ expect(args).toEqual({ path: 'notes.md' })
+ })
+
+ it('agrees on a JSON string a small model left a trailing comma in', async () => {
+ const args = await bothPathsAgree('{"path": "notes.md",}')
+ expect(args).toEqual({ path: 'notes.md' })
+ })
+
+ it('agrees on a single-quoted blob, the other shape repairJson exists for', async () => {
+ const args = await bothPathsAgree("{'path': 'notes.md'}")
+ expect(args).toEqual({ path: 'notes.md' })
+ })
+
+ it('agrees on a string that is not repairable at all', async () => {
+ const args = await bothPathsAgree('not-json-at-all')
+ expect(args).toEqual({})
+ })
+
+ it('agrees on a proper object, and leaves it untouched on both paths', async () => {
+ const args = await bothPathsAgree({ path: 'notes.md' })
+ expect(args).toEqual({ path: 'notes.md' })
+ })
+})
diff --git a/src/api/providers/__tests__/tool-arguments-stay-objects.test.ts b/src/api/providers/__tests__/tool-arguments-stay-objects.test.ts
new file mode 100644
index 00000000..5a2437f1
--- /dev/null
+++ b/src/api/providers/__tests__/tool-arguments-stay-objects.test.ts
@@ -0,0 +1,212 @@
+/**
+ * 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, …>`.
+ *
+ * Vor 0e740f60 prueften beide Provider das nur im REPARATURZWEIG. Der
+ * Erfolgszweig gab zurueck, was `JSON.parse` produziert hatte, unter einer
+ * `Record<string, any>`-Annotation:
+ *
+ * openai-provider.safeParseArgs `try { return JSON.parse(args) }`
+ * anthropic-provider.flushToolUseBlocks `try { args = JSON.parse(…) }`
+ *
+ * `null` ging damit an jedes nachgelagerte `args.foo` (TypeError im
+ * Tool-Dispatcher, nicht im Provider — also weit weg von der Ursache), und
+ * `42` an einen Aufruf, der Schluessel erwartet.
+ *
+ * Beide Faelle werden hier ueber einen ECHTEN Provider-Aufruf mit gemocktem
+ * `fetch` gefahren, nicht ueber die private Methode: was der Provider nach
+ * aussen gibt, ist das, was der Tool-Loop bekommt.
+ *
+ * Run: npx vitest run src/api/providers/__tests__/tool-arguments-stay-objects.test.ts
+ */
+import { describe, it, expect, vi, afterEach } from 'vitest'
+import { OpenAIProvider } from '../openai-provider'
+import { AnthropicProvider } from '../anthropic-provider'
+import type { ProviderConfig, ChatStreamChunk, ToolCall } from '../types'
+
+// api.openai.com und api.anthropic.com stehen beide auf der gepinnten
+// CSP-Liste, also nimmt der Provider den direkten `fetch` — genau den, den
+// `vi.stubGlobal` hier ersetzt. Ein Fantasie-Host wuerde ueber localFetch
+// laufen und das Setup vom `window`-Stub abhaengig machen.
+function openAIConfig(): ProviderConfig {
+ return {
+ id: 'openai', name: 'OpenAI', enabled: true,
+ baseUrl: 'https://api.openai.com/v1', apiKey: 'sk-test', isLocal: false,
+ }
+}
+
+function anthropicConfig(): ProviderConfig {
+ return {
+ id: 'anthropic', name: 'Anthropic', enabled: true,
+ baseUrl: 'https://api.anthropic.com', apiKey: 'sk-ant-test', isLocal: false,
+ }
+}
+
+/** Eine nicht-streamende OpenAI-Antwort mit genau einem Tool-Call. */
+function openAIToolCallResponse(args: string): Response {
+ return new Response(JSON.stringify({
+ choices: [{
+ message: {
+ content: '',
+ tool_calls: [{
+ id: 'call_1', type: 'function',
+ function: { name: 'file_read', arguments: args },
+ }],
+ },
+ finish_reason: 'tool_calls',
+ }],
+ }), { status: 200 })
+}
+
+function sse(events: string[]): Response {
+ return new Response(events.join(''), {
+ status: 200, headers: { 'Content-Type': 'text/event-stream' },
+ })
+}
+
+async function drain(gen: AsyncGenerator<ChatStreamChunk>): Promise<ChatStreamChunk[]> {
+ const out: ChatStreamChunk[] = []
+ for await (const c of gen) out.push(c)
+ return out
+}
+
+/** Der eine Tool-Call, oder ein lautes Scheitern — `[0]` auf einer leeren
+ * Liste wuerde die Assertion sonst in `undefined` aufloesen. */
+function onlyCall(calls: ToolCall[]): ToolCall {
+ if (calls.length !== 1) {
+ throw new Error(`erwartet: genau ein Tool-Call, bekommen: ${calls.length}`)
+ }
+ return calls[0]
+}
+
+/**
+ * Die Behauptung, die der alte Erfolgszweig gebrochen hat: was rauskommt, ist
+ * indizierbar. `Object.keys(null)` wirft, `Object.keys(42)` nicht — deshalb
+ * steht die Typpruefung daneben und nicht nur der `toEqual`-Vergleich.
+ */
+function expectPlainObject(args: Record<string, unknown>): void {
+ expect(args).not.toBeNull()
+ expect(typeof args).toBe('object')
+ expect(Array.isArray(args)).toBe(false)
+ expect(() => Object.keys(args)).not.toThrow()
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+})
+
+describe('openai-provider hands on an object even when the model sent none', () => {
+ it('turns a "null" arguments payload into an empty object, not into null', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(openAIToolCallResponse('null')))
+
+ 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('turns a "42" arguments payload into an empty object', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(openAIToolCallResponse('42')))
+
+ 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"}'),
+ ))
+
+ const result = await new OpenAIProvider(openAIConfig())
+ .chatWithTools('gpt-4o', [{ role: 'user', content: 'read it' }], [])
+
+ expect(onlyCall(result.toolCalls).function.arguments).toEqual({ path: 'README.md' })
+ })
+
+ // Der Streaming-Pfad sammelt `arguments` erst aus Fragmenten zusammen und
+ // schickt das Ergebnis durch dieselbe Methode — dieselbe Pruefung muss dort
+ // greifen, sonst haengt sie an der zufaellig gewaehlten Transportart.
+ it('applies the same check to the streamed tool-call accumulator', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response([
+ 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","function":{"name":"file_read","arguments":"nu"}}]}}]}\n\n',
+ 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"ll"}}]}}]}\n\n',
+ 'data: {"choices":[{"delta":{},"finish_reason":"tool_calls"}]}\n\n',
+ 'data: [DONE]\n\n',
+ ].join(''), { status: 200 })))
+
+ const chunks = await drain(new OpenAIProvider(openAIConfig())
+ .chatStream('gpt-4o', [{ role: 'user', content: 'read it' }], {
+ tools: [{
+ type: 'function',
+ function: {
+ name: 'file_read', description: 'read',
+ parameters: { type: 'object', properties: {}, required: [] },
+ },
+ }],
+ }))
+
+ const args = onlyCall(chunks.flatMap(c => c.toolCalls ?? [])).function.arguments
+ expectPlainObject(args)
+ expect(args).toEqual({})
+ })
+})
+
+describe('anthropic-provider hands on an object even when the model sent none', () => {
+ // `input_json_delta` kommt in Fragmenten. Hier buchstabieren die Fragmente
+ // zusammen `null` — gueltiges JSON, aber kein Objekt.
+ it('turns tool input that decodes to null 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":"nu"}}\n\n',
+ 'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"ll"}}\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 call = onlyCall(chunks.flatMap(c => c.toolCalls ?? []))
+ expect(call.function.name).toBe('file_read')
+ expectPlainObject(call.function.arguments)
+ expect(call.function.arguments).toEqual({})
+ })
+
+ it('turns tool input that decodes to a number 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":"42"}}\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',
+ 'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\\"path\\":"}}\n\n',
+ 'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"\\"README.md\\"}"}}\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' }]))
+
+ expect(onlyCall(chunks.flatMap(c => c.toolCalls ?? [])).function.arguments)
+ .toEqual({ path: 'README.md' })
+ })
+})
diff --git a/src/hooks/__tests__/useCodex-path-resolution.test.ts b/src/hooks/__tests__/useCodex-path-resolution.test.ts
index fc9926b1..3c6f78a6 100644
--- a/src/hooks/__tests__/useCodex-path-resolution.test.ts
+++ b/src/hooks/__tests__/useCodex-path-resolution.test.ts
@@ -131,3 +131,64 @@ describe('useCodex path-resolution drift detection', () => {
expect(src).not.toContain("!p.startsWith('C:') && !p.startsWith('\\\\\\\\')")
})
})
+
+// ────────────────────────────────────────────────────────────────────────
+// `toolArgs.path` ist Modell-Ausgabe, keine Zusage (0e740f60).
+//
+// Derselbe Block wie oben, eine Zeile hoeher: `const p: string =
+// toolArgs.path` war eine BEHAUPTUNG ueber das, was das Modell geschickt hat.
+// Ein Tool-Call `{"path": 42}` — bei kleinen Modellen keine Seltenheit — ging
+// ungeprueft in `p.startsWith(…)` und warf einen TypeError aus der
+// Tool-SCHLEIFE heraus, also nicht am Tool vorbei, sondern am ganzen Turn.
+// Der Fix ist der `typeof`-Guard an der oeffnenden Bedingung; die Zahl
+// erreicht damit das Tool, das sie mit seiner eigenen Meldung ablehnt.
+//
+// Was dieser Test ist und was nicht: er liest die QUELLE, so wie die
+// Drift-Erkennung darueber. Ein Test, der den echten Tool-Loop faehrt, gibt
+// es hier nicht — useCodex ist ein React-Hook, die vitest-Umgebung ist `node`
+// (keine DOM), und weder @testing-library/react noch react-test-renderer sind
+// Abhaengigkeiten dieses Projekts. Keine der 25 Dateien in diesem Verzeichnis
+// rendert einen Hook; alle pruefen entweder ausgelagerte Logik oder den
+// Quelltext. Diese Sonde ist damit ein Pin gegen das Zuruecknehmen des
+// Guards, kein Verhaltensbeweis — und sie ist als solcher benannt.
+// ────────────────────────────────────────────────────────────────────────
+
+/**
+ * Die Bedingung, unter der useCodex `toolArgs.path` als Zeichenkette liest —
+ * aus der Quelle GEHOLT, nicht abgeschrieben. Verschwindet die gelesene Zeile,
+ * scheitert der Test hier laut, statt still auf einer leeren Zeichenkette
+ * weiterzulaufen.
+ */
+function theConditionGuardingThePathRead(source: string): string {
+ const lines = source.split('\n')
+ // Verankert am Zeilenanfang: der Kommentar direkt darueber ZITIERT die alte
+ // Fassung derselben Zeile, und ein `includes` fände ihn zuerst.
+ const at = lines.findIndex(l => /^\s*const p: string = toolArgs\.path\b/.test(l))
+ if (at < 0) {
+ throw new Error(
+ 'useCodex.ts liest `toolArgs.path` nicht mehr ueber `const p: string` — ' +
+ 'dieser Test muss mit dem Umbau mitziehen statt stumm gruen zu bleiben',
+ )
+ }
+ for (let i = at - 1; i >= 0 && at - i <= 5; i--) {
+ if (/^\s*if \(/.test(lines[i])) return lines[i]
+ }
+ throw new Error('ueber dem Pfad-Zugriff steht keine `if`-Zeile mehr')
+}
+
+describe('useCodex treats a model-supplied path as a string only when it is one', () => {
+ const src = readFileSync(
+ join(dirname(fileURLToPath(import.meta.url)), '../useCodex.ts'),
+ 'utf8',
+ )
+
+ it('opens the path-rewrite branch behind a typeof check, not behind an annotation', () => {
+ expect(theConditionGuardingThePathRead(src)).toContain("typeof toolArgs.path === 'string'")
+ })
+
+ it('keeps the empty-string skip the old truthiness guard already had', () => {
+ // `''` ist ein String und wuerde den typeof-Test passieren; ohne die
+ // Truthiness daneben haenge workDir sich an einen leeren Pfad.
+ expect(theConditionGuardingThePathRead(src)).toMatch(/typeof toolArgs\.path === 'string' && toolArgs\.path/)
+ })
+})