Skip to content

[Fix] Unsloth Studio: Strip ANSI escape codes from Studio tool output panes - #7976

Merged
wasimysaid merged 18 commits into
unslothai:mainfrom
Souravrajvi0:feat/strip-ansi-tool-output-c8fc
Aug 8, 2026
Merged

wasimysaid merged 18 commits into
unslothai:mainfrom
Souravrajvi0:feat/strip-ansi-tool-output-c8fc

Conversation

@Souravrajvi0

@Souravrajvi0 Souravrajvi0 commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #7962.

Colourised CLIs (ls --color, grep --color, npm, cargo, pytest) emit SGR/CSI escape sequences when they think they have a TTY. The tool output pane renders into a plain <pre>, so those sequences reached the DOM as literal text (\x1b[32m, cursor moves, erase-line, …) instead of styled output.

The generic fallback at tool-fallback.tsx:327 was the path called out in the issue. Terminal and Python tools route finished output through ToolResultOutput and live chunks through ToolLiveOutput, so those panes needed the same treatment or ls --color=always would still look broken in the common case.

Fix

Extract the existing stripAnsi helper from diagnostics into lib/strip-ansi.ts and apply it before render in every tool-output <pre>:

pane file
generic fallback result tool-fallback.tsx
finished terminal / python output tool-result-output.tsx (strip before tailing so escape bytes do not inflate the char budget)
live streaming output tool-live-output.tsx
diagnostics redaction tauri-diagnostics.ts (imports the shared helper)

Stripping rather than parsing SGR into coloured spans matches what the pane is for and keeps the diff small.

Changes

  • studio/frontend/src/lib/strip-ansi.ts: shared stripAnsi() (CSI / Fe escapes).
  • studio/frontend/src/components/assistant-ui/tool-fallback.tsx: strip fallback result text.
  • studio/frontend/src/components/assistant-ui/tool-result-output.tsx: strip before tailText.
  • studio/frontend/src/components/assistant-ui/tool-live-output.tsx: strip live chunks.
  • studio/frontend/src/lib/tauri-diagnostics.ts: import shared helper.
  • studio/frontend/tests/strip-ansi.test.ts: SGR, CSI erase, pytest markers, plain-text no-op.
  • tests/studio/playwright_strip_ansi_smoke.py + studio/frontend/smoke-ansi.html: component browser smoke harness.
  • tests/studio/playwright_strip_ansi_studio_e2e.py: Studio stack smoke (backend + vite dev + auth).

Testing

node --experimental-strip-types --test tests/strip-ansi.test.ts
✔ 5 pass  ✖ 0 fail

npm test
✔ 468 pass  ✖ 0 fail

python tests/studio/playwright_strip_ansi_smoke.py
[ansi-smoke] vite ready at http://127.0.0.1:8000
[ansi-smoke] tool-result-output text: 'file.txt\nerror'
[ansi-smoke] tool-fallback-result text: 'file.txt\nerror'
[ansi-smoke] all panes rendered clean text (no ANSI escapes)

python tests/studio/playwright_strip_ansi_studio_e2e.py
[ansi-studio] tool-result-output on Studio stack: 'file.txt\nerror'
[ansi-studio] tool-fallback-result on Studio stack: 'file.txt\nerror'
[ansi-studio] Studio stack smoke passed (backend up, vite dev, tool panes clean)

Not run here: full Studio chat journey with a loaded model invoking the live terminal tool (ls --color=always end-to-end through agent inference). That path uses the same panes exercised above; the remaining gap is model load + tool orchestration, not the stripper itself.

@Souravrajvi0
Souravrajvi0 force-pushed the feat/strip-ansi-tool-output-c8fc branch from 8bab387 to 9fe8cfb Compare August 6, 2026 03:42

@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: 8c55684804

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread studio/frontend/src/lib/strip-ansi.ts Outdated
// cargo, pytest, …). Built via fromCharCode so the source stays free of a
// literal ESC that some editors / log scrapers trip over.
const ANSI_ESCAPE_PATTERN = new RegExp(
`${String.fromCharCode(27)}(?:[@-Z\\-_]|\\[[0-?]*[ -/]*[@-~])`,

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 Strip OSC escape payloads too

When a tool emits OSC sequences such as terminal hyperlinks or title controls (ESC ] ... BEL / ESC \\), this pattern does not match them at all; only CSI (ESC[...) and a few two-byte escapes are removed. In those outputs the <pre> still receives raw control text like ]8;;file://... plus BEL/ST bytes, so ANSI garbage remains visible despite this new shared stripper. Please consume the full OSC payload before rendering, or use a more complete ANSI-strip pattern.

Useful? React with 👍 / 👎.

Comment on lines +305 to +306
: stripAnsi(
typeof result === "string" ? result : JSON.stringify(result, null, 2),

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 Strip object string fields before JSON serialization

When a fallback tool returns a structured object or array containing colored output (for example { stdout: "\u001b[32mfile\u001b[0m" }), JSON.stringify escapes the ESC byte to the literal text \u001b before stripAnsi runs, so the pane still shows \u001b[32m/[0m garbage. This path only cleans raw string results; sanitize nested string values before stringifying, or strip the escaped form after serialization.

Useful? React with 👍 / 👎.

@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: a2b07ca2ca

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

ART.mkdir(parents = True, exist_ok = True)

if AUTH_DIR.exists():
shutil.rmtree(AUTH_DIR)

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 Isolate the Studio auth directory before deleting it

When this e2e smoke is run outside a throwaway HOME, this recursively removes the user's real ~/.unsloth/studio/auth directory before starting the backend, wiping their auth DB/bootstrap password/session state. The backend is launched with the inherited environment plus only UNSLOTH_API_ONLY, so there is no temp UNSLOTH_STUDIO_HOME or similar isolation protecting local/CI installs; create a temporary Studio home/auth root for the test and delete only that.

Useful? React with 👍 / 👎.

Comment thread studio/frontend/src/lib/strip-ansi.ts Outdated
const BEL = String.fromCharCode(7);
const ANSI_ESCAPE_PATTERN = new RegExp(
[
`${ESC}(?:[@-Z\\-_]|\\[[0-?]*[ -/]*[@-~])`,

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 Strip SCS reset escapes emitted by terminfo

Fresh evidence in the revised pattern: it now handles OSC, but still does not match charset-designation sequences such as ESC ( B, which are commonly part of xterm-style sgr0 resets before the SGR reset. For output like \u001b(B\u001b[mok, this removes only \u001b[m and leaves \u001b(Bok, so the tool pane can still show ANSI garbage; include SCS sequences or use a more complete ANSI stripper.

Useful? React with 👍 / 👎.

Comment on lines +136 to +137
stdout = subprocess.PIPE,
stderr = subprocess.STDOUT,

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 Drain child output pipes during smoke runs

When the Studio backend or Vite writes more than the OS pipe buffer during startup, these stdout/stderr pipes are never read anywhere in the script, so the child can block and the smoke waits can hang or time out even though the service would otherwise be ready. Redirect the output to a log file/DEVNULL or drain it from a background thread before waiting on health.

Useful? React with 👍 / 👎.

@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: 0eccd2c1fd

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +50 to +51
stdout = subprocess.PIPE,
stderr = subprocess.STDOUT,

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 Drain the Vite stdout pipe in the component smoke

When npm/Vite logs enough output during startup, such as dependency optimization warnings or repeated errors in CI, this child writes to a pipe that the script never reads, so it can block once the OS pipe buffer fills while wait_for_vite or the browser step appears to hang. The Studio e2e helper now drains its children, but this component smoke still needs the same drain or a redirect to a log file/DEVNULL.

Useful? React with 👍 / 👎.

Comment thread studio/frontend/src/lib/strip-ansi.ts Outdated
[
`${ESC}(?:[@-Z\\-_]|\\[[0-?]*[ -/]*[@-~])`,
`${ESC}\\([ -/]*[0-?]*[@-~]`,
`${ESC}\\](?:[\\s\\S]*?)(?:${BEL}|${ESC}\\\\)`,

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 Avoid quadratic scans for unterminated OSC output

When a tool emits many OSC introducers without BEL/ST terminators, for example binary output or repeated \x1b] fragments, this lazy [\s\S]*? branch retries from each introducer and scans to the end each time. Because the live and finished tool panes run stripAnsi on the browser main thread, a few hundred KB of such output can freeze the Studio tab; consume unmatched OSC starts in linear time or use a bounded/non-backtracking matcher.

Useful? React with 👍 / 👎.

@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: 4478aecec0

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread studio/frontend/src/lib/strip-ansi.ts Outdated
}
j += 1;
}
index = terminated ? j : index + 2;

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 Consume unfinished OSC payloads

Fresh evidence in the linear scanner: when an OSC sequence has payload but no BEL/ST terminator yet, this branch only skips the ESC] introducer, so the remaining payload is appended as normal text. In live tool output, chunks are appended incrementally and stripped while the stream is still partial, so a split terminal hyperlink/title sequence such as ESC]8;;file://... visibly leaks 8;;file://... garbage until the terminator arrives; a final malformed OSC remains visible permanently. Advance through the scanned payload for unterminated OSCs instead of resetting to index + 2.

Useful? React with 👍 / 👎.

Comment thread studio/frontend/src/lib/strip-ansi.ts Outdated
Comment on lines +62 to +64
if (next >= 0x40 && next <= 0x5f) {
index += 2;
continue;

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 Consume DCS/PM/APC string-control payloads

When a tool emits ANSI string-control sequences such as DCS (ESC P ... ESC \\), PM (ESC ^ ... ESC \\), or APC (ESC _ ... ESC \\)—for example sixel/kitty graphics or terminal capability data—this single-character Fe branch strips only the two-byte introducer and leaves the payload plus terminator in the <pre>. That means these valid ANSI escapes still render garbage even though the new helper is now shared across tool panes; handle string-control payloads through their ST terminator before falling back to two-byte Fe controls.

Useful? React with 👍 / 👎.

index += 1;
}
if (index < text.length) {
index += 1;

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 Drop two-byte ESC 7/8/c controls

For non-CSI two-byte ANSI controls outside the @-_ range, such as DEC save/restore cursor (ESC 7/ESC 8) or full terminal reset (ESC c from reset/terminfo), this fallback consumes only the ESC byte and then renders the final byte as plain text. Those sequences are common in terminal-oriented command output, so the tool panes can still show stray 7, 8, or c characters despite the shared ANSI stripper; consume the full two-byte control for the Fs/Fp ranges as well.

Useful? React with 👍 / 👎.

@LeoBorcherding LeoBorcherding changed the title Strip ANSI escape codes from Studio tool output panes [Fix] Unsloth Studio: Strip ANSI escape codes from Studio tool output panes Aug 6, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@LeoBorcherding

Copy link
Copy Markdown
Collaborator

Pushed two commits since the last review:

4b0663e merges current main in, clearing the out-of-date-with-base block. That also drops the test_desktop_reliability_frontend_contract.py edit from this diff, since #7979 fixed the 30px nav-icon contract on main independently.

f13e2d2 fixes two things I found while re-checking the earlier review rounds:

  • stringifyToolResult pre-walked results with Object.entries before JSON.stringify, so any value carrying a toJSON serialized as {} — a tool result like { at: <Date> } rendered as {"at": {}} in the fallback pane instead of the ISO string. It now strips through a JSON.stringify replacer, which runs after toJSON. The replacer also reaches ANSI in object keys, which the pre-walk left rendering as the escaped-ESC text JSON emits, followed by [32m — the residue of the round-1 finding about escaped ESC bytes surviving serialization.
  • The CSI scan ran to the first 0x40-0x7e byte, so an aborted CSI consumed the introducer of the sequence after it and leaked that one's parameters as text: an ESC [ with no final byte followed by a real ESC [ 3 2 m rendered as 32mhi. It now scans only parameter/intermediate bytes and leaves the index on the offending byte when no final byte follows.

Tests cover both, plus the aborted-CSI and ANSI-in-keys cases: 17 in strip-ansi.test.ts, full frontend suite green, typecheck clean.

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

2 similar comments
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

Souravrajvi0 and others added 13 commits August 7, 2026 20:06
Colourised CLIs (ls --color, grep --color, npm, cargo, pytest) emit
SGR/CSI sequences that a plain <pre> cannot style, so they rendered as
literal escape text. Extract the existing stripAnsi helper and apply it
in the generic fallback plus the terminal/python result and live panes.

Fixes unslothai#7962
Playwright mounts ToolResultOutput and ToolFallbackResult with coloured
CLI output and asserts the rendered <pre> text is escape-free.
…ai#7962

Include studio E2E smoke (backend + vite + auth) and commit Playwright
screenshots so the PR description can embed before/after panes.
Extend stripAnsi to consume OSC payloads (hyperlinks, title controls)
terminated by BEL or ST. Add stripAnsiDeep/stringifyToolResult so
structured fallback tool output is cleaned before JSON.stringify.
Strip SCS charset resets, isolate Studio auth in the e2e smoke via a
temporary UNSLOTH_STUDIO_HOME, and drain child process pipes so long
smoke runs cannot hang on full OS buffers.
Use O(n) OSC scanning that skips only unterminated introducers, drain
Vite stdout in the strip-ansi smoke test, and align the desktop
reliability contract with the 30px titlebar control size.
Consume unterminated OSC payloads, DCS/PM/APC string controls, and
two-byte Fe sequences (DEC save/restore, reset). Update contract test
for the 30px New chat button.
…xt escape

stringifyToolResult walked the result with Object.entries before handing it to
JSON.stringify, so anything carrying a toJSON (Date, and friends) serialized as
{} in the fallback pane. Strip through a JSON.stringify replacer instead: it
runs after toJSON, and it also reaches ANSI in object keys, which the pre-walk
left rendering as escaped-unicode litter.

The CSI scan ran to the first 0x40-0x7e byte, so an aborted sequence consumed
the introducer of the sequence after it and leaked that one's parameters as
text. Scan only parameter / intermediate bytes and leave the index on the
offending byte when no final byte follows.
The update() path now wraps setup in _WindowsLauncherUpdateTransaction
instead of _release_self_exe_lock_windows. Align the ordering assertion
with the current studio.py structure.
provider.tsx now uses --studio-titlebar-navigation-offset-y 4px and
--studio-chat-header-padding-top 9px; update the desktop reliability
contract assertions to match.
@Souravrajvi0
Souravrajvi0 force-pushed the feat/strip-ansi-tool-output-c8fc branch from af8649a to 569f37f Compare August 7, 2026 20:06
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

wasimysaid and others added 2 commits August 8, 2026 14:22
…output-c8fc

# Conflicts:
#	studio/frontend/src/components/assistant-ui/tool-ui-python.tsx
#	tests/python/test_studio_runtime_gate.py
#	tests/studio/test_desktop_reliability_frontend_contract.py
@wasimysaid

Copy link
Copy Markdown
Collaborator

@codex review

@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: 971c545686

ℹ️ 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".

: result
? JSON.stringify(result, null, 2)
: "";
const output = result == null ? "" : stringifyToolResult(result);

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 Normalize both values before preserving full output

When a colorized terminal result is truncated, toolFullOutput retains the raw ANSI-bearing stream while this line cleans only the final result before preferFullToolOutput compares them. The cleaned truncated prefix no longer matches the raw stream (especially when the stream begins with SGR), so preferFullToolOutput falls through to concatenating the full stream and the result; after rendering strips the stream, users see the output followed by a duplicate truncated prefix. Strip both values before comparison, or choose the full/raw result first and sanitize only the selected display value.

Useful? React with 👍 / 👎.



def stop_process(proc: subprocess.Popen[str]) -> None:
proc.terminate()

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 Terminate the spawned Vite process tree

On each smoke run, npm run dev launches Vite as a descendant process, but this only signals and waits for the npm wrapper. The Vite process can therefore remain alive after the script exits, retaining port 8000 so a subsequent local smoke run fails at --strictPort and leaking a background service for the rest of the CI job. Start the server in its own process group/session and terminate that entire group during cleanup.

Useful? React with 👍 / 👎.

@wasimysaid

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: f345bb1a7f

ℹ️ 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".

@wasimysaid
wasimysaid merged commit 051e71c into unslothai:main Aug 8, 2026
35 of 40 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Unsloth Studio: ANSI escape codes render as literal text in the tool output pane

3 participants