Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
[Fix] Unsloth Studio: Strip ANSI escape codes from Studio tool output panes (#7976)
Souravrajvi0051e71cf2c23
diff --git a/.github/workflows/studio-frontend-ci.yml b/.github/workflows/studio-frontend-ci.ymlindex 681923e8631..aa2161cddc7 100644--- a/.github/workflows/studio-frontend-ci.yml+++ b/.github/workflows/studio-frontend-ci.yml@@ -17,6 +17,8 @@ on:- 'studio/frontend/**'- 'scripts/check_frontend_dep_removal.py'- 'tests/studio/test_frontend_dep_removal.py'++ - 'tests/studio/playwright_strip_ansi_smoke.py'- 'scripts/sync_allow_scripts_pins.py'- 'tests/studio/test_sync_allow_scripts_pins.py'- '.github/workflows/studio-frontend-ci.yml'@@ -146,6 +148,19 @@ jobs:- name: Unit testsrun: npm test++ - name: Install Chromium for tool-output smoke+ working-directory: ${{ github.workspace }}+ run: |+ python3 -m pip install 'playwright>=1.45,<2'+ python3 -m playwright install --with-deps chromium++ - name: Browser smoke for ANSI tool output+ working-directory: ${{ github.workspace }}+ env:+ PW_BROWSER: chromium+ run: python3 tests/studio/playwright_strip_ansi_smoke.py+- name: Buildrun: npm run builddiff --git a/studio/frontend/smoke-ansi-main.tsx b/studio/frontend/smoke-ansi-main.tsxnew file mode 100644index 00000000000..8c930aee450--- /dev/null+++ b/studio/frontend/smoke-ansi-main.tsx@@ -0,0 +1,48 @@+// 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 { createRoot } from "react-dom/client";+import { ToolResultOutput } from "@/components/assistant-ui/tool-result-output";+import { ToolFallbackResult } from "@/components/assistant-ui/tool-fallback";++import { ToolLiveOutputPane } from "@/components/assistant-ui/tool-live-output";+import { CodeExecutionResultOutput } from "@/components/assistant-ui/tool-ui-code-execution";++import { preferSanitizedFullToolOutput } from "@/features/chat";++const ESC = "\u001b";+const coloured = `${ESC}[32mfile.txt${ESC}[0m\n${ESC}[01;31merror${ESC}[0m`;++const truncated = "file.txt\n\n... (truncated; full output available in UI)";++const root = document.getElementById("root");+if (!root) {+ throw new Error("missing #root");+}++createRoot(root).render(+ <>+ <section data-smoke="tool-result-output">+ <h1>ToolResultOutput</h1>+ <ToolResultOutput text={coloured} />+ </section>+ <section data-smoke="tool-fallback-result">+ <h1>ToolFallbackResult</h1>+ <ToolFallbackResult result={coloured} />+ </section>+ <section data-smoke="tool-live-output">+ <h1>ToolLiveOutput</h1>+ <ToolLiveOutputPane output={coloured} />+ </section>+ <section data-smoke="code-execution-result">+ <h1>CodeExecutionResultOutput</h1>+ <CodeExecutionResultOutput result={coloured} />+ </section>+ <section data-smoke="reconciled-terminal-result">+ <h1>Reconciled terminal result</h1>+ <pre>{preferSanitizedFullToolOutput(coloured, truncated)}</pre>+ </section>+++ </>,+);diff --git a/studio/frontend/smoke-ansi.html b/studio/frontend/smoke-ansi.htmlnew file mode 100644index 00000000000..8868d03ea51--- /dev/null+++ b/studio/frontend/smoke-ansi.html@@ -0,0 +1,11 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <title>strip-ansi smoke</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/smoke-ansi-main.tsx"></script>+ </body>+</html>diff --git a/studio/frontend/src/components/assistant-ui/tool-fallback.tsx b/studio/frontend/src/components/assistant-ui/tool-fallback.tsxindex d0bc12706e7..9a4e9c4392e 100644--- a/studio/frontend/src/components/assistant-ui/tool-fallback.tsx+++ b/studio/frontend/src/components/assistant-ui/tool-fallback.tsx@@ -10,6 +10,7 @@ import {} from "@/components/ui/collapsible";import { Spinner } from "@/components/ui/spinner";import { useCollapseScrollLock } from "@/hooks/use-collapse-scroll-lock";+import { stripAnsi, stringifyToolResult } from "@/lib/strip-ansi";import { cn } from "@/lib/utils";import {type ToolCallMessagePartComponent,@@ -296,6 +297,10 @@ function ToolFallbackResult({}const imageResult = isMcpImageResult(result) ? result : null;+ // Colourised CLIs (ls --color, grep --color, npm, cargo, pytest) emit SGR+ // escapes that a plain <pre> cannot style; strip them so the pane stays+ // readable (#7962).+ const resultText = imageResult ? null : stringifyToolResult(result);return (<div@@ -308,7 +313,7 @@ function ToolFallbackResult({<>{imageResult.text && (<pre className="aui-tool-fallback-result-content whitespace-pre-wrap">- {imageResult.text}+ {stripAnsi(imageResult.text)}</pre>)}<div className="mt-2 flex flex-col gap-2">@@ -325,7 +330,7 @@ function ToolFallbackResult({</>) : (<pre className="aui-tool-fallback-result-content whitespace-pre-wrap">- {typeof result === "string" ? result : JSON.stringify(result, null, 2)}+ {resultText}</pre>)}</div>diff --git a/studio/frontend/src/components/assistant-ui/tool-live-output.tsx b/studio/frontend/src/components/assistant-ui/tool-live-output.tsxindex df202b57f07..3318dcc2c87 100644--- a/studio/frontend/src/components/assistant-ui/tool-live-output.tsx+++ b/studio/frontend/src/components/assistant-ui/tool-live-output.tsx@@ -5,8 +5,8 @@import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";import { useToolOutputFor, useToolPaneScope } from "@/features/chat";+import { stripAnsi, tailToolOutput } from "@/lib/strip-ansi";import { useEffect, useMemo, useRef } from "react";-import { tailText } from "./tool-result-output";/*** Live-scrolling stdout/stderr pane for a running server-side tool, backed by@@ -21,13 +21,21 @@ export function ToolLiveOutput({ toolCallId }: { toolCallId: string }) {paneScope,toolCallId,);+ return output ? <ToolLiveOutputPane output={output} /> : null;+}++/** Presentational production pane, exported so browser smoke tests this exact path. */+export function ToolLiveOutputPane({ output }: { output: string }) {const scrollRef = useRef<HTMLPreElement>(null);// Pinned to the bottom until the user scrolls up (handler below), so// streaming chunks no longer yank them down.const pinnedToBottom = useRef(true);- // The stream can reach hundreds of KB; render only the tail while live.- const visible = useMemo(() => tailText(output).visible, [output]);+ // The stream can reach hundreds of KB; render only the clean tail while live.+ const visible = useMemo(+ () => tailToolOutput(stripAnsi(output)).visible,+ [output],+ );const handleScroll = () => {const el = scrollRef.current;@@ -46,10 +54,6 @@ export function ToolLiveOutput({ toolCallId }: { toolCallId: string }) {}}, [visible]);- if (!output) {- return null;- }-return (<div className="aui-tool-live-output mt-2 border-t border-dashed pt-2"><span className="text-xs font-medium text-muted-foreground">output</span>diff --git a/studio/frontend/src/components/assistant-ui/tool-result-output.tsx b/studio/frontend/src/components/assistant-ui/tool-result-output.tsxindex 45f72ed96c8..29338956d9a 100644--- a/studio/frontend/src/components/assistant-ui/tool-result-output.tsx+++ b/studio/frontend/src/components/assistant-ui/tool-result-output.tsx@@ -3,34 +3,9 @@"use client";+import { stripAnsi, tailToolOutput } from "@/lib/strip-ansi";import { useMemo, useState } from "react";-/** Tail-line cap so a huge output never mounts a megabyte <pre> block. */-const TAIL_LINES = 2000;-/** Char backstop for pathological single-line outputs. */-const TAIL_CHARS = 200_000;--interface Tail {- visible: string;- hiddenLines: number;- hiddenChars: number;-}--export function tailText(text: string): Tail {- let visible = text;- let hiddenLines = 0;- let hiddenChars = 0;- const lines = visible.split("\n");- if (lines.length > TAIL_LINES) {- hiddenLines = lines.length - TAIL_LINES;- visible = lines.slice(hiddenLines).join("\n");- }- if (visible.length > TAIL_CHARS) {- hiddenChars = visible.length - TAIL_CHARS;- visible = visible.slice(hiddenChars);- }- return { visible, hiddenLines, hiddenChars };-}/*** Finished-tool output pane: renders the tail (~2000 lines) with a "Show all"@@ -39,7 +14,10 @@ export function tailText(text: string): Tail {*/export function ToolResultOutput({ text }: { text: string }) {const [showAll, setShowAll] = useState(false);- const tail = useMemo(() => tailText(text), [text]);+ // Strip SGR before tailing so colour codes neither inflate the char budget+ // nor leak into the DOM as literal escape text (#7962).+ const cleaned = useMemo(() => stripAnsi(text), [text]);+ const tail = useMemo(() => tailToolOutput(cleaned), [cleaned]);const truncated = !showAll && (tail.hiddenLines > 0 || tail.hiddenChars > 0);return (@@ -56,7 +34,7 @@ export function ToolResultOutput({ text }: { text: string }) {</button>)}<pre className="mt-1 max-h-60 overflow-auto whitespace-pre-wrap break-words font-mono text-xs">- {showAll ? text : tail.visible}+ {showAll ? cleaned : tail.visible}</pre></>);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.tsxindex 84309815e5f..bb2320904b8 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@@ -4,6 +4,8 @@"use client";import { copyToClipboard } from "@/lib/copy-to-clipboard";++import { stringifyToolResult } from "@/lib/strip-ansi";import {type ToolCallMessagePartComponent,useAuiState,@@ -98,6 +100,32 @@ function CopyBtn({ text }: { text: string }) {</button>);}+export function CodeExecutionResultOutput({ result }: { result: unknown }) {+ const resultText = useMemo(+ () => (result == null ? "" : stringifyToolResult(result)),+ [result],+ );+ const displayedResult = useMemo(+ () => truncateResult(resultText),+ [resultText],+ );++ if (!resultText) {+ return null;+ }+ return (+ <div>+ <div className="flex justify-end">+ <CopyBtn text={resultText} />+ </div>+ <pre className="mt-1 max-h-64 overflow-auto whitespace-pre-wrap break-words rounded bg-muted/50 p-2 text-xs">+ {displayedResult}+ </pre>+ </div>+ );+}++const CodeExecutionToolUIImpl: ToolCallMessagePartComponent = ({args,@@ -154,20 +182,6 @@ const CodeExecutionToolUIImpl: ToolCallMessagePartComponent = ({}}, [isRunning, hasText]);- const resultText = useMemo(- () =>- typeof result === "string"- ? result- : result != null- ? JSON.stringify(result, null, 2)- : "",- [result],- );- const displayedResult = useMemo(- () => truncateResult(resultText),- [resultText],- );-return (<ToolFallbackRoot open={open} onOpenChange={setOpen}><ToolFallbackTrigger@@ -181,16 +195,9 @@ const CodeExecutionToolUIImpl: ToolCallMessagePartComponent = ({<Spinner className="size-3.5" /><span>{runningLabel}</span></div>- ) : resultText ? (- <div>- <div className="flex justify-end">- <CopyBtn text={resultText} />- </div>- <pre className="mt-1 max-h-64 overflow-auto whitespace-pre-wrap break-words rounded bg-muted/50 p-2 text-xs">- {displayedResult}- </pre>- </div>- ) : null}+ ) : (+ <CodeExecutionResultOutput result={result} />+ )}</ToolFallbackContent></ToolFallbackRoot>);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.tsxindex ec240600727..c5f45d89a41 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@@ -9,6 +9,8 @@ import {} from "@assistant-ui/react";import { FileTextIcon, LibraryBigIcon } from "lucide-react";import { Spinner } from "@/components/ui/spinner";++import { stringifyToolResult } from "@/lib/strip-ansi";import { memo, useEffect, useMemo, useState } from "react";import { Badge } from "./badge";import {@@ -76,6 +78,8 @@ const KnowledgeBaseToolUIImpl: ToolCallMessagePartComponent = ({}) => {const query = (args as { query?: string })?.query ?? "";const isRunning = status?.type === "running";++ const resultText = result == null ? "" : stringifyToolResult(result);const citations = useMemo(() => parseCitations(result), [result]);// Citations render in RagSourcesGroup; this block keeps a one-line summary.const docCount = useMemo(@@ -122,11 +126,9 @@ const KnowledgeBaseToolUIImpl: ToolCallMessagePartComponent = ({{citations.length === 1 ? "" : "s"} from {docCount} document{docCount === 1 ? "" : "s"}. See Document Sources below.</div>- ) : result ? (+ ) : resultText ? (<pre className="max-h-40 overflow-auto whitespace-pre-wrap break-words rounded bg-muted/50 p-2 text-xs">- {typeof result === "string"- ? result- : JSON.stringify(result, null, 2)}+ {resultText}</pre>) : (<div className="text-sm text-muted-foreground">No matching passages.</div>diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-python.tsxindex db6aff62149..04a38624a84 100644--- a/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx+++ b/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx@@ -6,12 +6,13 @@import { Spinner } from "@/components/ui/spinner";import { authFetch } from "@/features/auth";import {- preferFullToolOutput,+ preferSanitizedFullToolOutput,useChatRuntimeStore,useToolAwaitingApproval,useToolOutputFor,useToolPaneScope,} from "@/features/chat";+import { stringifyToolResult } from "@/lib/strip-ansi";import type { ToolCallMessagePartComponent } from "@assistant-ui/react";import { useToolArgsStatus } from "@assistant-ui/react";import { CodeIcon } from "lucide-react";@@ -148,10 +149,8 @@ const PythonToolUIImpl: ToolCallMessagePartComponent = ({output = result.text;images = result.images;sessionId = result.sessionId;- } else if (typeof result === "string") {- output = result;- } else if (result) {- output = JSON.stringify(result, null, 2);+ } else if (result != null) {+ output = stringifyToolResult(result);} else {output = "";}@@ -164,7 +163,7 @@ const PythonToolUIImpl: ToolCallMessagePartComponent = ({paneScope,toolCallId,);- const displayOutput = preferFullToolOutput(fullOutput, output);+ const displayOutput = preferSanitizedFullToolOutput(fullOutput, output);// The gate only opens once the call parsed, so a pending approval means the script is// written even while the args status still reads as streaming.diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsxindex b6ea2aaa6f9..af620963e47 100644--- a/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx+++ b/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx@@ -17,8 +17,10 @@ import { CopyBtn, ToolCodeCell } from "./tool-code-cell";import { ToolLiveOutput } from "./tool-live-output";import { ToolResultOutput } from "./tool-result-output";import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";++import { stringifyToolResult } from "@/lib/strip-ansi";import {- preferFullToolOutput,+ preferSanitizedFullToolOutput,useToolAwaitingApproval,useToolOutputFor,useToolPaneScope,@@ -35,12 +37,7 @@ const TerminalToolUIImpl: ToolCallMessagePartComponent = ({// Args still streaming = the model is WRITING the command, not running it yet.const { propStatus } = useToolArgsStatus();const isWritingCommand = isRunning && propStatus.command === "streaming";- const output =- typeof result === "string"- ? result- : result- ? JSON.stringify(result, null, 2)- : "";+ const output = result == null ? "" : stringifyToolResult(result);// Show the fuller live stream over a truncated result, keeping its exit// status. Session-transient: after a reload only the result remains.@@ -50,7 +47,10 @@ const TerminalToolUIImpl: ToolCallMessagePartComponent = ({paneScope,toolCallId,);- const displayOutput = preferFullToolOutput(fullOutput, output);+ // Compare the same plain-text representation on both sides. Otherwise a raw+ // SGR-prefixed stream cannot match its cleaned truncated result and the+ // reconciliation helper appends a duplicate prefix.+ const displayOutput = preferSanitizedFullToolOutput(fullOutput, output);// The gate only opens once the call parsed, so a pending approval means the command is// written even while the args status still reads as streaming.const awaitingApproval = useToolAwaitingApproval(toolCallId);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.tsxindex e11ef6cc2a2..a20236e3729 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@@ -5,6 +5,8 @@import { type ToolCallMessagePartComponent, useAuiState } from "@assistant-ui/react";import { GlobeIcon } from "lucide-react";++import { stringifyToolResult } from "@/lib/strip-ansi";import { memo, useEffect, useState } from "react";import { Source, SourceIcon, SourceTitle } from "./sources";import {@@ -97,11 +99,8 @@ const WebSearchToolUIImpl: ToolCallMessagePartComponent = ({}})();const isRunning = status?.type === "running";- const sources = result- ? parseSearchResults(- typeof result === "string" ? result : JSON.stringify(result),- )- : [];+ const resultText = result == null ? "" : stringifyToolResult(result);+ const sources = resultText ? parseSearchResults(resultText) : [];// Collapse when LLM starts generating text after the tool callconst hasText = useAuiState(({ message }) =>@@ -154,12 +153,10 @@ const WebSearchToolUIImpl: ToolCallMessagePartComponent = ({</Source>))}</div>- ) : result ? (+ ) : resultText ? (<div><pre className="max-h-40 overflow-auto whitespace-pre-wrap break-words rounded bg-muted/50 p-2 text-xs">- {typeof result === "string"- ? result- : JSON.stringify(result, null, 2)}+ {resultText}</pre></div>) : null}diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex 9a11bb39eb0..7579a47772e 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -60,6 +60,8 @@ export {export { resolveStagedDiffusionClassification } from "./lib/gpu-placement";export {preferFullToolOutput,++ preferSanitizedFullToolOutput,toolOutputKey,toolThreadScope,useToolOutputFor,diff --git a/studio/frontend/src/features/chat/tool-output-scope.ts b/studio/frontend/src/features/chat/tool-output-scope.tsindex abf81634316..2490b56e1eb 100644--- a/studio/frontend/src/features/chat/tool-output-scope.ts+++ b/studio/frontend/src/features/chat/tool-output-scope.ts@@ -5,6 +5,8 @@import { useAuiState } from "@assistant-ui/react";import { createContext, useContext } from "react";++import { stripAnsi } from "../../lib/strip-ansi";import type { ModelType } from "./types";/**@@ -142,3 +144,12 @@ export function preferFullToolOutput(full: string, result: string): string {}return `${full.replace(/\s+$/, "")}\n\n${result}`;}+++/** Normalize both sources before deciding whether the live stream is fuller. */+export function preferSanitizedFullToolOutput(+ full: string,+ result: string,+): string {+ return preferFullToolOutput(stripAnsi(full), stripAnsi(result));+}diff --git a/studio/frontend/src/lib/strip-ansi.ts b/studio/frontend/src/lib/strip-ansi.tsnew file mode 100644index 00000000000..8c13a27ee20--- /dev/null+++ b/studio/frontend/src/lib/strip-ansi.ts@@ -0,0 +1,244 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++const ESC = 0x1b;+const BEL = 0x07;++const CAN = 0x18;+const SUB = 0x1a;+const C1_DCS = 0x90;+const C1_SOS = 0x98;+const C1_CSI = 0x9b;+const C1_ST = 0x9c;+const C1_OSC = 0x9d;+const C1_PM = 0x9e;+const C1_APC = 0x9f;++function isCsiFinal(code: number): boolean {+ return code >= 0x40 && code <= 0x7e;+}++/** CSI parameter (0x30-0x3f) and intermediate (0x20-0x2f) bytes. */+function isCsiParameterOrIntermediate(code: number): boolean {+ return code >= 0x20 && code <= 0x3f;+}++function isScsFinal(code: number): boolean {+ return (code >= 0x30 && code <= 0x3f) || isCsiFinal(code);+}++function isEscStringControlIntroducer(code: number): boolean {+ // DCS (P), SOS (X), PM (^), APC (_)+ return code === 0x50 || code === 0x58 || code === 0x5e || code === 0x5f;+}++function isC1StringControlIntroducer(code: number): boolean {+ return code === C1_DCS || code === C1_SOS || code === C1_PM || code === C1_APC;+}++/** Advance past an OSC / DCS / SOS / PM / APC payload. */+function consumeStringControl(+ text: string,+ afterIntro: number,+ allowBelTerminator: boolean,+): number {+ let cursor = afterIntro;+ while (cursor < text.length) {+ const code = text.charCodeAt(cursor);++ if (code === CAN || code === SUB) {+ return cursor + 1;+ }+ if (allowBelTerminator && code === BEL) {+ return cursor + 1;+ }+ if (code === C1_ST) {+ return cursor + 1;+ }+ if (code === ESC) {+ if (cursor + 1 < text.length && text.charCodeAt(cursor + 1) === 0x5c) {+ return cursor + 2;+ }+ // Preserve a new escape introducer so the outer scanner can consume it.+ break;+ }+ cursor += 1;+ }+ // Unterminated string controls are intentionally hidden while streaming.+ return cursor;+}++function consumeCsi(text: string, afterIntro: number): number {+ let cursor = afterIntro;+ while (+ cursor < text.length &&+ isCsiParameterOrIntermediate(text.charCodeAt(cursor))+ ) {+ cursor += 1;+ }+ // An aborted CSI (ESC/C1/newline before the final byte) leaves the cursor on+ // the offending byte so a following sequence is not swallowed with it.+ if (cursor < text.length && isCsiFinal(text.charCodeAt(cursor))) {+ cursor += 1;+ }+ return cursor;+}++/** Strip ECMA-48 CSI / SCS / OSC / string-control sequences in one linear pass. */+export function stripAnsi(text: string): string {+ let out = "";+ let index = 0;+ while (index < text.length) {+ const code = text.charCodeAt(index);++ if (code === CAN || code === SUB) {+ index += 1;+ continue;+ }++ if (code === C1_CSI) {+ index = consumeCsi(text, index + 1);+ continue;+ }+ if (code === C1_OSC) {+ index = consumeStringControl(text, index + 1, true);+ continue;+ }+ if (isC1StringControlIntroducer(code)) {+ index = consumeStringControl(text, index + 1, false);+ continue;+ }+ // Other C1 bytes are single control functions and have no printable form.+ if (code >= 0x80 && code <= 0x9f) {+ index += 1;+ continue;+ }+ if (code !== ESC) {+ out += text[index] ?? "";+ index += 1;+ continue;+ }+ if (index + 1 >= text.length) {+ break;+ }++ const next = text.charCodeAt(index + 1);+ if (next === 0x5b) {+ index = consumeCsi(text, index + 2);+ continue;+ }+ if (next === 0x5d) {+ index = consumeStringControl(text, index + 2, true);+ continue;+ }+ if (isEscStringControlIntroducer(next)) {+ index = consumeStringControl(text, index + 2, false);+ continue;+ }+ if (next >= 0x20 && next <= 0x2f) {+ index += 2;+ while (+ index < text.length &&+ text.charCodeAt(index) >= 0x20 &&+ text.charCodeAt(index) <= 0x2f+ ) {+ index += 1;+ }+ if (index < text.length && isScsFinal(text.charCodeAt(index))) {+ index += 1;+ }+ continue;+ }+ if (next >= 0x30 && next <= 0x7e && next !== 0x5b && next !== 0x5d) {+ index += 2;+ continue;+ }+ index += 1;+ }+ return out;+}+++/** Tail-line cap so a huge output never mounts a megabyte <pre> block. */+const TAIL_LINES = 2000;+/** Char backstop for pathological single-line outputs. */+const TAIL_CHARS = 200_000;++export interface ToolOutputTail {+ visible: string;+ hiddenLines: number;+ hiddenChars: number;+}++export function tailToolOutput(text: string): ToolOutputTail {+ let visible = text;+ let hiddenLines = 0;+ let hiddenChars = 0;+ const lines = visible.split("\n");+ if (lines.length > TAIL_LINES) {+ hiddenLines = lines.length - TAIL_LINES;+ visible = lines.slice(hiddenLines).join("\n");+ }+ if (visible.length > TAIL_CHARS) {+ hiddenChars = visible.length - TAIL_CHARS;+ visible = visible.slice(hiddenChars);+ }+ return { visible, hiddenLines, hiddenChars };+}++/**+ * JSON.stringify replacer stripping ANSI from string values and object keys.+ * A replacer sees values after toJSON, so Date and friends keep serializing+ * normally; pre-walking the object would have flattened them to {}.+ */+function stripAnsiReplacer(_key: string, value: unknown): unknown {+ if (typeof value === "string") {+ return stripAnsi(value);+ }+ if (value === null || typeof value !== "object" || Array.isArray(value)) {+ return value;+ }++ const entries = Object.entries(value).map(([key, entry]) => ({+ key,+ cleanedKey: stripAnsi(key),+ entry,+ }));+ if (entries.every(({ key, cleanedKey }) => key === cleanedKey)) {+ return value;+ }++ // A stripped key can collide with a real key (or another stripped key). Keep+ // every field visible rather than silently dropping one through fromEntries.+ const plainKeys = new Set(+ entries+ .filter(({ key, cleanedKey }) => key === cleanedKey)+ .map(({ key }) => key),+ );+ const usedKeys = new Set<string>();+ return Object.fromEntries(+ entries.map(({ key, cleanedKey, entry }) => {+ if (key === cleanedKey) {+ usedKeys.add(key);+ return [key, entry];+ }++ let displayKey = cleanedKey;+ let suffix = 1;+ while (plainKeys.has(displayKey) || usedKeys.has(displayKey)) {+ const label = suffix === 1 ? "ansi" : `ansi ${suffix}`;+ displayKey = `${cleanedKey} [${label}]`;+ suffix += 1;+ }+ usedKeys.add(displayKey);+ return [displayKey, entry];+ }),+ );+}++/** Plain-text tool result for a <pre>: strings directly, objects as stripped JSON. */+export function stringifyToolResult(result: unknown): string {+ return typeof result === "string"+ ? stripAnsi(result)+ : JSON.stringify(result, stripAnsiReplacer, 2);+}diff --git a/studio/frontend/src/lib/tauri-diagnostics.ts b/studio/frontend/src/lib/tauri-diagnostics.tsindex d5c04ab2dbe..7e460e399bc 100644--- a/studio/frontend/src/lib/tauri-diagnostics.ts+++ b/studio/frontend/src/lib/tauri-diagnostics.ts@@ -3,6 +3,7 @@import { isTauri } from "@/lib/api-base";import { copyToClipboard } from "@/lib/copy-to-clipboard";+import { stripAnsi } from "@/lib/strip-ansi";export interface FrontendSupportSnapshot {status?: string | null;@@ -25,15 +26,6 @@ export interface CopySupportDiagnosticsResult {const FALLBACK_LOG_LINE_LIMIT = 200;-const ANSI_ESCAPE_PATTERN = new RegExp(- `${String.fromCharCode(27)}(?:[@-Z\\-_]|\\[[0-?]*[ -/]*[@-~])`,- "g",-);--function stripAnsi(text: string): string {- return text.replace(ANSI_ESCAPE_PATTERN, "");-}-export function redactDiagnosticsText(text: string): string {let redacted = stripAnsi(text);diff --git a/studio/frontend/tests/strip-ansi.test.ts b/studio/frontend/tests/strip-ansi.test.tsnew file mode 100644index 00000000000..a7cfcf0bbb8--- /dev/null+++ b/studio/frontend/tests/strip-ansi.test.ts@@ -0,0 +1,183 @@+// 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 test from "node:test";++import {+ stripAnsi,+ stringifyToolResult,+ tailToolOutput,+} from "../src/lib/strip-ansi.ts";++const ESC = String.fromCharCode(27);+const BEL = String.fromCharCode(7);++const CAN = String.fromCharCode(0x18);+const SUB = String.fromCharCode(0x1a);++const C1_DCS = String.fromCharCode(0x90);+const C1_CSI = String.fromCharCode(0x9b);+const C1_ST = String.fromCharCode(0x9c);+const C1_OSC = String.fromCharCode(0x9d);++test("strips SGR colour sequences from ls --color / grep --color output", () => {+ const coloured = `${ESC}[32mfile.txt${ESC}[0m\n${ESC}[01;31mmatch${ESC}[0m`;+ assert.equal(stripAnsi(coloured), "file.txt\nmatch");+});++test("strips cursor / erase CSI used by npm and cargo progress", () => {+ const progress = `Downloading${ESC}[2K${ESC}[1GDone`;+ assert.equal(stripAnsi(progress), "DownloadingDone");+});++test("leaves plain text and newlines alone", () => {+ assert.equal(stripAnsi("hello\nworld"), "hello\nworld");+ assert.equal(stripAnsi(""), "");+});++test("strips pytest-style green pass markers", () => {+ const line = `${ESC}[32mPASSED${ESC}[0m tests/strip-ansi.test.ts`;+ assert.equal(stripAnsi(line), "PASSED tests/strip-ansi.test.ts");+});++test("shrinks colourised output so tailing counts visible glyphs not escapes", () => {+ const coloured = `${"ok\n".repeat(10)}${ESC}[32m${"x".repeat(500)}${ESC}[0m`;+ const cleaned = stripAnsi(coloured);+ assert.equal(cleaned.includes(ESC), false);+ assert.ok(cleaned.length < coloured.length);+});+++test("tailing uses cleaned glyph counts and enforces both boundaries", () => {+ const visible = "x".repeat(200_000);+ const coloured = `${ESC}[32m${visible}${ESC}[0m`;+ assert.equal(tailToolOutput(coloured).hiddenChars > 0, true);+ assert.deepEqual(tailToolOutput(stripAnsi(coloured)), {+ visible,+ hiddenLines: 0,+ hiddenChars: 0,+ });++ const lines = Array.from({ length: 2001 }, (_, index) => String(index)).join("\n");+ const tail = tailToolOutput(lines);+ assert.equal(tail.hiddenLines, 1);+ assert.equal(tail.visible.startsWith("1\n"), true);+});++test("strips OSC terminal hyperlinks terminated by BEL", () => {+ const linked = `${ESC}]8;;file:///tmp/demo${BEL}file.txt${ESC}]8;;${BEL}`;+ assert.equal(stripAnsi(linked), "file.txt");+});++test("strips OSC sequences terminated by ST (ESC backslash)", () => {+ const titled = `${ESC}]0;npm install${ESC}\\`;+ assert.equal(stripAnsi(titled), "");+});++test("strips SCS charset resets emitted by terminfo sgr0", () => {+ const reset = `${ESC}(B${ESC}[mok`;+ assert.equal(stripAnsi(reset), "ok");+});++test("strips many unterminated OSC introducers without quadratic work", () => {+ const garbage = `${ESC}]`.repeat(500);+ assert.equal(stripAnsi(garbage), "");+});++test("hides partial OSC payloads while a hyperlink is still streaming", () => {+ const partial = `${ESC}]8;;file:///tmp/demo`;+ assert.equal(stripAnsi(partial), "");+});+++test("streaming controls stay hidden until complete and reveal later text", () => {+ let accumulated = `${ESC}]8;;file:///tmp/demo`;+ assert.equal(stripAnsi(accumulated), "");+ accumulated += `${BEL}link${ESC}]8;;${BEL}`;+ assert.equal(stripAnsi(accumulated), "link");++ accumulated = `${ESC}[31`;+ assert.equal(stripAnsi(accumulated), "");+ accumulated += `mred${ESC}[0m`;+ assert.equal(stripAnsi(accumulated), "red");+});++test("CAN and SUB cancel control strings without hiding following text", () => {+ assert.equal(stripAnsi(`${ESC}]0;title${CAN}visible`), "visible");+ assert.equal(stripAnsi(`${C1_OSC}0;title${SUB}visible`), "visible");+ assert.equal(stripAnsi(`${ESC}[31${CAN}visible`), "visible");+});+++test("malformed SCS leaves its violating byte and following text visible", () => {+ assert.equal(stripAnsi(`${ESC}(\nplain`), "\nplain");+});++test("strips DCS payloads terminated by ST", () => {+ const dcs = `${ESC}Pfake-sixel${ESC}\\ok`;+ assert.equal(stripAnsi(dcs), "ok");+});+++test("strips SOS payloads and 8-bit C1 control forms", () => {+ assert.equal(stripAnsi(`${ESC}Xprivate${ESC}\\ok`), "ok");+ assert.equal(stripAnsi(`${C1_CSI}32mgreen${C1_CSI}0m`), "green");+ assert.equal(stripAnsi(`${C1_OSC}0;title${C1_ST}ok`), "ok");+ assert.equal(stripAnsi(`${C1_DCS}payload${C1_ST}ok`), "ok");+});++test("strips DEC save, restore, and full reset controls", () => {+ assert.equal(stripAnsi(`${ESC}7text${ESC}8`), "text");+ assert.equal(stripAnsi(`${ESC}chello`), "hello");+});++test("an aborted CSI does not swallow the sequence that follows it", () => {+ assert.equal(stripAnsi(`${ESC}[${ESC}[32mhi`), "hi");+ assert.equal(stripAnsi(`${ESC}[32\nplain`), "\nplain");+});++test("stringifyToolResult cleans nested tool object fields before JSON display", () => {+ const rendered = stringifyToolResult({+ stdout: `${ESC}[32mfile.txt${ESC}[0m`,+ nested: [{ line: `${ESC}[31merror${ESC}[0m` }],+ });+ const parsed = JSON.parse(rendered);+ assert.equal(parsed.stdout, "file.txt");+ assert.equal(parsed.nested[0]?.line, "error");+});++test("stringifyToolResult strips ANSI out of object keys too", () => {+ const rendered = stringifyToolResult({ [`${ESC}[32mstdout`]: "ok" });+ assert.equal(rendered.includes("\\u001b"), false);+ assert.match(rendered, /"stdout": "ok"/);+});+++test("stringifyToolResult preserves fields whose cleaned keys collide", () => {+ const rendered = stringifyToolResult({+ [`${ESC}[31mkey`]: "ansi",+ key: "plain",+ [`${ESC}[32mkey`]: "second ansi",+ });+ const parsed = JSON.parse(rendered);+ assert.deepEqual(parsed, {+ "key [ansi]": "ansi",+ key: "plain",+ "key [ansi 2]": "second ansi",+ });+});++test("stringifyToolResult keeps toJSON serialization (Date stays an ISO string)", () => {+ const rendered = stringifyToolResult({ at: new Date("2020-01-02T03:04:05Z") });+ assert.match(rendered, /"at": "2020-01-02T03:04:05\.000Z"/);+});++test("stringifyToolResult avoids \\u001b litter for structured tool output", () => {+ const rendered = stringifyToolResult({+ stdout: `${ESC}[32mfile.txt${ESC}[0m`,+ });+ assert.equal(rendered.includes("\\u001b"), false);+ assert.equal(rendered.includes("[32m"), false);+ assert.match(rendered, /"stdout": "file\.txt"/);+});diff --git a/tests/studio/fixtures/ansi-smoke-screenshots/smoke-ansi.png b/tests/studio/fixtures/ansi-smoke-screenshots/smoke-ansi.pngnew file mode 100644index 00000000000..36a6f2d8666Binary files /dev/null and b/tests/studio/fixtures/ansi-smoke-screenshots/smoke-ansi.png differdiff --git a/tests/studio/playwright_strip_ansi_smoke.py b/tests/studio/playwright_strip_ansi_smoke.pynew file mode 100644index 00000000000..5871f02c1dc--- /dev/null+++ b/tests/studio/playwright_strip_ansi_smoke.py@@ -0,0 +1,149 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Browser smoke for #7962: production tool-output panes strip ANSI before render."""++from __future__ import annotations++import os++import signal+import subprocess+import sys+import threading+import time+import urllib.error+import urllib.request+from pathlib import Path++from playwright.sync_api import expect, sync_playwright++sys.path.insert(0, str(Path(__file__).resolve().parent))+from _playwright_robust import chromium_launch_args # noqa: E402++FRONTEND = Path(__file__).resolve().parents[2] / "studio" / "frontend"+BASE = os.environ.get("SMOKE_BASE_URL", "http://127.0.0.1:8000")+ART = Path(os.environ.get("PW_ART_DIR", "logs/playwright-ansi-smoke"))+SECTIONS = (+ "tool-result-output",+ "tool-fallback-result",+ "tool-live-output",+ "code-execution-result",+ "reconciled-terminal-result",+)+ESC = "\u001b"+++def info(msg: str) -> None:+ print(f"[ansi-smoke] {msg}", flush = True)+++def wait_for_vite(timeout_s: float = 120.0) -> None:+ url = f"{BASE}/smoke-ansi.html"+ deadline = time.time() + timeout_s+ while time.time() < deadline:+ try:+ with urllib.request.urlopen(url, timeout = 2) as response:+ if response.status == 200:+ return+ except (urllib.error.URLError, TimeoutError):+ pass+ time.sleep(0.5)+ raise RuntimeError(f"vite dev server did not become ready at {url}")+++def drain_process_output(proc: subprocess.Popen[str]) -> None:+ if proc.stdout is not None:+ for _ in proc.stdout:+ pass+++def start_vite() -> subprocess.Popen[str]:+ process_group = (+ {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP}+ if os.name == "nt"+ else {"start_new_session": True}+ )+ proc = subprocess.Popen(+ ["npm", "run", "dev", "--", "--host", "127.0.0.1", "--port", "8000", "--strictPort"],+ cwd = FRONTEND,+ stdout = subprocess.PIPE,+ stderr = subprocess.STDOUT,+ text = True,+ **process_group,+ )+ threading.Thread(target = drain_process_output, args = (proc,), daemon = True).start()+ return proc+++def stop_process(proc: subprocess.Popen[str]) -> None:+ if proc.poll() is not None:+ return++ if os.name == "nt":+ subprocess.run(+ ["taskkill", "/PID", str(proc.pid), "/T"],+ check = False,+ stdout = subprocess.DEVNULL,+ stderr = subprocess.DEVNULL,+ )+ else:+ try:+ os.killpg(proc.pid, signal.SIGTERM)+ except ProcessLookupError:+ return++ try:+ proc.wait(timeout = 10)+ except subprocess.TimeoutExpired:+ if os.name == "nt":+ subprocess.run(+ ["taskkill", "/PID", str(proc.pid), "/T", "/F"],+ check = False,+ stdout = subprocess.DEVNULL,+ stderr = subprocess.DEVNULL,+ )+ else:+ try:+ os.killpg(proc.pid, signal.SIGKILL)+ except ProcessLookupError:+ pass+ proc.wait(timeout = 10)+++def main() -> None:+ ART.mkdir(parents = True, exist_ok = True)+ info(f"starting vite dev server in {FRONTEND}")+ vite = start_vite()+ try:+ wait_for_vite()+ info(f"vite ready at {BASE}")++ with sync_playwright() as playwright:+ browser_name = os.environ.get("PW_BROWSER", "chromium").lower()+ if browser_name not in {"chromium", "firefox", "webkit"}:+ raise ValueError(f"unsupported PW_BROWSER: {browser_name}")+ browser_type = getattr(playwright, browser_name)+ launch_args = chromium_launch_args() if browser_name == "chromium" else []+ browser = browser_type.launch(headless = True, args = launch_args)+ page = browser.new_page()+ page.goto(f"{BASE}/smoke-ansi.html", wait_until = "networkidle")+ page.screenshot(path = str(ART / "smoke-ansi.png"), full_page = True)++ for section in SECTIONS:+ pane = page.locator(f'section[data-smoke="{section}"] pre').first+ expect(pane).to_be_visible(timeout = 15_000)+ text = pane.inner_text()+ info(f"{section} text: {text!r}")+ assert text == "file.txt\nerror", f"{section} rendered unexpected text: {text!r}"+ assert ESC not in text, f"{section} still contains ESC"+ assert "[32m" not in text, f"{section} still shows SGR garbage"++ info("all production panes rendered clean text (no ANSI escapes)")+ browser.close()+ finally:+ stop_process(vite)+++if __name__ == "__main__":+ main()