Skip to content

Studio: don't crash the app when a tool arg isn't a string - #9641

Merged
danielhanchen merged 7 commits into
unslothai:mainfrom
NilayYadav:fix-tool-card-arg-coercion
Aug 25, 2026
Merged

danielhanchen merged 7 commits into
unslothai:mainfrom
NilayYadav:fix-tool-card-arg-coercion

Conversation

@NilayYadav

@NilayYadav NilayYadav commented Aug 24, 2026 •

Copy link
Copy Markdown
Collaborator

If a model sends a tool call with a number instead of a string, the whole app dies and shows "Something went wrong!". Reopening the chat brings it right back, because the bad message is saved.

The python card does code.split("\n") on whatever the model sent. ?? "" only covers null and undefined, so a number goes straight to .split and throws. A tool card has no boundary above it — the nearest catcher is the router's — so the entire UI unmounts. markdown-block-boundary.tsx documents the same failure measured on a Markdown block.

Every card now reads its text arguments through one helper, toolArgText, so a number renders as 42 instead of taking the session with it:

card argument call it makes
python code .split("\n")
terminal command .slice(0, 60)
code_execution command .replace(/\s+/g, " ")
image_generation prompt .trim()
web_search query, url .trim(), .startsWith() — already coerced
search_knowledge_base query interpolated only — never threw, coerced for consistency

code_execution and image_generation were missed in the first pass and crash the same way. code_execution arguments are the model's own server_tool_use JSON forwarded untouched (external_provider.py:2818); image_generation carries revised_prompt from the provider, and Studio accepts a user-supplied OpenAI-compatible base_url, so that string is third-party controlled.

The arg interfaces now say unknown rather than string, so an uncoerced read is a type error rather than a runtime one.

render_html is left alone: it already guards with typeof === "string", which is crash-safe by a different rule.

Tests cover the coercion behaviourally and assert through the TypeScript AST that every card uses it, with a closed-world check that fails when a new tool-ui-*.tsx appears unaccounted for — a new card is how this comes back.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: de19960ed7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@NilayYadav

Copy link
Copy Markdown
Collaborator Author

GitHub Actions reproduction

The crash and its fix are reproduced on Actions in one run, 3 jobs. Same workflow, same runner image, same npm ci; the only thing that changes between jobs is the six tool-card sources, checked out at a different commit each time. Each job asserts a predeclared crash count, so a wrong result fails the job rather than being read off a log.

The probe takes the argument derivation straight out of each shipped card — the way tests/search-images.test.ts already does — and runs it on 42, which is what a local model sends when it decides code is a number.

Tool card Reads Call it makes main 785a68dc4 this PR at 6b06eabd0 head de19960ed
python code .split("\n") 💥 code.split is not a function ✅ "42" ✅ "42"
terminal command .slice(0, 60) 💥 command.slice is not a function ✅ "42" ✅ "42"
search_knowledge_base query interpolated only ✅ never threw ✅ ✅
web_search query, url .trim(), .startsWith() ✅ already coerced ✅ ✅
code_execution command .replace(/\s+/g, " ") 💥 command.replace is not a function 💥 still crashed ✅ "42"
image_generation prompt .trim() 💥 prompt.trim is not a function 💥 still crashed ✅ "42"

4 crashed → 2 crashed → 0 crashed, each asserted exactly.

The two that survived the first pass are reachable the same way the ones it fixed are:

  • code_execution arguments are the model's own server_tool_use JSON, parsed and forwarded untouched — external_provider.py:2818, emit_args = {"kind": kind, **parsed_args}.
  • image_generation carries revised_prompt from the provider (external_provider.py:5858), and Studio accepts a user-supplied OpenAI-compatible base_url, so that string is third-party controlled rather than always OpenAI's.

On severity: markdown-block-boundary.tsx already documents this exact failure measured on a Markdown block — a throw with no boundary above it reaches TanStack Router's CatchBoundaryImpl, which replaces the whole of Studio with "Something went wrong!" and unmounts the assistant-ui runtime. Tool cards have no such boundary, and the argument is persisted with the message, so the thread stays dead on every reopen.

