Repository navigation
[Fix] Unsloth Studio: Strip ANSI escape codes from Studio tool output panes - #7976
Conversation
8bab387 to
9fe8cfb
Compare
There was a problem hiding this comment.
💡 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".
| // 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-?]*[ -/]*[@-~])`, |
There was a problem hiding this comment.
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 👍 / 👎.
| : stripAnsi( | ||
| typeof result === "string" ? result : JSON.stringify(result, null, 2), |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
💡 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) |
There was a problem hiding this comment.
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 👍 / 👎.
| const BEL = String.fromCharCode(7); | ||
| const ANSI_ESCAPE_PATTERN = new RegExp( | ||
| [ | ||
| `${ESC}(?:[@-Z\\-_]|\\[[0-?]*[ -/]*[@-~])`, |
There was a problem hiding this comment.
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 👍 / 👎.
| stdout = subprocess.PIPE, | ||
| stderr = subprocess.STDOUT, |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
💡 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".
| stdout = subprocess.PIPE, | ||
| stderr = subprocess.STDOUT, |
There was a problem hiding this comment.
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 👍 / 👎.
| [ | ||
| `${ESC}(?:[@-Z\\-_]|\\[[0-?]*[ -/]*[@-~])`, | ||
| `${ESC}\\([ -/]*[0-?]*[@-~]`, | ||
| `${ESC}\\](?:[\\s\\S]*?)(?:${BEL}|${ESC}\\\\)`, |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
💡 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".
| } | ||
| j += 1; | ||
| } | ||
| index = terminated ? j : index + 2; |
There was a problem hiding this comment.
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 👍 / 👎.
| if (next >= 0x40 && next <= 0x5f) { | ||
| index += 2; | ||
| continue; |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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 👍 / 👎.
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
Pushed two commits since the last review:
Tests cover both, plus the aborted-CSI and ANSI-in-keys cases: 17 in @codex review |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
2 similar comments
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
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.
af8649a to
569f37f
Compare
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
…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
|
@codex review |
There was a problem hiding this comment.
💡 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); |
There was a problem hiding this comment.
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() |
There was a problem hiding this comment.
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 👍 / 👎.
…nto feat/strip-ansi-tool-output-c8fc
|
@codex review |
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
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:327was the path called out in the issue. Terminal and Python tools route finished output throughToolResultOutputand live chunks throughToolLiveOutput, so those panes needed the same treatment orls --color=alwayswould still look broken in the common case.Fix
Extract the existing
stripAnsihelper from diagnostics intolib/strip-ansi.tsand apply it before render in every tool-output<pre>:tool-fallback.tsxtool-result-output.tsx(strip before tailing so escape bytes do not inflate the char budget)tool-live-output.tsxtauri-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: sharedstripAnsi()(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 beforetailText.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
Not run here: full Studio chat journey with a loaded model invoking the live terminal tool (
ls --color=alwaysend-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.