Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

studio: keep each tool-call round separate when the delta index restarts (#8754)

Maheswar Kumar84c1887fcf25
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index bc4c8729c93..cfc82f79e70 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -82,7 +82,11 @@ import {
type CodexReasoningLedger,
} from "../codex-reasoning";
-import { resolveToolCallPartId } from "../tool-call-id";
+import { toolCallReplayArguments } from "../tool-call-arguments";
+import {
+ findStreamedToolCallPartIndex,
+ resolveToolCallPartId,
+} from "../tool-call-id";
import { buildResearchInferenceRequest } from "../research-inference-request";
import { pickFriendlyContainerName } from "../lib/friendly-names";
@@ -976,10 +980,7 @@ function serializeAssistantToolCallPart(
return null;
}
- const argumentsStr =
- typeof tc.argsText === "string" && tc.argsText.length > 0
- ? tc.argsText
- : JSON.stringify(tc.args ?? {});
+ const argumentsStr = toolCallReplayArguments(tc.argsText, tc.args);
const entry: SerializedToolCall = {
id: tc.toolCallId,
type: "function" as const,
@@ -4633,6 +4634,7 @@ export function createOpenAIStreamAdapter(
type PositionedToolCallPart = ToolCallMessagePart & {
textCursor?: number;
_delta_index?: number;
+ _has_stable_id?: boolean;
extra_content?: unknown;
provenance?: ToolCallProvenance;
};
@@ -6043,12 +6045,18 @@ export function createOpenAIStreamAdapter(
const stablePartId = stableId
? resolveToolPartId(stableId)
: undefined;
- // Match an existing fragment by resolved id first (canonical), then
- // by index slot; fall back to a minted tool_call_<n> id
- // for streams that send neither.
- let existing = stablePartId
- ? toolCallParts.find((p) => p.toolCallId === stablePartId)
- : undefined;
+ // match by resolved id when the fragment carries one, else by
+ // index slot; streams that send neither get a minted
+ // tool_call_<n> id.
+ const existingIndex = findStreamedToolCallPartIndex(
+ toolCallParts,
+ stablePartId,
+ idx,
+ );
+ const existing =
+ existingIndex === -1
+ ? undefined
+ : toolCallParts[existingIndex];
if (
stablePartId &&
@@ -6056,11 +6064,6 @@ export function createOpenAIStreamAdapter(
) {
codexRoundToolCallIds.push(stablePartId);
}
- if (!existing && idx !== undefined) {
- existing = toolCallParts.find(
- (p) => (p as PositionedToolCallPart)._delta_index === idx,
- );
- }
const argsFragment = call.function?.arguments ?? "";
if (existing) {
const prevName = existing.toolName ?? "";
@@ -6083,6 +6086,11 @@ export function createOpenAIStreamAdapter(
.extra_content;
const updated: PositionedToolCallPart = {
...(existing as PositionedToolCallPart),
+ // a late id claims the slot its id-less opening fragment
+ // created, so tool_start and tool_end find the same card.
+ ...(stablePartId
+ ? { toolCallId: stablePartId, _has_stable_id: true }
+ : {}),
toolName: nextName,
argsText: merged,
args: parsedArgs,
@@ -6093,10 +6101,7 @@ export function createOpenAIStreamAdapter(
: {}),
...(idx !== undefined ? { _delta_index: idx } : {}),
};
- const replaceIdx = toolCallParts.indexOf(existing);
- if (replaceIdx >= 0) {
- toolCallParts[replaceIdx] = updated;
- }
+ toolCallParts[existingIndex] = updated;
} else {
const callId =
stablePartId || `tool_call_${idx ?? toolCallParts.length}`;
@@ -6127,6 +6132,7 @@ export function createOpenAIStreamAdapter(
...(call.extra_content !== undefined
? { extra_content: call.extra_content }
: {}),
+ ...(stablePartId ? { _has_stable_id: true } : {}),
...(idx !== undefined ? { _delta_index: idx } : {}),
};
toolCallParts.push(fresh);
diff --git a/studio/frontend/src/features/chat/tool-call-arguments.ts b/studio/frontend/src/features/chat/tool-call-arguments.ts
new file mode 100644
index 00000000000..7f0076fd3b0
--- /dev/null
+++ b/studio/frontend/src/features/chat/tool-call-arguments.ts
@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * The `function.arguments` string to replay for a stored tool call.
+ *
+ * `argsText` is the text the provider streamed and is preferred so replay is
+ * byte-exact. Text that does not parse would be replayed on every later request
+ * in the thread, and strict chat templates reject the whole request rather than
+ * one call, so it falls back to the structured args the part already carries.
+ */
+export function toolCallReplayArguments(
+ argsText: string | undefined,
+ args: unknown,
+): string {
+ if (typeof argsText === "string" && argsText.length > 0) {
+ try {
+ JSON.parse(argsText);
+ return argsText;
+ } catch {
+ // unparsable, so the structured args below stand in for it
+ }
+ }
+ return JSON.stringify(args ?? {});
+}
diff --git a/studio/frontend/src/features/chat/tool-call-id.ts b/studio/frontend/src/features/chat/tool-call-id.ts
index 5bad56f89ad..61a79caf678 100644
--- a/studio/frontend/src/features/chat/tool-call-id.ts
+++ b/studio/frontend/src/features/chat/tool-call-id.ts
@@ -16,3 +16,54 @@ export function resolveToolCallPartId(
ids.set(backendId, partId);
return partId;
}
+
+export interface StreamedToolCallPart {
+ toolCallId: string;
+ _delta_index?: number;
+ _has_stable_id?: boolean;
+}
+
+/**
+ * Newest part holding `deltaIndex`, or -1. `unownedOnly` restricts the match to
+ * a slot no provider id has claimed yet.
+ */
+function findDeltaIndexSlot(
+ parts: readonly StreamedToolCallPart[],
+ deltaIndex: number | undefined,
+ unownedOnly: boolean,
+): number {
+ if (deltaIndex === undefined) {
+ return -1;
+ }
+ for (let i = parts.length - 1; i >= 0; i -= 1) {
+ const part = parts[i];
+ if (part._delta_index !== deltaIndex) {
+ continue;
+ }
+ return unownedOnly && part._has_stable_id ? -1 : i;
+ }
+ return -1;
+}
+
+/**
+ * Index of the tool-call part a `delta.tool_calls[]` fragment continues, or -1
+ * when the fragment starts a new call.
+ *
+ * Providers restart `tool_calls[].index` at 0 for every tool round inside one
+ * assistant response, so the index slot alone cannot separate a continuation
+ * from the next round's opening fragment. A fragment carrying a stable id
+ * therefore matches on that id, and falls back to the index slot only while no
+ * other id owns it, which covers servers that stamp the real id on a later
+ * fragment. Id-less fragments continue the newest part in their slot.
+ */
+export function findStreamedToolCallPartIndex(
+ parts: readonly StreamedToolCallPart[],
+ partId: string | undefined,
+ deltaIndex: number | undefined,
+): number {
+ if (!partId) {
+ return findDeltaIndexSlot(parts, deltaIndex, false);
+ }
+ const byId = parts.findIndex((part) => part.toolCallId === partId);
+ return byId === -1 ? findDeltaIndexSlot(parts, deltaIndex, true) : byId;
+}
diff --git a/studio/frontend/src/features/chat/utils/chat-import.ts b/studio/frontend/src/features/chat/utils/chat-import.ts
index 6bd76b77f36..ea5a1643ffc 100644
--- a/studio/frontend/src/features/chat/utils/chat-import.ts
+++ b/studio/frontend/src/features/chat/utils/chat-import.ts
@@ -148,7 +148,9 @@ function oaiMessagesToRecords(
const name = typeof fn.name === "string" ? fn.name : "unknown";
const argsStr = typeof fn.arguments === "string" ? fn.arguments : "{}";
let args: unknown = {};
- try { args = JSON.parse(argsStr); } catch { /* keep empty */ }
+ // _raw matches what the stream adapter and the backend keep for
+ // arguments the model did not emit as valid JSON.
+ try { args = JSON.parse(argsStr); } catch { args = { _raw: argsStr }; }
const result = toolResults.get(tcId);
parts.push({
type: "tool-call",
diff --git a/studio/frontend/tests/tool-call-delta-index.test.ts b/studio/frontend/tests/tool-call-delta-index.test.ts
new file mode 100644
index 00000000000..53f18be74bd
--- /dev/null
+++ b/studio/frontend/tests/tool-call-delta-index.test.ts
@@ -0,0 +1,164 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { toolCallReplayArguments } from "../src/features/chat/tool-call-arguments.ts";
+import {
+ type StreamedToolCallPart,
+ findStreamedToolCallPartIndex,
+} from "../src/features/chat/tool-call-id.ts";
+
+interface DeltaFragment {
+ id?: string;
+ index?: number;
+ arguments: string;
+}
+
+/** Accumulate `delta.tool_calls[]` fragments the way the chat adapter does. */
+function accumulate(
+ fragments: DeltaFragment[],
+): (StreamedToolCallPart & { argsText: string })[] {
+ const parts: (StreamedToolCallPart & { argsText: string })[] = [];
+ for (const fragment of fragments) {
+ const target = findStreamedToolCallPartIndex(
+ parts,
+ fragment.id,
+ fragment.index,
+ );
+ if (target === -1) {
+ parts.push({
+ toolCallId:
+ fragment.id ?? `tool_call_${fragment.index ?? parts.length}`,
+ argsText: fragment.arguments,
+ ...(fragment.id ? { _has_stable_id: true } : {}),
+ ...(fragment.index !== undefined
+ ? { _delta_index: fragment.index }
+ : {}),
+ });
+ continue;
+ }
+ parts[target] = {
+ ...parts[target],
+ ...(fragment.id ? { toolCallId: fragment.id, _has_stable_id: true } : {}),
+ argsText: parts[target].argsText + fragment.arguments,
+ };
+ }
+ return parts;
+}
+
+test("tool rounds that both reuse index 0 stay separate calls", () => {
+ const parts = accumulate([
+ { id: "call-A", index: 0, arguments: '{"query":' },
+ { index: 0, arguments: '"first"}' },
+ { id: "call-B", index: 0, arguments: '{"query":' },
+ { index: 0, arguments: '"second"}' },
+ ]);
+
+ assert.deepEqual(
+ parts.map((part) => [part.toolCallId, part.argsText]),
+ [
+ ["call-A", '{"query":"first"}'],
+ ["call-B", '{"query":"second"}'],
+ ],
+ );
+});
+
+test("a fragment with a fresh id never merges into a slot another id owns", () => {
+ assert.equal(
+ findStreamedToolCallPartIndex(
+ [{ toolCallId: "call-A", _delta_index: 0, _has_stable_id: true }],
+ "call-B",
+ 0,
+ ),
+ -1,
+ );
+});
+
+test("an id stamped on a later fragment adopts its own opening slot", () => {
+ const parts = accumulate([
+ { index: 0, arguments: "" },
+ { id: "call-A", index: 0, arguments: '{"query":' },
+ { index: 0, arguments: '"first"}' },
+ ]);
+
+ assert.deepEqual(
+ parts.map((part) => [part.toolCallId, part.argsText]),
+ [["call-A", '{"query":"first"}']],
+ );
+});
+
+test("a late id still keeps the next round's call separate", () => {
+ const parts = accumulate([
+ { index: 0, arguments: "" },
+ { id: "call-A", index: 0, arguments: '{"query":"first"}' },
+ { id: "call-B", index: 0, arguments: '{"query":"second"}' },
+ ]);
+
+ assert.deepEqual(
+ parts.map((part) => [part.toolCallId, part.argsText]),
+ [
+ ["call-A", '{"query":"first"}'],
+ ["call-B", '{"query":"second"}'],
+ ],
+ );
+});
+
+test("parallel calls in one round accumulate per index", () => {
+ const parts = accumulate([
+ { id: "call-A", index: 0, arguments: '{"a":' },
+ { id: "call-B", index: 1, arguments: '{"b":' },
+ { index: 0, arguments: "1}" },
+ { index: 1, arguments: "2}" },
+ ]);
+
+ assert.deepEqual(
+ parts.map((part) => [part.toolCallId, part.argsText]),
+ [
+ ["call-A", '{"a":1}'],
+ ["call-B", '{"b":2}'],
+ ],
+ );
+});
+
+test("an id-less stream still accumulates by index alone", () => {
+ const parts = accumulate([
+ { index: 0, arguments: '{"q":' },
+ { index: 0, arguments: '"x"}' },
+ ]);
+
+ assert.deepEqual(
+ parts.map((part) => [part.toolCallId, part.argsText]),
+ [["tool_call_0", '{"q":"x"}']],
+ );
+});
+
+test("a fragment carrying neither id nor index starts its own call", () => {
+ assert.equal(
+ findStreamedToolCallPartIndex(
+ [{ toolCallId: "call-A", _delta_index: 0 }],
+ undefined,
+ undefined,
+ ),
+ -1,
+ );
+});
+
+test("replayed arguments keep parsable text and fall back otherwise", () => {
+ assert.equal(
+ toolCallReplayArguments('{"query":"first"}', { query: "first" }),
+ '{"query":"first"}',
+ );
+ assert.equal(
+ toolCallReplayArguments('{"query":"first"}{"query":"second"}', {
+ _raw: '{"query":"first"}{"query":"second"}',
+ }),
+ '{"_raw":"{\\"query\\":\\"first\\"}{\\"query\\":\\"second\\"}"}',
+ );
+ assert.equal(
+ toolCallReplayArguments("", { query: "first" }),
+ '{"query":"first"}',
+ );
+ assert.equal(toolCallReplayArguments(undefined, undefined), "{}");
+});