@NilayYadav

Copy link
Copy Markdown
Collaborator Author

Studio before/after

Two isolated installs on this box, install.sh --local each, separate homes, caches, ports and passwords, each stamped with the SHA it was built from and each logged into with its own credential so the side answering is provably the side that was built.

  • BEFORE 785a68dc4 — the PR's own merge base, and also current upstream main.
  • AFTER de19960ed — this PR's head.

Both sides were seeded with the same stored thread through the real chat-history API (stored_message_count: 2 on both), holding a python call with {"code": 42} and a code_execution call with {"command": 42}. The thread is then reopened from history, which is the path that matters: the argument is persisted with the message, so this is what the user sees on every visit, not a one-off streaming glitch. The frontend build is the only variable.

PR 9641 Studio before/after

fact BEFORE 785a68dc4 AFTER de19960ed
app_crashed true false
crash_banner "Something went wrong" null
tool_cards_rendered 0 2
body_char_count 32 618
card_texts {} Used tool: Python: 42 script Copy Download python 42 / Used tool: Ran `42`

BEFORE is not a broken card — it is a blank white page carrying Something went wrong! and a Show Error button. No sidebar, no thread list, no composer: the router boundary has taken the entire application, which is the 32 characters of body text. AFTER is the whole of Studio with the thread open and both cards drawn, each showing the argument the model actually sent.

@NilayYadav

Copy link
Copy Markdown
Collaborator Author

CI triage

35 pass, 1 fail. The failure is not this PR's.

Repo tests (CPU) — FAIL: README: Launch section documents -H 0.0.0.0 opt-in (expected to find '0.0.0.0'). I extracted README.md and tests/sh/test_install_host_defaults.sh at 785a68dc4 and ran the test with no PR code: the same 10 passed / 1 failed. That SHA is this PR's merge base and current upstream main, so main fails this on its own — the README's Launch section no longer contains the string the test asserts. A rebase will not clear it, and it will fail every open PR until main is fixed. This PR touches nine files, all under studio/frontend/; no README, no shell, no Python.

(Python 3.13) — failed once on test_openai_tool_passthrough.py::…retry_adopts_delayed_response with a TimeoutError, 29623 passed / 1 failed. It is an asyncio.Event()-gated streaming test and references nothing this PR changes. (Python 3.11) passed the same suite on the same head, and the job passed on rerun with no code change. Flake.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@NilayYadav
NilayYadav force-pushed the fix-tool-card-arg-coercion branch from de19960 to bbf5502 Compare August 24, 2026 20:43
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: bbf55029de

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

NilayYadav and others added 3 commits August 25, 2026 02:18
The args are covered, but the same crash is still reachable through the
image card's RESULT and through a tool name.

parseImageSize guards nullish only, so a provider that answers "size": 1024
reached .match on a number; the metadata line joins size, quality and mime,
and Array.join calls ToString on each, so an object whose own toString is
null throws "Cannot convert object to primitive value"; extensionForMime
calls .toLowerCase on a mime that is the chunk's own inlineData.mimeType on
the Gemini path. These sit on the same result object whose prompt this branch
already coerces, for the same reason: Studio takes a user-set base_url.

A tool name lands in tool-fallback whenever it matches nothing in thread.tsx's
by_name map, which a non-string always does, and formatMcpToolName then calls
.startsWith on it. message-response-details-sheet.tsx and use-chat-search-index
already guard typeof toolName === "string"; this was the one place that did not.

Serialised objects are now capped at 100k characters. The engines disagree
about how long a string may be -- V8 stops at ~512Mi and throws, JSC at ~2Gi --
so an uncapped serialisation renders as "" in Chrome and as hundreds of
megabytes of DOM in Safari. Only the JSON branch is capped, so every string
argument is returned exactly as before.

The catch is not unreachable, and the comment now says what was measured:
Chrome, Firefox and Safari all parse at least 4,000,000 levels of nesting, and
then Firefox throws InternalError: too much recursion and Safari RangeError
out of JSON.stringify where Chrome returns the string. On two of three engines
that catch is load-bearing for ordinary wire data.

