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: don't crash the app when a tool arg isn't a string (#9641)

Nilay5001473dd094
diff --git a/studio/frontend/src/components/assistant-ui/tool-arg-text.ts b/studio/frontend/src/components/assistant-ui/tool-arg-text.ts
new file mode 100644
index 00000000000..de612447fb6
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/tool-arg-text.ts
@@ -0,0 +1,49 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * How much of a serialised object a card shows. Only the JSON branch is capped,
+ * so every string argument is returned untouched.
+ *
+ * Engines disagree about how long a string may be (V8 ~512 Mi then RangeError,
+ * SpiderMonkey ~1 Gi, JavaScriptCore ~2 Gi), so an uncapped serialisation is ""
+ * in Chrome and hundreds of megabytes of DOM in Safari. Measured at 100k nesting
+ * levels: Chrome produced 600,002 characters, Firefox and Safari threw.
+ */
+const MAX_SERIALISED_LENGTH = 100_000;
+
+/**
+ * A tool-call argument as text, whatever the model actually sent.
+ *
+ * Arguments reach a card as parsed JSON, so a prop declared `string` is a
+ * request to the model, not a guarantee from it. `{"code": 42}` used to reach
+ * `code.split("\n")` during render, and a throw in a card has no boundary above
+ * it: the router catches it and replaces all of Studio with "Something went
+ * wrong!" (markdown-block-boundary.tsx measures the same failure). The message
+ * is persisted, so reopening the thread reproduces it.
+ */
+export const toolArgText = (value: unknown): string => {
+ if (value == null) return "";
+ if (typeof value === "string") return value;
+ try {
+ if (typeof value === "object") {
+ // SERIALISED, not coerced: `String({"toString":null})` throws "Cannot
+ // convert object to primitive value", the exact crash this stops. JSON
+ // also shows what arrived, which "[object Object]" never did.
+ // `?? ""` because a `toJSON` returning undefined makes stringify do so.
+ const json = JSON.stringify(value) ?? "";
+ return json.length > MAX_SERIALISED_LENGTH
+ ? `${json.slice(0, MAX_SERIALISED_LENGTH)}…`
+ : json;
+ }
+ // NOT a template literal: `String(sym)` returns the descriptive string
+ // (ECMA-262 22.1.1.1), `${sym}` throws.
+ return String(value);
+ } catch {
+ // Load-bearing, not defensive. All three engines parse 4,000,000 levels of
+ // nesting; Firefox then throws "InternalError: too much recursion" and
+ // Safari a RangeError out of JSON.stringify where Chrome succeeds. Keep the
+ // binding bare: Firefox's is not a RangeError.
+ return "";
+ }
+};
diff --git a/studio/frontend/src/components/assistant-ui/tool-fallback.tsx b/studio/frontend/src/components/assistant-ui/tool-fallback.tsx
index d52100225eb..50736ed4a5d 100644
--- a/studio/frontend/src/components/assistant-ui/tool-fallback.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-fallback.tsx
@@ -37,6 +37,7 @@ import {
useRef,
useState,
} from "react";
+import { toolArgText } from "./tool-arg-text";
const ANIMATION_DURATION = 200;
@@ -122,7 +123,10 @@ function ToolFallbackTrigger({
className,
...props
}: ComponentProps<typeof CollapsibleTrigger> & {
- toolName: string;
+ // Straight off the wire: provider SSE is relayed verbatim, and a non-string
+ // name matches nothing in thread.tsx's by_name map, which is exactly why it
+ // lands HERE, where formatMcpToolName calls `.startsWith` on it.
+ toolName: unknown;
mcpServer?: string;
status?: ToolCallMessagePartStatus;
icon?: ElementType;
@@ -134,7 +138,8 @@ function ToolFallbackTrigger({
const StatusIcon = statusIconMap[statusType];
const label = isCancelled ? "Cancelled tool" : "Used tool";
- const displayName = formatMcpToolName(toolName, mcpServer) ?? toolName;
+ const name = toolArgText(toolName);
+ const displayName = formatMcpToolName(name, mcpServer) ?? name;
return (
<CollapsibleTrigger
diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-code-execution.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-code-execution.tsx
index bb2320904b8..26390838566 100644
--- a/studio/frontend/src/components/assistant-ui/tool-ui-code-execution.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-ui-code-execution.tsx
@@ -14,6 +14,7 @@ import { CopyIcon, FileTextIcon, TerminalIcon } from "lucide-react";
import { Tick02Icon } from "@/lib/tick-icon";
import { HugeiconsIcon } from "@hugeicons/react";
import { Spinner } from "@/components/ui/spinner";
+import { toolArgText } from "./tool-arg-text";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
ToolFallbackContent,
@@ -38,8 +39,9 @@ import {
*/
interface CodeExecutionArgs {
kind?: "bash" | "text_editor";
- command?: string;
- path?: string;
+ // Straight off the wire: the model, not the schema, decides the JSON type.
+ command?: unknown;
+ path?: unknown;
}
const MAX_COMMAND_LABEL = 80;
@@ -134,8 +136,8 @@ const CodeExecutionToolUIImpl: ToolCallMessagePartComponent = ({
}) => {
const parsedArgs = (args as CodeExecutionArgs) ?? {};
const kind = parsedArgs.kind ?? "bash";
- const command = parsedArgs.command ?? "";
- const path = parsedArgs.path ?? "";
+ const command = toolArgText(parsedArgs.command);
+ const path = toolArgText(parsedArgs.path);
const isRunning = status?.type === "running";
const commandLabel = command ? truncateCommandLabel(command) : "";
diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-image-generation.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-image-generation.tsx
index af988cbe7fb..5496fddcb78 100644
--- a/studio/frontend/src/components/assistant-ui/tool-ui-image-generation.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-ui-image-generation.tsx
@@ -13,6 +13,7 @@ import type { CSSProperties, MouseEvent } from "react";
import { memo, useCallback, useEffect, useRef, useState } from "react";
import { useGeneratedImageOverlay } from "./generated-image-overlay-context";
import { downloadImagePart } from "./image";
+import { toolArgText } from "./tool-arg-text";
import {
ToolFallbackContent,
ToolFallbackRoot,
@@ -31,20 +32,27 @@ import {
* JSON with an empty Result block (the "no image" symptom).
*/
interface ImageGenerationArgs {
- prompt?: string;
+ // Straight off the wire; the provider decides the JSON type, not this file.
+ prompt?: unknown;
kind?: string;
openai_image_generation_call_id?: unknown;
openai_response_id?: unknown;
openai_reasoning_item?: unknown;
}
+/**
+ * Straight off the wire, like the args above. Only `image_b64` is type-guarded
+ * before use; `size`, `quality` and `background` are copied verbatim from the
+ * provider (external_provider.py:5883) and on the Gemini path so is `image_mime`
+ * (:4481). Studio takes a user-set `base_url`, so none of them is ours.
+ */
interface ImageGenerationResult {
image_b64?: string;
- image_mime?: string;
- size?: string;
- quality?: string;
- background?: string;
- prompt?: string;
+ image_mime?: unknown;
+ size?: unknown;
+ quality?: unknown;
+ background?: unknown;
+ prompt?: unknown;
}
type GeneratedImagePart = {
@@ -92,10 +100,12 @@ const formatGeneratedImageLabel = (prompt: string): string => {
: `Generated image: ${prompt}`;
};
+// Takes text: `size?.match` guards nullish only, so `"size": 1024` reached
+// `.match` on a number.
const parseImageSize = (
- size?: string,
+ size: string,
): { width: number; height: number } | null => {
- const match = size?.match(/^(\d+)x(\d+)$/i);
+ const match = size.match(/^(\d+)x(\d+)$/i);
if (!match) return null;
const width = Number(match[1]);
const height = Number(match[2]);
@@ -159,7 +169,7 @@ const ImageGenerationToolUIImpl: ToolCallMessagePartComponent = ({
}) => {
const { openOverlay } = useGeneratedImageOverlay();
const parsedArgs = (args as ImageGenerationArgs) ?? {};
- const prompt = parsedArgs.prompt ?? "";
+ const prompt = toolArgText(parsedArgs.prompt);
const isRunning = status?.type === "running";
const isImageResult =
@@ -167,7 +177,11 @@ const ImageGenerationToolUIImpl: ToolCallMessagePartComponent = ({
typeof result === "object" &&
typeof (result as ImageGenerationResult).image_b64 === "string";
const imageResult = isImageResult ? (result as ImageGenerationResult) : null;
- const imageDimensions = parseImageSize(imageResult?.size);
+ // Coerced for the same reason `prompt` is: these reach `.match`,
+ // `.toLowerCase` and `Array.join`, all of which throw on a non-string.
+ const size = toolArgText(imageResult?.size);
+ const quality = toolArgText(imageResult?.quality);
+ const imageDimensions = parseImageSize(size);
const imageFrameStyle: CSSProperties = {
width: imageDimensions
? getInlineImageFrameWidth(imageDimensions)
@@ -177,17 +191,15 @@ const ImageGenerationToolUIImpl: ToolCallMessagePartComponent = ({
const imageBoxStyle: CSSProperties | undefined = imageDimensions
? { aspectRatio: `${imageDimensions.width} / ${imageDimensions.height}` }
: undefined;
- const mime = imageResult?.image_mime || "image/png";
+ const mime = toolArgText(imageResult?.image_mime) || "image/png";
const imageSrc = imageResult?.image_b64
? `data:${mime};base64,${imageResult.image_b64}`
: null;
- const imageTitle =
- imageResult?.prompt?.trim() || prompt.trim() || "Generated image";
- const captionPrompt = imageResult?.prompt?.trim() || prompt.trim();
+ const resultPrompt = toolArgText(imageResult?.prompt).trim();
+ const imageTitle = resultPrompt || prompt.trim() || "Generated image";
+ const captionPrompt = resultPrompt || prompt.trim();
const promptLikelyNeedsExpansion = captionPrompt.length > 220;
- const imageMetadata = [imageResult?.size, imageResult?.quality, mime]
- .filter(Boolean)
- .join(" · ");
+ const imageMetadata = [size, quality, mime].filter(Boolean).join(" · ");
const openaiImageGenerationCallId =
typeof parsedArgs.openai_image_generation_call_id === "string"
? parsedArgs.openai_image_generation_call_id
diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-knowledge-base.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-knowledge-base.tsx
index c5f45d89a41..9bffe7587e3 100644
--- a/studio/frontend/src/components/assistant-ui/tool-ui-knowledge-base.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-ui-knowledge-base.tsx
@@ -13,6 +13,7 @@ import { Spinner } from "@/components/ui/spinner";
import { stringifyToolResult } from "@/lib/strip-ansi";
import { memo, useEffect, useMemo, useState } from "react";
import { Badge } from "./badge";
+import { toolArgText } from "./tool-arg-text";
import {
ToolFallbackContent,
ToolFallbackRoot,
@@ -76,7 +77,7 @@ const KnowledgeBaseToolUIImpl: ToolCallMessagePartComponent = ({
result,
status,
}) => {
- const query = (args as { query?: string })?.query ?? "";
+ const query = toolArgText((args as { query?: unknown })?.query);
const isRunning = status?.type === "running";
const resultText = result == null ? "" : stringifyToolResult(result);
diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx
index e09187c8576..47de7ea56d3 100644
--- a/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx
@@ -22,6 +22,7 @@ import { CodeIcon } from "lucide-react";
import { memo, useEffect, useRef, useState } from "react";
import { pythonToolImagePath } from "./python-tool-image-path";
import { CopyBtn, ToolCodeCell } from "./tool-code-cell";
+import { toolArgText } from "./tool-arg-text";
import {
ToolFallbackContent,
ToolFallbackRoot,
@@ -141,7 +142,7 @@ const PythonToolUIImpl: ToolCallMessagePartComponent = ({
result,
status,
}) => {
- const code = (args as { code?: string })?.code ?? "";
+ const code = toolArgText((args as { code?: unknown })?.code);
const firstLine = code.split("\n")[0]?.slice(0, 60) ?? "";
const isRunning = status?.type === "running";
// Args still streaming = the model is WRITING the code, not running it yet.
diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx
index e91e2d3737b..81de7ef06ea 100644
--- a/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx
@@ -14,6 +14,7 @@ import {
ToolFallbackTrigger,
} from "./tool-fallback";
import { CopyBtn, ToolCodeCell } from "./tool-code-cell";
+import { toolArgText } from "./tool-arg-text";
import { ToolLiveOutput } from "./tool-live-output";
import { ToolResultOutput } from "./tool-result-output";
import { SandboxFiles } from "./sandbox-files-view";
@@ -34,7 +35,7 @@ const TerminalToolUIImpl: ToolCallMessagePartComponent = ({
result,
status,
}) => {
- const command = (args as { command?: string })?.command ?? "";
+ const command = toolArgText((args as { command?: unknown })?.command);
const isRunning = status?.type === "running";
// Args still streaming = the model is WRITING the command, not running it yet.
const { propStatus } = useToolArgsStatus();
diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-web-search.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-web-search.tsx
index 204d1a93a2a..06b2b541dce 100644
--- a/studio/frontend/src/components/assistant-ui/tool-ui-web-search.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-ui-web-search.tsx
@@ -14,6 +14,7 @@ import { stringifyToolResult } from "@/lib/strip-ansi";
import { memo, useEffect, useState } from "react";
import { SearchImageThumb } from "./search-image";
import { Source, SourceIcon, SourceTitle } from "./sources";
+import { toolArgText } from "./tool-arg-text";
import {
ToolFallbackContent,
ToolFallbackRoot,
@@ -89,13 +90,13 @@ const WebSearchToolUIImpl: ToolCallMessagePartComponent = ({
}) => {
// Coerced, like image_queries below: a local model routinely emits a number or an
// object here, and .trim() on one crashes the card that was meant to show the call.
- const query = String((args as { query?: unknown })?.query ?? "");
- const url = String((args as { url?: unknown })?.url ?? "").trim();
+ const query = toolArgText((args as { query?: unknown })?.query);
+ const url = toolArgText((args as { url?: unknown })?.url).trim();
const isUrlFetch = !!url;
const rawImageQueries = (args as { image_queries?: unknown })?.image_queries;
const imageQueries = Array.isArray(rawImageQueries)
? rawImageQueries
- .map((q) => String(q).trim())
+ .map((q) => toolArgText(q).trim())
.filter(Boolean)
.slice(0, 5)
: [];
diff --git a/studio/frontend/tests/search-images.test.ts b/studio/frontend/tests/search-images.test.ts
index bbd466096d3..26893ecaddd 100644
--- a/studio/frontend/tests/search-images.test.ts
+++ b/studio/frontend/tests/search-images.test.ts
@@ -26,6 +26,7 @@ import {
searchResultText,
stripSearchImageTokens,
} from "../src/features/chat/search-images/search-images.ts";
+import { toolArgText } from "../src/components/assistant-ui/tool-arg-text.ts";
import { safeMarkdownUrl } from "../src/lib/safe-markdown-url.ts";
const ENTRY = {
@@ -905,12 +906,16 @@ test("the web search card survives a query that is not a string", () => {
cardSource.indexOf("const isUrlFetch ="),
);
assert.ok(args.length > 0, "the args derivation moved");
- const derive = new Function(
+ // Passed in because the derivation now calls it: one coercion shared by every
+ // card (see tool-card-arg-coercion.test.ts).
+ const derived = new Function(
"args",
+ "toolArgText",
ts.transpileModule(`${args}\nreturn [query.trim(), url];`, {
compilerOptions: { target: ts.ScriptTarget.ES2022 },
}).outputText,
- ) as (args: unknown) => [string, string];
+ ) as (args: unknown, coerce: typeof toolArgText) => [string, string];
+ const derive = (args: unknown): [string, string] => derived(args, toolArgText);
assert.deepEqual(derive({ query: 42 }), ["42", ""]);
assert.deepEqual(derive({ query: null, url: 7 }), ["", "7"]);
assert.deepEqual(derive({}), ["", ""]);
diff --git a/studio/frontend/tests/tool-card-arg-coercion.test.ts b/studio/frontend/tests/tool-card-arg-coercion.test.ts
new file mode 100644
index 00000000000..29002d97c98
--- /dev/null
+++ b/studio/frontend/tests/tool-card-arg-coercion.test.ts
@@ -0,0 +1,329 @@
+// 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, readdirSync } from "node:fs";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import ts from "typescript";
+
+import { toolArgText } from "../src/components/assistant-ui/tool-arg-text.ts";
+
+const CARDS_DIR = "../src/components/assistant-ui/";
+
+const sourceFile = (relative: string): ts.SourceFile => {
+ const path = fileURLToPath(new URL(relative, import.meta.url));
+ return ts.createSourceFile(
+ path,
+ readFileSync(path, "utf8"),
+ ts.ScriptTarget.ESNext,
+ true,
+ ts.ScriptKind.TSX,
+ );
+};
+
+// The shapes local models actually send. See tool-arg-text.ts for what a throw
+// in a card costs.
+test("toolArgText renders whatever the model sent as text", () => {
+ assert.equal(toolArgText(42), "42");
+ assert.equal(toolArgText(0), "0");
+ assert.equal(toolArgText(true), "true");
+ assert.equal(toolArgText(["ls", "-la"]), '["ls","-la"]');
+ assert.equal(toolArgText({ cmd: "ls" }), '{"cmd":"ls"}');
+ assert.equal(toolArgText("print(1)"), "print(1)");
+});
+
+// `{"toString":null}` is valid JSON whose own property shadows the callable one
+// on Object.prototype, so coercing it throws through the very helper meant to
+// prevent the crash. Arrays reach it too, elementwise.
+test("toolArgText survives an object that cannot be coerced", () => {
+ const hostile = JSON.parse('{"code":{"toString":null}}').code;
+ assert.equal(toolArgText(hostile), '{"toString":null}');
+ assert.equal(
+ toolArgText(JSON.parse('[{"toString":null}]')),
+ '[{"toString":null}]',
+ );
+ assert.equal(
+ toolArgText(JSON.parse('{"valueOf":null,"toString":null}')),
+ '{"valueOf":null,"toString":null}',
+ );
+});
+
+// Only the JSON branch is bounded; capping a string would truncate a legitimate
+// `code`. Chrome and Safari differ 4x in maximum string length, so an uncapped
+// serialisation is "" on one and hundreds of megabytes of DOM on the other.
+test("toolArgText caps a serialised object but never a string", () => {
+ const long = "x".repeat(500_000);
+ assert.equal(toolArgText(long), long);
+
+ // Wide rather than deep: a deep one hits the engine's own recursion limit
+ // first, and that limit is not the same on every engine.
+ const wide = JSON.parse(`[${new Array(200_000).fill(0).join(",")}]`);
+ const out = toolArgText(wide);
+ assert.ok(out.length <= 100_001, `serialised object was ${out.length} chars`);
+ assert.ok(out.endsWith("…"), "a truncated value says so");
+ assert.ok(out.startsWith("[0,0,0,"), "the head of the value still shows");
+
+ // Anything under the cap is exact, with no marker.
+ assert.equal(toolArgText({ cmd: "ls" }), '{"cmd":"ls"}');
+});
+
+// Absent and null both mean "the model has not written this yet", and the cards
+// branch on the empty string to show their writing state.
+test("toolArgText maps a missing argument to the empty string", () => {
+ assert.equal(toolArgText(undefined), "");
+ assert.equal(toolArgText(null), "");
+});
+
+test("a coerced argument survives the calls the cards make on it", () => {
+ assert.equal(toolArgText(42).split("\n")[0], "42");
+ assert.equal(toolArgText(42).slice(0, 60), "42");
+ assert.equal(toolArgText(42).trim(), "42");
+});
+
+// The helper's whole contract, over the shapes JSON can carry.
+test("toolArgText never throws", () => {
+ const shapes: unknown[] = [
+ undefined,
+ null,
+ 0,
+ -1.5,
+ true,
+ "",
+ "text",
+ [],
+ {},
+ [1, [2, [3]]],
+ { nested: { deep: [1, 2] } },
+ JSON.parse('{"toString":null}'),
+ JSON.parse('[{"toString":null}]'),
+ JSON.parse('{"valueOf":null,"toString":null}'),
+ Object.create(null),
+ ];
+ for (const shape of shapes) {
+ assert.doesNotThrow(() => toolArgText(shape));
+ assert.equal(typeof toolArgText(shape), "string");
+ }
+});
+
+/**
+ * Every `const <name> = ...` initializer declared inside `component`.
+ *
+ * Scoped to the component because tool-ui-web-search.tsx's module-level parsing
+ * helpers declare a `url` of their own out of a regex match.
+ */
+function readConsts(
+ relative: string,
+ component: string,
+ name: string,
+): string[] {
+ const source = sourceFile(relative);
+ let body: ts.Node | undefined;
+ const findComponent = (node: ts.Node): void => {
+ if (ts.isVariableDeclaration(node) && node.name.getText() === component) {
+ body = node.initializer;
+ }
+ // tool-fallback.tsx spells its components as function declarations.
+ if (ts.isFunctionDeclaration(node) && node.name?.getText() === component) {
+ body = node.body;
+ }
+ node.forEachChild(findComponent);
+ };
+ source.forEachChild(findComponent);
+ assert.ok(body, `${relative} does not declare ${component}`);
+
+ const found: string[] = [];
+ const visit = (node: ts.Node): void => {
+ if (
+ ts.isVariableDeclaration(node) &&
+ node.name.getText() === name &&
+ node.initializer
+ ) {
+ found.push(node.initializer.getText());
+ }
+ node.forEachChild(visit);
+ };
+ body.forEachChild(visit);
+ return found;
+}
+
+// The argument each card calls a string method on. Asserting the declaration
+// rather than the whole line lets a card spell the read either way it already
+// does: an `args` cast, or a parsed-args object.
+const COERCED: ReadonlyArray<
+ readonly [file: string, component: string, props: readonly string[]]
+> = [
+ ["tool-ui-python.tsx", "PythonToolUIImpl", ["code"]],
+ ["tool-ui-terminal.tsx", "TerminalToolUIImpl", ["command"]],
+ ["tool-ui-knowledge-base.tsx", "KnowledgeBaseToolUIImpl", ["query"]],
+ ["tool-ui-web-search.tsx", "WebSearchToolUIImpl", ["query", "url"]],
+ [
+ "tool-ui-code-execution.tsx",
+ "CodeExecutionToolUIImpl",
+ ["command", "path"],
+ ],
+ [
+ "tool-ui-image-generation.tsx",
+ "ImageGenerationToolUIImpl",
+ // size/quality/mime come off the RESULT, so they are the provider's JSON
+ // rather than the model's, and die the same way.
+ ["prompt", "resultPrompt", "size", "quality", "mime"],
+ ],
+ ["tool-fallback.tsx", "ToolFallbackTrigger", ["name"]],
+];
+
+const COERCION_CALL = /^toolArgText\(/;
+
+test("every card reads its text arguments through toolArgText", () => {
+ for (const [file, component, props] of COERCED) {
+ for (const prop of props) {
+ const [initializer, ...rest] = readConsts(
+ CARDS_DIR + file,
+ component,
+ prop,
+ );
+ assert.ok(initializer, `${file} does not declare ${prop}`);
+ assert.equal(rest.length, 0, `${file} declares ${prop} more than once`);
+ assert.match(
+ initializer,
+ COERCION_CALL,
+ `${file} reads ${prop} without coercing it; a model that sends a number there takes all of Studio down`,
+ );
+ }
+ }
+});
+
+// render_html is crash safe a different way: `typeof === "string"` drops a
+// non-string rather than rendering it. Listed so the closure test stays exact.
+const TYPEOF_GUARDED: ReadonlyArray<readonly [string, string]> = [
+ ["tool-ui-render-html.tsx", "RenderHtmlToolUIImpl"],
+];
+
+// A new card is the way this bug comes back, so adding one has to fail here
+// until somebody decides how it reads its arguments.
+test("no tool card escapes the coercion policy", () => {
+ const present = readdirSync(
+ fileURLToPath(new URL(CARDS_DIR, import.meta.url)),
+ )
+ .filter((f) => f.startsWith("tool-ui-") && f.endsWith(".tsx"))
+ .sort();
+ const accounted = [
+ ...COERCED.map(([file]) => file),
+ ...TYPEOF_GUARDED.map(([file]) => file),
+ ]
+ // COERCED also covers tool-fallback.tsx, which is the card every UNKNOWN
+ // tool lands on rather than a tool-ui-* of its own.
+ .filter((file) => file.startsWith("tool-ui-"))
+ .sort();
+ assert.deepEqual(
+ present,
+ accounted,
+ "a tool card is not listed in COERCED or TYPEOF_GUARDED",
+ );
+});
+
+// The card's own parseImageSize and metadata line, lifted from the shipped
+// source like the web search derivation in search-images.test.ts, so the test
+// cannot drift from the card.
+test("the image card survives a result whose fields are not strings", () => {
+ const file = `${CARDS_DIR}tool-ui-image-generation.tsx`;
+ const raw = readFileSync(
+ fileURLToPath(new URL(file, import.meta.url)),
+ "utf8",
+ );
+ const parser = raw.match(/const parseImageSize = \([\s\S]*?\n\};/);
+ assert.ok(parser, "parseImageSize moved");
+
+ // The card's own derivations, in the order it writes them.
+ const one = (name: string): string => {
+ const [initializer, ...rest] = readConsts(
+ file,
+ "ImageGenerationToolUIImpl",
+ name,
+ );
+ assert.ok(initializer, `${file} does not declare ${name}`);
+ assert.equal(rest.length, 0, `${file} declares ${name} more than once`);
+ return `const ${name} = ${initializer};`;
+ };
+ const body = [
+ parser[0],
+ "const imageResult = __result;",
+ one("size"),
+ one("quality"),
+ one("mime"),
+ one("imageDimensions"),
+ one("imageSrc"),
+ one("imageMetadata"),
+ "return { imageDimensions, imageSrc, imageMetadata };",
+ ].join("\n");
+ const render = new Function(
+ "__result",
+ "toolArgText",
+ ts.transpileModule(body, {
+ compilerOptions: { target: ts.ScriptTarget.ES2022 },
+ }).outputText,
+ ) as (
+ result: Record<string, unknown>,
+ coerce: typeof toolArgText,
+ ) => Record<string, unknown>;
+ const run = (result: Record<string, unknown>) =>
+ render({ image_b64: "AAA", ...result }, toolArgText);
+
+ // A provider that answers "size": 1024 rather than "1024x1024".
+ assert.deepEqual(run({ size: 1024, quality: "hd" }), {
+ imageDimensions: null,
+ imageSrc: "data:image/png;base64,AAA",
+ imageMetadata: "1024 · hd · image/png",
+ });
+ const hostile = JSON.parse('{"toString":null}');
+ assert.doesNotThrow(() => run({ size: hostile }));
+ assert.doesNotThrow(() => run({ quality: hostile }));
+ assert.doesNotThrow(() => run({ image_mime: hostile }));
+ assert.doesNotThrow(() => run({ image_mime: 42 }));
+ // A well-formed result renders exactly as it always did.
+ assert.deepEqual(
+ run({ size: "1024x768", quality: "hd", image_mime: "image/webp" }),
+ {
+ imageDimensions: { width: 1024, height: 768 },
+ imageSrc: "data:image/webp;base64,AAA",
+ imageMetadata: "1024x768 · hd · image/webp",
+ },
+ );
+});
+
+// A tool name is provider data too, and a non-string one matches nothing in
+// thread.tsx's by_name map, so it always reaches this card.
+test("the fallback card survives a tool name that is not a string", () => {
+ const source = readFileSync(
+ fileURLToPath(new URL(`${CARDS_DIR}tool-fallback.tsx`, import.meta.url)),
+ "utf8",
+ );
+ assert.match(
+ source,
+ /const name = toolArgText\(toolName\);/,
+ "tool-fallback.tsx reads toolName without coercing it",
+ );
+ assert.match(
+ source,
+ /formatMcpToolName\(name, mcpServer\) \?\? name/,
+ "tool-fallback.tsx passes the raw toolName to formatMcpToolName",
+ );
+ assert.equal(toolArgText(123).startsWith("mcp__"), false);
+});
+
+const TYPEOF_GUARD = /typeof parsedArgs\.\w+ === "string"/;
+
+test("the typeof-guarded card still guards", () => {
+ for (const [file, component] of TYPEOF_GUARDED) {
+ for (const prop of ["code", "title"]) {
+ const [initializer] = readConsts(CARDS_DIR + file, component, prop);
+ assert.ok(initializer, `${file} does not declare ${prop}`);
+ assert.match(
+ initializer,
+ TYPEOF_GUARD,
+ `${file} reads ${prop} without a type guard`,
+ );
+ }
+ }
+});