Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(chat): tool calls broke when a server sent the id or name a chunk late

purpledecaafba2599
diff --git a/src/api/__tests__/provider-toolcall-deltas.test.ts b/src/api/__tests__/provider-toolcall-deltas.test.ts
new file mode 100644
index 00000000..65274cd2
--- /dev/null
+++ b/src/api/__tests__/provider-toolcall-deltas.test.ts
@@ -0,0 +1,119 @@
+/**
+ * Streamed tool-call assembly across OpenAI-compat servers (2026-07-28)
+ *
+ * LU talks to whatever OpenAI-compatible backend the user points it at, and
+ * they do not all stream tool calls the way OpenAI does: the id can arrive a
+ * chunk late, the name can arrive with the arguments, and `index` — required by
+ * the spec — is sometimes missing entirely. The accumulator only ever read id
+ * and name from the FIRST delta, so those servers produced a call with an empty
+ * name (nothing to dispatch) or an empty tool_call_id (422 on the next turn).
+ *
+ * Run: npx vitest run src/api/__tests__/provider-toolcall-deltas.test.ts
+ */
+import { describe, it, expect, vi, afterEach } from 'vitest'
+import { OpenAIProvider } from '../providers/openai-provider'
+import type { ProviderConfig, ChatStreamChunk } from '../providers/types'
+
+function makeConfig(overrides: Partial<ProviderConfig> = {}): ProviderConfig {
+ return {
+ id: 'openai',
+ name: 'TestProvider',
+ enabled: true,
+ baseUrl: 'https://api.test.com/v1',
+ apiKey: 'test-key',
+ isLocal: false,
+ ...overrides,
+ }
+}
+
+function sseResponse(events: string[]): Response {
+ return new Response(events.map(e => `data: ${e}\n\n`).join(''), {
+ status: 200,
+ headers: { 'Content-Type': 'text/event-stream' },
+ })
+}
+
+async function toolCallsFrom(events: string[]) {
+ const provider = new OpenAIProvider(makeConfig())
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(sseResponse(events))
+ const chunks: ChatStreamChunk[] = []
+ for await (const c of provider.chatStream('m', [{ role: 'user', content: 'hi' }])) chunks.push(c)
+ return chunks.find(c => c.done)?.toolCalls ?? []
+}
+
+afterEach(() => {
+ vi.restoreAllMocks()
+})
+
+describe('streamed tool calls', () => {
+ it('assembles the OpenAI shape (id + name up front, arguments in pieces)', async () => {
+ const calls = await toolCallsFrom([
+ '{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_a","function":{"name":"file_read","arguments":""}}]}}]}',
+ '{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"path\\":"}}]}}]}',
+ '{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\\"a.txt\\"}"}}]}}]}',
+ '[DONE]',
+ ])
+ expect(calls).toHaveLength(1)
+ expect(calls[0].id).toBe('call_a')
+ expect(calls[0].function.name).toBe('file_read')
+ expect(calls[0].function.arguments).toEqual({ path: 'a.txt' })
+ })
+
+ it('keeps an id that only arrives in a later delta', async () => {
+ const calls = await toolCallsFrom([
+ '{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"name":"shell_execute"}}]}}]}',
+ '{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_late","function":{"arguments":"{}"}}]}}]}',
+ '[DONE]',
+ ])
+ expect(calls[0].id).toBe('call_late')
+ expect(calls[0].function.name).toBe('shell_execute')
+ })
+
+ it('keeps a name that only arrives in a later delta', async () => {
+ const calls = await toolCallsFrom([
+ '{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_b"}]}}]}',
+ '{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"name":"web_search","arguments":"{\\"q\\":\\"x\\"}"}}]}}]}',
+ '[DONE]',
+ ])
+ expect(calls[0].function.name).toBe('web_search')
+ expect(calls[0].function.arguments).toEqual({ q: 'x' })
+ })
+
+ it('does not double a name that every delta repeats', async () => {
+ const calls = await toolCallsFrom([
+ '{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"c","function":{"name":"file_write","arguments":"{"}}]}}]}',
+ '{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"name":"file_write","arguments":"}"}}]}}]}',
+ '[DONE]',
+ ])
+ expect(calls[0].function.name).toBe('file_write')
+ })
+
+ it('assembles a call from deltas that carry no index at all', async () => {
+ const calls = await toolCallsFrom([
+ '{"choices":[{"delta":{"tool_calls":[{"id":"call_x","function":{"name":"file_list","arguments":"{\\"p"}}]}}]}',
+ '{"choices":[{"delta":{"tool_calls":[{"function":{"arguments":"ath\\":\\".\\"}"}}]}}]}',
+ '[DONE]',
+ ])
+ expect(calls).toHaveLength(1)
+ expect(calls[0].id).toBe('call_x')
+ expect(calls[0].function.arguments).toEqual({ path: '.' })
+ })
+
+ it('keeps two index-less calls apart by their ids', async () => {
+ const calls = await toolCallsFrom([
+ '{"choices":[{"delta":{"tool_calls":[{"id":"one","function":{"name":"a","arguments":"{}"}}]}}]}',
+ '{"choices":[{"delta":{"tool_calls":[{"id":"two","function":{"name":"b","arguments":"{}"}}]}}]}',
+ '[DONE]',
+ ])
+ expect(calls).toHaveLength(2)
+ expect(calls.map(c => c.function.name)).toEqual(['a', 'b'])
+ })
+
+ it('never hands back an empty tool_call_id', async () => {
+ const calls = await toolCallsFrom([
+ '{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"name":"file_read","arguments":"{}"}}]}}]}',
+ '[DONE]',
+ ])
+ expect(calls[0].id).toBeTruthy()
+ })
+})
diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.ts
index 10477c04..6832b617 100644
--- a/src/api/providers/openai-provider.ts
+++ b/src/api/providers/openai-provider.ts
@@ -150,6 +150,25 @@ function guessContextFromName(model: string): number {
// applyMaxTokens and getContextLength read it through another.
const catalogContext = new Map<string, number>()
+/**
+ * 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)
+}
+
/** Test-only: reset the endpoint catalogue between test cases. */
export function __clearContextCatalogForTests(): void {
catalogContext.clear()
@@ -367,11 +386,21 @@ export class OpenAIProvider implements ProviderClient {
// Accumulate streamed tool calls
if (choice.delta?.tool_calls) {
for (const tc of choice.delta.tool_calls) {
- const existing = toolCallAccum.get(tc.index)
+ 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(tc.index, {
+ toolCallAccum.set(key, {
id: tc.id || '',
name: tc.function?.name || '',
args: tc.function?.arguments || '',
@@ -650,9 +679,11 @@ export class OpenAIProvider implements ProviderClient {
if (accum.size === 0) return []
const calls: ToolCall[] = []
- for (const [, tc] of accum) {
+ for (const [index, tc] of accum) {
calls.push({
- id: tc.id,
+ // A server that never sent an id would otherwise put an empty
+ // tool_call_id in the follow-up message and 422 the next turn.
+ id: tc.id || `call_${index}`,
function: {
name: tc.name,
arguments: this.safeParseArgs(tc.args),