Measured across the three engines with each card's own derivation lifted out
of its source: 139 of 344 renders killed the whole app before this branch,
0 after, identically in Chromium, Firefox and WebKit. Of the 205 inputs that
already rendered, 142 are byte-identical and the other 63 are non-strings that
used to print [object Object].
@danielhanchen

Copy link
Copy Markdown
Member

Review, cross-engine simulation, and two more holes of the same class

Reviewed at 2cde3d439 and pushed e442bd16c on top, then merged current main in. The bug is real, the fix is right, and the same crash was still reachable through two paths this branch had not covered.

The crash, reproduced independently

Each card's own const <arg> = ... initializer was lifted out of the shipped source with the TypeScript AST and run inside a React tree shaped like Studio's: a shell (sidebar, thread, composer) under one class boundary standing in for TanStack Router's CatchBoundaryImpl, with no boundary between it and the card. 43 argument shapes a model or provider can put on the wire, 8 derivations, in all three engines.

engine shell killed on 785a68dc4 shell killed on this branch
Chromium (Chrome, Edge) 139 / 344 0 / 344
Firefox (SpiderMonkey) 139 / 344 0 / 344
WebKit (Safari) 139 / 344 0 / 344

Identical counts in all three. web_search and search_knowledge_base are in that 139: the description says they were already safe, but String(...) and template interpolation both throw on {"toString":null}, so this branch fixes four more cases than it claims.

The new test file also fails on the base for the right reason (tool-ui-python.tsx reads code without coercing it), so it is a real regression test rather than one that passes either way.

Two more paths of the same class, now fixed

  1. tool-ui-image-generation.tsx, the result side. The branch coerces prompt off the result but not its siblings. parseImageSize guards nullish only, so "size": 1024 reached .match on a number; the metadata line [size, quality, mime].join(" - ") calls ToString per element; extensionForMime calls .toLowerCase on a mime that is the chunk's own inlineData.mimeType on the Gemini path. Same provider-controlled object, same argument for coercing it.

    size: 1024                      parseImageSize=CRASH(TypeError: size?.match is not a function)
    quality: {"toString":null}      imageMetadata join=CRASH(Cannot convert object to primitive value)
    image_mime: {"toString":null}   data: template=CRASH(Cannot convert object to primitive value)
    
  2. tool-fallback.tsx. A tool name is provider data too, and a non-string name matches nothing in thread.tsx's by_name map, so it always lands on the fallback card, where formatMcpToolName calls .startsWith on it. message-response-details-sheet.tsx and use-chat-search-index.ts already guard typeof toolName === "string"; this was the one place that did not.

One thing the coercion introduced, also fixed

Serialising an object creates a string where the old code threw, and the engines cap string length differently: V8 at ~512 MiB with a RangeError, SpiderMonkey ~1 GiB, JavaScriptCore ~2 GiB. Measured at 100k nesting levels, Chrome produced 600,002 characters and handed them to React. Serialised objects are now capped at 100k characters; only the JSON branch is capped, so every string argument is returned exactly as before.

While measuring that: the catch is not unreachable. All three engines parse at least 4,000,000 levels of nesting, and then Firefox throws InternalError: too much recursion and Safari RangeError: Maximum call stack size exceeded out of JSON.stringify, where Chrome returns the string. On two of three engines that catch is load-bearing for ordinary wire data, so the comment now says so. Keep the binding bare, incidentally: Firefox's error is an InternalError, not a RangeError.

Nothing that worked before changes

Of the 205 inputs that already rendered on the base, 142 are byte-identical on this branch and the other 63 are all non-strings that previously printed [object Object], ls,-la or [object Map]. Not one string, null or absent argument renders differently, on any engine. The change is frontend-source only: no package.json, no lockfile, no build config, no backend, no API and no schema, so an existing install is unaffected until it is upgraded, and on upgrade a thread that was permanently dead starts rendering.

