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
Studio: keep the output a timed-out python or terminal call already produced (#10664)
Nilayd7bc72c1f965
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex 10a00db2416..cc12d109d25 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -14710,7 +14710,10 @@ def _appended_by_the_loop(text: str) -> float:except Exception: # noqa: BLE001 -- an unpriced nudge, not a failed tool calllogger.debug("result budget: tool error nudge unavailable", exc_info = True)return 0.0- if not text.startswith(TOOL_ERROR_PREFIXES):+ # `lstrip` because `is_tool_error` does: a result whose first byte is a newline still+ # gets the nudge, so measuring the unstripped text reserves nothing for one that will+ # certainly be appended.+ if not text.lstrip().startswith(TOOL_ERROR_PREFIXES):return 0.0return _text_token_cost(TOOL_ERROR_NUDGE, _window_context_tokens())@@ -14721,6 +14724,7 @@ def _truncate(workdir: str | None = None,scope: "str | None" = "",hint: str = "",+ reserve_tokens: float = 0.0,) -> str:# Resolved per call, not bound at import: the default would freeze the constant# before any model is loaded, which is exactly when the window is still unknown.@@ -14734,7 +14738,11 @@ def _truncate(# the prompt with the nudge past the end of it. Charged only to the results that will# actually carry one, since a reserve taken from every result spends room the thread# has.- cap, cost = limit, _appended_by_the_loop(text)+ # `reserve_tokens` is whatever the CALLER will put after this result, priced the same+ # way as the loop's own nudge. Without it a caller that concatenates two fitted+ # strings spends the room twice: each `_truncate` reads the same `_request_result_room`+ # and neither knows about the other, so the message the model is handed is the sum.+ cap, cost = limit, _appended_by_the_loop(text) + reserve_tokensif hint:# Priced in tokens, not characters, and taken off the budget before it is converted# (see `_dense_char_limit`). A failing absolute path is dense: subtracting its@@ -14750,7 +14758,7 @@ def _truncate(# Nothing to spend on advice: at zero room the stub IS the message, and when# paying for it would cut the output in half the output is worth more than the# advice about it. Nothing is dropped while the result fits anyway.- limit, hint, cost = plain, "", _appended_by_the_loop(text)+ limit, hint, cost = plain, "", _appended_by_the_loop(text) + reserve_tokenselse:limit = _dense_char_limit(text, limit, cost)# Mode-neutral notice: this result serves both the streaming UI and@@ -16135,6 +16143,34 @@ def _created_file_sentinels(return out+def _timed_out_result(+ output: str | None, timeout: int, workdir: str | None, scope: "str | None"+) -> str:+ """Captured output, then the timeout status line.++ Output leads: a finished card shows the live stream when the result is a prefix of it+ (`preferFullToolOutput`), so a leading status would show the output twice.+ """+ ended = _truncate(f"Execution timed out after {timeout} seconds.")+ partial = _defuse_sentinels(output or "")+ if not partial.strip():+ return ended+ # Both cuts price against the same room, so the head reserves the status line's share.+ ctx = _window_context_tokens()+ head = _truncate(+ partial,+ workdir = workdir,+ scope = scope,+ reserve_tokens = _text_token_cost(f"\n{ended}", ctx),+ )+ result = f"{head}\n{ended}"+ # With the retry nudge, a stub or short head served whole can overrun a room the status fits.+ room = _request_result_room()+ if room is not None and _text_token_cost(result, ctx) + _appended_by_the_loop(result) > room:+ return ended+ return result++def _python_exec(code: str,cancel_event = None,@@ -16250,7 +16286,7 @@ def _python_exec(# A run that wrote its file and then hung still produced that file, so# report it: `printf data > report.csv; sleep 999` is downloadable.if timed_out:- ended = _truncate(f"Execution timed out after {timeout} seconds.")+ ended = _timed_out_result(output, timeout, spill_dir, spill_scope)return ended + (_created_file_sentinels(workdir, _before, _scratch_name, call_token)if session_id@@ -16403,7 +16439,7 @@ def _bash_exec(# A run that wrote its file and then hung still produced that file, so# report it: `printf data > report.csv; sleep 999` is downloadable.if timed_out:- ended = _truncate(f"Execution timed out after {timeout} seconds.")+ ended = _timed_out_result(output, timeout, spill_dir, spill_scope)return ended + (_created_file_sentinels(workdir, _before, None, call_token) if session_id else "")diff --git a/studio/backend/tests/test_tool_output_streaming.py b/studio/backend/tests/test_tool_output_streaming.pyindex 62ba0a3be5f..9f3605f82c1 100644--- a/studio/backend/tests/test_tool_output_streaming.py+++ b/studio/backend/tests/test_tool_output_streaming.py@@ -536,6 +536,63 @@ def test_python_exec_timeout_message_identical_with_streaming():assert streamed == baseline == "Execution timed out after 1 seconds."+def test_python_exec_timeout_keeps_output_already_printed():+ # The run printed a progress line before it overran the timeout. That text was+ # captured; it must reach the model instead of only the status line.+ code = "import sys, time\nprint('progress')\nsys.stdout.flush()\ntime.sleep(30)\n"+ baseline = _python_exec(code, timeout = 1)+ streamed = _python_exec(code, timeout = 1, output_callback = lambda _t: None)+ assert streamed == baseline+ assert "progress" in baseline+ assert baseline.endswith("Execution timed out after 1 seconds.")+++def test_bash_exec_timeout_keeps_output_already_printed():+ command = "echo progress; sleep 30"+ baseline = _bash_exec(command, timeout = 1)+ streamed = _bash_exec(command, timeout = 1, output_callback = lambda _t: None)+ assert streamed == baseline+ assert "progress" in baseline+ assert baseline.endswith("Execution timed out after 1 seconds.")+++def test_python_exec_timeout_still_says_so_when_the_output_printed_a_marker():+ # The replay strips only a well-formed envelope trailing the result, and the status line+ # always trails, so a printed marker line cannot cut the result.+ from core.inference.tool_loop_controller import strip_result_for_model++ code = "print('__RAG_SOURCES__:[]')\nimport time\ntime.sleep(30)\n"+ result = _python_exec(code, timeout = 1)++ assert result.endswith("Execution timed out after 1 seconds.")+ assert "__RAG_SOURCES__:[]" in result+ assert strip_result_for_model(result, "python") == result+++def test_bash_exec_timeout_still_says_so_when_the_output_printed_a_marker():+ from core.inference.tool_loop_controller import strip_result_for_model++ result = _bash_exec("echo '__RAG_SOURCES__:[]'; sleep 30", timeout = 1)++ assert result.endswith("Execution timed out after 1 seconds.")+ assert "__RAG_SOURCES__:[]" in result+ assert strip_result_for_model(result, "terminal") == result+++def test_a_truncated_timeout_card_does_not_repeat_the_output():+ # The finished card keeps the live stream when the result is a prefix of it, and+ # appends the whole result when it is not (`preferFullToolOutput` in+ # tool-output-result.ts). The captured output therefore has to LEAD the result, or a+ # truncated timeout renders its stdout twice. Asserted on the shape the frontend+ # matches on, so a future reordering of this branch fails here rather than in a card.+ code = "print('x' * 200000)\nimport sys, time\nsys.stdout.flush()\ntime.sleep(30)\n"+ result = _python_exec(code, timeout = 1)++ assert "\n\n... (truncated" in result, "not truncated, so nothing was measured"+ body = result.split("\n\n... (truncated")[0]+ assert body.startswith("x"), result[:120]++def test_python_exec_callback_errors_do_not_break_execution():def bad_callback(_text: str) -> None:raise ValueError("observer bug")diff --git a/studio/backend/tests/test_tool_result_fits_window.py b/studio/backend/tests/test_tool_result_fits_window.pyindex c497c016af9..8bba856e6fe 100644--- a/studio/backend/tests/test_tool_result_fits_window.py+++ b/studio/backend/tests/test_tool_result_fits_window.py@@ -2113,12 +2113,143 @@ class TestWhatTheLoopAppendsIsPricedToo:_within_room(out + TOOL_ERROR_NUDGE, 400)+ def test_a_result_whose_first_byte_is_a_newline_pays_for_one_too(self, monkeypatch):+ """`is_tool_error` lstrips before it matches, so a result that opens with a blank+ line and then an error prefix does carry the nudge. Measured on the unstripped+ text it reserved nothing, and the room was then overspent by the whole nudge."""+ from core.inference.tool_call_parser import TOOL_ERROR_NUDGE++ # As above, and the leading newline is the whole difference: the same prefixes,+ # one byte further in.+ failed = self._fitted(monkeypatch, "\nError: ")+ fine = self._fitted(monkeypatch, "\nAlpha: ")++ assert fine - failed >= len(TOOL_ERROR_NUDGE) * 0.9, (failed, fine)+def test_an_ordinary_result_does_not_pay_for_one(self, monkeypatch):"""The control: charged to the results that carry it, not to every result. Areserve taken from all of them spends room the thread has."""assert self._fitted(monkeypatch, "Alpha: ") == self._fitted(monkeypatch, "Bravo: ")+class TestATimedOutCallIsPricedWithItsStatusLine:+ """A timed-out `python` or `terminal` call hands back the output it had already+ printed with the status line after it. The two are fitted separately against the same+ `_request_result_room`, so without a reserve the output takes all of it and the line+ is spent on top -- and `python` and `terminal` are the tools that cap themselves, so+ no `_fit_result_to_room` downstream corrects the overspend.++ Measured the way the retry nudge is: the same captured output, fitted once with a+ status line coming after it and once without, and the difference is what the line+ costs.+ """++ PRINTED = 40_000++ def _completed(self, monkeypatch, room: int) -> str:+ """The same output from a run that finished, so nothing is appended to it."""+ _window(monkeypatch, 4096)+ _tokenizer(monkeypatch)+ return tools.execute_tool(+ "python", {"code": f"print('x' * {self.PRINTED})"}, result_budget_tokens = room+ )++ def _timed_out(self, monkeypatch, room: int) -> str:+ """The same output, from a run that then overran its limit."""+ _window(monkeypatch, 4096)+ _tokenizer(monkeypatch)+ code = (+ f"print('x' * {self.PRINTED})\nimport sys, time\nsys.stdout.flush()\ntime.sleep(30)\n"+ )+ return tools.execute_tool("python", {"code": code}, timeout = 1, result_budget_tokens = room)++ def _captured_everything(self, out: str) -> None:+ """The notice counts the whole captured text, so this is what says the drain got+ all of it. Without it a short capture would satisfy the size comparison below for+ the wrong reason."""+ assert f"{self.PRINTED + 1} chars total" in out, out[-200:]++ def test_the_status_line_is_deducted_from_what_the_output_may_take(self, monkeypatch):+ completed = self._completed(monkeypatch, 400)+ timed_out = self._timed_out(monkeypatch, 400)+ self._captured_everything(completed)+ self._captured_everything(timed_out)++ line = "\nExecution timed out after 1 seconds."+ assert timed_out.endswith(line)+ body = timed_out[: -len(line)]++ # In characters, at the rate the fixture's counter charges them.+ assert len(completed) - len(body) >= len(line) * 0.9, (len(body), len(completed))++ def test_the_terminal_side_pays_for_it_too(self, monkeypatch):+ _window(monkeypatch, 4096)+ _tokenizer(monkeypatch)+ printing = f"awk 'BEGIN {{ for (i = 0; i < {self.PRINTED}; i++) printf \"x\" }}'"++ completed = tools.execute_tool("terminal", {"command": printing}, result_budget_tokens = 400)+ timed_out = tools.execute_tool(+ "terminal",+ {"command": f"{printing}; sleep 30"},+ timeout = 1,+ result_budget_tokens = 400,+ )+ assert f"{self.PRINTED} chars total" in completed+ assert f"{self.PRINTED} chars total" in timed_out++ line = "\nExecution timed out after 1 seconds."+ assert timed_out.endswith(line)+ body = timed_out[: -len(line)]++ assert len(completed) - len(body) >= len(line) * 0.9, (len(body), len(completed))++ def test_the_output_and_the_status_line_fit_the_room_together(self, monkeypatch):+ """The invariant the deduction buys: what the model is handed is inside the room."""+ out = self._timed_out(monkeypatch, 400)++ assert out.endswith("Execution timed out after 1 seconds.")+ assert "x" in out, "the captured output was dropped, so nothing was measured"+ _within_room(out, 400)++ def test_a_room_with_no_space_for_output_gets_the_status_line_alone(self, monkeypatch):+ """At zero room the output's omission stub would overrun what the status line fits."""+ out = self._timed_out(monkeypatch, 20)++ assert out == "Execution timed out after 1 seconds."+ _within_room(out, 20)++ def test_output_that_reads_as_an_error_pays_for_the_nudge_it_brings(self, monkeypatch):+ """Error-looking output brings the retry nudge, so it is kept only where that fits."""+ from core.inference.tool_call_parser import TOOL_ERROR_NUDGE+ from core.inference.tool_loop_controller import is_tool_error++ _window(monkeypatch, 4096)+ _tokenizer(monkeypatch)+ code = "import sys, time\nprint('Error: failed')\nsys.stdout.flush()\ntime.sleep(30)\n"++ tight = tools.execute_tool("python", {"code": code}, timeout = 1, result_budget_tokens = 40)+ assert tight == "Execution timed out after 1 seconds."+ _within_room(tight + (TOOL_ERROR_NUDGE if is_tool_error(tight) else ""), 40)++ roomy = tools.execute_tool("python", {"code": code}, timeout = 1, result_budget_tokens = 400)+ assert roomy.startswith("Error: failed"), roomy++ def test_a_silent_timeout_pays_nothing_for_output_it_never_had(self, monkeypatch):+ """The control: charged to the calls that carry output, and a command that printed+ nothing still gets exactly the sentence it always did."""+ _window(monkeypatch, 4096)+ _tokenizer(monkeypatch)++ out = tools.execute_tool(+ "python",+ {"code": "import time\ntime.sleep(30)\n"},+ timeout = 1,+ result_budget_tokens = 400,+ )++ assert out == "Execution timed out after 1 seconds."++class TestTheResultIsFittedAsItIsReplayed:"""`_defuse_sentinels` inserts a space into every line that opens with a frontendmarker. Applied after the fit, output full of such lines grows once it has beendiff --git a/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-python.tsxindex af2f4b8e8fc..2a6d506c3c9 100644--- a/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx+++ b/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx@@ -9,13 +9,13 @@ import { SandboxFiles } from "./sandbox-files-view";import { isSandboxFileList, type SandboxFile } from "./sandbox-files";import {preferSanitizedFullToolOutput,+ toolResultText,useChatRuntimeStore,useChatPreferencesStore,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";@@ -100,7 +100,7 @@ const PythonToolUIImpl: ToolCallMessagePartComponent = ({files = result.files ?? [];sessionId = result.sessionId;} else if (result != null) {- output = stringifyToolResult(result);+ output = toolResultText(result);} else {output = "";}diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsxindex 9e63889dbbf..3ca82ec95d9 100644--- a/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx+++ b/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx@@ -21,9 +21,9 @@ import { SandboxFiles } from "./sandbox-files-view";import { isSandboxToolResult, type SandboxFile } from "./sandbox-files";import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";-import { stringifyToolResult } from "@/lib/strip-ansi";import {preferSanitizedFullToolOutput,+ toolResultText,useToolAwaitingApproval,useToolOutputFor,useToolPaneScope,@@ -51,10 +51,10 @@ const TerminalToolUIImpl: ToolCallMessagePartComponent = ({const sessionId = structured?.sessionId ?? "";const output =structured !== null- ? stringifyToolResult(structured.text)+ ? toolResultText(structured.text): result == null? ""- : stringifyToolResult(result);+ : toolResultText(result);// Show the fuller live stream over a truncated result, keeping its exit// status. Session-transient: after a reload only the result remains.diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex 83d9406978d..ade81dea8b0 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -77,6 +77,7 @@ export {preferFullToolOutput,preferSanitizedFullToolOutput,toolOutputKey,+ toolResultText,toolThreadScope,useToolOutputFor,useUnresolvedToolPaneScope,diff --git a/studio/frontend/src/features/chat/tool-output-result.ts b/studio/frontend/src/features/chat/tool-output-result.tsnew file mode 100644index 00000000000..b37f14168c0--- /dev/null+++ b/studio/frontend/src/features/chat/tool-output-result.ts@@ -0,0 +1,92 @@+// 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 { stringifyToolResult, stripAnsi } from "../../lib/strip-ansi";++// Footer the backend appends when it truncates a result to protect the context window (see+// backend tools._truncate). Marks where the result stops being a copy of the stream.+const TRUNCATION_FOOTER_MARKER = "\n\n... (truncated";++// Written only by the backend, after the footer, so swapping in the stream would drop it.+const TIMEOUT_STATUS_TAIL = /\nExecution timed out after \d+ seconds\.$/;++// Backend `_defuse_sentinels` indents these lines in the result but not the stream, and stripping+// ANSI can expose one at a line start, so both sides are normalized.+const SENTINEL_LINE = /^(__FILES__:|__IMAGES__:|__RAG_SOURCES__:)/gm;++function defuseSentinels(text: string): string {+ return text.replace(SENTINEL_LINE, " $1");+}++/** Whether the live stdout holds more real output than the model-visible `result` and should be+ * preserved for the finished card. Shared by writer and reader so they agree. True when the+ * result is truncated, OR the stream is longer. Truncation cannot fall back to length: a+ * truncated result may be longer once its footer or exit line is appended. Also true when a+ * short stream is absent from the result, since a cancelled tool returns only a status line. */+export function shouldPreserveFullOutput(rawFull: string, rawResult: string): boolean {+ const full = defuseSentinels(rawFull);+ const result = defuseSentinels(rawResult);+ if (!full) {+ return false;+ }+ if (result.includes(TRUNCATION_FOOTER_MARKER)) {+ return true;+ }+ if (full.length > result.length) {+ return true;+ }+ // Stream no longer than the result, but a timed-out or cancelled tool's status line never+ // echoes the captured stdout: preserve the stream whenever its content is absent from the+ // result, trimmed to ignore trailing-newline drift.+ const core = full.trim();+ return core.length > 0 && !result.includes(core);+}++/** Pick what a finished python/terminal card shows. Prefer the fuller live stream over the+ * truncated `result`, but the result can carry failure or exit text that never reached+ * stdout, so show the stream when the result is just a truncated prefix of it, else append+ * the result so its status survives. */+export function preferFullToolOutput(rawFull: string, rawResult: string): string {+ const full = defuseSentinels(rawFull);+ const result = defuseSentinels(rawResult);+ if (!shouldPreserveFullOutput(full, result)) {+ return result;+ }+ const marker = result.indexOf(TRUNCATION_FOOTER_MARKER);+ const core = marker === -1 ? result : result.slice(0, marker);+ if (!core || full === result || full.startsWith(core)) {+ // The stream lacks the status the backend put after the footer.+ const status = result.match(TIMEOUT_STATUS_TAIL)?.[0];+ return status ? `${full.replace(/\s+$/, "")}\n\n${status.trimStart()}` : full;+ }+ // Failed executions prefix the result, not the stream, with "Exit code N:", so+ // `full.startsWith(core)` misses and a plain append would duplicate the stdout. Re-attach+ // just the exit prefix to the fuller stream so the status survives.+ const exitMatch = core.match(/^(Exit code -?\d+:\n)([\s\S]*)$/);+ if (exitMatch && full.startsWith(exitMatch[2])) {+ const hint = result.match(/\nHint:[\s\S]*$/)?.[0] ?? "";+ return `${exitMatch[1]}${full}${hint}`;+ }+ return `${full.replace(/\s+$/, "")}\n\n${result}`;+}++/** A tool result as card text; strings stay raw for `preferSanitizedFullToolOutput` to strip. */+export function toolResultText(result: unknown): string {+ return typeof result === "string" ? result : stringifyToolResult(result);+}++/** Normalize both sources before deciding whether the live stream is fuller. */+export function preferSanitizedFullToolOutput(+ full: string,+ result: string,+): string {+ // Output, footer and status are stripped apart, or an escape left open would swallow the rest.+ const status = result.match(TIMEOUT_STATUS_TAIL)?.[0] ?? "";+ const body = status ? result.slice(0, result.length - status.length) : result;+ const footer = body.lastIndexOf(TRUNCATION_FOOTER_MARKER);+ const cut = footer === -1 ? body.length : footer;+ return preferFullToolOutput(+ stripAnsi(full),+ stripAnsi(body.slice(0, cut)) + stripAnsi(body.slice(cut)) + status,+ );+}diff --git a/studio/frontend/src/features/chat/tool-output-scope.ts b/studio/frontend/src/features/chat/tool-output-scope.tsindex 419ee9fca1a..10cfe74e7ef 100644--- a/studio/frontend/src/features/chat/tool-output-scope.ts+++ b/studio/frontend/src/features/chat/tool-output-scope.ts@@ -6,7 +6,6 @@import { useAuiState } from "@assistant-ui/react";import { createContext, useContext } from "react";-import { stripAnsi } from "../../lib/strip-ansi";import type { ModelType } from "./types";/** Pane scope prefix for the transient tool-output store keys. Local GGUF tool ids are only@@ -66,61 +65,10 @@ export function toolOutputKey(paneScope: string, toolCallId: string): string {return `${paneScope}\u0000${toolCallId}`;}-// Footer the backend appends when it truncates a result to protect the context window (see-// backend tools._truncate). Marks where the result stops being a copy of the stream.-const TRUNCATION_FOOTER_MARKER = "\n\n... (truncated";--/** Whether the live stdout holds more real output than the model-visible `result` and should be- * preserved for the finished card. Shared by writer and reader so they agree. True when the- * result is truncated, OR the stream is longer. Truncation cannot fall back to length: a- * truncated result may be longer once its footer or exit line is appended. Also true when a- * short stream is absent from the result, since a cancelled tool returns only a status line. */-export function shouldPreserveFullOutput(full: string, result: string): boolean {- if (!full) {- return false;- }- if (result.includes(TRUNCATION_FOOTER_MARKER)) {- return true;- }- if (full.length > result.length) {- return true;- }- // Stream no longer than the result, but a timed-out or cancelled tool's status line never- // echoes the captured stdout: preserve the stream whenever its content is absent from the- // result, trimmed to ignore trailing-newline drift.- const core = full.trim();- return core.length > 0 && !result.includes(core);-}--/** Pick what a finished python/terminal card shows. Prefer the fuller live stream over the- * truncated `result`, but the result can carry failure or exit text that never reached- * stdout, so show the stream when the result is just a truncated prefix of it, else append- * the result so its status survives. */-export function preferFullToolOutput(full: string, result: string): string {- if (!shouldPreserveFullOutput(full, result)) {- return result;- }- const marker = result.indexOf(TRUNCATION_FOOTER_MARKER);- const core = marker === -1 ? result : result.slice(0, marker);- if (!core || full === result || full.startsWith(core)) {- return full;- }- // Failed executions prefix the result, not the stream, with "Exit code N:", so- // `full.startsWith(core)` misses and a plain append would duplicate the stdout. Re-attach- // just the exit prefix to the fuller stream so the status survives.- const exitMatch = core.match(/^(Exit code -?\d+:\n)([\s\S]*)$/);- if (exitMatch && full.startsWith(exitMatch[2])) {- const hint = result.match(/\nHint:[\s\S]*$/)?.[0] ?? "";- return `${exitMatch[1]}${full}${hint}`;- }- 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));-}+// Kept React-free so node tests can import it without the runner hanging.+export {+ preferFullToolOutput,+ preferSanitizedFullToolOutput,+ shouldPreserveFullOutput,+ toolResultText,+} from "./tool-output-result";diff --git a/studio/frontend/tests/timeout-card-keeps-its-status.test.ts b/studio/frontend/tests/timeout-card-keeps-its-status.test.tsnew file mode 100644index 00000000000..17ac92c2c81--- /dev/null+++ b/studio/frontend/tests/timeout-card-keeps-its-status.test.ts@@ -0,0 +1,122 @@+// 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 { registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();++const { preferFullToolOutput, preferSanitizedFullToolOutput, toolResultText } = await import(+ "../src/features/chat/tool-output-result.ts"+);++// A timed-out python/terminal call returns the output it had already printed and then says+// it timed out. Past the model's cap that reads+// `<head>\n\n... (truncated ...)\nExecution timed out after N seconds.`, and the live stdout+// the card kept has no such sentence anywhere in it -- only the backend writes it. So+// substituting the fuller stream for the result, which is what the card does whenever the+// result is a truncated prefix of the stream, used to drop the status and leave a card that+// reads as a command that finished normally.+const SENTENCE = "Execution timed out after 300 seconds.";+const HEAD = "x".repeat(40);+const STREAM = `${"x".repeat(200)}\n`;+const NOTICE =+ "\n\n... (truncated to 40 chars for the model; 201 chars total. The full output is " ++ "not retained here; any files the code wrote persist in the working directory.)";++test("a truncated timed-out card still says the call timed out", () => {+ const card = preferFullToolOutput(STREAM, `${HEAD}${NOTICE}\n${SENTENCE}`);++ // The stream is the better copy of the output -- it is the part the cap cut -- but the+ // status it never carried has to survive with it.+ assert.ok(card.startsWith(HEAD), "the stream was not preserved");+ assert.ok(card.includes(SENTENCE), "the card no longer says the call timed out");+ // Once, not once per source: appending the whole result would repeat the output.+ assert.equal(card.split(SENTENCE).length - 1, 1);+ assert.ok(!card.includes(NOTICE.trimStart()), "the model's cap notice leaked into the card");+});++test("a completed truncated card still shows the stream alone", () => {+ // The control: with no status after the footer there is nothing to re-attach, and the+ // card must not grow a second copy of the output.+ assert.equal(preferFullToolOutput(STREAM, `${HEAD}${NOTICE}`), STREAM);+});++test("an untruncated timed-out card is left exactly as the backend wrote it", () => {+ const result = `progress\n\n${SENTENCE}`;++ assert.equal(preferFullToolOutput("progress\n", result), result);+});++test("a failed call still re-attaches its exit prefix rather than the timeout one", () => {+ // The sibling case this one is modelled on, asserted here so the new branch cannot+ // shadow it.+ assert.equal(preferFullToolOutput("boom\n", "Exit code 1:\nboom\n"), "Exit code 1:\nboom\n");+});++test("a stream whose marker line the backend indented is shown once", () => {+ // The result carries the backend's indent before a marker line; the stream does not.+ const timedOut = "progress\n__RAG_SOURCES__:[]\nfinished step\n";+ const timedOutCard = preferFullToolOutput(+ timedOut,+ `progress\n __RAG_SOURCES__:[]\nfinished step\n\n${SENTENCE}`,+ );+ assert.equal(timedOutCard.split("finished step").length - 1, 1, timedOutCard);+ assert.ok(timedOutCard.endsWith(SENTENCE), timedOutCard);++ const completed = "progress\n__FILES__:[]\nfinished step\n";+ const completedCard = preferFullToolOutput(completed, "progress\n __FILES__:[]\nfinished step\n");+ assert.equal(completedCard.split("finished step").length - 1, 1, completedCard);+});++test("a colored marker line is shown once whether or not the result was truncated", () => {+ // The backend indents only a line-start marker, so a colored one stays unindented until+ // stripping ANSI moves it to the line start.+ const esc = String.fromCharCode(27);+ const line = `${esc}[31m__FILES__:[]${esc}[0m`;++ const short = `progress\n${line}\nfinished\n`;+ const shortCard = preferSanitizedFullToolOutput(short, `${short}\n${SENTENCE}`);+ assert.equal(shortCard.split("progress").length - 1, 1, shortCard);++ const long = `progress\n${line}\n${"y".repeat(200)}\n`;+ const longCard = preferSanitizedFullToolOutput(long, `progress\n${line}\n${NOTICE}\n${SENTENCE}`);+ assert.equal(longCard.split("progress").length - 1, 1, longCard);+ assert.ok(longCard.endsWith(SENTENCE), longCard);+ assert.ok(!longCard.includes("... (truncated"), longCard);+});++test("an escape sequence the killed program left open does not swallow the timeout status", () => {+ // Stripping consumes everything after an unterminated OSC, including an appended status.+ const esc = String.fromCharCode(27);+ const stream = `progress\n${esc}]0;running`;+ const card = preferSanitizedFullToolOutput(stream, `${stream}\n${SENTENCE}`);+ assert.ok(card.endsWith(SENTENCE), JSON.stringify(card));+});++test("the timeout status survives a card built from the raw tool result", () => {+ // Stripping a string result before reconciling lost the status, with or without a saved stream.+ const esc = String.fromCharCode(27);+ const stream = `progress\n${esc}]0;running`;+ const result = `${stream}\n${SENTENCE}`;+ for (const full of [stream, ""]) {+ const card = preferSanitizedFullToolOutput(full, toolResultText(result));+ assert.ok(card.endsWith(SENTENCE), JSON.stringify(card));+ }+ assert.equal(toolResultText({ ok: true }), '{\n "ok": true\n}');+});++test("an escape sequence the cap cut open does not repeat the output on a timed-out card", () => {+ // Stripping an escape the cap cut open also ate the footer, so the whole result was appended.+ const esc = String.fromCharCode(27);+ const bel = String.fromCharCode(7);+ const stream = `progress\n${esc}]0;${"t".repeat(200)}${bel}done with step\n`;+ const result = `progress\n${esc}]0;${"t".repeat(20)}${NOTICE}\n${SENTENCE}`;+ for (const full of [stream, ""]) {+ const card = preferSanitizedFullToolOutput(full, result);+ assert.equal(card.split("progress").length - 1, 1, JSON.stringify(card));+ assert.ok(card.endsWith(SENTENCE), JSON.stringify(card));+ }+});