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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
fix(studio): show the confirmation card the argument text the tool is run with (#10023)
Long Yixingd12aedda2d7f
diff --git a/studio/backend/core/inference/studio_tool_loop.py b/studio/backend/core/inference/studio_tool_loop.pyindex d47d5df5f41..acfa0675644 100644--- a/studio/backend/core/inference/studio_tool_loop.py+++ b/studio/backend/core/inference/studio_tool_loop.py@@ -67,6 +67,7 @@ from core.inference.tool_call_parser import (from core.inference.tool_loop_controller import (ToolLoopController,awaiting_approval_status,+ canonical_arguments_text,mcp_display_parts,strip_result_for_model,)@@ -1061,13 +1062,15 @@ def _unrun_call_card(first makes both cases end the same way, and keeps the invariant the loop istested on, that every tool_end closes a tool_start."""+ shown = arguments if isinstance(arguments, dict) else {}return [_sse({"type": "tool_start","tool_name": tool_name,"tool_call_id": tool_call_id,- "arguments": arguments if isinstance(arguments, dict) else {},+ "arguments": shown,+ "arguments_text": canonical_arguments_text(shown),"provenance": provenance,}),diff --git a/studio/backend/core/inference/tool_loop_controller.py b/studio/backend/core/inference/tool_loop_controller.pyindex 83c84402482..7bbfbd56a69 100644--- a/studio/backend/core/inference/tool_loop_controller.py+++ b/studio/backend/core/inference/tool_loop_controller.py@@ -185,6 +185,11 @@ class CoercedArguments:healed: bool = False+def canonical_arguments_text(arguments: Any) -> str:+ """The one JSON encoding of an argument mapping, so the card and the replay agree."""+ return json.dumps(arguments, ensure_ascii = False, sort_keys = True, separators = (",", ":"))++@dataclass(frozen = True)class ToolCallDecision:"""Decision made before any visible tool event is emitted."""@@ -246,6 +251,8 @@ class ToolCallDecision:"tool_name": self.tool_name,"tool_call_id": self.card_id,"arguments": arguments,+ # Re-encoding `arguments` in the browser would round ids past 2**53 (JSON.parse).+ "arguments_text": canonical_arguments_text(arguments),"provenance": self.provenance,}@@ -268,12 +275,7 @@ class ToolCallDecision:# is not worth resending -- it is the content that overflowed the window."arguments": json.dumps(_unreadable_arguments_summary(fragment))if fragment is not None- else json.dumps(- self.arguments,- ensure_ascii = False,- sort_keys = True,- separators = (",", ":"),- ),+ else canonical_arguments_text(self.arguments),},}if self.tool_call_id:diff --git a/studio/backend/tests/test_external_tool_truncated_and_budget.py b/studio/backend/tests/test_external_tool_truncated_and_budget.pyindex 87724bb4358..9f3b9d49342 100644--- a/studio/backend/tests/test_external_tool_truncated_and_budget.py+++ b/studio/backend/tests/test_external_tool_truncated_and_budget.py@@ -441,3 +441,23 @@ def test_budget_exhausted_mcp_card_carries_server_display_name(tmp_path, monkeyp]assert len(mcp_starts) == 1assert mcp_starts[0]["provenance"].get("mcp_server") == "GitHub"+++def test_an_unrun_card_shows_the_id_the_call_named():+ """This loop builds its own tool_start instead of going through the controller, so the+ exact-text guarantee has to be covered here too."""+ import json as _json++ from core.inference.studio_tool_loop import _unrun_call_card++ lines = _unrun_call_card(+ tool_name = "del_rec",+ tool_call_id = "c1",+ arguments = {"id": 9007199254740993},+ result = "not run",+ provenance = {"source": "local"},+ )+ start = _json.loads(lines[0].removeprefix("data: ").strip())++ assert start["type"] == "tool_start"+ assert start["arguments_text"] == '{"id":9007199254740993}'diff --git a/studio/backend/tests/test_tool_loop_controller.py b/studio/backend/tests/test_tool_loop_controller.pyindex 76f8ff6c9ba..dcb179980f9 100644--- a/studio/backend/tests/test_tool_loop_controller.py+++ b/studio/backend/tests/test_tool_loop_controller.py@@ -283,6 +283,31 @@ def test_strip_result_for_model_removes_frontend_image_sentinel():assert strip_result_for_model("plain text") == "plain text"+def test_the_card_text_keeps_digits_the_browser_would_round():+ """`JSON.parse` reads 9007199254740993 back as ...992, so a card that re-encodes the+ parsed arguments in the browser would show a record the tool is not being run with."""+ exact = 9007199254740993+ controller = ToolLoopController(tools = [_tool("del_rec")])+ decision = controller.prepare_call(_call("del_rec", {"id": exact}))+ payload = decision.tool_start_payload()++ assert payload["arguments"]["id"] == exact+ assert payload["arguments_text"] == '{"id":9007199254740993}'+ assert payload["arguments_text"] == decision.as_assistant_tool_call()["function"]["arguments"]+++def test_an_unreadable_fragment_is_carried_as_the_text_the_card_shows():+ """The replay substitutes a summary for the fragment, so the two texts are meant to differ."""+ truncated = '{"path": "a.py", "edits"'+ controller = ToolLoopController(tools = [_tool("edit_file")])+ decision = controller.prepare_call(_call("edit_file", truncated))+ payload = decision.tool_start_payload()++ assert payload["arguments"] == {"raw": truncated}+ assert json.loads(payload["arguments_text"]) == {"raw": truncated}+ assert payload["arguments_text"] != decision.as_assistant_tool_call()["function"]["arguments"]++# --- schema-aware argument typing -------------------------------------------------------_MCP_SERVER = {"id": "notes", "display_name": "Notes"}diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex c56d1cf508c..27821afcaaa 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -108,7 +108,9 @@ import {import {createBoundaryScan,+ mergedToolCallArgumentsText,splitTopLevelJsonObjects,+ toolCallArgumentsText,toolCallReplayArguments,} from "../tool-call-arguments";import {@@ -6779,6 +6781,10 @@ export function createOpenAIStreamAdapter(useChatRuntimeStore.getState().clearToolFullOutput(staleKey);const toolArgs = (toolEvent.arguments ??{}) as ToolCallMessagePart["args"];+ const toolArgsText = toolCallArgumentsText(+ toolEvent.arguments_text,+ toolArgs,+ );const idx = toolCallParts.findIndex((p) => p.toolCallId === id,);@@ -6789,7 +6795,7 @@ export function createOpenAIStreamAdapter(toolCallParts[idx] = {...existing,toolName: toolEvent.tool_name as string,- argsText: JSON.stringify(toolArgs),+ argsText: toolArgsText,args: toolArgs,provenance: mergeToolProvenance(existing.provenance,@@ -6801,7 +6807,7 @@ export function createOpenAIStreamAdapter(type: "tool-call" as const,toolCallId: id,toolName: toolEvent.tool_name as string,- argsText: JSON.stringify(toolArgs),+ argsText: toolArgsText,args: toolArgs,textCursor: cumulativeText.length,...(toolProvenance ? { provenance: toolProvenance } : {}),@@ -6978,6 +6984,8 @@ export function createOpenAIStreamAdapter(...(toolCallParts[idx].args ?? {}),...(nextArgs ?? {}),} as ToolCallMessagePart["args"];+ const overwrittenArgumentKeys =+ nextArgs !== undefined ? Object.keys(nextArgs) : [];// Merge tool_end native_part into args.google so the// outbound translator replays both start (executableCode)// and end (result / inlineData) on the same turn.@@ -7059,7 +7067,11 @@ export function createOpenAIStreamAdapter(toolCallParts[idx] = {...existing,args: mergedArgs,- argsText: JSON.stringify(mergedArgs ?? {}),+ argsText: mergedToolCallArgumentsText(+ existing.argsText,+ mergedArgs,+ overwrittenArgumentKeys,+ ),result: parsedResult,provenance: mergeToolProvenance(existing.provenance,diff --git a/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx b/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsxindex 3ba2337e544..b123003ffe9 100644--- a/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx+++ b/studio/frontend/src/features/chat/prompt-storage/prompt-storage-dialog.tsx@@ -77,6 +77,7 @@ import {} from "../utils/chat-history-storage";import { notifyChatHistoryUpdated } from "../api/chat-api";import { toolResultModelText } from "../api/chat-adapter";+import { toolCallReplayArguments } from "../tool-call-arguments";import { usePlusMenuPrefsStore } from "../stores/plus-menu-prefs-store";import type { ThreadRecord, MessageRecord } from "../types";import {@@ -351,7 +352,10 @@ function messageToOpenAI(msg: { role: unknown; content: unknown; attachments?: u} else if (p.type === "tool-call") {const id = typeof p.toolCallId === "string" ? p.toolCallId : `call_${toolCalls.length}`;const name = typeof p.toolName === "string" ? p.toolName : "unknown";- const argsStr = p.args != null ? JSON.stringify(p.args) : (typeof p.argsText === "string" ? p.argsText : "{}");+ const argsStr = toolCallReplayArguments(+ typeof p.argsText === "string" ? p.argsText : undefined,+ p.args,+ );toolCalls.push({ id, type: "function", function: { name, arguments: argsStr } });if (p.result !== undefined && p.result !== null) {// Keep base64 image payloads out of exports: MCP image results carrydiff --git a/studio/frontend/src/features/chat/tool-call-arguments.ts b/studio/frontend/src/features/chat/tool-call-arguments.tsindex 9339557d039..e41b755a0f5 100644--- a/studio/frontend/src/features/chat/tool-call-arguments.ts+++ b/studio/frontend/src/features/chat/tool-call-arguments.ts@@ -199,3 +199,239 @@ export function toolCallReplayArguments(}return serialized;}++/**+ * Prefers the backend's own encoding: re-encoding after `JSON.parse` rounds integers past+ * 2**53 and would show a value the tool is not being run with.+ */+export function toolCallArgumentsText(+ exactText: unknown,+ args: unknown,+): string {+ if (typeof exactText === "string" && exactText.length > 0) {+ try {+ JSON.parse(exactText);+ return exactText;+ } catch {+ // Unparseable text cannot be these arguments, and this card is an approval+ // boundary, so fall back to the structured ones.+ }+ }+ return JSON.stringify(args ?? {});+}++type JsonTextNode =+ | { kind: "object"; entries: Array<{ key: string; value: JsonTextNode }> }+ | { kind: "array"; items: JsonTextNode[] }+ | { kind: "scalar"; raw: string; value: unknown };++const JSON_WHITESPACE = /\s/;+const JSON_VALUE_DELIMITER = /[\s,}\]]/;++class JsonTextParser {+ private offset = 0;+ private readonly text: string;++ constructor(text: string) {+ this.text = text;+ }++ parse(): JsonTextNode {+ const value = this.parseValue();+ this.skipWhitespace();+ if (this.offset !== this.text.length) {+ throw new Error("Trailing JSON text");+ }+ return value;+ }++ private skipWhitespace(): void {+ while (JSON_WHITESPACE.test(this.text[this.offset] ?? "")) {+ this.offset += 1;+ }+ }++ private parseString(): { raw: string; value: string } {+ const start = this.offset;+ this.offset += 1;+ let escaped = false;+ while (this.offset < this.text.length) {+ const char = this.text[this.offset++];+ if (escaped) {+ escaped = false;+ } else if (char === "\\") {+ escaped = true;+ } else if (char === '"') {+ const raw = this.text.slice(start, this.offset);+ return { raw, value: JSON.parse(raw) as string };+ }+ }+ throw new Error("Unterminated JSON string");+ }++ private parseValue(): JsonTextNode {+ this.skipWhitespace();+ const char = this.text[this.offset];+ if (char === "{") {+ return this.parseObject();+ }+ if (char === "[") {+ return this.parseArray();+ }+ if (char === '"') {+ const parsed = this.parseString();+ return { kind: "scalar", raw: parsed.raw, value: parsed.value };+ }++ const start = this.offset;+ while (+ this.offset < this.text.length &&+ !JSON_VALUE_DELIMITER.test(this.text[this.offset])+ ) {+ this.offset += 1;+ }+ const raw = this.text.slice(start, this.offset);+ if (!raw) {+ throw new Error("Missing JSON value");+ }+ return { kind: "scalar", raw, value: JSON.parse(raw) as unknown };+ }++ private parseObject(): JsonTextNode {+ this.offset += 1;+ const entries: Array<{ key: string; value: JsonTextNode }> = [];+ this.skipWhitespace();+ if (this.text[this.offset] === "}") {+ this.offset += 1;+ return { kind: "object", entries };+ }+ while (this.offset < this.text.length) {+ this.skipWhitespace();+ if (this.text[this.offset] !== '"') {+ throw new Error("Invalid JSON key");+ }+ const key = this.parseString().value;+ this.skipWhitespace();+ if (this.text[this.offset++] !== ":") {+ throw new Error("Missing JSON colon");+ }+ entries.push({ key, value: this.parseValue() });+ this.skipWhitespace();+ const separator = this.text[this.offset++];+ if (separator === "}") {+ return { kind: "object", entries };+ }+ if (separator !== ",") {+ throw new Error("Invalid JSON object separator");+ }+ }+ throw new Error("Unterminated JSON object");+ }++ private parseArray(): JsonTextNode {+ this.offset += 1;+ const items: JsonTextNode[] = [];+ this.skipWhitespace();+ if (this.text[this.offset] === "]") {+ this.offset += 1;+ return { kind: "array", items };+ }+ while (this.offset < this.text.length) {+ items.push(this.parseValue());+ this.skipWhitespace();+ const separator = this.text[this.offset++];+ if (separator === "]") {+ return { kind: "array", items };+ }+ if (separator !== ",") {+ throw new Error("Invalid JSON array separator");+ }+ }+ throw new Error("Unterminated JSON array");+ }+}++function stringifyJson(value: unknown): string {+ return JSON.stringify(value) ?? "null";+}++function mergeJsonNode(node: JsonTextNode, current: unknown): string {+ if (+ node.kind === "object" &&+ current !== null &&+ typeof current === "object" &&+ !Array.isArray(current)+ ) {+ const record = current as Record<string, unknown>;+ const previousKeys = new Set(node.entries.map((entry) => entry.key));+ const entries = node.entries+ .filter((entry) => Object.hasOwn(record, entry.key))+ .map(+ (entry) =>+ `${JSON.stringify(entry.key)}:${mergeJsonNode(entry.value, record[entry.key])}`,+ );+ for (const [key, value] of Object.entries(record)) {+ if (!previousKeys.has(key))+ entries.push(`${JSON.stringify(key)}:${stringifyJson(value)}`);+ }+ return `{${entries.join(",")}}`;+ }+ if (node.kind === "array" && Array.isArray(current)) {+ return `[${current+ .map((value, index) =>+ index < node.items.length+ ? mergeJsonNode(node.items[index], value)+ : stringifyJson(value),+ )+ .join(",")}]`;+ }+ if (node.kind === "scalar" && Object.is(node.value, current)) {+ return node.raw;+ }+ return stringifyJson(current);+}++/**+ * Unchanged values keep their original JSON lexemes (an executed integer past 2**53 stays+ * exact); keys in `overwrittenKeys` are re-serialized from the tool_end object.+ */+export function mergedToolCallArgumentsText(+ previousText: unknown,+ mergedArgs: unknown,+ overwrittenKeys: readonly string[] = [],+): string {+ if (typeof previousText !== "string" || previousText.length === 0) {+ return stringifyJson(mergedArgs ?? {});+ }+ try {+ const parsed = new JsonTextParser(previousText).parse();+ if (+ parsed.kind !== "object" ||+ mergedArgs === null ||+ typeof mergedArgs !== "object" ||+ Array.isArray(mergedArgs)+ ) {+ return mergeJsonNode(parsed, mergedArgs);+ }+ const record = mergedArgs as Record<string, unknown>;+ const forced = new Set(overwrittenKeys);+ const previousKeys = new Set(parsed.entries.map((entry) => entry.key));+ const entries = parsed.entries+ .filter((entry) => Object.hasOwn(record, entry.key))+ .map(+ (entry) =>+ `${JSON.stringify(entry.key)}:${+ forced.has(entry.key)+ ? stringifyJson(record[entry.key])+ : mergeJsonNode(entry.value, record[entry.key])+ }`,+ );+ for (const [key, value] of Object.entries(record)) {+ if (!previousKeys.has(key))+ entries.push(`${JSON.stringify(key)}:${stringifyJson(value)}`);+ }+ return `{${entries.join(",")}}`;+ } catch {+ return stringifyJson(mergedArgs ?? {});+ }+}diff --git a/studio/frontend/tests/tool-call-arguments-precision.test.ts b/studio/frontend/tests/tool-call-arguments-precision.test.tsnew file mode 100644index 00000000000..73ba7b85d66--- /dev/null+++ b/studio/frontend/tests/tool-call-arguments-precision.test.ts@@ -0,0 +1,180 @@+// 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 { readFileSync } from "node:fs";+import test from "node:test";+import { fileURLToPath } from "node:url";++import {+ mergedToolCallArgumentsText,+ toolCallArgumentsText,+ toolCallReplayArguments,+} from "../src/features/chat/tool-call-arguments.ts";++const WIRE =+ '{"arguments":{"id":9007199254740993},"arguments_text":"{\\"id\\":9007199254740993}"}';++test("the card shows the id the tool is run with, not the one JSON.parse returned", () => {+ const event = JSON.parse(WIRE) as {+ arguments: unknown;+ arguments_text: string;+ };+ assert.equal(JSON.stringify(event.arguments), '{"id":9007199254740992}');++ assert.equal(+ toolCallArgumentsText(event.arguments_text, event.arguments),+ '{"id":9007199254740993}',+ );+});++test("an event without the backend's text still renders", () => {+ assert.equal(toolCallArgumentsText(undefined, { q: "gpu" }), '{"q":"gpu"}');+ assert.equal(toolCallArgumentsText("", { q: "gpu" }), '{"q":"gpu"}');+ assert.equal(toolCallArgumentsText(undefined, undefined), "{}");+});++test("completing a call keeps the exact text when nothing merged in", () => {+ const event = JSON.parse(WIRE) as {+ arguments: unknown;+ arguments_text: string;+ };+ const exact = toolCallArgumentsText(event.arguments_text, event.arguments);++ assert.equal(+ mergedToolCallArgumentsText(exact, event.arguments),+ '{"id":9007199254740993}',+ );+});++test("a merge adds metadata without rewriting the executed integer", () => {+ const merged = mergedToolCallArgumentsText('{"id":9007199254740993}', {+ id: 9007199254740992,+ google: { native_part: 1 },+ });++ assert.equal(merged, '{"id":9007199254740993,"google":{"native_part":1}}');+});++test("an explicitly overwritten key uses the tool_end value", () => {+ // The two encodings collide, so comparing them would keep text describing the old value.+ const collided = mergedToolCallArgumentsText(+ '{"id":9007199254740993}',+ { id: 9007199254740992 },+ ["id"],+ );++ assert.equal(collided, '{"id":9007199254740992}');+});++test("nested metadata appends without rewriting earlier numeric lexemes", () => {+ const merged = mergedToolCallArgumentsText(+ '{"google":{"native_part":{"parts":[{"result":{"id":9007199254740993}}]}}}',+ {+ google: {+ native_part: {+ parts: [+ { result: { id: 9007199254740992 } },+ { inlineData: { mimeType: "image/png" } },+ ],+ },+ },+ },+ );+ assert.equal(+ merged,+ '{"google":{"native_part":{"parts":[{"result":{"id":9007199254740993}},{"inlineData":{"mimeType":"image/png"}}]}}}',+ );+});++test("prompt replay prefers exact parsable argument text", () => {+ assert.equal(+ toolCallReplayArguments('{"id":9007199254740993}', {+ id: 9007199254740992,+ }),+ '{"id":9007199254740993}',+ );+});++// Read as source: the helpers only hold the line if the adapter routes through them.+const ADAPTER = readFileSync(+ fileURLToPath(+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),+ ),+ "utf8",+);+const PROMPT_STORAGE = readFileSync(+ fileURLToPath(+ new URL(+ "../src/features/chat/prompt-storage/prompt-storage-dialog.tsx",+ import.meta.url,+ ),+ ),+ "utf8",+);++test("the adapter builds tool-call argument text through the helpers", () => {+ assert.match(ADAPTER, /toolCallArgumentsText\(\s*toolEvent\.arguments_text/);+ assert.match(ADAPTER, /argsText: mergedToolCallArgumentsText\(/);+ assert.equal(ADAPTER.includes("argsText: JSON.stringify(toolArgs)"), false);+ assert.equal(+ ADAPTER.includes("argsText: JSON.stringify(mergedArgs ?? {})"),+ false,+ );+});++test("prompt export routes through the exact-text replay helper", () => {+ assert.match(PROMPT_STORAGE, /const argsStr = toolCallReplayArguments\(/);+ assert.equal(+ PROMPT_STORAGE.includes("p.args != null ? JSON.stringify(p.args)"),+ false,+ );+});++test("argument text that does not parse is not shown on an approval card", () => {+ for (const junk of [+ "not json at all",+ " ",+ '{"id":1',+ "<script>alert(1)</script>",+ ]) {+ assert.equal(toolCallArgumentsText(junk, { q: "gpu" }), '{"q":"gpu"}');+ }+ assert.equal(+ toolCallArgumentsText('{"id":9007199254740993}', { id: 9007199254740992 }),+ '{"id":9007199254740993}',+ );+});++test("a Gemini native_part merge keeps the executed integer", () => {+ // The adapter computes overwritten keys BEFORE folding native_part into args.google, so+ // `google` takes the lexeme-preserving path.+ const card = '{"google":{"executableCode":{"code":"print(1)"}},"id":9007199254740993}';+ const mergedArgs = {+ google: { executableCode: { code: "print(1)" }, native_part: { inlineData: "AAA" } },+ id: 9007199254740992,+ };++ const merged = mergedToolCallArgumentsText(card, mergedArgs, []);++ assert.ok(merged.includes("9007199254740993"), merged);+ assert.ok(merged.includes("native_part"), merged);+ assert.deepEqual(JSON.parse(merged), {+ google: { executableCode: { code: "print(1)" }, native_part: { inlineData: "AAA" } },+ id: 9007199254740992,+ });+});++test("a card stored before this change still merges", () => {+ const legacy = JSON.stringify({ id: 9007199254740992, q: "gpu" });+ const merged = mergedToolCallArgumentsText(legacy, { id: 9007199254740992, q: "gpu", done: true }, []);++ assert.deepEqual(JSON.parse(merged), { id: 9007199254740992, q: "gpu", done: true });+});++test("unreadable stored text falls back instead of throwing", () => {+ for (const junk of ["", " ", "{", "not json", '{"a":1} trailing']) {+ const out = mergedToolCallArgumentsText(junk, { a: 1 }, []);+ assert.deepEqual(JSON.parse(out), { a: 1 });+ }+});