Everything that was run

  • npm ci leaves the tree clean; npm run typecheck (both tsconfigs) clean; npm test 4899 / 4899.
  • Same suite on Node 22.12 and Node 24: both green. (Node 20 cannot run npm test at all, since --experimental-strip-types did not exist before 22.6. That is independent of this branch, but it does mean the "node": "^20.19.0" engines range is not accurate.)
  • npm run build succeeds.
  • Windows CRLF checkout simulated (every source rewritten to \r\n): tests pass. macOS AppleDouble ._tool-ui-*.tsx sidecar in the cards directory: the closed-world test is unaffected, since it filters on the tool-ui- prefix.
  • Adversarial helper probe over deep nesting, circular refs, a throwing toJSON, a throwing enumerable getter, BigInt inside an object, Symbol.toPrimitive: null, null-prototype objects and __proto__ from JSON.parse: no throw, always a string, and Object.prototype is not polluted.

CI note

The Repo tests (CPU) red was not this branch's, but the description's reading of it is now out of date: main has since rewritten tests/sh/test_install_host_defaults.sh, which now passes 45 / 0. Merging main in clears it, and I have done that.

Follow-ups, deliberately not in this branch

Same bug class, different layer, so they want their own change:

  • chat-adapter.ts:6642 puts argsText straight into <pre>{argsText}</pre> when a provider sends arguments as an object rather than the JSON string the spec requires, and React throws Objects are not valid as a React child. The concatenating branch at :6592 throws on {"toString":null} inside the stream generator instead.
  • tool-ui-python.tsx:41 isStructuredResult checks only that the keys exist, where the terminal card's isSandboxToolResult checks their types. A {"text":["hi"]} result reaches charCodeAt. Not reachable from the live backend, which builds that envelope itself, but reachable from an Open WebUI import.
  • sandbox-files.ts:55 isSandboxFileList validates name but not size, and formatSize does size < 1024.
  • A ToolCardBoundary in the shape of markdown-block-boundary.tsx would contain any future throw in a card, including result-side ones, rather than relying on every new card remembering to coerce.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 67f5cdc8a3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

if (typeof value === "object") {
// `?? ""` because a `toJSON` can return undefined, a function or a symbol,
// for which JSON.stringify returns undefined rather than a string.
const json = JSON.stringify(value) ?? "";

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Apply the cap while serializing large object arguments

When a model supplies a large object or array as an argument, JSON.stringify still traverses the complete value and allocates the entire serialized string before the 100,000-character slice is applied. Reopening a persisted thread containing a multi-megabyte malformed argument can therefore block the UI and temporarily duplicate the whole payload in memory, whereas the previous object coercion was constant-size; enforce the limit during serialization rather than after materializing the full JSON.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The mechanism is described correctly, JSON.stringify does materialize the whole string before the slice. The magnitude is not, and the comparison to a constant-size predecessor points at code that was removed for being a crash: String() on {"toString":null} throws "Cannot convert object to primitive value", which is the P1 on this same file earlier in this PR.

Measured on this branch, Node 24, against the wire payload that has to exist for the value to reach the card at all:

wire 0.2 MB   JSON.parse   0.4 ms / +0.2 MB    toolArgText   0.3 ms / +0.1 MB   out=100001 chars
wire 2.1 MB   JSON.parse   4.1 ms / +0.8 MB    toolArgText   2.2 ms / +1.0 MB   out=100001 chars
wire  21 MB   JSON.parse  42.1 ms / +7.6 MB    toolArgText  27.8 ms / +10.5 MB  out=100001 chars

The helper is cheaper than the parse that is its own precondition. chat-adapter.ts:6597 and :6646 JSON.parse the full argsText and keep both the raw string and the parsed graph on the message part, so on reopening a persisted thread that payload is already resident twice, permanently, before this function runs. The transient third copy is the smallest of the three and the only one that is bounded on the way out.

Enforcing the limit during serialization has no cheap form. There is no streaming or bounded JSON.stringify in the platform and no TC39 proposal for one (the closest is the WICG async-JSON discussion, which stalled on needing a full synchronous copy first). A replacer cannot see accumulated output length, so a budget there is an estimate over pre-escaping values, and MDN notes the replacer is invoked per key-value pair and is slower than plain JSON.stringify on large objects, which is exactly the input this is meant to protect. A real bound means a streaming serializer dependency (json-stream-lite, big-json) inside a helper whose entire contract is that it cannot throw, and this repo pins and supply-chain-audits frontend deps.

Also worth noting that this path is unreachable on a well-formed call: a string argument takes the early return and is never serialized, so everything here is already the malformed-input branch.

Leaving the cap where it is. It bounds what reaches the DOM, which is the cost that actually shows up as a frozen tab.

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed this on main, where tool-ui-python.tsx:144 and tool-ui-code-execution.tsx:137 still call string methods straight on the model's argument and take the whole app down on a persisted thread. Note #9640 adds the same guard in tool-ui-python.tsx, so the two overlap and we should reconcile them before either lands.

Also moves the toolArgText docblock back onto the function, where a second
docblock for the cap constant had displaced it. Comments only, AST verified.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: e0c22943c4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Cuts the preamble that restated tool-arg-text.ts's own docblock. Comments
only, AST verified.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from NilayYadav Aug 25, 2026
@unslothai unslothai deleted a comment from NilayYadav Aug 25, 2026
@unslothai unslothai deleted a comment from Etherll Aug 25, 2026
@unslothai unslothai deleted a comment from NilayYadav Aug 25, 2026
@unslothai unslothai deleted a comment from NilayYadav Aug 25, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 4505152afa

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 5001473 into unslothai:main Aug 25, 2026
34 of 35 checks passed
danielhanchen added a commit that referenced this pull request Aug 25, 2026
* Studio: coerce model-supplied tool args before the cards render them

* Studio: coerce the two tool cards the first pass missed, behind one helper

* Studio: serialise object tool args instead of coercing them

* Studio: coerce the provider-controlled fields the args pass missed

The args are covered, but the same crash is still reachable through the
image card's RESULT and through a tool name.

parseImageSize guards nullish only, so a provider that answers "size": 1024
reached .match on a number; the metadata line joins size, quality and mime,
and Array.join calls ToString on each, so an object whose own toString is
null throws "Cannot convert object to primitive value"; extensionForMime
calls .toLowerCase on a mime that is the chunk's own inlineData.mimeType on
the Gemini path. These sit on the same result object whose prompt this branch
already coerces, for the same reason: Studio takes a user-set base_url.

A tool name lands in tool-fallback whenever it matches nothing in thread.tsx's
by_name map, which a non-string always does, and formatMcpToolName then calls
.startsWith on it. message-response-details-sheet.tsx and use-chat-search-index
already guard typeof toolName === "string"; this was the one place that did not.

Serialised objects are now capped at 100k characters. The engines disagree
about how long a string may be -- V8 stops at ~512Mi and throws, JSC at ~2Gi --
so an uncapped serialisation renders as "" in Chrome and as hundreds of
megabytes of DOM in Safari. Only the JSON branch is capped, so every string
argument is returned exactly as before.

The catch is not unreachable, and the comment now says what was measured:
Chrome, Firefox and Safari all parse at least 4,000,000 levels of nesting, and
then Firefox throws InternalError: too much recursion and Safari RangeError
out of JSON.stringify where Chrome returns the string. On two of three engines
that catch is load-bearing for ordinary wire data.

Measured across the three engines with each card's own derivation lifted out
of its source: 139 of 344 renders killed the whole app before this branch,
0 after, identically in Chromium, Firefox and WebKit. Of the 205 inputs that
already rendered, 142 are byte-identical and the other 63 are non-strings that
used to print [object Object].

* Studio: tighten the tool arg coercion comments

Also moves the toolArgText docblock back onto the function, where a second
docblock for the cap constant had displaced it. Comments only, AST verified.

* Studio: trim the tool arg coercion test comments

Cuts the preamble that restated tool-arg-text.ts's own docblock. Comments
only, AST verified.

---------

Co-authored-by: danielhanchen <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants