Skip to content

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.

Studio: stream live tool output with SSE heartbeats, fix web page extraction, and surface interrupted turns (#7083)

Daniel Han73af334d1143
diff --git a/studio/backend/core/inference/_html_to_md.py b/studio/backend/core/inference/_html_to_md.py
index e7de4a53128..92471b98661 100644
--- a/studio/backend/core/inference/_html_to_md.py
+++ b/studio/backend/core/inference/_html_to_md.py
@@ -7,6 +7,11 @@ Minimal HTML-to-Markdown converter using only the standard library.
Replaces the external ``html2text`` (GPL-3.0) dependency with a ~250-line
``html.parser.HTMLParser`` subclass. Covers headings, links, bold/italic,
lists, tables, blockquotes, code blocks, and entity decoding.
+
+``main_content=True`` also applies a readability-style heuristic: scope
+conversion to the page's ``<article>`` (else ``<main>``) subtree when it
+carries substantial text, and strip known boilerplate fragments (skip-links,
+error placeholders, session banners, cookie prompts) from the result.
"""
from __future__ import annotations
@@ -27,8 +32,138 @@ _SKIP_TAGS = frozenset(
"math",
"nav",
"footer",
+ # Never-rendered / form-chrome elements, not page content.
+ "template",
+ "dialog",
+ "button",
+ "select",
+ "datalist",
+ }
+)
+# <aside> is NOT skipped: docs use it for admonition callouts (real content);
+# page-furniture asides are excluded by the main-content scoping pass instead.
+
+# Void elements never produce an end tag, so they must not join the
+# open-element stack used to bound hidden subtrees.
+_VOID_TAGS = frozenset(
+ {
+ "area",
+ "base",
+ "br",
+ "col",
+ "embed",
+ "hr",
+ "img",
+ "input",
+ "link",
+ "meta",
+ "param",
+ "source",
+ "track",
+ "wbr",
}
)
+
+
+def _style_hides_element(style: str) -> bool:
+ """True when an inline ``style`` sets ``display:none`` / ``visibility:hidden``.
+
+ Parsed per property so an unrelated value that merely contains ``none`` is
+ not misread as hidden."""
+ lowered = style.lower()
+ if "none" not in lowered and "hidden" not in lowered:
+ return False
+ for declaration in style.split(";"):
+ prop, sep, value = declaration.partition(":")
+ if not sep:
+ continue
+ prop = prop.strip().lower()
+ # Drop any !important flag and keep the first token of the value.
+ value = value.split("!", 1)[0].strip().lower()
+ if prop == "display" and value == "none":
+ return True
+ if prop == "visibility" and value == "hidden":
+ return True
+ return False
+
+
+def _is_hidden_element(attr_dict: dict) -> bool:
+ """True when the element is not rendered: ``hidden`` attribute,
+ ``aria-hidden="true"``, or an inline ``style`` hiding it. Such JS-only
+ placeholders ship in the HTML but must not reach the output. ``hidden`` is
+ enumerated: any present value (even ``hidden="false"``) means not rendered."""
+ if "hidden" in attr_dict:
+ return True
+ if (attr_dict.get("aria-hidden") or "").strip().lower() == "true":
+ return True
+ return _style_hides_element(attr_dict.get("style") or "")
+
+
+# HTML5 optional end tags: a listed start tag implicitly closes an open element
+# of the key type (as browsers do), else an unclosed ``<p hidden>``/``<li hidden>``
+# swallows every following sibling. Keys: closable elements; values: closers.
+_P_CLOSING_TAGS = frozenset(
+ {
+ "address",
+ "article",
+ "aside",
+ "blockquote",
+ "details",
+ "div",
+ "dl",
+ "fieldset",
+ "figcaption",
+ "figure",
+ "footer",
+ "form",
+ "h1",
+ "h2",
+ "h3",
+ "h4",
+ "h5",
+ "h6",
+ "header",
+ "hgroup",
+ "hr",
+ "main",
+ "menu",
+ "nav",
+ "ol",
+ "p",
+ "pre",
+ "section",
+ "table",
+ "ul",
+ }
+)
+_IMPLICIT_CLOSERS: dict = {
+ "p": _P_CLOSING_TAGS,
+ "li": frozenset({"li"}),
+ "dt": frozenset({"dt", "dd"}),
+ "dd": frozenset({"dt", "dd"}),
+ "tr": frozenset({"tr"}),
+ "td": frozenset({"td", "th", "tr"}),
+ "th": frozenset({"td", "th", "tr"}),
+ "option": frozenset({"option", "optgroup"}),
+ "optgroup": frozenset({"optgroup"}),
+}
+
+
+# Item tag -> container tags that re-scope it: a nested container makes an inner
+# item a descendant, not an optional-close sibling, so recovery must stop there
+# rather than close (and un-hide) the outer item and leak its nested content.
+_CLOSE_BARRIERS: dict = {
+ "li": frozenset({"ul", "ol", "menu"}),
+ "dt": frozenset({"dl"}),
+ "dd": frozenset({"dl"}),
+ "tr": frozenset({"table"}),
+ "td": frozenset({"table"}),
+ "th": frozenset({"table"}),
+ "option": frozenset({"select", "datalist"}),
+ "optgroup": frozenset({"select", "datalist"}),
+}
+
+
_BLOCK_TAGS = frozenset(
{
"p",
@@ -51,13 +186,33 @@ _INLINE_EMPHASIS = {"strong": "**", "b": "**", "em": "*", "i": "*"}
class _MarkdownRenderer(HTMLParser):
- """HTMLParser subclass that emits Markdown tokens into a list."""
+ """HTMLParser subclass that emits Markdown tokens into a list.
- def __init__(self):
+ ``scope_tags`` restricts emission to the subtree(s) of the given tags
+ (e.g. ``{"article"}``): outside them every handler is a no-op, which is
+ how the readability-style main-content pass drops page furniture.
+ """
+
+ def __init__(self, scope_tags: frozenset[str] | None = None):
super().__init__(convert_charrefs = False)
self._out: list[str] = []
self._skip_depth: int = 0
+ # Main-content scoping: emit only while inside a scope tag.
+ self._scope_tags = scope_tags
+ self._scope_depth: int = 0
+
+ # Output boundaries per top-level scope element, so a caller can size each
+ # candidate alone and a swarm of tiny sibling cards can't clear the threshold.
+ self.scope_segments: list[str] = []
+ self._scope_seg_start: int | None = None
+
+ # Hidden-subtree tracking: stack of open non-void tags plus the indices
+ # where a hidden element started. End tags pop to the matching tag, so
+ # an omitted </p>/<li> close cannot leave the renderer stuck hidden.
+ self._open_tags: list[str] = []
+ self._hidden_marks: list[int] = []
+
# Link state
self._link_href: str | None = None
self._link_text_parts: list[str] = []
@@ -150,16 +305,95 @@ class _MarkdownRenderer(HTMLParser):
# ------------------------------------------------------------------
# Tag handlers
# ------------------------------------------------------------------
+ # Structural bookkeeping shared by every start tag (skip/hidden/scope).
+ def _close_implicit(self, tag: str) -> None:
+ """HTML5 optional-end-tag recovery for a start tag about to open.
+
+ Pops each implicitly-closed ancestor (and its hidden marks), scanning the
+ whole stack so an open ``<p>``/``<li>`` still closes under an unclosed inline
+ ``<span>``. Stops at a ``_CLOSE_BARRIERS`` container so recovery never crosses
+ a nested list/table/dl and leaks the outer item's hidden content. Runs even
+ for skipped ``<nav>``/``<footer>``, which also close ``<p>``."""
+ barriers = _CLOSE_BARRIERS.get(tag, ())
+ while True:
+ close_at = None
+ for i in range(len(self._open_tags) - 1, -1, -1):
+ name = self._open_tags[i]
+ if tag in _IMPLICIT_CLOSERS.get(name, ()):
+ close_at = i
+ break
+ # A barrier container re-scopes the item; stop before it.
+ if name in barriers:
+ break
+ if close_at is None:
+ break
+ del self._open_tags[close_at:]
+ while self._hidden_marks and self._hidden_marks[-1] >= close_at:
+ self._hidden_marks.pop()
+
+ def _enter_tag(self, tag: str, attr_dict: dict) -> bool:
+ """Track open/hidden/scope state; return True when the tag's content
+ should be rendered (False = suppressed). Caller runs ``_close_implicit``
+ first so recovery also fires for skipped tags."""
+ if tag not in _VOID_TAGS:
+ self._open_tags.append(tag)
+ if _is_hidden_element(attr_dict):
+ self._hidden_marks.append(len(self._open_tags) - 1)
+ elif _is_hidden_element(attr_dict):
+ # Void elements never join the stack, so suppress a hidden one inline.
+ return False
+ if self._scope_tags is not None and tag in self._scope_tags:
+ if self._scope_depth == 0:
+ self._scope_seg_start = len(self._out)
+ self._scope_depth += 1
+ if self._hidden_marks:
+ return False
+ if self._scope_tags is not None and self._scope_depth == 0:
+ return False
+ return True
+
+ def _exit_tag(self, tag: str) -> bool:
+ """Pop to the matching open tag; return True when the end tag should
+ be rendered (False = it closed inside a hidden / out-of-scope region)."""
+ suppressed = bool(self._hidden_marks) or (
+ self._scope_tags is not None and self._scope_depth == 0
+ )
+ if tag not in _VOID_TAGS:
+ # Pop to the innermost matching open tag (recovers omitted closes).
+ for i in range(len(self._open_tags) - 1, -1, -1):
+ if self._open_tags[i] == tag:
+ del self._open_tags[i:]
+ while self._hidden_marks and self._hidden_marks[-1] >= i:
+ self._hidden_marks.pop()
+ break
+ if self._scope_tags is not None and tag in self._scope_tags and self._scope_depth > 0:
+ self._scope_depth -= 1
+ if self._scope_depth == 0 and self._scope_seg_start is not None:
+ self.scope_segments.append("".join(self._out[self._scope_seg_start :]))
+ self._scope_seg_start = None
+ return not suppressed
+
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
tag = tag.lower()
+ if self._skip_depth:
+ # Inside a skipped subtree: only track nested skip depth.
+ if tag in _SKIP_TAGS:
+ self._skip_depth += 1
+ return
+
+ # Recover optional end tags before the skip decision: a skipped
+ # <nav>/<footer> still implicitly closes an open <p>, releasing its
+ # hidden mark so following siblings render.
+ self._close_implicit(tag)
+
if tag in _SKIP_TAGS:
self._skip_depth += 1
return
- if self._skip_depth:
- return
attr_dict = dict(attrs)
+ if not self._enter_tag(tag, attr_dict):
+ return
if tag in _HEADING_TAGS:
level = int(tag[1])
@@ -250,6 +484,9 @@ class _MarkdownRenderer(HTMLParser):
if self._skip_depth:
return
+ if not self._exit_tag(tag):
+ return
+
if tag in _HEADING_TAGS:
self._emit("\n\n")
@@ -308,8 +545,13 @@ class _MarkdownRenderer(HTMLParser):
# ------------------------------------------------------------------
# Text / entity handlers
# ------------------------------------------------------------------
+ def _text_suppressed(self) -> bool:
+ if self._skip_depth or self._hidden_marks:
+ return True
+ return self._scope_tags is not None and self._scope_depth == 0
+
def handle_data(self, data: str) -> None:
- if self._skip_depth:
+ if self._text_suppressed():
return
if self._in_pre:
self._pre_parts.append(data)
@@ -326,12 +568,12 @@ class _MarkdownRenderer(HTMLParser):
self._emit(text)
def handle_entityref(self, name: str) -> None:
- if self._skip_depth:
+ if self._text_suppressed():
return
self._emit(html.unescape(f"&{name};"))
def handle_charref(self, name: str) -> None:
- if self._skip_depth:
+ if self._text_suppressed():
return
self._emit(html.unescape(f"&#{name};"))
@@ -366,6 +608,14 @@ class _MarkdownRenderer(HTMLParser):
else:
self._out.append("\n\n" + prefixed + "\n\n")
+ # A scope left open by truncated HTML never reached _exit_tag, so its output
+ # never joined scope_segments and would score 0. Flush the still-open segment
+ # here (after the side-buffers) so a truncated main-content page is scored.
+ if self._scope_seg_start is not None:
+ self.scope_segments.append("".join(self._out[self._scope_seg_start :]))
+ self._scope_seg_start = None
+ self._scope_depth = 0
+
# Post-processing
def _cleanup(text: str) -> str:
@@ -399,17 +649,124 @@ def _cleanup(text: str) -> str:
return "\n".join(out).strip()
-# Public API
-def html_to_markdown(source_html: str) -> str:
- """Convert HTML to Markdown (headings, links, emphasis, lists, tables, blockquotes, code, entities).
+# Known boilerplate fragments stripped from main-content conversions, matched
+# only against short lines. Sources: GitHub page furniture / client-side error
+# placeholders, skip-links, cookie banners.
+_BOILERPLATE_FRAGMENTS = (
+ "skip to content",
+ "skip to main content",
+ "there was an error while loading",
+ "please reload this page",
+ "you can't perform that action at this time",
+ "you signed in with another tab or window",
+ "you signed out in another tab or window",
+ "you switched accounts on another tab or window",
+ "reload to refresh your session",
+ "you must be signed in to change notification settings",
+ "uh oh!",
+ "{{ message }}",
+ "this website uses cookies",
+ "we use cookies",
+ "accept all cookies",
+ "manage cookie preferences",
+)
+# Only shorter lines are eligible for boilerplate dropping; real content
+# sentences quoting a fragment run longer.
+_BOILERPLATE_MAX_LINE_CHARS = 300
+
+# Normalized furniture phrases for whole-segment matching. See _line_is_boilerplate.
+_BOILERPLATE_NORMALIZED = frozenset(
+ re.sub(r"\s+", " ", fragment).strip().casefold().rstrip(".!:")
+ for fragment in _BOILERPLATE_FRAGMENTS
+)
- ``<script>``, ``<style>``, and ``<head>`` are stripped entirely.
- """
- # Normalize line endings before parsing.
- source_html = source_html.replace("\r\n", "\n").replace("\r", "\n")
- renderer = _MarkdownRenderer()
+
+def _line_is_boilerplate(line: str) -> bool:
+ """True only when a whole line is composed of known furniture phrases.
+
+ Splits on sentence terminators and requires every segment to be furniture, so a
+ line stacking several phrases is dropped while prose that merely quotes one is
+ kept (its other words leave a non-furniture segment)."""
+ normalized = re.sub(r"\s+", " ", line).strip().casefold()
+ if not normalized:
+ return False
+ segments = [segment.strip().rstrip(".!:") for segment in re.split(r"[.!]", normalized)]
+ segments = [segment for segment in segments if segment]
+ return bool(segments) and all(segment in _BOILERPLATE_NORMALIZED for segment in segments)
+
+
+def _strip_boilerplate_lines(text: str) -> str:
+ """Drop short lines that consist entirely of known page-furniture phrases.
+
+ Fenced code blocks are preserved verbatim: boilerplate never renders
+ inside ``<pre>``, while READMEs legitimately quote error strings."""
+ out: list[str] = []
+ in_fence = False
+ for line in text.split("\n"):
+ if line.lstrip().startswith("```"):
+ in_fence = not in_fence
+ out.append(line)
+ continue
+ if not in_fence and len(line) <= _BOILERPLATE_MAX_LINE_CHARS and _line_is_boilerplate(line):
+ continue
+ out.append(line)
+ # Collapse blank runs the dropped lines may have left behind.
+ return re.sub(r"\n{3,}", "\n\n", "\n".join(out)).strip()
+
+
+def _render(source_html: str, scope_tags: frozenset[str] | None) -> str:
+ renderer = _MarkdownRenderer(scope_tags = scope_tags)
renderer.feed(source_html)
renderer.close()
renderer.flush_pending()
raw = "".join(renderer._out)
return _cleanup(raw)
+
+
+def _select_main_scope_render(source_html: str, tag: str) -> tuple[int, str]:
+ """Length and boilerplate-stripped render of the largest single ``<tag>``
+ subtree. Sizing candidates one at a time stops many tiny sibling cards from
+ clearing the threshold together, and returning that one subtree keeps
+ unrelated siblings (related cards, comment threads) out of the output."""
+ renderer = _MarkdownRenderer(scope_tags = frozenset({tag}))
+ renderer.feed(source_html)
+ renderer.close()
+ renderer.flush_pending()
+ best_len = 0
+ best_render = ""
+ for seg in renderer.scope_segments:
+ rendered = _strip_boilerplate_lines(_cleanup(seg))
+ if len(rendered) > best_len:
+ best_len = len(rendered)
+ best_render = rendered
+ return best_len, best_render
+
+
+# A scoped conversion below this size is judged not to be the page's main
+# content (e.g. an empty <article> stub) and the next candidate is tried.
+_MIN_MAIN_CONTENT_CHARS = 200
+
+
+# Public API
+def html_to_markdown(source_html: str, *, main_content: bool = False) -> str:
+ """Convert HTML to Markdown (headings, links, emphasis, lists, tables, blockquotes, code, entities).
+
+ ``<script>``, ``<style>``, and ``<head>`` are stripped entirely, as are
+ subtrees hidden from rendering (``hidden`` / ``aria-hidden="true"``).
+
+ ``main_content=True`` applies a readability-style heuristic for page
+ fetches: prefer the ``<article>`` subtree (GitHub renders READMEs there),
+ then ``<main>``, falling back to the whole document, and strip known
+ boilerplate fragments from the result.
+ """
+ # Normalize line endings before parsing.
+ source_html = source_html.replace("\r\n", "\n").replace("\r", "\n")
+ if main_content:
+ for scope_tag in ("article", "main"):
+ # Render only the chosen subtree so sibling <article>/<main>
+ # elements do not leak in once the largest passes the size gate.
+ length, rendered = _select_main_scope_render(source_html, scope_tag)
+ if length >= _MIN_MAIN_CONTENT_CHARS:
+ return rendered
+ return _strip_boilerplate_lines(_render(source_html, None))
+ return _render(source_html, None)
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 6b6c5373ebd..8f19973cdaf 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -301,6 +301,27 @@ def _gguf_has_genuine_tool_signal(text: str, signals, active_tools: list[dict])
return False
+_TEXT_TOOL_NAME_RE = re.compile(r'"name"\s*:\s*"([\w.\-]+)"')
+_TEXT_TOOL_GEMMA_RE = re.compile(r"\s*call:([\w.\-]+)")
+_TEXT_TOOL_REHEARSAL_RE = re.compile(r"\s*([\w.\-]+)\s*\[ARGS\]")
+
+
+def _sniff_text_tool_name(text: str, enabled_names: set) -> str:
+ """Best-effort tool name from a partially drained TEXT tool call, gated on
+ enabled names so prose can never spawn a card. Used only to open the live
+ argument pane early; the authoritative parse still happens at stream end."""
+ m = _TEXT_TOOL_NAME_RE.search(text[:4096])
+ if m and m.group(1) in enabled_names:
+ return m.group(1)
+ m = _TEXT_TOOL_GEMMA_RE.match(text[:256])
+ if m and m.group(1) in enabled_names:
+ return m.group(1)
+ m = _TEXT_TOOL_REHEARSAL_RE.match(text[:256])
+ if m and m.group(1) in enabled_names:
+ return m.group(1)
+ return ""
+
+
def _is_rehearsal_prefix(stripped: str, active_tools: list[dict]) -> bool:
"""True if ``stripped`` is a (possibly partial) prefix of ``NAME[ARGS]`` for an
active tool -- the bare tool name arriving in its own chunk before ``[ARGS]{...}``.
@@ -8984,6 +9005,7 @@ class LlamaCppBackend:
{"type": "content", "text": "token"} -- streamed content tokens (cumulative)
{"type": "reasoning", "text": "token"} -- streamed reasoning tokens (cumulative)
"""
+ from core.inference.tool_stream_exec import accepts_output_callback, stream_tool_execution
from core.inference.tools import (
build_rag_autoinject,
execute_tool,
@@ -9268,6 +9290,17 @@ class LlamaCppBackend:
provisional_started_tool_calls: dict[str, str] = {}
resolved_provisional_tool_call_ids: set[str] = set()
_suppress_visible_output = _forced_tool_call_pending
+ # Cards that already got their first tool_args event; later
+ # fragments stream individually so a big payload isn't a dead spinner.
+ arg_streamed_tool_call_ids: set[str] = set()
+ # TEXT tool-call path: a committed call's raw text streams to a
+ # provisional card under the parser's first-call id ("call_0"), so
+ # the final tool_start reconciles in place.
+ _text_args_call_start = -1
+ _text_args_streamed_upto = -1
+ _text_args_id = ""
+ _text_args_name = ""
+ _confirm_gated_iteration = bool(confirm_tool_calls) and not bypass_permissions
with self._open_stream(url, payload, cancel_event) as (
response,
@@ -9430,6 +9463,29 @@ class LlamaCppBackend:
provisional = True,
),
}
+ # Stream argument text so the UI shows the code being
+ # written: first event the backlog, later the fragment.
+ # Display only; accumulator untouched.
+ if current_id in provisional_started_tool_calls:
+ if current_id not in arg_streamed_tool_call_ids:
+ arg_streamed_tool_call_ids.add(current_id)
+ _args_backlog = tool_calls_acc[idx]["function"].get(
+ "arguments", ""
+ )
+ if _args_backlog:
+ yield {
+ "type": "tool_args",
+ "tool_call_id": current_id,
+ "tool_name": current_name,
+ "text": _args_backlog,
+ }
+ elif func.get("arguments"):
+ yield {
+ "type": "tool_args",
+ "tool_call_id": current_id,
+ "tool_name": current_name,
+ "text": func["arguments"],
+ }
continue
# ── Reasoning tokens ──
@@ -9468,7 +9524,60 @@ class LlamaCppBackend:
content_accum += token
if detect_state == _S_DRAINING:
- pass # accumulate silently
+ # Accumulate silently for parsing, but stream the drained
+ # TEXT call to a provisional card. Gated on an enabled-name
+ # sniff + size floor so prose/small calls spawn no pane; id
+ # matches the first call so the final tool_start reconciles.
+ if (
+ not has_structured_tc
+ and not _confirm_gated_iteration
+ and _text_args_call_start >= 0
+ ):
+ if not _text_args_id:
+ _call_text = content_accum[_text_args_call_start:]
+ _sniffed = _sniff_text_tool_name(
+ _call_text, _enabled_tool_names
+ )
+ if _sniffed and (
+ _sniffed == "render_html"
+ or len(_call_text)
+ >= _PROVISIONAL_ARGS_MIN_CHARS
+ ):
+ _text_args_id = "call_0"
+ _text_args_name = _sniffed
+ if (
+ _text_args_id
+ not in provisional_started_tool_calls
+ ):
+ provisional_started_tool_calls[
+ _text_args_id
+ ] = _sniffed
+ yield {
+ "type": "tool_start",
+ "tool_name": _sniffed,
+ "tool_call_id": _text_args_id,
+ "arguments": {},
+ "provenance": tool_event_provenance(
+ provisional = True,
+ ),
+ }
+ yield {
+ "type": "tool_args",
+ "tool_call_id": _text_args_id,
+ "tool_name": _sniffed,
+ "text": _call_text,
+ }
+ _text_args_streamed_upto = len(content_accum)
+ elif len(content_accum) > _text_args_streamed_upto:
+ yield {
+ "type": "tool_args",
+ "tool_call_id": _text_args_id,
+ "tool_name": _text_args_name,
+ "text": content_accum[
+ _text_args_streamed_upto:
+ ],
+ }
+ _text_args_streamed_upto = len(content_accum)
elif detect_state == _S_STREAMING:
if in_thinking:
@@ -9575,6 +9684,11 @@ class LlamaCppBackend:
# without yielding. A live <think> prefix is
# separate from it -- close that.
detect_state = _S_DRAINING
+ # Call text begins at the held buffer
+ # (live arg display only; UI extracts the code).
+ _text_args_call_start = len(content_accum) - len(
+ content_buffer
+ )
if _close_streamed_think():
yield {
"type": "content",
@@ -9602,6 +9716,11 @@ class LlamaCppBackend:
"text": cleaned,
}
detect_state = _S_DRAINING
+ # Live-arg display starts at the held buffer
+ # (visible prefix flushed above; UI extracts the code).
+ _text_args_call_start = len(content_accum) - len(
+ content_buffer
+ )
elif _hold_buffer or (
is_prefix
and (
@@ -9849,9 +9968,20 @@ class LlamaCppBackend:
f"{'structured delta' if has_structured_tc else 'content text'}"
)
if not tool_calls:
- # DRAINING but no tool calls (false positive). Merge
- # accumulated metrics from prior tool iterations so
- # they aren't silently dropped.
+ # DRAINING but no tool calls (false positive): close any
+ # provisional cards (a sniff can open one whose call never
+ # parses); without a tool_end the card spins forever.
+ for _pid, _pname in provisional_started_tool_calls.items():
+ if _pid not in resolved_provisional_tool_call_ids:
+ resolved_provisional_tool_call_ids.add(_pid)
+ yield {
+ "type": "tool_end",
+ "tool_name": _pname,
+ "tool_call_id": _pid,
+ "result": "",
+ "provenance": tool_event_provenance(provisional = True),
+ }
+ # Merge metrics from prior tool iterations so they aren't dropped.
yield {"type": "status", "text": ""}
if content_accum:
# Strip leaked tool-call XML before yielding.
@@ -9912,9 +10042,22 @@ class LlamaCppBackend:
assistant_msg: dict = {"role": "assistant", "content": content_text}
assistant_appended = False
+ # The text-path provisional card uses the parser's default id ("call_0");
+ # a Mistral-style call carries its own id and would open a duplicate. Reuse
+ # the card's id for the first matching call (same tool name) to reconcile.
+ _text_provisional_id = _text_args_id if not has_structured_tc else ""
+
for tc in tool_calls or []:
func = tc.get("function", {})
tool_name = func.get("name", "")
+ if (
+ _text_provisional_id
+ and _text_provisional_id in provisional_started_tool_calls
+ and _text_provisional_id not in resolved_provisional_tool_call_ids
+ and tc.get("id") not in provisional_started_tool_calls
+ and provisional_started_tool_calls[_text_provisional_id] == tool_name
+ ):
+ tc = {**tc, "id": _text_provisional_id}
provisional_match = tc.get("id") in provisional_started_tool_calls
decision = tool_controller.prepare_call(
tc,
@@ -10026,15 +10169,33 @@ class LlamaCppBackend:
):
result = RAG_SEARCH_CAP_NUDGE
else:
- result = execute_tool(
- decision.tool_name,
- decision.arguments,
+ # Execute in a worker thread so live stdout chunks and heartbeats
+ # stream while the tool blocks (the SSE route turns heartbeats into
+ # keepalives). Result is byte-identical to a direct call.
+ def _invoke_tool(_output_callback, _decision = decision):
+ # execute_tool is injectable and may be monkey-patched with the
+ # pre-PR signature; forward output_callback only if it's accepted.
+ kwargs = dict(
+ cancel_event = cancel_event,
+ timeout = _effective_timeout,
+ session_id = session_id,
+ thread_id = thread_id,
+ rag_scope = rag_scope,
+ disable_sandbox = bypass_permissions,
+ )
+ if accepts_output_callback(execute_tool):
+ kwargs["output_callback"] = _output_callback
+ return execute_tool(
+ _decision.tool_name,
+ _decision.arguments,
+ **kwargs,
+ )
+
+ result = yield from stream_tool_execution(
+ _invoke_tool,
+ tool_name = decision.tool_name,
+ tool_call_id = decision.tool_call_id,
cancel_event = cancel_event,
- timeout = _effective_timeout,
- session_id = session_id,
- thread_id = thread_id,
- rag_scope = rag_scope,
- disable_sandbox = bypass_permissions,
)
if decision.tool_name == "search_knowledge_base":
_kb_search_count += 1
diff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.py
index c1fffb71cb2..f4c243d1bf3 100644
--- a/studio/backend/core/inference/safetensors_agentic.py
+++ b/studio/backend/core/inference/safetensors_agentic.py
@@ -15,6 +15,7 @@ parses tool calls from the cumulative text and dispatches via
"""
import bisect
+import inspect
import re
import threading
from typing import Callable, Generator, Optional
@@ -60,6 +61,7 @@ from core.inference.tool_loop_controller import (
status_for_tool,
tool_event_provenance,
)
+from core.inference.tool_stream_exec import stream_tool_execution
from state.tool_approvals import (
TOOL_REJECTED_MESSAGE,
abort_tool_decision,
@@ -402,6 +404,22 @@ def _tool_event_provenance(**flags: object) -> dict[str, object]:
return tool_event_provenance(**flags)
+def _accepts_output_callback(func: Callable[..., str]) -> bool:
+ """Whether an injectable ``execute_tool`` supports ``output_callback``.
+
+ The loop's ``execute_tool`` is a parameter (tests inject fakes), so forward
+ the live-output kwarg only when the callable declares it or takes ``**kwargs``.
+ """
+ try:
+ sig = inspect.signature(func)
+ except (TypeError, ValueError):
+ return False
+ params = sig.parameters
+ if "output_callback" in params:
+ return True
+ return any(p.kind is inspect.Parameter.VAR_KEYWORD for p in params.values())
+
+
def _call_single_turn(single_turn, conversation: list, active_tools: list[dict]):
"""Call a single-turn generator with active tool schemas when supported."""
try:
@@ -552,6 +570,9 @@ def run_safetensors_tool_loop(
provisional_render_html_started = False
provisional_resolved = False
provisional_render_html_id = f"call_{next_call_id}"
+ # Live-args offset for the provisional render_html card: the drained call
+ # text streams as tool_args so the canvas shows the HTML being written.
+ _live_args_streamed_upto = -1
# When a human confirmation gate is active the real tool_start is keyed
# by an approval id and carries awaiting_confirmation, so an early
# provisional card (keyed by tool_call_id, no approval) would show the
@@ -623,6 +644,30 @@ def run_safetensors_tool_loop(
"arguments": {},
"provenance": _tool_event_provenance(provisional = True),
}
+ # Backlog first: everything drained so far.
+ yield {
+ "type": "tool_args",
+ "tool_call_id": provisional_render_html_id,
+ "tool_name": "render_html",
+ "text": content_accum,
+ }
+ _live_args_streamed_upto = len(content_accum)
+ elif (
+ provisional_render_html_started
+ and not provisional_resolved
+ and _live_args_streamed_upto >= 0
+ and len(content_accum) > _live_args_streamed_upto
+ ):
+ # Still writing the call: stream the fragment so the canvas
+ # renders live. Display only; content_accum still feeds the
+ # stream-end parser verbatim.
+ yield {
+ "type": "tool_args",
+ "tool_call_id": provisional_render_html_id,
+ "tool_name": "render_html",
+ "text": content_accum[_live_args_streamed_upto:],
+ }
+ _live_args_streamed_upto = len(content_accum)
continue
if detect_state == _state_streaming:
@@ -663,6 +708,13 @@ def run_safetensors_tool_loop(
"arguments": {},
"provenance": _tool_event_provenance(provisional = True),
}
+ yield {
+ "type": "tool_args",
+ "tool_call_id": provisional_render_html_id,
+ "tool_name": "render_html",
+ "text": content_accum,
+ }
+ _live_args_streamed_upto = len(content_accum)
continue
cumulative_display = candidate
cleaned = strip_tool_markup_streaming(
@@ -819,6 +871,13 @@ def run_safetensors_tool_loop(
"arguments": {},
"provenance": _tool_event_provenance(provisional = True),
}
+ yield {
+ "type": "tool_args",
+ "tool_call_id": provisional_render_html_id,
+ "tool_name": "render_html",
+ "text": content_accum,
+ }
+ _live_args_streamed_upto = len(content_accum)
elif is_prefix and (is_rehearsal_prefix or len(stripped) < _MAX_BUFFER_CHARS):
# A rehearsal prefix is self-bounded; the buffer cap must not cut long MCP names short.
continue
@@ -1146,10 +1205,12 @@ def run_safetensors_tool_loop(
):
result = RAG_SEARCH_CAP_NUDGE
else:
- try:
- result = execute_tool(
- decision.tool_name,
- decision.arguments,
+ # Execute in a worker thread so live stdout chunks and heartbeats
+ # stream while the tool blocks (the SSE route turns heartbeats into
+ # keepalives). execute_tool is injectable; pass output_callback
+ # only when it accepts it.
+ def _invoke_tool(_output_callback, _decision = decision):
+ kwargs = dict(
cancel_event = cancel_event,
timeout = eff_timeout,
session_id = session_id,
@@ -1157,6 +1218,17 @@ def run_safetensors_tool_loop(
rag_scope = rag_scope,
disable_sandbox = bypass_permissions,
)
+ if _accepts_output_callback(execute_tool):
+ kwargs["output_callback"] = _output_callback
+ return execute_tool(_decision.tool_name, _decision.arguments, **kwargs)
+
+ try:
+ result = yield from stream_tool_execution(
+ _invoke_tool,
+ tool_name = decision.tool_name,
+ tool_call_id = decision.tool_call_id,
+ cancel_event = cancel_event,
+ )
except Exception as exc:
logger.exception("Tool %s raised: %s", decision.tool_name, exc)
result = f"Error: tool raised an exception: {exc}"
diff --git a/studio/backend/core/inference/sandbox_site/__init__.py b/studio/backend/core/inference/sandbox_site/__init__.py
new file mode 100644
index 00000000000..eea99aa5264
--- /dev/null
+++ b/studio/backend/core/inference/sandbox_site/__init__.py
@@ -0,0 +1,6 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+# Package marker only, so wheel builds ship this directory. It goes on the
+# sandbox PYTHONPATH so site machinery imports the sibling ``sitecustomize`` at
+# startup; nothing in the backend imports it directly.
diff --git a/studio/backend/core/inference/sandbox_site/sitecustomize.py b/studio/backend/core/inference/sandbox_site/sitecustomize.py
new file mode 100644
index 00000000000..d655e8e35a8
--- /dev/null
+++ b/studio/backend/core/inference/sandbox_site/sitecustomize.py
@@ -0,0 +1,313 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Sandbox-side compatibility shim for ChatGPT code-interpreter paths.
+
+Models habitually write to /mnt/data (or /mnt/outputs, /home/sandbox,
+/workspace), none of which exist in the Studio sandbox. This module sits on the
+sandbox subprocess PYTHONPATH (see ``tools._build_safe_env``), so it loads at
+interpreter startup in every sandboxed ``python`` run and any Python the
+``terminal`` tool launches.
+
+It remaps those prefixes onto the CWD in ``open`` / ``io.open``, ``os.open``,
+``os.makedirs`` / ``os.mkdir`` and ``pathlib.Path.mkdir``. A write/create to a
+convention prefix always heals onto the CWD; a READ heals only when the mapped
+target already exists (re-reading an earlier write), so a genuinely missing
+input stays truthful on the path the model used instead of silently reading a
+same-basename workdir file. Since prefix lists cannot cover every invented path,
+``open`` / ``io.open`` also get a create-mode fallback: an absolute path outside
+the CWD whose parent is missing is redirected to the basename in the CWD. Reads
+and mkdir never use the fallback (an arbitrary absolute directory can legitimately
+succeed). It is collision-safe: it refuses to redirect onto an existing CWD file
+(letting open raise). The patch set (io.open, os.open, os.mkdir, Path.mkdir, and
+the <3.11 ``_NormalAccessor.open``) covers the low-level entry points pathlib
+routes through. A one-line stderr notice fires on the first remap, and everything
+is wrapped in try/except so a failure never breaks the interpreter.
+
+Identical with and without output streaming because the child env is.
+"""
+
+import builtins
+import io
+import json
+import os
+import sys
+
+# Code-interpreter convention prefixes. Remapping is gated on the prefix being
+# ABSENT (see _remap) so a genuine host mount / user dir is never shadowed.
+_PREFIXES = ("/mnt/data", "/mnt/outputs", "/home/sandbox", "/workspace")
+# /tmp exists on the host; separate only to note that. The absence gate applies alike.
+_CONDITIONAL_PREFIXES = ("/tmp/outputs",)
+_notified = False
+# Invented absolute write path -> healed CWD target, so re-writing the same
+# artifact re-serves it instead of tripping the anti-clobber guard.
+_remapped_writes: dict = {}
+# Each tool call is a fresh subprocess (in-process map starts empty), so this
+# on-disk sidecar carries the map across runs. It records only sources the
+# fallback healed, so an unrelated same-basename file is never adopted.
+_REMAP_SIDECAR = ".unsloth_sandbox_remap.json"
+
+
+def _note(subject, original, mapped):
+ """Print the one-shot stderr notice so the model learns the real location.
+
+ ``subject`` is what "does not exist" (the prefix, or the whole invented
+ path); ``original`` is echoed in the ``(original -> mapped)`` tail.
+ """
+ global _notified
+ if _notified:
+ return
+ _notified = True
+ print(
+ f"note: {subject} does not exist in this sandbox; "
+ f"using the working directory instead ({original} -> {mapped})",
+ file = sys.stderr,
+ )
+
+
+def _contained_join(cwd, rel):
+ """Join ``rel`` onto ``cwd`` so the result can never escape ``cwd``.
+
+ A habit path can carry ``..`` segments; joining verbatim would let the target
+ climb above the sandbox. ``..`` components are dropped and empty / ``.`` ones
+ ignored, keeping the result under ``cwd``.
+ """
+ parts = []
+ for part in rel.split("/"):
+ if part == "" or part == ".":
+ continue
+ if part == "..":
+ if parts:
+ parts.pop()
+ continue
+ parts.append(part)
+ return os.path.join(cwd, *parts) if parts else cwd
+
+
+def _map_onto_cwd(
+ prefix,
+ text,
+ notify = True,
+):
+ """Map ``<prefix>/rest`` onto ``./rest`` in the CWD, noting it once.
+
+ The suffix is contained under the CWD (see ``_contained_join``) so a path
+ like ``/mnt/data/../other_session/file`` cannot escape the workdir.
+ ``notify`` is False when the caller may keep the original path (a read), so
+ the one-shot notice is not spent on a remap that never happens.
+ """
+ rel = text[len(prefix) :].lstrip("/")
+ mapped = _contained_join(os.getcwd(), rel)
+ if notify:
+ _note(prefix, text, mapped)
+ return mapped
+
+
+def _sidecar_path(cwd):
+ return os.path.join(cwd, _REMAP_SIDECAR)
+
+
+def _load_sidecar(cwd):
+ """Return the persisted ``source -> healed target`` map, or {} on any error
+ (missing/corrupt/foreign sidecar degrades to in-process-only behaviour)."""
+ try:
+ with open(_sidecar_path(cwd)) as fh:
+ data = json.load(fh)
+ except Exception: # noqa: BLE001 - a bad sidecar must never break user code
+ return {}
+ return data if isinstance(data, dict) else {}
+
+
+def _record_sidecar(cwd, source, target):
+ """Persist ``source -> target`` so the next run re-serves it.
+
+ Written atomically (temp + ``os.replace``) and wrapped so a read-only/full
+ filesystem never breaks the interpreter. The path is inside the CWD, so the
+ patched ``open`` leaves it untouched (no remap, no recursion).
+ """
+ try:
+ data = _load_sidecar(cwd)
+ if data.get(source) == target:
+ return
+ data[source] = target
+ tmp = _sidecar_path(cwd) + ".tmp"
+ with open(tmp, "w") as fh:
+ json.dump(data, fh)
+ os.replace(tmp, _sidecar_path(cwd))
+ except Exception: # noqa: BLE001 - persistence is best effort only
+ pass
+
+
+def _is_creating_mode(mode):
+ """True only when an ``open()`` mode string can CREATE a missing file.
+
+ Only ``w`` / ``a`` / ``x`` create. ``r+`` / ``rb+`` require the path to exist,
+ so they must not trip the write fallback (which would corrupt an unrelated
+ same-basename file); ``w+`` / ``a+`` / ``x+`` still match.
+ """
+ return isinstance(mode, str) and any(c in mode for c in ("w", "a", "x"))
+
+
+def _remap_open(file, mode):
+ """Remap for ``open()`` / ``io.open()``.
+
+ A prefix remap runs first: a write/create heals onto the CWD; a READ heals
+ only when the mapped target already exists (re-reading an earlier write),
+ else the original path is kept so a genuine missing input fails truthfully
+ instead of silently reading a same-basename workdir file. Only if no prefix
+ matched and the call creates does the fallback kick in: an absolute target
+ outside the CWD whose parent is missing is redirected to the basename in the
+ CWD, unless ``CWD/<basename>`` already exists (an unrelated file), in which
+ case the original path is kept so open raises.
+ """
+ creating = _is_creating_mode(mode)
+ # notify=False: emit the notice only once we commit to the mapping below.
+ mapped = _remap(file, notify = False)
+ if mapped is not file:
+ # Write always heals; a read only when the mapped target exists (else keep
+ # the original path so a missing input stays truthful).
+ if creating or os.path.exists(mapped):
+ # Commit: emit the notice now (the notify=False peek above deferred it).
+ _remap(file, notify = True)
+ return mapped
+ return file
+ if not creating:
+ return file
+ try:
+ text = os.fspath(file)
+ except TypeError:
+ return file
+ # bytes paths left untouched (str-only, matching the prefix remaps).
+ if not isinstance(text, str) or not os.path.isabs(text):
+ return file
+ cwd = os.getcwd()
+ # Already inside the CWD: a real target the model meant; leave it alone.
+ if text == cwd or text.startswith(cwd + os.sep):
+ return file
+ parent = os.path.dirname(text)
+ # Redirect only when the parent is missing; an existing external directory is
+ # a deliberate target and stays truthful (os.path.exists follows symlinks).
+ if parent and os.path.exists(parent):
+ return file
+ base = os.path.basename(text)
+ # A trailing sep or '.'/'..' basename would redirect onto the CWD or its
+ # parent; refuse and let open raise.
+ if base in ("", ".", ".."):
+ return file
+ remapped = os.path.join(cwd, base)
+ # Never clobber an unrelated file sharing this basename (lexists catches
+ # dangling symlinks). But a target this fallback already healed for the same
+ # invented path (in-process map or cross-run sidecar) is the artifact being
+ # re-written, so re-serve it instead of raising on every overwrite.
+ if os.path.lexists(remapped) and remapped not in (
+ _remapped_writes.get(text),
+ _load_sidecar(cwd).get(text),
+ ):
+ return file
+ _remapped_writes[text] = remapped
+ _record_sidecar(cwd, text, remapped)
+ _note(text, text, remapped)
+ return remapped
+
+
+def _remap(path, notify = True):
+ """Map ``<prefix>/rest`` onto ``./rest`` in the CWD; other paths pass through.
+
+ ``notify`` is forwarded to ``_map_onto_cwd``; ``_remap_open`` passes False so
+ a read that keeps its original path emits no false notice.
+ """
+ try:
+ text = os.fspath(path)
+ except TypeError:
+ return path
+ if not isinstance(text, str):
+ return path
+ for prefix in _PREFIXES + _CONDITIONAL_PREFIXES:
+ # Heal only while the real prefix directory is absent, so a genuine host
+ # mount / user directory at that prefix is never shadowed.
+ if (text == prefix or text.startswith(prefix + "/")) and not os.path.exists(prefix):
+ return _map_onto_cwd(prefix, text, notify = notify)
+ return path
+
+
+def _install():
+ import pathlib
+
+ original_open = builtins.open
+ original_io_open = io.open
+ original_os_open = os.open
+ original_makedirs = os.makedirs
+ original_mkdir = os.mkdir
+ original_path_mkdir = pathlib.Path.mkdir
+
+ def _open(
+ file,
+ mode = "r",
+ *args,
+ **kwargs,
+ ):
+ return original_open(_remap_open(file, mode), mode, *args, **kwargs)
+
+ def _io_open(
+ file,
+ mode = "r",
+ *args,
+ **kwargs,
+ ):
+ return original_io_open(_remap_open(file, mode), mode, *args, **kwargs)
+
+ # mkdir/makedirs get only the prefix remap, never the write-mode fallback:
+ # an arbitrary absolute directory can legitimately succeed on the host.
+ def _makedirs(name, *args, **kwargs):
+ return original_makedirs(_remap(name), *args, **kwargs)
+
+ def _mkdir(path, *args, **kwargs):
+ return original_mkdir(_remap(path), *args, **kwargs)
+
+ def _os_open(
+ path,
+ flags,
+ mode = 0o777,
+ *,
+ dir_fd = None,
+ ):
+ # Path.touch() etc. go through os.open, not builtins.open. Only O_CREAT
+ # can create, so only it maps to "creating" mode; O_TRUNC / O_APPEND
+ # without O_CREAT still require the file to exist, so behave as a read.
+ logical_mode = "w" if (flags & os.O_CREAT) else "r"
+ mapped = _remap_open(path, logical_mode)
+ if dir_fd is None:
+ return original_os_open(mapped, flags, mode)
+ return original_os_open(mapped, flags, mode, dir_fd = dir_fd)
+
+ def _path_mkdir(self, *args, **kwargs):
+ # pathlib probes Path.is_dir()/os.stat (unpatched) on FileExistsError, so
+ # a bare os.mkdir remap would still raise when the target exists. Remap
+ # the receiver up front so parents/exist_ok stays idempotent.
+ mapped = _remap(self)
+ target = self if mapped is self else self.__class__(mapped)
+ return original_path_mkdir(target, *args, **kwargs)
+
+ builtins.open = _open
+ # pathlib.Path.open / write_text / read_text call io.open directly, so patch both.
+ io.open = _io_open
+ # Python < 3.11 only: pathlib's accessor captured the ORIGINAL io.open at
+ # import (``_NormalAccessor.open = io.open``), so the io.open patch misses it.
+ # Repoint it at the same wrapper (staticmethod to stay unbound); 3.11+ dropped
+ # the accessor, so this is a no-op there.
+ accessor = getattr(pathlib, "_NormalAccessor", None)
+ if accessor is not None and hasattr(accessor, "open"):
+ accessor.open = staticmethod(_io_open)
+ # Path.touch() and other low-level opens call os.open directly, so patch it too.
+ os.open = _os_open
+ os.makedirs = _makedirs
+ # Path.mkdir(parents=True) calls os.mkdir per component, so patch os.mkdir;
+ # patch Path.mkdir itself too so exist_ok/parents land on the mapped path.
+ os.mkdir = _mkdir
+ pathlib.Path.mkdir = _path_mkdir
+
+
+try:
+ _install()
+except Exception: # noqa: BLE001 - a broken shim must never break user code
+ pass
diff --git a/studio/backend/core/inference/tool_stream_exec.py b/studio/backend/core/inference/tool_stream_exec.py
new file mode 100644
index 00000000000..9cdb21bf8ae
--- /dev/null
+++ b/studio/backend/core/inference/tool_stream_exec.py
@@ -0,0 +1,284 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Streaming wrapper around blocking server-side tool execution.
+
+``stream_tool_execution`` runs a blocking tool call in a worker thread and
+turns it into a generator that yields:
+
+* ``{"type": "tool_output", "tool_name", "tool_call_id", "text"}`` -- an
+ incremental stdout/stderr chunk (python/terminal tools) for live UI output;
+* ``{"type": "heartbeat"}`` -- emitted whenever nothing else has been yielded
+ for ``heartbeat_interval_s`` seconds, so the SSE route can write a
+ keepalive and reverse proxies (Cloudflare tunnels cap idle streams at
+ ~100 s) never see a silent connection while a tool runs;
+
+and *returns* the tool's final result string via ``StopIteration.value``
+(``result = yield from stream_tool_execution(...)``). The returned result is
+byte-identical to calling the tool directly, so tool-result parsing, nudging,
+and healing downstream are untouched.
+"""
+
+from __future__ import annotations
+
+import inspect
+import queue
+import threading
+import time
+from typing import Any, Callable, Generator
+
+from loggers import get_logger
+
+logger = get_logger(__name__)
+
+
+def accepts_output_callback(func: Callable[..., str]) -> bool:
+ """Whether an injectable ``execute_tool`` supports ``output_callback``.
+
+ ``execute_tool`` is replaceable (tests inject fakes / the pre-PR signature),
+ so forward the kwarg only when the callable declares it or takes ``**kwargs``
+ (passing it unconditionally would ``TypeError`` on an old signature).
+ """
+ try:
+ params = inspect.signature(func).parameters
+ except (TypeError, ValueError):
+ return False
+ if "output_callback" in params:
+ return True
+ return any(p.kind is inspect.Parameter.VAR_KEYWORD for p in params.values())
+
+
+# Cadence of heartbeat events while a tool blocks with no output. Well under
+# common proxy idle caps (Cloudflare ~100 s, nginx default 60 s).
+TOOL_HEARTBEAT_INTERVAL_S = 10.0
+
+# How often the wrapper wakes to poll for output / completion / cancellation.
+_POLL_INTERVAL_S = 0.25
+
+# Upper bound on how long teardown waits for the worker once the stream is
+# closed or errors. A cancel-observing tool returns within this after
+# ``cancel_event`` is set; a cancel-ignoring one is a daemon left to finish on
+# its own rather than blocking teardown for the tool's full timeout.
+_WORKER_JOIN_TIMEOUT_S = 5.0
+
+# Cap on total streamed live-output characters per tool call, bounding the
+# transient UI stream so a tight print loop cannot flood the SSE channel. Much
+# higher than the model-visible result cap (tools._MAX_OUTPUT_CHARS) since the
+# UI keeps the live stream as the displayed output when the result is truncated.
+TOOL_OUTPUT_STREAM_MAX_CHARS = 400_000
+
+_STREAM_CAPPED_NOTICE = "\n... (further live output not streamed)\n"
+
+
+def _drain_queue(q: "queue.Queue", sentinel: object, max_chars: int | None) -> tuple[str, bool]:
+ """Pull every currently-queued item, joining chunks in FIFO order.
+
+ With ``max_chars`` set, stop concatenating at the budget and discard the
+ remaining chunks in place, bounding peak allocation when a chatty tool queues
+ far more than the cap before the consumer wakes. The crossing chunk is sliced
+ to one char past the budget, enough for the caller's truncation to stay
+ byte-identical. Returns ``(joined_text, hit_sentinel)``; the surplus is still
+ scanned so completion is detected promptly.
+ """
+ parts: list[str] = []
+ total = 0
+ dropping = False
+ hit_sentinel = False
+ while True:
+ try:
+ item = q.get_nowait()
+ except queue.Empty:
+ break
+ if item is sentinel:
+ hit_sentinel = True
+ break
+ if dropping:
+ continue
+ if max_chars is not None and total + len(item) > max_chars:
+ # Keep one char past the budget as the overflow signal; drop the rest.
+ parts.append(item[: max(0, max_chars - total) + 1])
+ dropping = True
+ continue
+ parts.append(item)
+ total += len(item)
+ return "".join(parts), hit_sentinel
+
+
+def stream_tool_execution(
+ invoke: Callable[[Callable[[str], None]], str],
+ *,
+ tool_name: str,
+ tool_call_id: str = "",
+ cancel_event: Any = None,
+ heartbeat_interval_s: float = TOOL_HEARTBEAT_INTERVAL_S,
+ poll_interval_s: float = _POLL_INTERVAL_S,
+) -> Generator[dict, None, str]:
+ """Run ``invoke(output_callback)`` in a thread; yield live events; return the result.
+
+ ``invoke`` receives a thread-safe ``callable(str)`` it may call with
+ incremental output chunks (or ignore entirely). Exceptions raised by the
+ tool propagate to the caller unchanged after the worker thread finishes.
+
+ ``cancel_event`` is the request-level cancellation signal already handed to
+ the tool. If the consumer closes this generator early (an SSE disconnect
+ calls ``gen.close()``, raising ``GeneratorExit`` at a ``yield``), the wrapper
+ sets it so a cancel-observing tool stops, then joins the worker with a bounded
+ timeout. Set ONLY on that abnormal-exit path, never on a clean finish, because
+ the event is shared across a turn's tool calls and setting it early would
+ abort the next tool.
+ """
+ output_queue: queue.Queue[Any] = queue.Queue()
+ done_sentinel = object()
+ outcome: dict[str, Any] = {}
+
+ # Bound accepted output at the PRODUCER boundary: the consumer-side cap alone
+ # wouldn't stop a fast worker enqueuing unboundedly while a slow SSE client
+ # backpressures. Accept at most one char past the cap (so the consumer still
+ # emits the capped notice) and drop the rest. The final result is captured
+ # independently, so this never changes the byte-identical result.
+ accepted_output_chars = 0
+ accepted_output_lock = threading.Lock()
+
+ def _on_output(text: str) -> None:
+ nonlocal accepted_output_chars
+ if not text:
+ return
+ with accepted_output_lock:
+ remaining = TOOL_OUTPUT_STREAM_MAX_CHARS + 1 - accepted_output_chars
+ if remaining <= 0:
+ return
+ accepted = text[:remaining]
+ accepted_output_chars += len(accepted)
+ output_queue.put(accepted)
+
+ def _run() -> None:
+ try:
+ outcome["result"] = invoke(_on_output)
+ except BaseException as exc: # noqa: BLE001 - re-raised on the caller side
+ outcome["error"] = exc
+ finally:
+ # Posted after the result/error is recorded; wakes the consumer
+ # immediately so fast tools pay no poll-interval latency.
+ output_queue.put(done_sentinel)
+
+ worker = threading.Thread(
+ target = _run,
+ daemon = True,
+ name = f"tool-exec-{tool_name or 'unknown'}",
+ )
+ worker.start()
+
+ # Heartbeats are paced by counting idle queue polls rather than a wall clock
+ # (tests patch ``time.monotonic`` globally, so the wrapper must not read it).
+ idle_polls_per_heartbeat = max(1, int(round(heartbeat_interval_s / poll_interval_s)))
+ idle_polls = 0
+ streamed_chars = 0
+ stream_capped = False
+ finished = False
+
+ def _drain_pending(max_chars: int | None = None) -> str:
+ nonlocal finished
+ text, hit_sentinel = _drain_queue(output_queue, done_sentinel, max_chars)
+ if hit_sentinel:
+ finished = True
+ return text
+
+ def _drain_and_drop() -> None:
+ """Discard the current and every queued chunk without concatenating.
+
+ Past the cap every chunk is dropped, so don't pay to build a combined
+ string only to drop it. Still detect completion so the loop can exit.
+ """
+ nonlocal finished
+ while True:
+ try:
+ item = output_queue.get_nowait()
+ except queue.Empty:
+ return
+ if item is done_sentinel:
+ finished = True
+ return
+
+ abnormal_exit = False
+ try:
+ while not finished:
+ try:
+ item = output_queue.get(timeout = poll_interval_s)
+ except queue.Empty:
+ # A disconnect sets cancel_event while the worker is silent;
+ # surface a heartbeat this poll so the route regains control and
+ # tears down at once, not after a full heartbeat interval.
+ if cancel_event is not None and cancel_event.is_set():
+ yield {"type": "heartbeat"}
+ continue
+ idle_polls += 1
+ if idle_polls >= idle_polls_per_heartbeat:
+ idle_polls = 0
+ yield {"type": "heartbeat"}
+ continue
+
+ if item is done_sentinel:
+ break
+
+ if stream_capped:
+ # Past the cap: drop this chunk and every queued sibling (see
+ # _drain_and_drop). Pace with one time.sleep per poll (not
+ # time.monotonic -- tests patch the clock), counted as an idle
+ # poll so heartbeats keep flowing while the queue stays non-empty.
+ _drain_and_drop()
+ if finished:
+ break
+ time.sleep(poll_interval_s)
+ idle_polls += 1
+ if idle_polls >= idle_polls_per_heartbeat:
+ idle_polls = 0
+ yield {"type": "heartbeat"}
+ continue
+
+ # Bound the join to the remaining budget so the crossing batch can't
+ # allocate far past the cap (surplus is truncated below anyway); the
+ # prefix is long enough that truncation stays byte-identical.
+ budget = TOOL_OUTPUT_STREAM_MAX_CHARS - streamed_chars
+ chunk = item + _drain_pending(max_chars = budget - len(item))
+ idle_polls = 0
+ if streamed_chars + len(chunk) > TOOL_OUTPUT_STREAM_MAX_CHARS:
+ chunk = chunk[: max(0, TOOL_OUTPUT_STREAM_MAX_CHARS - streamed_chars)]
+ chunk += _STREAM_CAPPED_NOTICE
+ stream_capped = True
+ streamed_chars += len(chunk)
+ if chunk:
+ yield {
+ "type": "tool_output",
+ "tool_name": tool_name,
+ "tool_call_id": tool_call_id,
+ "text": chunk,
+ }
+ except BaseException:
+ # The loop only raises when the consumer closes us early: an SSE
+ # disconnect calls gen.close() (GeneratorExit at the yield) or the route
+ # throws in. Signal cancellation so a cancel-observing tool returns; the
+ # daemon worker is then abandoned (see finally). Re-raise so the caller
+ # sees the real cause (GeneratorExit must not be swallowed). Runs ONLY on
+ # abnormal exit, so the shared cancel_event is never set out from under
+ # the next tool in a clean multi-tool turn.
+ abnormal_exit = True
+ if cancel_event is not None:
+ try:
+ cancel_event.set()
+ except Exception:
+ pass
+ raise
+ finally:
+ # Clean finish: the worker already recorded its result and queued the
+ # sentinel we consumed, so this join returns at once. Abnormal exit:
+ # cancel_event is set and the daemon worker abandoned, so join with a zero
+ # timeout -- teardown never blocks the caller (the route may close this
+ # generator on the event loop), and the daemon cannot outlive the process.
+ worker.join(timeout = 0 if abnormal_exit else _WORKER_JOIN_TIMEOUT_S)
+
+ error = outcome.get("error")
+ if error is not None:
+ raise error
+ # Returned verbatim (the loop's record_result handles non-str), so the
+ # final tool result is byte-identical to a direct execute_tool call.
+ return outcome.get("result")
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 84a67c6ad40..3f9d3417494 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -13,6 +13,7 @@ import signal
os.environ["UNSLOTH_IS_PRESENT"] = "1"
import asyncio
+import queue
import random
import re
import shlex
@@ -21,6 +22,7 @@ import subprocess
import sys
import tempfile
import threading
+import time
import urllib.parse
import urllib.request
@@ -73,7 +75,21 @@ if sys.platform != "win32":
# Raster-image allowlist for sandbox file serving.
# No .svg (XSS via embedded scripts), no .html, no .pdf.
_IMAGE_EXTS = frozenset({".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"})
-_MAX_OUTPUT_CHARS = 8000 # truncate long output
+
+
+def _env_int(name: str, default: int) -> int:
+ """Read an int env override; fall back to ``default`` on unset/garbage."""
+ try:
+ value = int(os.environ.get(name, "") or default)
+ except (TypeError, ValueError):
+ return default
+ return value if value > 0 else default
+
+
+# Model-visible cap on python/terminal tool results (protects the context
+# window). The live UI stream is capped separately and higher, so _truncate's
+# notice stays mode-neutral (see tool_stream_exec.TOOL_OUTPUT_STREAM_MAX_CHARS).
+_MAX_OUTPUT_CHARS = _env_int("UNSLOTH_TOOL_RESULT_MAX_CHARS", 16000)
_BLOCKED_COMMANDS_COMMON = frozenset(
{
"rm",
@@ -204,8 +220,7 @@ def _find_blocked_commands(command: str) -> set[str]:
blocked: set[str] = set()
# punctuation_chars splits separators into their own tokens, so command
- # position is detected even in `echo done; rm -rf x` (no whitespace) or
- # quote-split names (`r''m` collapses to `rm` after `;`).
+ # position is detected even in `echo done; rm -rf x` (no whitespace).
try:
if sys.platform == "win32":
tokens = shlex.split(command, posix = False)
@@ -309,6 +324,9 @@ def _find_blocked_commands(command: str) -> set[str]:
return blocked
+# Directory holding the sandbox ``sitecustomize.py`` shim (code-interpreter
+# path remap); placed on the sandboxed child's PYTHONPATH in _build_safe_env.
+_SANDBOX_SITE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "sandbox_site")
# ── "Approve for me" (permission_mode="auto") safety detection ──────────────
# Auto mode pauses only calls classified here as potentially unsafe. The sandbox
# and hard blocks (blocklist, rlimits) still apply at run time; this gate only
@@ -2476,9 +2494,11 @@ def _build_safe_env(workdir: str) -> dict[str, str]:
"""Build a minimal, credential-free environment for sandboxed subprocesses.
Whitelist-built from scratch (parent env NOT inherited): only PATH/HOME/
- TMPDIR/LANG/TERM/PYTHONIOENCODING (+VIRTUAL_ENV or Windows SystemRoot) reach
- the child; all credential vars (HF_TOKEN, AWS_*, etc.) are absent. HOME
- points at the sandbox workdir so SDKs can't read the operator's cached creds.
+ TMPDIR/LANG/TERM/PYTHONIOENCODING/PYTHONPATH (+VIRTUAL_ENV or Windows
+ SystemRoot) reach the child; all credential vars (HF_TOKEN, AWS_*, etc.)
+ are absent. HOME points at the sandbox workdir so SDKs can't read the
+ operator's cached creds. PYTHONPATH carries only the sandbox sitecustomize
+ shim directory.
"""
# Start from the running interpreter's dir so 'python'/'pip' resolve to the
# same environment the Studio server runs in.
@@ -2508,6 +2528,9 @@ def _build_safe_env(workdir: str) -> dict[str, str]:
"LANG": os.environ.get("LANG", "C.UTF-8"),
"TERM": "dumb",
"PYTHONIOENCODING": "utf-8",
+ # sitecustomize shim: remaps ChatGPT code-interpreter paths (/mnt/data
+ # etc.) onto the sandbox CWD; see sandbox_site/sitecustomize.py.
+ "PYTHONPATH": _SANDBOX_SITE_DIR,
}
if venv:
env["VIRTUAL_ENV"] = venv
@@ -2542,13 +2565,10 @@ _BYPASS_ENV_SECRET_NAMES = frozenset(
"KAGGLE_KEY",
"MYSQL_PWD", # exact name: markers use PASSWD, not PWD (PWD is the cwd var)
"LD_PRELOAD",
- # Auth brokers / capability handles: not secrets by value, but they
- # hand the child the operator's live agent (ssh/gpg), kube config, or
- # docker daemon. Names are listed because there is no value signal to
- # key off. URL config vars (HTTP_PROXY, PIP_INDEX_URL, DATABASE_URL,
- # ...) are intentionally NOT name-listed: a benign proxy/index without
- # credentials must keep working in bypass mode, while a credentialed
- # value is dropped by _is_secret_env_value() regardless of its name.
+ # Auth brokers / capability handles: hand the child the operator's live
+ # agent (ssh/gpg), kube config, or docker daemon. Listed by name (no
+ # value signal). URL config vars are NOT name-listed: a credentialed
+ # value is dropped by _is_secret_env_value() regardless of name.
"SSH_AUTH_SOCK",
"SSH_AGENT_PID",
"GPG_AGENT_INFO",
@@ -2568,37 +2588,30 @@ _BYPASS_ENV_SECRET_MARKERS = (
"CREDENTIAL",
"PRIVATE_KEY",
"AUTH", # e.g. NPM_CONFIG__AUTH (npm _auth), REDISCLI_AUTH
- # Azure App Service connection strings: SQLCONNSTR_/CUSTOMCONNSTR_/... and
- # WEBSITE_CONTENTAZUREFILECONNECTIONSTRING carry DB/storage credentials.
+ # Azure App Service connection strings carry DB/storage credentials.
"CONNSTR",
"CONNECTIONSTRING",
)
# Non-secret hardening flags that match a secret prefix/marker but must be KEPT
-# so bypass mode does not silently undo an operator's opt-out. AWS_EC2_METADATA_
-# DISABLED tells the AWS SDK/CLI not to pull instance-role creds from IMDS;
-# dropping it would re-open that path for a bypassed tool.
+# so bypass mode does not undo an operator's opt-out (e.g.
+# AWS_EC2_METADATA_DISABLED blocks the AWS SDK from pulling IMDS creds).
_BYPASS_ENV_KEEP_NAMES = frozenset(
{
"AWS_EC2_METADATA_DISABLED",
"AWS_EC2_METADATA_V1_DISABLED",
}
)
-# Matches a URL that embeds userinfo before the host, covering both
-# "scheme://user:pass@host" and token-only "scheme://token@host" (and
-# percent-encoded variants). The userinfo must precede the first '/', so an '@'
-# in a path or query does not false-positive. Used to scrub credential-bearing
-# URL values regardless of the variable's name.
+# Matches a URL embedding userinfo before the host ("scheme://user:pass@host"
+# and token-only forms). The userinfo must precede the first '/', so an '@' in
+# a path/query does not false-positive.
_URL_USERINFO_RE = re.compile(r"://[^/\s@]+@")
-# Connection-string credential fields (ADO.NET / Azure storage / Service Bus):
-# "...;Password=...", "...;AccountKey=...", "...;SharedAccessKey=...". Catches
-# credential-bearing values whose names dodge the name classifier. "accesskey"
-# also covers Shared/Secret AccessKey via substring; the Name fields (e.g.
-# SharedAccessKeyName=) do not match since "=" must follow the keyword.
+# Connection-string credential fields (ADO.NET / Azure storage / Service Bus)
+# whose names dodge the name classifier. The Name fields (SharedAccessKeyName=)
+# don't match since "=" must follow the keyword.
_SECRET_VALUE_RE = re.compile(r"(?i)(?:password|pwd|accountkey|accesskey)\s*=\s*[^\s;]")
-# Names that hold no secret value but point SDKs at the operator's real
+# Names holding no secret value but pointing SDKs at the operator's real
# home/cache/config (cached tokens, cred files), defeating the HOME repoint.
-# Startup always sets HF_HOME (-> $HF_HOME/token), so this is the live leak.
# Dropped in bypass mode so tools fall back to the empty repointed HOME.
_BYPASS_ENV_CRED_LOCATION_NAMES = frozenset(
{
@@ -2679,12 +2692,12 @@ def _is_secret_env_value(value: str) -> bool:
def _build_bypass_env(workdir: str) -> dict[str, str]:
- """Env for bypass exec: full host env (unrestricted) minus credential vars,
- with HOME/TMPDIR repointed at the workdir so SDKs cannot read cached creds.
+ """Env for bypass exec: full host env minus credential vars, with HOME/TMPDIR
+ repointed at the workdir so SDKs cannot read cached creds.
- Note: stripping the child env is necessary but not sufficient on its own -
- a same-UID child can still read the parent's environment via procfs, so
- callers also harden the parent (see _harden_parent_against_proc_env_leak).
+ Stripping the child env is necessary but not sufficient (a same-UID child can
+ read the parent's env via procfs), so callers also harden the parent (see
+ _harden_parent_against_proc_env_leak).
"""
env = {
k: v
@@ -2699,6 +2712,12 @@ def _build_bypass_env(workdir: str) -> dict[str, str]:
# the bypassed tool writes under the per-session sandbox dir on every OS.
env["TEMP"] = workdir
env["TMP"] = workdir
+ # sitecustomize path shim (see _build_safe_env). Bypass inherits the
+ # operator's PYTHONPATH, so prepend rather than replace.
+ inherited_pythonpath = env.get("PYTHONPATH", "")
+ env["PYTHONPATH"] = os.pathsep.join(
+ part for part in (_SANDBOX_SITE_DIR, inherited_pythonpath) if part
+ )
# Windows SDKs read creds under the profile dirs, not $HOME; repoint set
# ones to the workdir (HOMEDRIVE/HOMEPATH are dropped above).
for var in _BYPASS_ENV_WINDOWS_PROFILE_VARS:
@@ -2789,24 +2808,14 @@ def _harden_parent_against_proc_env_leak() -> bool:
"""Make the Studio process's /proc/<pid>/environ unreadable to its children.
Stripping the child env is not enough on Linux: a bypassed same-UID child
- runs unsandboxed and can read /proc/<getppid()>/environ to recover the
- tool-executing process's *unfiltered* secrets (HF_TOKEN, cloud keys, ...).
- Clearing the dumpable flag (PR_SET_DUMPABLE=0) reparents this process's
- /proc entries to root, so a same-UID child can no longer read its environ.
-
- Returns True when the process is hardened or hardening is unnecessary (no
- /proc leak off Linux), and False when it is needed but could not be applied
- (e.g. prctl denied by a seccomp policy). Callers must fail closed - refuse
- the unsandboxed exec - when this returns False, rather than running with the
- parent environ still readable.
-
- Scope: this closes the direct parent read (the demonstrated leak). It is a
- mitigation, not a full boundary - a bypassed tool is unsandboxed by design,
- so it can still walk /proc to a same-UID *ancestor* (e.g. the launching
- shell) or read on-disk credentials by absolute path. Complete isolation
- needs a separate uid / PID+mount namespace, which is out of scope here; the
- UI already warns the mode is dangerous. Applied lazily on first bypass exec
- so non-bypass operation is unchanged.
+ can read /proc/<getppid()>/environ to recover the parent's unfiltered
+ secrets. Clearing PR_SET_DUMPABLE reparents this process's /proc entries to
+ root, closing that read.
+
+ Returns True when hardened or unnecessary (off Linux), False when needed but
+ unappliable (e.g. prctl denied by seccomp); callers must then fail closed.
+ This is a mitigation, not a full boundary - a bypassed tool can still walk
+ /proc to an ancestor or read creds by path. Applied lazily on first bypass.
"""
global _parent_proc_hardened
if _parent_proc_hardened:
@@ -2933,11 +2942,20 @@ WEB_SEARCH_TOOL = {
},
}
+# Appended to the python/terminal descriptions: models habitually write to
+# /mnt/data (a ChatGPT code-interpreter path), which does not exist here.
+_SANDBOX_PATHS_NOTE = (
+ " Read and write files using relative paths in the current working "
+ "directory, which persists for this conversation; absolute paths like "
+ "/mnt/data or /tmp/outputs do not exist."
+)
+
PYTHON_TOOL = {
"type": "function",
"function": {
"name": "python",
- "description": "Execute Python code in a sandbox and return stdout/stderr.",
+ "description": "Execute Python code in a sandbox and return stdout/stderr."
+ + _SANDBOX_PATHS_NOTE,
"parameters": {
"type": "object",
"properties": {
@@ -2955,7 +2973,7 @@ TERMINAL_TOOL = {
"type": "function",
"function": {
"name": "terminal",
- "description": "Execute a terminal command and return stdout/stderr.",
+ "description": "Execute a terminal command and return stdout/stderr." + _SANDBOX_PATHS_NOTE,
"parameters": {
"type": "object",
"properties": {
@@ -3034,9 +3052,8 @@ ALL_TOOLS = [
]
-# OpenAI's function.name regex ^[a-zA-Z0-9_-]{1,64}$, enforced before streaming.
-# MCP tool names with '.', '/', spaces, etc. would 400 the whole request, so we
-# validate up front and skip with a warning.
+# OpenAI's function.name regex; MCP names that violate it would 400 the whole
+# request, so validate up front and skip with a warning.
_OPENAI_FN_NAME_RE = re.compile(r"^[a-zA-Z0-9_-]{1,64}$")
@@ -3082,8 +3099,7 @@ def _mcp_specs_for_server(server: dict, mcp_tools: list[dict]) -> list[dict]:
async def get_enabled_mcp_tools() -> list[dict]:
servers = [s for s in mcp_servers_db.list_servers() if s.get("is_enabled")]
- # Never spawn stdio servers when stdio is disabled on this host (e.g. a DB
- # carried from a desktop install onto a Colab/network deployment).
+ # Never spawn stdio servers when stdio is disabled on this host.
if not stdio_mcp_enabled():
servers = [s for s in servers if not is_stdio(s["url"])]
if not servers:
@@ -3108,15 +3124,11 @@ async def get_enabled_mcp_tools() -> list[dict]:
),
return_exceptions = True,
)
- # An edit/delete can land while we await a probe (up to 305 s for
- # OAuth); its cache eviction is a no-op against an entry we haven't
- # written yet. Re-read and drop a result whose server changed or
- # was removed mid-probe, else a stale tool list caches indefinitely.
+ # An edit/delete can land while we await a probe; re-read and drop a
+ # result whose server changed or was removed mid-probe, else a stale
+ # tool list (or cool-off on a just-fixed server) persists.
current = {s["id"]: s for s in mcp_servers_db.list_servers()}
for server, payload in zip(uncached, results):
- # Guard the failure branch too: a stale failure must not park a
- # cool-off on the fresh config, or the server the user just fixed
- # is skipped for the whole window.
fresh = current.get(server["id"])
if fresh is None or any(
fresh.get(k) != server.get(k) for k in TOOL_CACHE_INVALIDATING_FIELDS
@@ -3175,6 +3187,7 @@ def execute_tool(
thread_id: str | None = None,
rag_scope: dict | None = None,
disable_sandbox: bool = False,
+ output_callback = None,
) -> str:
"""Execute a tool by name with the given arguments; returns a string.
@@ -3187,6 +3200,10 @@ def execute_tool(
``disable_sandbox``: Bypass Permissions; run python/terminal without the
safety checks, blocklist, or resource caps (secrets still stripped). Only
affects local code tools; web_search / MCP are unchanged.
+ ``output_callback``: optional ``callable(str)`` invoked with incremental
+ stdout/stderr chunks while python/terminal executions run (UI live
+ output). Purely observational: the returned result string is identical
+ with or without it. Tools without incremental output ignore it.
"""
logger.info(f"execute_tool: name={name}, session_id={session_id}, timeout={timeout}")
effective_timeout = _EXEC_TIMEOUT if timeout is _TIMEOUT_UNSET else timeout
@@ -3247,6 +3264,7 @@ def execute_tool(
arguments.get("query", ""),
url = arguments.get("url"),
timeout = effective_timeout,
+ cancel_event = cancel_event,
)
if name == "python":
return _python_exec(
@@ -3255,6 +3273,7 @@ def execute_tool(
effective_timeout,
session_id,
disable_sandbox = disable_sandbox,
+ output_callback = output_callback,
)
if name == "terminal":
return _bash_exec(
@@ -3263,6 +3282,7 @@ def execute_tool(
effective_timeout,
session_id,
disable_sandbox = disable_sandbox,
+ output_callback = output_callback,
)
return f"Unknown tool: {name}"
@@ -3468,11 +3488,10 @@ def build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> di
sidebar_k = _opt_int(rag_scope.get("default_top_k"))
top_k = min(sidebar_k, lean_k) if sidebar_k is not None else lean_k
- # Whole-document mode: a thread-attached file under budget is injected in full so
- # the model reads everything. A KB selection is exclusive, so whole-doc never
- # preempts it; in a project chat the project sources are still retrieved top-K and
- # appended under one citation numbering. Oversized files (or no thread doc) fall
- # through to the combined top-K retrieval below.
+ # Whole-document mode: a thread-attached file under budget is injected in
+ # full. A KB selection is exclusive so whole-doc never preempts it; project
+ # sources are still retrieved top-K and appended under one citation
+ # numbering. Oversized/absent thread docs fall through to top-K below.
if whole_doc_requested:
try:
budget = _whole_doc_budget(rag_scope, conversation)
@@ -3577,9 +3596,8 @@ def build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> di
_MAX_PAGE_CHARS = 16000 # cap fetched page text (after HTML-to-MD conversion)
-# Raw download cap > _MAX_PAGE_CHARS because SSR pages embed large <head>
-# sections stripped during conversion; 512 KB reaches article content even
-# where <head> alone is ~200 KB.
+# Raw download cap > _MAX_PAGE_CHARS since SSR pages embed large <head> sections
+# stripped during conversion; 512 KB still reaches article content.
_MAX_FETCH_BYTES = 512 * 1024
_USER_AGENTS = (
@@ -3662,10 +3680,8 @@ def _validate_and_resolve_host(hostname: str, port: int) -> tuple[bool, str, str
for *_, sockaddr in infos:
ip = ipaddress.ip_address(sockaddr[0])
- # `not ip.is_global` is the source of truth: it rejects every category
- # below PLUS shared/CGNAT (100.64.0.0/10) and benchmarking/doc ranges
- # Python marks is_private=False and is_global=False. The explicit
- # predicates only give human-readable categories in the error message.
+ # `not ip.is_global` is the source of truth (also rejects CGNAT and
+ # benchmarking/doc ranges); the explicit predicates only label the error.
if (
not ip.is_global
or ip.is_private
@@ -3682,28 +3698,208 @@ def _validate_and_resolve_host(hostname: str, port: int) -> tuple[bool, str, str
return True, "", first_ip
-def _fetch_page_text(
+# First path segments on github.com that are site pages, not repo owners.
+_GITHUB_NON_OWNER_SEGMENTS = frozenset(
+ {
+ "about",
+ "apps",
+ "codespaces",
+ "collections",
+ "contact",
+ "customer-stories",
+ "dashboard",
+ "discussions",
+ "enterprise",
+ "explore",
+ "features",
+ "issues",
+ "join",
+ "login",
+ "marketplace",
+ "new",
+ "notifications",
+ "organizations",
+ "orgs",
+ "pricing",
+ "pulls",
+ "search",
+ "security",
+ "settings",
+ "signup",
+ "site",
+ "sponsors",
+ "team",
+ "topics",
+ "trending",
+ }
+)
+_GITHUB_NAME_RE = re.compile(r"\A[A-Za-z0-9_.\-]{1,100}\Z")
+
+
+def _github_repo_readme_api_url(url: str) -> str | None:
+ """README API URL for a ``github.com/{owner}/{repo}`` page, else None.
+
+ A repo root page rendered as HTML is mostly UI chrome (nav, file table,
+ stats); the ``/readme`` API returns the raw README markdown unauthenticated,
+ which is what the model actually wants to read.
+ """
+ from urllib.parse import urlparse
+
+ parsed = urlparse(url)
+ host = (parsed.hostname or "").lower()
+ if host not in ("github.com", "www.github.com"):
+ return None
+ parts = [p for p in parsed.path.split("/") if p]
+ if len(parts) != 2:
+ return None
+ owner, repo = parts
+ if owner.lower() in _GITHUB_NON_OWNER_SEGMENTS:
+ return None
+ if repo.endswith(".git"):
+ repo = repo[: -len(".git")]
+ if not (_GITHUB_NAME_RE.match(owner) and _GITHUB_NAME_RE.match(repo)):
+ return None
+ return f"https://api.github.com/repos/{owner}/{repo}/readme"
+
+
+# A single fetch can chain several steps (README API attempt, HTML fallback, up
+# to five redirect hops, each reading a body). A per-operation socket timeout
+# bounds one stalled step but not their sum, and nothing aborts on client
+# disconnect, so one overall wall-clock deadline (plus a cooperative
+# cancel_event) bounds the whole fetch instead.
+def _fetch_budget_exceeded(deadline, cancel_event):
+ """User-facing error string when the fetch must stop early, else None."""
+ if cancel_event is not None and cancel_event.is_set():
+ return "Failed to fetch URL: cancelled."
+ if deadline is not None and time.monotonic() >= deadline:
+ return "Failed to fetch URL: timed out."
+ return None
+
+
+def _fetch_hop_timeout(timeout, deadline):
+ """Per-operation socket timeout: the lesser of the caller's per-op timeout
+ and the time left on the deadline, so one slow hop cannot overrun the whole
+ budget. Callers check ``_fetch_budget_exceeded`` first, so remaining time is
+ positive here; the tiny floor only guards a race."""
+ if deadline is None:
+ return timeout
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ remaining = 0.001
+ return remaining if timeout is None else min(timeout, remaining)
+
+
+def _resolve_with_budget(hostname, port, deadline, cancel_event):
+ """``_validate_and_resolve_host`` bounded by the overall fetch budget.
+
+ ``getaddrinfo`` is blocking with no deadline of its own, so a slow resolver
+ (or a request cancelled before dispatch) could run past the budget. Resolve
+ on a daemon thread and poll the budget so the fetch aborts on time; the
+ abandoned lookup is discarded. With no deadline and no cancel_event this is a
+ plain synchronous call, so opt-out callers keep the old behavior and cost.
+ """
+ budget_error = _fetch_budget_exceeded(deadline, cancel_event)
+ if budget_error is not None:
+ return False, budget_error, ""
+ if deadline is None and cancel_event is None:
+ return _validate_and_resolve_host(hostname, port)
+
+ result: "queue.Queue" = queue.Queue(maxsize = 1)
+
+ def _resolve():
+ try:
+ result.put(_validate_and_resolve_host(hostname, port))
+ except Exception as exc: # defensive: never let the worker die silently
+ result.put((False, f"Failed to resolve host: {exc}", ""))
+
+ threading.Thread(target = _resolve, name = "web-fetch-dns", daemon = True).start()
+ while True:
+ budget_error = _fetch_budget_exceeded(deadline, cancel_event)
+ if budget_error is not None:
+ return False, budget_error, ""
+ try:
+ return result.get(timeout = 0.05)
+ except queue.Empty:
+ continue
+
+
+def _read_capped_body(resp, max_bytes, timeout, deadline, cancel_event):
+ """Read up to ``max_bytes``, enforcing the overall budget between chunks.
+
+ A single ``resp.read(max_bytes)`` can block for the whole transfer if the
+ server dribbles bytes just inside each socket-inactivity timeout, so the body
+ is read in chunks with the budget re-checked (and the socket timeout
+ re-tightened toward the deadline) each round. The joined bytes are identical
+ to one capped read. Returns ``(error_or_None, body_bytes)``.
+ """
+ # Best-effort handle on the underlying socket so its timeout tightens as the
+ # deadline nears; absent on test doubles, where the between-chunk budget
+ # check still bounds the read.
+ sock = getattr(getattr(getattr(resp, "fp", None), "raw", None), "_sock", None)
+ chunks = []
+ remaining = max_bytes
+ while remaining > 0:
+ budget_error = _fetch_budget_exceeded(deadline, cancel_event)
+ if budget_error is not None:
+ try:
+ resp.close()
+ except Exception:
+ pass
+ return budget_error, b""
+ if sock is not None:
+ try:
+ sock.settimeout(_fetch_hop_timeout(timeout, deadline))
+ except Exception:
+ pass
+ chunk = resp.read(min(65536, remaining))
+ if not chunk:
+ break
+ chunks.append(chunk)
+ remaining -= len(chunk)
+ budget_error = _fetch_budget_exceeded(deadline, cancel_event)
+ if budget_error is not None:
+ try:
+ resp.close()
+ except Exception:
+ pass
+ return budget_error, b""
+ return None, b"".join(chunks)
+
+
+def _fetch_url_raw(
url: str,
- max_chars: int = _MAX_PAGE_CHARS,
timeout: int = 30,
-) -> str:
- """Fetch a URL and return plain text content (HTML tags stripped).
+ extra_headers: dict | None = None,
+ deadline: float | None = None,
+ cancel_event = None,
+) -> tuple[str | None, str, str]:
+ """Fetch a URL with SSRF protection; return ``(error, body_text, content_type)``.
- Blocks private/loopback/link-local targets (SSRF protection) and caps
- the download size to avoid unbounded memory usage.
+ ``error`` is a user-facing message string when the fetch failed (the
+ existing "Blocked:" / "Failed to fetch URL:" wording), else ``None``.
+ Blocks private/loopback/link-local targets and caps the download size.
+
+ ``deadline`` is an optional ``time.monotonic`` cutoff for the whole fetch
+ (redirect hops and body read included) and ``cancel_event`` aborts it when
+ the caller goes away; both default off so callers keep the old behavior.
"""
from urllib.parse import urlparse
parsed = urlparse(url)
if parsed.scheme not in ("http", "https"):
- return f"Blocked: only http/https URLs are allowed (got {parsed.scheme!r})."
+ return f"Blocked: only http/https URLs are allowed (got {parsed.scheme!r}).", "", ""
if not parsed.hostname:
- return "Blocked: URL is missing a hostname."
+ return "Blocked: URL is missing a hostname.", "", ""
port = parsed.port or (443 if parsed.scheme == "https" else 80)
- ok, reason, pinned_ip = _validate_and_resolve_host(parsed.hostname, port)
+ ok, reason, pinned_ip = _resolve_with_budget(
+ parsed.hostname,
+ port,
+ deadline,
+ cancel_event,
+ )
if not ok:
- return reason
+ return reason, "", ""
try:
from urllib.error import HTTPError as _HTTPError
@@ -3715,6 +3911,9 @@ def _fetch_page_text(
ua = random.choice(_USER_AGENTS)
for _hop in range(5):
+ budget_error = _fetch_budget_exceeded(deadline, cancel_event)
+ if budget_error is not None:
+ return budget_error, "", ""
# Pin to the validated IP (prevents DNS rebinding): rewrite URL to
# the IP, set the Host header.
cp = urlparse(current_url)
@@ -3728,64 +3927,214 @@ def _fetch_page_text(
_SNIHTTPSHandler(current_host),
)
- req = urllib.request.Request(
- pinned_url,
- headers = {
- "User-Agent": ua,
- "Host": current_host,
- },
- )
+ headers = {
+ "User-Agent": ua,
+ "Host": current_host,
+ }
+ if extra_headers:
+ headers.update(extra_headers)
+ req = urllib.request.Request(pinned_url, headers = headers)
try:
- resp = opener.open(req, timeout = timeout)
+ # Cap the socket timeout at the time left on the overall deadline
+ # so a single slow hop cannot outlast the whole fetch budget.
+ resp = opener.open(req, timeout = _fetch_hop_timeout(timeout, deadline))
except _HTTPError as e:
if e.code not in (301, 302, 303, 307, 308):
- return f"Failed to fetch URL: HTTP {e.code} {getattr(e, 'reason', '')}"
+ return f"Failed to fetch URL: HTTP {e.code} {getattr(e, 'reason', '')}", "", ""
location = e.headers.get("Location")
if not location:
- return "Failed to fetch URL: redirect missing Location header."
+ return "Failed to fetch URL: redirect missing Location header.", "", ""
current_url = urljoin(current_url, location)
rp = urlparse(current_url)
if rp.scheme not in ("http", "https") or not rp.hostname:
- return "Blocked: redirect target is not a valid http/https URL."
+ return "Blocked: redirect target is not a valid http/https URL.", "", ""
rp_port = rp.port or (443 if rp.scheme == "https" else 80)
- ok2, reason2, pinned_ip = _validate_and_resolve_host(
+ ok2, reason2, pinned_ip = _resolve_with_budget(
rp.hostname,
rp_port,
+ deadline,
+ cancel_event,
)
if not ok2:
- return reason2
+ return reason2, "", ""
current_host = rp.hostname
continue
- # Success: read capped body.
- raw_bytes = resp.read(max_bytes)
+ # Success: read the capped body enforcing the budget between chunks
+ # (see _read_capped_body), so a slow-drip server can't stretch a
+ # single resp.read past the deadline.
+ body_error, raw_bytes = _read_capped_body(
+ resp,
+ max_bytes,
+ timeout,
+ deadline,
+ cancel_event,
+ )
+ if body_error is not None:
+ return body_error, "", ""
break
else:
- return "Failed to fetch URL: too many redirects."
+ return "Failed to fetch URL: too many redirects.", "", ""
charset = resp.headers.get_content_charset() or "utf-8"
- raw_html = raw_bytes.decode(charset, errors = "replace")
+ # get_content_type() defaults to "text/plain" when the header is
+ # absent (RFC 2045); report "" instead so callers can tell a missing
+ # header apart from a server that really declared text/plain.
+ if resp.headers.get("Content-Type") is None:
+ content_type = ""
+ else:
+ content_type = (resp.headers.get_content_type() or "").lower()
+ return None, raw_bytes.decode(charset, errors = "replace"), content_type
except _HTTPError as e:
- return f"Failed to fetch URL: HTTP {e.code} {getattr(e, 'reason', '')}"
+ return f"Failed to fetch URL: HTTP {e.code} {getattr(e, 'reason', '')}", "", ""
except Exception as e:
- return f"Failed to fetch URL: {e}"
+ return f"Failed to fetch URL: {e}", "", ""
+
+
+# Tags that, at the very START of a body, mark it as HTML. Excludes ambiguous
+# tags (<div>/<p>/<span>/<a>/<img>/<h1>..<h6>/<table>) that legitimately open
+# centered-logo or badge-layout Markdown READMEs and must stay Markdown.
+_HTML_LEADING_TAGS = (
+ "html",
+ "head",
+ "body",
+ "title",
+ "meta",
+ "link",
+ "script",
+ "style",
+ "article",
+ "section",
+ "main",
+ "header",
+ "footer",
+ "nav",
+ "aside",
+ "figure",
+ "form",
+ "ul",
+ "ol",
+ "dl",
+ "pre",
+ "blockquote",
+)
+_HTML_LEADING_RE = re.compile(r"<(?:!doctype\s+html|/?(?:" + "|".join(_HTML_LEADING_TAGS) + r")\b)")
- # Convert HTML to Markdown with the builtin converter (no external deps).
- from ._html_to_md import html_to_markdown
- text = html_to_markdown(raw_html)
+def _looks_like_html(body: str) -> bool:
+ """True only when the document ITSELF opens with HTML.
+ Matches an HTML doctype or a leading document/structure tag after optional
+ whitespace, not a mere substring, so a Markdown README with a fenced HTML
+ example or tags further down stays Markdown. Also detects bare fragments
+ (``<body>``/``<article>``/...) with no doctype, so a page with a
+ missing/wrong Content-Type is still converted.
+ """
+ probe = body.lstrip()[:256].lower()
+ return bool(_HTML_LEADING_RE.match(probe))
+
+
+# Stricter than _HTML_LEADING_RE: only a real document opener (doctype or leading
+# <html>/<head>/<body>), never a block tag a Markdown file can open with. Used on
+# the raw GitHub README body so a Markdown README starting with an HTML block is
+# not run through html_to_markdown, which would collapse its headings, lists and
+# fenced code onto one line.
+_HTML_DOCUMENT_RE = re.compile(r"<(?:!doctype\s+html\b|/?(?:html|head|body)\b)")
+
+
+def _looks_like_html_document(body: str) -> bool:
+ """True only when the body opens as a full HTML document (e.g. a .html README)."""
+ probe = body.lstrip()[:256].lower()
+ return bool(_HTML_DOCUMENT_RE.match(probe))
+
+
+def _truncate_page_text(text: str, max_chars: int) -> str:
if not text:
return "(page returned no readable text)"
if len(text) > max_chars:
- text = text[:max_chars] + f"\n\n... (truncated, {len(text)} chars total)"
+ return text[:max_chars] + f"\n\n... (truncated, {len(text)} chars total)"
return text
+def _fetch_page_text(
+ url: str,
+ max_chars: int = _MAX_PAGE_CHARS,
+ timeout: int = 30,
+ cancel_event = None,
+) -> str:
+ """Fetch a URL and return readable text content.
+
+ HTML responses are converted to Markdown with a main-content heuristic
+ (``<article>``/``<main>`` scoping, hidden-element and boilerplate
+ stripping); non-HTML text responses are returned as-is. GitHub repo root
+ pages are rewritten to the README API so the model reads the README
+ instead of the repo page's UI chrome. Blocks private/loopback/link-local
+ targets (SSRF protection) and caps the download size.
+ """
+ # One wall-clock budget for the whole fetch. The README API attempt and its
+ # HTML fallback both draw from it, so a slow/failed API call cannot hand the
+ # fallback a fresh full timeout and double the worst case.
+ deadline = None if timeout is None else time.monotonic() + timeout
+ readme_api_url = _github_repo_readme_api_url(url)
+ if readme_api_url:
+ err, body, _ctype = _fetch_url_raw(
+ readme_api_url,
+ timeout = timeout,
+ extra_headers = {
+ "Accept": "application/vnd.github.raw+json",
+ "X-GitHub-Api-Version": "2022-11-28",
+ },
+ deadline = deadline,
+ cancel_event = cancel_event,
+ )
+ # The README API is unauthenticated and rate-limited; on any failure fall
+ # back to the HTML page fetch. A 200 body is authoritative even when it is
+ # HTML (a .html README): convert it rather than falling back to the repo
+ # page's UI chrome, keeping the raw body if extraction yields nothing.
+ if err is None and body.strip():
+ readme_body = body
+ # The raw file is almost always Markdown. Only a real HTML document (a
+ # .html README) is converted; a Markdown README that merely opens with
+ # a block tag is kept as-is (see _HTML_DOCUMENT_RE).
+ if _looks_like_html_document(body):
+ from ._html_to_md import html_to_markdown
+ converted = html_to_markdown(body, main_content = True)
+ readme_body = converted if converted.strip() else body
+ if readme_body.strip():
+ return _truncate_page_text(
+ f"README of {url} (fetched via the GitHub README API):\n\n" + readme_body,
+ max_chars,
+ )
+
+ err, body, content_type = _fetch_url_raw(
+ url,
+ timeout = timeout,
+ deadline = deadline,
+ cancel_event = cancel_event,
+ )
+ if err is not None:
+ return err
+
+ # Trust a declared HTML type, and otherwise sniff the body: servers with a
+ # missing or wrong Content-Type (e.g. text/plain on an HTML page) still get
+ # converted, matching the pre-extraction behavior of always converting.
+ is_html = "html" in content_type or _looks_like_html(body)
+ if not is_html:
+ # Plain text / markdown / JSON (e.g. raw.githubusercontent.com):
+ # converting through the HTML renderer would collapse its whitespace.
+ return _truncate_page_text(body.strip(), max_chars)
+
+ # Convert HTML to Markdown with the builtin converter (no external deps).
+ from ._html_to_md import html_to_markdown
+
+ return _truncate_page_text(html_to_markdown(body, main_content = True), max_chars)
+
+
def _web_search(
query: str,
max_results: int = 5,
timeout: int = _EXEC_TIMEOUT,
url: str | None = None,
+ cancel_event = None,
) -> str:
"""Search the web using DuckDuckGo and return formatted results.
@@ -3794,14 +4143,25 @@ def _web_search(
# Direct URL fetch mode.
if url and url.strip():
fetch_timeout = 60 if timeout is None else min(timeout, 60)
- return _fetch_page_text(url.strip(), timeout = fetch_timeout)
+ return _fetch_page_text(
+ url.strip(),
+ timeout = fetch_timeout,
+ cancel_event = cancel_event,
+ )
if not query or not query.strip():
return "No query provided."
+ # A disconnect sets cancel_event; DDGS.text() is blocking and cannot be
+ # interrupted mid-flight, so gate on either side: skip an already-cancelled
+ # request, and discard results that land after the client has gone.
+ if cancel_event is not None and cancel_event.is_set():
+ return "Search cancelled."
try:
from ddgs import DDGS
results = DDGS(timeout = timeout).text(query, max_results = max_results)
+ if cancel_event is not None and cancel_event.is_set():
+ return "Search cancelled."
if not results:
return "No results found."
parts = []
@@ -4799,19 +5159,37 @@ def _check_code_safety(code: str) -> str | None:
return None
+def _capture_process_group(proc):
+ """Return the setsid process-group id, or ``None`` when unavailable.
+
+ Captured right after ``Popen`` so a later ``poll()`` / ``wait()`` that reaps
+ the leader cannot make ``os.getpgid(proc.pid)`` fail first. POSIX-only:
+ Windows has no process groups (and no ``os.getpgid``), so return ``None``
+ there and let the single-pid ``proc.kill()`` fallback handle cleanup.
+ """
+ if os.name != "posix" or not hasattr(os, "getpgid"):
+ return None
+ try:
+ return os.getpgid(proc.pid)
+ except (AttributeError, ProcessLookupError, PermissionError, OSError):
+ return None
+
+
def _kill_process_tree(proc) -> None:
"""SIGKILL the setsid process group; fall back to single-pid kill."""
if proc.poll() is not None:
return
- try:
- pgid = os.getpgid(proc.pid)
- except (ProcessLookupError, PermissionError):
- pgid = None
- if pgid is not None:
+ pgid = None
+ if hasattr(os, "getpgid"):
+ try:
+ pgid = os.getpgid(proc.pid)
+ except (ProcessLookupError, PermissionError, OSError):
+ pgid = None
+ if pgid is not None and hasattr(os, "killpg"):
try:
os.killpg(pgid, signal.SIGKILL)
return
- except (ProcessLookupError, PermissionError):
+ except (ProcessLookupError, PermissionError, OSError):
pass
try:
proc.kill()
@@ -4819,36 +5197,250 @@ def _kill_process_tree(proc) -> None:
pass
+def _killpg_captured(pgid) -> None:
+ """SIGKILL a process group captured before its leader was waited on.
+
+ Once ``proc`` exits, ``os.getpgid(proc.pid)`` fails and ``_kill_process_tree``
+ short-circuits, so a stdout-holding grandchild that outlived the parent could
+ not otherwise be signaled. The pre-captured setsid group id still targets the
+ whole tree. No-op with no ``os.killpg`` (Windows) or nothing captured.
+ """
+ if pgid is None or not hasattr(os, "killpg"):
+ return
+ try:
+ os.killpg(pgid, signal.SIGKILL)
+ except (ProcessLookupError, PermissionError, OSError):
+ pass
+
+
def _cancel_watcher(
proc,
cancel_event,
poll_interval = 0.2,
+ pgid = None,
):
- """Daemon thread that kills a process when cancel_event is set."""
+ """Daemon thread that kills a process when cancel_event is set.
+
+ ``pgid`` is the group id captured right after spawn; killing it directly
+ reaps a stdout-holding grandchild even when the watcher's own ``poll()``
+ already reaped the leader (which makes ``_kill_process_tree`` short-circuit).
+ """
while proc.poll() is None:
if cancel_event is not None and cancel_event.is_set():
+ _killpg_captured(pgid)
_kill_process_tree(proc)
return
cancel_event.wait(poll_interval) if cancel_event else None
def _truncate(text: str, limit: int = _MAX_OUTPUT_CHARS) -> str:
+ # Mode-neutral notice: this result serves both the streaming UI and
+ # non-streaming callers and must stay byte-identical with and without an
+ # output_callback (a regression-tested invariant), so it can't claim the
+ # user saw the full output.
if len(text) > limit:
- return text[:limit] + f"\n\n... (truncated, {len(text)} chars total)"
+ return text[:limit] + (
+ f"\n\n... (truncated to {limit} chars for the model; {len(text)} chars "
+ "total. The full output is not retained here; any files the code wrote "
+ "persist in the working directory.)"
+ )
return text
+# ChatGPT code-interpreter path conventions models write out of habit; none
+# exist in the Studio sandbox, so a failure on one earns the retry hint.
+_MISSING_PATH_PREFIXES = (
+ "/mnt/data",
+ "/mnt/outputs",
+ "/home/sandbox",
+ "/workspace",
+ "/tmp/outputs",
+)
+
+# Matches the quoted path in a Python OSError str and the bare path in a bash
+# "No such file or directory" error; applied only to the error line.
+_QUOTED_ABS_PATH_RE = re.compile(r"""['"](/[^'"\n]+)['"]""")
+_BASH_ABS_PATH_RE = re.compile(r"(/[^\s:'\"]+):\s*No such file or directory")
+
+# The sandbox CWD is a per-thread dir under ~/studio_sandbox; an absolute path
+# under it is a genuine local miss, not a hallucinated out-of-sandbox write.
+_SANDBOX_ROOT = os.path.join(os.path.expanduser("~"), "studio_sandbox")
+
+
+def _missing_error_lines(output: str) -> list[str]:
+ """The lines that actually name a missing file (a FileNotFoundError message
+ or a bash "No such file or directory"). Traceback frame lines such as
+ ``File "/workspace/proj/script.py"`` are excluded, so an unrelated absolute
+ path mentioned elsewhere in the output is never treated as the failing one."""
+ return [
+ line
+ for line in output.splitlines()
+ if "No such file or directory" in line or "FileNotFoundError" in line
+ ]
+
+
+def _extract_missing_abs_path(output: str) -> str | None:
+ """Pull the absolute path a FileNotFoundError / bash error named, if any."""
+ for line in reversed(_missing_error_lines(output)):
+ m = _QUOTED_ABS_PATH_RE.search(line)
+ if m:
+ return m.group(1)
+ m = _BASH_ABS_PATH_RE.search(line)
+ if m:
+ return m.group(1)
+ return None
+
+
+def _is_outside_workdir(abs_path: str, workdir: str | None = None) -> bool:
+ """True when ``abs_path`` is not the working directory or under it.
+
+ ``workdir`` is the executor's actual working directory (defaults to the
+ sandbox root). Project-backed sessions run under a root OUTSIDE
+ ``~/studio_sandbox`` (see ``_get_workdir``), so a legitimate miss inside a
+ project must be judged against the real workdir, not a static sandbox root,
+ or it is wrongly classed as an external habit path.
+ """
+ try:
+ root = os.path.realpath(workdir or _SANDBOX_ROOT)
+ rp = os.path.realpath(abs_path)
+ except (OSError, ValueError):
+ return True
+ return rp != root and not rp.startswith(root + os.sep)
+
+
+def _missing_path_hint(output: str, workdir: str | None = None) -> str:
+ """Model-visible healing when an execution fails on an absolute path missing
+ in the sandbox (a code-interpreter habit path, or one invented from the CWD).
+ Detected on the full pre-truncation output; the hint echoes the failing path
+ so the model retries with the right relative name."""
+ error_lines = _missing_error_lines(output)
+ if not error_lines:
+ return ""
+ abs_path = _extract_missing_abs_path(output)
+ # A convention prefix is an out-of-sandbox signal only when the exact failing
+ # path could not be isolated; scoped to the failing-path error line(s) so a
+ # prefix mentioned elsewhere doesn't trigger a misleading hint.
+ convention = any(prefix in line for line in error_lines for prefix in _MISSING_PATH_PREFIXES)
+ if abs_path is not None:
+ # Judge the isolated path against the real workdir even when it matches a
+ # convention prefix, so a genuine miss inside a project rooted under such
+ # a prefix (e.g. /workspace/proj) is not steered out of its subdirectory.
+ if not _is_outside_workdir(abs_path, workdir):
+ return ""
+ elif not convention:
+ # Nothing marks this as an out-of-sandbox miss; stay silent.
+ return ""
+ if abs_path:
+ example = f"'{os.path.basename(abs_path)}', not '{abs_path}'"
+ else:
+ example = "'output.html', not '/mnt/data/output.html'"
+ return (
+ "\nHint: that absolute path does not exist in this sandbox. The current "
+ "working directory is writable and persists for this conversation; retry "
+ f"with a relative path (for example {example})."
+ )
+
+
+def _drain_process_output(
+ proc,
+ timeout,
+ output_callback,
+ cancel_event = None,
+ *,
+ pgid = None,
+) -> tuple[str, bool]:
+ """``proc.communicate(timeout=...)`` equivalent that also streams each
+ stdout line to ``output_callback`` as it is produced.
+
+ Returns ``(output, timed_out)``. The joined output is identical to what
+ ``communicate`` would return: the same TextIOWrapper decodes the stream,
+ so encoding, error replacement, and newline translation all match. On
+ timeout the process tree is killed (mirroring the non-streaming path).
+ With ``timeout=None`` the drain waits for EOF like ``communicate`` would,
+ stopping early only when ``cancel_event`` is set.
+ """
+ chunks: list[str] = []
+
+ # Captured before waiting so a stdout-holding grandchild can still be killed
+ # after the leader is reaped (getpgid then fails). Callers pass it in from
+ # right after Popen; fall back to capturing here for direct callers.
+ if pgid is None:
+ pgid = _capture_process_group(proc)
+
+ def _reader() -> None:
+ try:
+ for line in iter(proc.stdout.readline, ""):
+ chunks.append(line)
+ if output_callback is not None:
+ try:
+ output_callback(line)
+ except Exception: # noqa: BLE001 - observer must never kill the tool
+ logger.debug("tool output_callback raised", exc_info = True)
+ except (ValueError, OSError):
+ pass # pipe closed during kill
+
+ reader = threading.Thread(target = _reader, daemon = True)
+ reader.start()
+ started_at = time.monotonic()
+ timed_out = False
+ try:
+ proc.wait(timeout = timeout)
+ except subprocess.TimeoutExpired:
+ timed_out = True
+ _kill_process_tree(proc)
+ # Also kill the pre-captured group in case the leader was reaped in the
+ # window before _kill_process_tree sampled its pgid, reaping a
+ # stdout-holding grandchild (matches the non-streaming timeout path).
+ _killpg_captured(pgid)
+ try:
+ proc.wait(timeout = 5)
+ except subprocess.TimeoutExpired:
+ pass
+ # A grandchild that inherited stdout can hold the pipe open past the main
+ # process's exit.
+ if not timed_out:
+ if timeout is not None:
+ # Wait out the remaining budget like communicate() would, polling
+ # cancel_event in slices (the cancel watcher is gone once the leader
+ # exits) so a chatty grandchild doesn't keep draining after a Stop.
+ # The normal path still reaches EOF on its own with the same bytes.
+ deadline = started_at + timeout
+ while reader.is_alive():
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ timed_out = True
+ _killpg_captured(pgid)
+ break
+ if cancel_event is not None and cancel_event.is_set():
+ _killpg_captured(pgid)
+ break
+ reader.join(timeout = min(0.5, remaining))
+ else:
+ # Unlimited timeout: drain until the pipe closes (like
+ # communicate(timeout=None)), stopping early only on cancellation.
+ while reader.is_alive():
+ if cancel_event is not None and cancel_event.is_set():
+ _killpg_captured(pgid)
+ break
+ reader.join(timeout = 0.5)
+ reader.join(timeout = 5)
+ return "".join(chunks), timed_out
+
+
def _python_exec(
code: str,
cancel_event = None,
timeout: int = _EXEC_TIMEOUT,
session_id: str | None = None,
disable_sandbox: bool = False,
+ output_callback = None,
) -> str:
"""Execute Python code in a subprocess sandbox.
disable_sandbox (Bypass Permissions): skip the safety analysis and rlimit
pre-exec, and use the host env minus secrets.
+ output_callback: optional callable(str) streamed each stdout line as it is
+ produced; the returned result is unchanged.
"""
if not code or not code.strip():
return "No code provided."
@@ -4907,23 +5499,32 @@ def _python_exec(
else:
popen_kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW
- proc = subprocess.Popen([sys.executable, tmp_path], **popen_kwargs)
+ # -u forces unbuffered child stdout so a bare print() streams live
+ # instead of sitting in the pipe's block buffer until exit. Applied
+ # unconditionally to stay byte-identical with and without streaming;
+ # unlike PYTHONUNBUFFERED=1 it never pollutes the child's os.environ.
+ proc = subprocess.Popen([sys.executable, "-u", tmp_path], **popen_kwargs)
+
+ # Capture the group before any watcher can reap the leader (see
+ # _capture_process_group); None on Windows.
+ pgid = _capture_process_group(proc)
- # Spawn cancel watcher if we have a cancel event
if cancel_event is not None:
watcher = threading.Thread(
- target = _cancel_watcher, args = (proc, cancel_event), daemon = True
+ target = _cancel_watcher,
+ args = (proc, cancel_event, 0.2, pgid),
+ daemon = True,
)
watcher.start()
- try:
- output, _ = proc.communicate(timeout = timeout)
- except subprocess.TimeoutExpired:
- _kill_process_tree(proc)
- try:
- proc.communicate(timeout = 5)
- except subprocess.TimeoutExpired:
- pass
+ # Always drain via _drain_process_output (output_callback may be None):
+ # it kills the captured group on cancellation, reaping a grandchild that
+ # outlived the leader, and returns bytes identical to communicate() so
+ # the streaming vs non-streaming result stays byte-identical.
+ output, timed_out = _drain_process_output(
+ proc, timeout, output_callback, cancel_event, pgid = pgid
+ )
+ if timed_out:
return _truncate(f"Execution timed out after {timeout} seconds.")
if cancel_event is not None and cancel_event.is_set():
@@ -4932,7 +5533,13 @@ def _python_exec(
result = output or ""
if proc.returncode != 0:
result = f"Exit code {proc.returncode}:\n{result}"
+ # Detect the missing-path pattern on the full output (truncation could
+ # hide the trailing traceback); append the hint after truncation. External
+ # paths are judged against the real workdir (project sessions live outside
+ # the default sandbox root).
+ hint = _missing_path_hint(result, workdir)
result = _truncate(result) if result.strip() else "(no output)"
+ result += hint
# Detect new/overwritten images and append sentinel for the frontend
if session_id and os.path.isdir(workdir):
@@ -4971,11 +5578,14 @@ def _bash_exec(
timeout: int = _EXEC_TIMEOUT,
session_id: str | None = None,
disable_sandbox: bool = False,
+ output_callback = None,
) -> str:
"""Execute a bash command in a subprocess sandbox.
disable_sandbox (Bypass Permissions): skip the command blocklist and rlimit
pre-exec, and use the host env minus secrets.
+ output_callback: optional callable(str) streamed each stdout line as it is
+ produced; the returned result is unchanged.
"""
if not command or not command.strip():
return "No command provided."
@@ -5000,6 +5610,11 @@ def _bash_exec(
stdout = subprocess.PIPE,
stderr = subprocess.STDOUT,
text = True,
+ # Match _python_exec: decode utf-8 with "replace" so invalid output
+ # bytes never raise UnicodeDecodeError (which the streaming reader
+ # thread would swallow), keeping both paths byte-identical.
+ encoding = "utf-8",
+ errors = "replace",
cwd = workdir,
env = safe_env,
)
@@ -5010,20 +5625,25 @@ def _bash_exec(
proc = subprocess.Popen(_get_shell_cmd(command), **popen_kwargs)
+ # Capture the group before any watcher can poll/reap the leader (see
+ # _python_exec); None on Windows.
+ pgid = _capture_process_group(proc)
+
if cancel_event is not None:
watcher = threading.Thread(
- target = _cancel_watcher, args = (proc, cancel_event), daemon = True
+ target = _cancel_watcher,
+ args = (proc, cancel_event, 0.2, pgid),
+ daemon = True,
)
watcher.start()
- try:
- output, _ = proc.communicate(timeout = timeout)
- except subprocess.TimeoutExpired:
- _kill_process_tree(proc)
- try:
- proc.communicate(timeout = 5)
- except subprocess.TimeoutExpired:
- pass
+ # Always drain via _drain_process_output (see _python_exec): kills the
+ # captured group on cancellation and returns bytes identical to
+ # communicate(), keeping streaming vs non-streaming byte-identical.
+ output, timed_out = _drain_process_output(
+ proc, timeout, output_callback, cancel_event, pgid = pgid
+ )
+ if timed_out:
return _truncate(f"Execution timed out after {timeout} seconds.")
if cancel_event is not None and cancel_event.is_set():
@@ -5032,7 +5652,10 @@ def _bash_exec(
result = output or ""
if proc.returncode != 0:
result = f"Exit code {proc.returncode}:\n{result}"
- return _truncate(result) if result.strip() else "(no output)"
+ # Same missing-path healing as _python_exec.
+ hint = _missing_path_hint(result, workdir)
+ result = _truncate(result) if result.strip() else "(no output)"
+ return result + hint
except Exception as e:
return f"Execution error: {e}"
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 9bf57fa607c..0541a81ff20 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -1083,6 +1083,10 @@ _OPENAI_PASSTHROUGH_PREHEADER_STATUS_WINDOW_S = 0.1
_OPENAI_PASSTHROUGH_PENDING_RESPONSE_KEEPALIVE_S = 5.0
_OPENAI_PASSTHROUGH_SSE_KEEPALIVE = ": keep-alive\n\n"
_OPENAI_LLAMA_ADMISSION_POLL_S = 0.25
+# Idle window before a local tool-loop stream emits an SSE keepalive comment
+# (e.g. prompt prefill between tool iterations). A second layer atop the
+# tool_stream_exec heartbeats, keeping proxies (Cloudflare drops idle at ~100s).
+_LOCAL_TOOL_STREAM_STALL_KEEPALIVE_S = 15.0
def _openai_llama_admission_capacity(request: Optional[Request], llama_backend = None) -> int:
@@ -2298,6 +2302,36 @@ async def _stop_local_disconnect_cancel_watcher(watcher) -> None:
pass
+async def _drain_pending_next_task(task, cancel_event) -> None:
+ """Wait for a pending ``asyncio.to_thread(next, gen, ...)`` task to finish
+ before its generator is closed.
+
+ On disconnect a ``next(gen)`` call may still run in a worker thread;
+ cancelling the awaiting task does NOT stop it, and ``gen.close()`` mid-
+ ``next(gen)`` raises ``ValueError: generator already executing``, leaking the
+ generator's cleanup. So re-set the cancel flag (the generator polls it) and
+ shield the task until the worker returns. No-op when there is no pending task.
+ """
+ if task is None:
+ return
+ if cancel_event is not None:
+ cancel_event.set()
+ while not task.done():
+ try:
+ await asyncio.shield(task)
+ except asyncio.CancelledError:
+ if cancel_event is not None:
+ cancel_event.set()
+ continue
+ except Exception:
+ break
+ if task.done():
+ try:
+ task.exception()
+ except (asyncio.CancelledError, Exception):
+ pass
+
+
# Centralized local/server tool nudge. Keep render_html guidance gated to turns
# where the canvas tool is actually present in the tool schema; otherwise
# small local models can hallucinate a missing tool call instead of following
@@ -7462,13 +7496,35 @@ async def openai_chat_completions(
asyncio.to_thread(next, gen, _tool_sentinel)
)
try:
- event = await asyncio.shield(next_task)
+ # Stall-timeout wait: keepalive while the generator stays
+ # silent (e.g. prefill between tool iterations). asyncio.wait
+ # never cancels next_task, matching the finally-drain shield.
+ while True:
+ done_tasks, _ = await asyncio.wait(
+ {next_task},
+ timeout = _LOCAL_TOOL_STREAM_STALL_KEEPALIVE_S,
+ )
+ if done_tasks:
+ break
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
+ event = next_task.result()
finally:
if next_task.done():
next_task = None
if event is _tool_sentinel:
break
+ if event["type"] == "heartbeat":
+ # Tool-wrapper heartbeat while a server-side tool blocks; keeps SSE alive.
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
+ continue
+
+ if event["type"] in ("tool_output", "tool_args"):
+ # Live stdout/stderr or tool-call arguments, forwarded
+ # verbatim for the UI. Final result still arrives in tool_end.
+ yield f"data: {json.dumps(event)}\n\n"
+ continue
+
if event["type"] == "status":
# Empty status marks an iteration boundary in the
# GGUF tool loop (e.g. after a re-prompt). Reset the
@@ -8018,7 +8074,18 @@ async def openai_chat_completions(
asyncio.to_thread(next, gen, _gguf_sentinel)
)
try:
- cumulative = await asyncio.shield(next_task)
+ # Stall-timeout wait: keepalive while the generator stays
+ # silent (e.g. no-tool prefill). asyncio.wait never cancels
+ # next_task, matching the finally-drain shield (see GGUF stream).
+ while True:
+ done_tasks, _ = await asyncio.wait(
+ {next_task},
+ timeout = _LOCAL_TOOL_STREAM_STALL_KEEPALIVE_S,
+ )
+ if done_tasks:
+ break
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
+ cumulative = next_task.result()
finally:
if next_task.done():
next_task = None
@@ -8709,6 +8776,7 @@ async def openai_chat_completions(
async def sf_tool_stream():
gen = None
+ _sf_next_task = None
disconnect_watcher = asyncio.create_task(
_await_disconnect_then_cancel(request, cancel_event)
)
@@ -8740,10 +8808,35 @@ async def openai_chat_completions(
api_monitor.finish(monitor_id, "cancelled")
return
- event = await asyncio.to_thread(next, gen, _sf_tool_sentinel)
+ # Stall keepalive (see GGUF tool stream): silent backend segments
+ # must not leave the SSE stream idle past proxy timeouts.
+ _sf_next_task = asyncio.create_task(
+ asyncio.to_thread(next, gen, _sf_tool_sentinel)
+ )
+ while True:
+ _sf_done, _ = await asyncio.wait(
+ {_sf_next_task},
+ timeout = _LOCAL_TOOL_STREAM_STALL_KEEPALIVE_S,
+ )
+ if _sf_done:
+ break
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
+ event = _sf_next_task.result()
+ # Done; drop the reference so the finally-block drain no-ops.
+ _sf_next_task = None
if event is _sf_tool_sentinel:
break
+ if event["type"] == "heartbeat":
+ # Tool-execution wrapper heartbeat -> SSE keepalive.
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
+ continue
+
+ if event["type"] in ("tool_output", "tool_args"):
+ # Live stdout/stderr, or tool-call arguments as the model writes them.
+ yield f"data: {json.dumps(event)}\n\n"
+ continue
+
if event["type"] == "status":
if not event["text"]:
# Iteration boundary: flush reasoning, then a fresh prefilled extractor for the next turn.
@@ -8835,9 +8928,15 @@ async def openai_chat_completions(
yield _openai_stream_error_sse(error_chunk)
finally:
await _stop_local_disconnect_cancel_watcher(disconnect_watcher)
+ # Drain a still-running next(gen) worker before closing: closing
+ # mid-next(gen) raises ValueError('generator already executing') and
+ # skips the generator's cleanup finally. Matches the GGUF tool stream.
+ await _drain_pending_next_task(_sf_next_task, cancel_event)
if gen is not None:
try:
- gen.close()
+ # Offload the close so the generator's cleanup runs off the event
+ # loop (matches the GGUF SSE path); a disconnect can't stall the loop.
+ await asyncio.to_thread(gen.close)
except (RuntimeError, ValueError):
pass
_sf_tracker.__exit__(None, None, None)
@@ -9027,6 +9126,8 @@ async def openai_chat_completions(
_tracker.__enter__()
async def stream_chunks():
+ gen = None
+ _next_task = None
disconnect_watcher = asyncio.create_task(
_await_disconnect_then_cancel(request, cancel_event)
)
@@ -9041,23 +9142,30 @@ async def openai_chat_completions(
prev_text = ""
# Split prefilled <think> into reasoning_content deltas (GGUF parity); single turn, serves MLX.
reasoning_extractor = _new_sf_reasoning_extractor()
- # Run the sync generator in a thread pool to avoid blocking the
- # event loop. Critical for compare mode: two SSE requests arrive
- # concurrently but the orchestrator serializes them via
- # _gen_lock; without run_in_executor the second request's
- # blocking lock acquisition would freeze the entire event loop,
- # stalling both streams.
+ # Run the sync generator in a worker thread so it can't block the event
+ # loop. Critical for compare mode: a second request's blocking _gen_lock
+ # acquisition would otherwise freeze the loop and stall both streams.
_DONE = object() # sentinel for generator exhaustion
- loop = asyncio.get_event_loop()
gen = generate()
while True:
if cancel_event.is_set():
backend.reset_generation_state()
break
- # next(gen, _DONE) returns _DONE instead of raising
- # StopIteration -- StopIteration can't propagate through
- # asyncio futures (Python limitation).
- cumulative = await loop.run_in_executor(None, next, gen, _DONE)
+ # Stall keepalive (see safetensors tool stream) each window while
+ # next(gen) runs in a worker. next(gen, _DONE) returns _DONE rather
+ # than raising StopIteration (which can't cross asyncio futures).
+ _next_task = asyncio.create_task(asyncio.to_thread(next, gen, _DONE))
+ while True:
+ _done_tasks, _ = await asyncio.wait(
+ {_next_task},
+ timeout = _LOCAL_TOOL_STREAM_STALL_KEEPALIVE_S,
+ )
+ if _done_tasks:
+ break
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
+ cumulative = _next_task.result()
+ # Done; drop the reference so the finally-block drain no-ops.
+ _next_task = None
if cumulative is _DONE:
break
if await request.is_disconnected():
@@ -9180,6 +9288,17 @@ async def openai_chat_completions(
yield _openai_stream_error_sse(error_chunk)
finally:
await _stop_local_disconnect_cancel_watcher(disconnect_watcher)
+ # Drain a still-running next(gen) worker before closing: closing
+ # mid-next(gen) raises ValueError('generator already executing') and
+ # skips the generator's cleanup finally. Matches the safetensors stream.
+ await _drain_pending_next_task(_next_task, cancel_event)
+ if gen is not None:
+ try:
+ # Offload the close so the generator's cleanup runs off the event
+ # loop (matches the GGUF SSE path); a disconnect can't stall the loop.
+ await asyncio.to_thread(gen.close)
+ except (RuntimeError, ValueError):
+ pass
_tracker.__exit__(None, None, None)
return _SameTaskStreamingResponse(
@@ -12389,8 +12508,12 @@ async def _anthropic_tool_stream(
ends_on_tool_use = False
tool_blocks_emitted = 0
drop_until_tool_end = False
+ # Last drop-branch keepalive, seeded to stream start so a chatty tool busy
+ # past the stall window still gets a keepalive though its events are dropped.
+ _last_drop_keepalive = time.monotonic()
gen = run_gen()
+ _next_task = None
# Watcher to cancel on disconnect: the in-loop poll fires only between
# events, so a mid-prefill disconnect would otherwise hold the decode slot.
disconnect_watcher = asyncio.create_task(
@@ -12401,13 +12524,42 @@ async def _anthropic_tool_stream(
if cancel_event.is_set() or await request.is_disconnected():
cancel_event.set()
return
- event = await asyncio.to_thread(next, gen, _sentinel)
+ # Stall keepalive (see GGUF tool stream): silent backend segments
+ # must not leave the SSE stream idle past proxy timeouts.
+ _next_task = asyncio.create_task(asyncio.to_thread(next, gen, _sentinel))
+ while True:
+ _done_tasks, _ = await asyncio.wait(
+ {_next_task},
+ timeout = _LOCAL_TOOL_STREAM_STALL_KEEPALIVE_S,
+ )
+ if _done_tasks:
+ break
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
+ event = _next_task.result()
+ # Done; drop the reference so the finally-block drain no-ops.
+ _next_task = None
if event is _sentinel:
break
etype = event.get("type")
+ if etype == "heartbeat":
+ # Tool-wrapper heartbeat -> SSE keepalive, checked BEFORE the drop
+ # skip: a dropped tool still runs server-side and its events keep the
+ # stall keepalive from firing, so dropping heartbeats would go silent.
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
+ continue
+ if etype in ("tool_output", "tool_args"):
+ # Live stdout / arg streaming have no Anthropic Messages equivalent
+ # (the full call/result follow in tool_use / tool_result), so drop them.
+ # They keep the stall keepalive from firing, so a chatty tool would go
+ # silent past the ~100s proxy cap; emit a rate-limited keepalive instead.
+ _now = time.monotonic()
+ if _now - _last_drop_keepalive >= _LOCAL_TOOL_STREAM_STALL_KEEPALIVE_S:
+ _last_drop_keepalive = _now
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
+ continue
if drop_until_tool_end:
- # disable_parallel_tool_use: a later tool call is being
- # dropped — skip every event until (and including) its tool_end.
+ # disable_parallel_tool_use: skip every event until (and
+ # including) this dropped tool call's tool_end.
if etype == "tool_end":
drop_until_tool_end = False
continue
@@ -12448,12 +12600,24 @@ async def _anthropic_tool_stream(
yield line
except Exception as e:
logger.error("anthropic_messages stream error: %s", e)
- _error_event = _anthropic_stream_error_event(e)
+ # force = True so an unclassified mid-stream failure (llama-server crash,
+ # decode OOM, dropped socket) still emits an SSE error and returns, instead
+ # of a normal message_stop that masks a truncated turn as a clean finish.
+ _error_event = _anthropic_stream_error_event(e, force = True)
if _error_event is not None:
yield _error_event
return
finally:
await _stop_local_disconnect_cancel_watcher(disconnect_watcher)
+ # Drain a still-running next(gen) worker before closing, so a mid-prefill
+ # disconnect releases the thread/generator/tool resources. Closing first
+ # would race into ValueError('generator already executing').
+ await _drain_pending_next_task(_next_task, cancel_event)
+ if gen is not None:
+ try:
+ await asyncio.to_thread(gen.close)
+ except (RuntimeError, ValueError):
+ pass
stop_reason = openai_finish_to_anthropic_stop(
captured_finish_reason, had_tool_calls = ends_on_tool_use
@@ -12490,6 +12654,7 @@ async def _anthropic_plain_stream(
captured_finish_reason = None
gen = run_gen()
+ _next_task = None
# Watcher to cancel on disconnect: the in-loop poll fires only between
# chunks, so a mid-prefill disconnect would otherwise hold the decode slot.
disconnect_watcher = asyncio.create_task(
@@ -12500,7 +12665,20 @@ async def _anthropic_plain_stream(
if cancel_event.is_set() or await request.is_disconnected():
cancel_event.set()
return
- cumulative = await asyncio.to_thread(next, gen, _sentinel)
+ # Stall keepalive (see Anthropic tool stream) each window while
+ # next(gen) runs in a worker.
+ _next_task = asyncio.create_task(asyncio.to_thread(next, gen, _sentinel))
+ while True:
+ _done_tasks, _ = await asyncio.wait(
+ {_next_task},
+ timeout = _LOCAL_TOOL_STREAM_STALL_KEEPALIVE_S,
+ )
+ if _done_tasks:
+ break
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
+ cumulative = _next_task.result()
+ # Done; drop the reference so the finally-block drain no-ops.
+ _next_task = None
if cumulative is _sentinel:
break
if isinstance(cumulative, dict):
@@ -12516,12 +12694,24 @@ async def _anthropic_plain_stream(
yield line
except Exception as e:
logger.error("anthropic_messages stream error: %s", e)
- _error_event = _anthropic_stream_error_event(e)
+ # force = True so an unclassified mid-stream failure (llama-server crash,
+ # decode OOM, dropped socket) still emits an SSE error and returns, instead
+ # of a normal message_stop that masks a truncated turn as a clean finish.
+ _error_event = _anthropic_stream_error_event(e, force = True)
if _error_event is not None:
yield _error_event
return
finally:
await _stop_local_disconnect_cancel_watcher(disconnect_watcher)
+ # Drain a still-running next(gen) worker before closing, so a mid-prefill
+ # disconnect releases the thread/generator/model resources. Closing first
+ # would race into ValueError('generator already executing').
+ await _drain_pending_next_task(_next_task, cancel_event)
+ if gen is not None:
+ try:
+ await asyncio.to_thread(gen.close)
+ except (RuntimeError, ValueError):
+ pass
stop_reason = openai_finish_to_anthropic_stop(captured_finish_reason, had_tool_calls = False)
for line in emitter.finish(stop_reason = stop_reason, stop_sequence = None):
diff --git a/studio/backend/tests/test_anthropic_messages.py b/studio/backend/tests/test_anthropic_messages.py
index 10cbc64ad35..3b0ea373727 100644
--- a/studio/backend/tests/test_anthropic_messages.py
+++ b/studio/backend/tests/test_anthropic_messages.py
@@ -1631,6 +1631,48 @@ class TestAnthropicMessagesToolRouting:
assert entry["status"] == "cancelled"
assert monitor.active_count() == 0
+ @staticmethod
+ def _sse_blob(chunks):
+ # StreamingResponse may hand back str or already-encoded bytes.
+ return "".join(c.decode() if isinstance(c, (bytes, bytearray)) else c for c in chunks)
+
+ def test_plain_streaming_unclassified_error_emits_error_event(self, monkeypatch):
+ # An unclassified mid-stream failure must surface as an SSE `error` event
+ # and stop, not a message_stop that masks a truncated turn as clean.
+ def _gen_boom(**_kwargs):
+ yield "partial"
+ raise RuntimeError("llama-server crashed mid-decode")
+
+ _mock_backend(monkeypatch, generate_chat_completion = _gen_boom)
+ payload = _basic_payload(stream = True)
+
+ response = _drive(anthropic_messages(payload, request = self._Request(), current_subject = "t"))
+ blob = self._sse_blob(self._consume_response(response))
+
+ assert "event: error" in blob
+ assert '"type": "error"' in blob
+ assert "event: message_stop" not in blob
+
+ def test_tool_streaming_unclassified_error_emits_error_event(self, monkeypatch):
+ # Same guarantee on the tool-calling stream path.
+ def _gen_tools_boom(**_kwargs):
+ yield {"type": "content", "text": "partial"}
+ raise RuntimeError("llama-server crashed mid-decode")
+
+ _mock_backend(monkeypatch, generate_chat_completion_with_tools = _gen_tools_boom)
+ payload = _basic_payload(
+ stream = True,
+ enable_tools = True,
+ tools = [{"type": "web_search_20250305", "name": "web_search"}],
+ )
+
+ response = _drive(anthropic_messages(payload, request = self._Request(), current_subject = "t"))
+ blob = self._sse_blob(self._consume_response(response))
+
+ assert "event: error" in blob
+ assert '"type": "error"' in blob
+ assert "event: message_stop" not in blob
+
def test_mixed_server_and_client_tools_rejected_with_400(self, monkeypatch):
_mock_backend(monkeypatch)
payload = _basic_payload(
@@ -2076,3 +2118,339 @@ def test_resumed_null_assistant_between_users_coalesced_on_messages_route(monkey
if isinstance(merged, list):
merged = " ".join(p.get("text", "") for p in merged if isinstance(p, dict))
assert "first question" in merged and "please continue" in merged
+
+
+def test_disable_parallel_tool_use_forwards_heartbeats_while_dropping():
+ """Heartbeats from a parallel-disabled, dropped tool call must still reach
+ the client as SSE keepalives: the dropped call runs server-side and the
+ stall keepalive never fires while the generator keeps producing events, so
+ swallowing them recreates the silent window keepalives exist to prevent."""
+ import threading as _threading
+
+ from routes.inference import (
+ _OPENAI_PASSTHROUGH_SSE_KEEPALIVE,
+ _anthropic_tool_stream,
+ )
+
+ def run_gen():
+ def gen():
+ yield {
+ "type": "tool_start",
+ "tool_name": "python",
+ "tool_call_id": "call_0",
+ "arguments": {},
+ }
+ yield {"type": "heartbeat"}
+ yield {
+ "type": "tool_end",
+ "tool_name": "python",
+ "tool_call_id": "call_0",
+ "result": "r1",
+ }
+ # Second call: dropped by disable_parallel_tool_use, still executed
+ # server-side (heartbeats + live output).
+ yield {
+ "type": "tool_start",
+ "tool_name": "python",
+ "tool_call_id": "call_1",
+ "arguments": {},
+ }
+ yield {"type": "heartbeat"}
+ yield {
+ "type": "tool_output",
+ "tool_name": "python",
+ "tool_call_id": "call_1",
+ "text": "x",
+ }
+ yield {"type": "heartbeat"}
+ yield {
+ "type": "tool_end",
+ "tool_name": "python",
+ "tool_call_id": "call_1",
+ "result": "r2",
+ }
+ yield {"type": "content", "text": "final answer"}
+
+ return gen()
+
+ async def _drive():
+ async def _is_disconnected():
+ return False
+
+ request = SimpleNamespace(is_disconnected = _is_disconnected)
+ resp = await _anthropic_tool_stream(
+ request,
+ _threading.Event(),
+ run_gen,
+ "msg_hb",
+ "m",
+ disable_parallel_tool_use = True,
+ )
+ return [chunk async for chunk in resp.body_iterator]
+
+ chunks = asyncio.run(_drive())
+ keepalives = [c for c in chunks if c == _OPENAI_PASSTHROUGH_SSE_KEEPALIVE]
+ # One heartbeat inside the kept call, two inside the dropped window.
+ assert len(keepalives) >= 3
+ # The dropped call must not surface as a second tool_use block.
+ tool_use_starts = [c for c in chunks if "content_block_start" in c and '"tool_use"' in c]
+ assert len(tool_use_starts) == 1
+
+
+def test_dropped_tool_output_events_emit_rate_limited_keepalives(monkeypatch):
+ """A chatty tool streaming tool_output/tool_args with no heartbeats keeps the
+ generator busy (stall keepalive never fires); the Anthropic path can't
+ translate those events and drops them. Dropping silently would let an idle
+ proxy kill the stream, so the drop branch emits a rate-limited keepalive."""
+ import threading as _threading
+
+ import routes.inference as inf_mod
+ from routes.inference import (
+ _OPENAI_PASSTHROUGH_SSE_KEEPALIVE,
+ _anthropic_tool_stream,
+ )
+
+ # Deterministic clock: only the drop-branch keepalive uses time.monotonic
+ # here, so jumping past the stall window per call makes each dropped event
+ # cross the rate-limit threshold. asyncio.wait uses the loop clock and
+ # next(gen) returns promptly, so the outer stall keepalive never fires --
+ # every keepalive here is from the drop branch.
+ _real_time = inf_mod.time
+ _tick = {"v": 0.0}
+
+ def _fast_monotonic():
+ _tick["v"] += 100.0
+ return _tick["v"]
+
+ fake_time = SimpleNamespace(
+ monotonic = _fast_monotonic,
+ sleep = _real_time.sleep,
+ time = _real_time.time,
+ perf_counter = _real_time.perf_counter,
+ )
+ monkeypatch.setattr(inf_mod, "time", fake_time)
+
+ n_output = 4
+
+ def run_gen():
+ def gen():
+ yield {
+ "type": "tool_start",
+ "tool_name": "python",
+ "tool_call_id": "call_0",
+ "arguments": {},
+ }
+ # Chatty streamed stdout, no heartbeats.
+ for i in range(n_output):
+ yield {
+ "type": "tool_output",
+ "tool_name": "python",
+ "tool_call_id": "call_0",
+ "text": f"line {i}\n",
+ }
+ yield {
+ "type": "tool_end",
+ "tool_name": "python",
+ "tool_call_id": "call_0",
+ "result": "done",
+ }
+ yield {"type": "content", "text": "final answer"}
+
+ return gen()
+
+ async def _drive():
+ async def _is_disconnected():
+ return False
+
+ request = SimpleNamespace(is_disconnected = _is_disconnected)
+ resp = await _anthropic_tool_stream(
+ request,
+ _threading.Event(),
+ run_gen,
+ "msg_drop_ka",
+ "m",
+ )
+ return [chunk async for chunk in resp.body_iterator]
+
+ chunks = asyncio.run(_drive())
+ keepalives = [c for c in chunks if c == _OPENAI_PASSTHROUGH_SSE_KEEPALIVE]
+ assert len(keepalives) == n_output
+ # Final answer still reaches the client (drop is transport-only).
+ assert any("final answer" in c for c in chunks)
+
+
+def test_parallel_disabled_dropped_call_output_emits_rate_limited_keepalives(monkeypatch):
+ """Under disable_parallel_tool_use a chatty second call is dropped whole
+ (drop_until_tool_end). Its tool_output/tool_args events must still emit
+ rate-limited keepalives: the drop window can last minutes with no heartbeats
+ and no stall keepalive, so swallowing them silently would let an idle proxy
+ kill the stream. The keepalive branch runs before the drop skip."""
+ import threading as _threading
+
+ import routes.inference as inf_mod
+ from routes.inference import (
+ _OPENAI_PASSTHROUGH_SSE_KEEPALIVE,
+ _anthropic_tool_stream,
+ )
+
+ # Deterministic clock: jumps past the stall window per call (see sibling test).
+ _real_time = inf_mod.time
+ _tick = {"v": 0.0}
+
+ def _fast_monotonic():
+ _tick["v"] += 100.0
+ return _tick["v"]
+
+ fake_time = SimpleNamespace(
+ monotonic = _fast_monotonic,
+ sleep = _real_time.sleep,
+ time = _real_time.time,
+ perf_counter = _real_time.perf_counter,
+ )
+ monkeypatch.setattr(inf_mod, "time", fake_time)
+
+ n_output = 4
+
+ def run_gen():
+ def gen():
+ # First (kept) call.
+ yield {
+ "type": "tool_start",
+ "tool_name": "python",
+ "tool_call_id": "call_0",
+ "arguments": {},
+ }
+ yield {
+ "type": "tool_end",
+ "tool_name": "python",
+ "tool_call_id": "call_0",
+ "result": "r1",
+ }
+ # Second call: dropped whole by disable_parallel_tool_use but still
+ # executed server-side, streaming chatty stdout with no heartbeats.
+ yield {
+ "type": "tool_start",
+ "tool_name": "python",
+ "tool_call_id": "call_1",
+ "arguments": {},
+ }
+ for i in range(n_output):
+ yield {
+ "type": "tool_output",
+ "tool_name": "python",
+ "tool_call_id": "call_1",
+ "text": f"line {i}\n",
+ }
+ yield {
+ "type": "tool_end",
+ "tool_name": "python",
+ "tool_call_id": "call_1",
+ "result": "r2",
+ }
+ yield {"type": "content", "text": "final answer"}
+
+ return gen()
+
+ async def _drive():
+ async def _is_disconnected():
+ return False
+
+ request = SimpleNamespace(is_disconnected = _is_disconnected)
+ resp = await _anthropic_tool_stream(
+ request,
+ _threading.Event(),
+ run_gen,
+ "msg_drop_ka2",
+ "m",
+ disable_parallel_tool_use = True,
+ )
+ return [chunk async for chunk in resp.body_iterator]
+
+ chunks = asyncio.run(_drive())
+ keepalives = [c for c in chunks if c == _OPENAI_PASSTHROUGH_SSE_KEEPALIVE]
+ assert len(keepalives) == n_output
+ # The dropped call must not surface as a second tool_use block.
+ tool_use_starts = [c for c in chunks if "content_block_start" in c and '"tool_use"' in c]
+ assert len(tool_use_starts) == 1
+ assert any("final answer" in c for c in chunks)
+
+
+def test_plain_stream_emits_keepalive_during_prompt_stall(monkeypatch):
+ """No-tool Anthropic stream must emit SSE keepalives while a long prompt
+ prefill blocks next(gen), matching the tool stream (finding 5). The old
+ single unbounded to_thread(next, ...) could sit silent past a proxy idle cap."""
+ import threading as _threading
+ import time as _time
+
+ from routes import inference as inf_mod
+ from routes.inference import _OPENAI_PASSTHROUGH_SSE_KEEPALIVE, _anthropic_plain_stream
+
+ monkeypatch.setattr(inf_mod, "_LOCAL_TOOL_STREAM_STALL_KEEPALIVE_S", 0.05)
+
+ def run_gen():
+ def gen():
+ _time.sleep(0.24) # stall past several shortened keepalive windows
+ yield "hello world"
+
+ return gen()
+
+ async def _drive():
+ async def _is_disconnected():
+ return False
+
+ request = SimpleNamespace(is_disconnected = _is_disconnected)
+ resp = await _anthropic_plain_stream(
+ request, _threading.Event(), run_gen, "msg_plain_ka", "m"
+ )
+ return [chunk async for chunk in resp.body_iterator]
+
+ chunks = asyncio.run(_drive())
+ keepalives = [c for c in chunks if c == _OPENAI_PASSTHROUGH_SSE_KEEPALIVE]
+ assert len(keepalives) >= 2
+ assert any("hello world" in c for c in chunks)
+
+
+def test_plain_stream_closes_generator_on_disconnect():
+ """On disconnect the no-tool teardown must drain any pending worker and close
+ the generator (finding 6). The old finally only stopped the disconnect
+ watcher, leaking the generator. A fake generator records close() so the
+ teardown is asserted deterministically, not via GC."""
+ import threading as _threading
+
+ from routes.inference import _anthropic_plain_stream
+
+ closed = _threading.Event()
+
+ class _FakeGen:
+ def __init__(self):
+ self._items = iter(["tok0", "tok1", "tok2", "tok3"])
+
+ def __next__(self):
+ return next(self._items)
+
+ def close(self):
+ closed.set()
+
+ def run_gen():
+ return _FakeGen()
+
+ state = {"disconnected": False}
+
+ async def _drive():
+ async def _is_disconnected():
+ return state["disconnected"]
+
+ request = SimpleNamespace(is_disconnected = _is_disconnected)
+ resp = await _anthropic_plain_stream(
+ request, _threading.Event(), run_gen, "msg_plain_close", "m"
+ )
+ out = []
+ async for chunk in resp.body_iterator:
+ out.append(chunk)
+ if "tok0" in chunk:
+ # Client drops after the first token; the next loop turn tears down.
+ state["disconnected"] = True
+ return out
+
+ asyncio.run(_drive())
+ assert closed.is_set()
diff --git a/studio/backend/tests/test_bypass_permissions.py b/studio/backend/tests/test_bypass_permissions.py
index 585aa207a7b..2635f4e7c85 100644
--- a/studio/backend/tests/test_bypass_permissions.py
+++ b/studio/backend/tests/test_bypass_permissions.py
@@ -13,6 +13,7 @@ never gating under bypass.
Run with: ``PYTHONPATH=studio/backend python -m pytest studio/backend/tests/test_bypass_permissions.py -q``
"""
+import io
import os
import sys
@@ -94,10 +95,23 @@ def test_safe_env_excludes_host_and_secret(monkeypatch, tmp_path):
class _FakeProc:
+ """A subprocess.Popen double for the drain path (``tools._drain_process_output``):
+ a readable ``stdout`` pipe yielding the fake output then EOF, plus
+ ``wait()`` / ``poll()`` / ``pid``. The pid is non-existent so
+ ``_capture_process_group``'s ``os.getpgid`` returns None; ``wait`` returns
+ immediately so the drain never kills.
+ """
+
returncode = 0
+ # Unlikely-to-exist pid: os.getpgid raises ProcessLookupError (caught) -> None.
+ pid = 2**22
+
+ def __init__(self):
+ # Readable stdout: iter(readline, "") yields "FAKEOUT" then hits EOF.
+ self.stdout = io.StringIO("FAKEOUT")
- def communicate(self, timeout = None):
- return ("FAKEOUT", None)
+ def wait(self, timeout = None):
+ return 0
def poll(self):
return 0
diff --git a/studio/backend/tests/test_llama_cpp_tool_loop.py b/studio/backend/tests/test_llama_cpp_tool_loop.py
index 8ccee79a4ee..c3161c57145 100644
--- a/studio/backend/tests/test_llama_cpp_tool_loop.py
+++ b/studio/backend/tests/test_llama_cpp_tool_loop.py
@@ -1498,6 +1498,59 @@ def test_textual_mistral_marker_not_leaked_when_inline_with_preface(monkeypatch)
assert any("Let me search." in t for t in content_texts)
+def test_textual_explicit_id_reuses_provisional_card(monkeypatch):
+ # A textual Mistral-style call with an explicit ``id`` must reconcile onto the
+ # open provisional TEXT card (keyed "call_0"), not spawn a duplicate under the
+ # explicit id (which the parser keeps for execution).
+ big_query = "cats " * 80 # push the drained call past the provisional floor
+ call = "[TOOL_CALLS]" + json.dumps(
+ [{"name": "web_search", "arguments": {"query": big_query}, "id": "explicit-42"}]
+ )
+ assert len(call) > 256
+ # Small chunks so the provisional card opens mid-generation (a single-shot
+ # delta parses instantly and never shows a provisional to exercise).
+ chunks = [call[i : i + 24] for i in range(0, len(call), 24)]
+ streams = [
+ [_sse({"content": c}) for c in chunks] + [_done()],
+ [_sse({"content": "done"}), _done()],
+ ]
+ payloads: list[dict] = []
+ backend = _make_backend(monkeypatch, streams, payloads)
+ calls: list[tuple[str, dict]] = []
+
+ def fake_execute_tool(name, arguments, **_kwargs):
+ calls.append((name, arguments))
+ return "result"
+
+ monkeypatch.setattr("core.inference.tools.execute_tool", fake_execute_tool)
+
+ events = list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "search"}],
+ tools = [{"type": "function", "function": {"name": "web_search"}}],
+ max_tool_iterations = 1,
+ )
+ )
+
+ assert calls == [("web_search", {"query": big_query})]
+ tool_starts = [e for e in events if e.get("type") == "tool_start"]
+ # Empty-args card = provisional open; full-args card = reconciled real start.
+ provisional = [e for e in tool_starts if not e.get("arguments")]
+ real = [e for e in tool_starts if e.get("arguments", {}).get("query")]
+ assert len(provisional) == 1, tool_starts # provisional actually opened
+ prov_id = provisional[0]["tool_call_id"]
+ # Exactly one real card, sharing the provisional id, not a duplicate under
+ # the explicit "explicit-42" id.
+ assert len(real) == 1, tool_starts
+ assert real[0]["tool_call_id"] == prov_id
+ assert real[0]["tool_name"] == "web_search"
+ assert {e["tool_call_id"] for e in tool_starts} == {prov_id}
+ # A single tool_end reconciles the card; no stale empty-result close.
+ ends = [e for e in events if e.get("type") == "tool_end"]
+ assert [e["tool_call_id"] for e in ends] == [prov_id]
+ assert ends[0]["result"] == "result"
+
+
def test_textual_llama_python_tag_marker_not_leaked(monkeypatch):
# Same leak class for the Llama-3 built-in ``<|python_tag|>NAME.call(...)`` form.
streams = [
@@ -2916,3 +2969,204 @@ def test_gguf_valid_tool_calls_respect_max_tool_iterations(monkeypatch):
m.get("role") == "user" and "used all available tool calls" in m.get("content", "")
for m in payloads[2]["messages"]
), payloads[2]["messages"]
+
+
+# ── Live tool-call argument streaming (tool_args events) ─────────────────────
+
+
+def _python_tool_schema() -> list[dict]:
+ return [
+ {
+ "type": "function",
+ "function": {
+ "name": "python",
+ "description": "Run python code.",
+ "parameters": {
+ "type": "object",
+ "properties": {"code": {"type": "string"}},
+ "required": ["code"],
+ },
+ },
+ }
+ ]
+
+
+def test_structured_tool_args_stream_to_provisional_card(monkeypatch):
+ """A large structured tool call must stream its arguments as tool_args events
+ to the provisional card (backlog that triggered the card, then each
+ fragment), while the executed call and the model's view stay exactly what the
+ accumulator built."""
+
+ code = "print('x')\n" + ("# pad\n" * 80)
+ args_json = json.dumps({"code": code})
+ call_id = "call_live_args"
+ split = _PROVISIONAL_ARGS_MIN_CHARS + 16
+ frag1, frag2, frag3 = (
+ args_json[:split],
+ args_json[split : split + 40],
+ args_json[split + 40 :],
+ )
+
+ def _tc_delta(fragment: str, with_header: bool) -> str:
+ entry: dict = {"index": 0, "function": {"arguments": fragment}}
+ if with_header:
+ entry.update({"id": call_id, "type": "function"})
+ entry["function"]["name"] = "python"
+ return _sse({"tool_calls": [entry]})
+
+ first_stream = [
+ _tc_delta(frag1, with_header = True),
+ _tc_delta(frag2, with_header = False),
+ _tc_delta(frag3, with_header = False),
+ _done(),
+ ]
+ second_stream = [_sse({"content": "Done."}), _done()]
+ payloads: list[dict] = []
+ backend = _make_backend(monkeypatch, [first_stream, second_stream], payloads)
+
+ executed: list[tuple[str, dict]] = []
+
+ def fake_execute_tool(name, arguments, **_kwargs):
+ executed.append((name, arguments))
+ return "ok"
+
+ monkeypatch.setattr("core.inference.tools.execute_tool", fake_execute_tool)
+
+ events = list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "run it"}],
+ tools = _python_tool_schema(),
+ max_tool_iterations = 1,
+ )
+ )
+
+ starts = [e for e in events if e.get("type") == "tool_start"]
+ assert starts and starts[0]["tool_call_id"] == call_id
+
+ args_events = [e for e in events if e.get("type") == "tool_args"]
+ assert args_events, "no tool_args events were streamed"
+ assert all(e["tool_call_id"] == call_id for e in args_events)
+ # First event is the backlog, the rest raw fragments; together the args JSON.
+ assert args_events[0]["text"] == frag1
+ assert "".join(e["text"] for e in args_events) == args_json
+
+ # The streamed display path must not perturb execution or the model view.
+ assert executed == [("python", {"code": code})]
+ assistant_messages = [m for m in payloads[1]["messages"] if m.get("role") == "assistant"]
+ tc = assistant_messages[-1]["tool_calls"][0]
+ assert tc["id"] == call_id
+ # Controller re-serializes args (normalized JSON); parsed payload unchanged.
+ assert json.loads(tc["function"]["arguments"]) == {"code": code}
+
+
+def test_text_tool_call_streams_args_and_reconciles_card(monkeypatch):
+ """A TEXT (XML) tool call must stream its raw call text as tool_args under the
+ id the stream-end parser assigns ("call_0"), so the provisional card and the
+ final tool_start reconcile."""
+
+ code = "print('hello')\n" + ("# filler\n" * 60)
+ call_json = json.dumps({"name": "python", "arguments": {"code": code}})
+ call_text = f"<tool_call>{call_json}</tool_call>"
+ chunks = [call_text[i : i + 48] for i in range(0, len(call_text), 48)]
+ first_stream = [_sse({"content": chunk}) for chunk in chunks] + [_done()]
+ second_stream = [_sse({"content": "Done."}), _done()]
+ payloads: list[dict] = []
+ backend = _make_backend(monkeypatch, [first_stream, second_stream], payloads)
+
+ executed: list[tuple[str, dict]] = []
+
+ def fake_execute_tool(name, arguments, **_kwargs):
+ executed.append((name, arguments))
+ return "ok"
+
+ monkeypatch.setattr("core.inference.tools.execute_tool", fake_execute_tool)
+
+ events = list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "run it"}],
+ tools = _python_tool_schema(),
+ max_tool_iterations = 1,
+ )
+ )
+
+ starts = [e for e in events if e.get("type") == "tool_start"]
+ assert starts, "no tool_start emitted"
+ # Provisional card first (parser's first-call id), then the reconciling start.
+ assert starts[0]["tool_call_id"] == "call_0"
+ assert starts[0]["arguments"] == {}
+ assert starts[-1]["tool_call_id"] == "call_0"
+
+ args_events = [e for e in events if e.get("type") == "tool_args"]
+ assert args_events, "no tool_args events for the text call"
+ assert all(e["tool_call_id"] == "call_0" for e in args_events)
+ streamed = "".join(e["text"] for e in args_events)
+ # Streamed text is the drained call (display only); it must never leak into
+ # content events.
+ assert '"name": "python"' in streamed
+ assert executed == [("python", {"code": code})]
+ content_events = [e for e in events if e.get("type") == "content"]
+ assert not any("<tool_call>" in e["text"] for e in content_events)
+
+
+def test_ordinary_json_answer_streams_no_tool_args(monkeypatch):
+ """A large ordinary JSON answer (no enabled tool name) must not spawn a
+ provisional card or tool_args events; it stays a normal content answer."""
+
+ answer = json.dumps({"result": "fine", "data": ["x" * 40] * 12, "note": "not a tool call"})
+ chunks = [answer[i : i + 64] for i in range(0, len(answer), 64)]
+ stream = [_sse({"content": chunk}) for chunk in chunks] + [_done()]
+ payloads: list[dict] = []
+ backend = _make_backend(monkeypatch, [stream], payloads)
+
+ events = list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "give me json"}],
+ tools = _python_tool_schema(),
+ max_tool_iterations = 1,
+ )
+ )
+
+ assert not [e for e in events if e.get("type") == "tool_args"]
+ assert not [e for e in events if e.get("type") == "tool_start"]
+ content_events = [e for e in events if e.get("type") == "content"]
+ assert content_events and answer in content_events[-1]["text"]
+
+
+def test_provisional_text_card_closed_when_parse_fails(monkeypatch):
+ """A >=256-char enabled-name text sniff opens a provisional card; if the
+ drained text then fails to parse (auto-heal off, truncated call), the
+ DRAINING false-positive path must close the card with a tool_end instead of
+ leaving it spinning forever."""
+
+ # Truncated mid-arguments and never closed: unparseable without healing.
+ call_text = '<tool_call>{"name": "python", "arguments": {"code": "' + "x" * (
+ _PROVISIONAL_ARGS_MIN_CHARS + 64
+ )
+ chunks = [call_text[i : i + 48] for i in range(0, len(call_text), 48)]
+ stream = [_sse({"content": chunk}) for chunk in chunks] + [_done()]
+ payloads: list[dict] = []
+ backend = _make_backend(monkeypatch, [stream], payloads)
+
+ executed: list[tuple[str, dict]] = []
+
+ def fake_execute_tool(name, arguments, **_kwargs):
+ executed.append((name, arguments))
+ return "ok"
+
+ monkeypatch.setattr("core.inference.tools.execute_tool", fake_execute_tool)
+
+ events = list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "run it"}],
+ tools = _python_tool_schema(),
+ max_tool_iterations = 1,
+ auto_heal_tool_calls = False,
+ )
+ )
+
+ starts = [e for e in events if e.get("type") == "tool_start"]
+ ends = [e for e in events if e.get("type") == "tool_end"]
+ assert starts and starts[0]["tool_call_id"] == "call_0"
+ assert executed == [] # nothing parsed, nothing ran
+ assert ends, "provisional card left dangling (no tool_end)"
+ assert ends[-1]["tool_call_id"] == "call_0"
diff --git a/studio/backend/tests/test_sandbox_sitecustomize.py b/studio/backend/tests/test_sandbox_sitecustomize.py
new file mode 100644
index 00000000000..3ac427f9f1b
--- /dev/null
+++ b/studio/backend/tests/test_sandbox_sitecustomize.py
@@ -0,0 +1,522 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Hermetic tests for the sandbox sitecustomize path-remap shim.
+
+The shim (``core/inference/sandbox_site/sitecustomize.py``) runs at interpreter
+startup inside every sandboxed tool subprocess and remaps ChatGPT
+code-interpreter habit paths (``/mnt/data`` etc.) onto the per-conversation
+working directory. Importing it calls ``_install()``, which monkeypatches
+``builtins.open`` / ``io.open`` / ``os.makedirs`` / ``os.mkdir`` /
+``pathlib.Path.mkdir`` process-wide, so these tests
+load it into a throwaway module and restore those globals immediately, then
+exercise the pure ``_remap()`` function directly -- no subprocess, and no real
+``/mnt`` or ``/tmp`` writes. The mkdir test keeps the patch installed under a
+``chdir`` into ``tmp_path`` so the only real writes land in that temp dir.
+"""
+
+from __future__ import annotations
+
+import builtins
+import importlib.util
+import io
+import os
+import pathlib
+from pathlib import Path
+
+import pytest
+
+_SHIM = (
+ Path(__file__).resolve().parent.parent
+ / "core"
+ / "inference"
+ / "sandbox_site"
+ / "sitecustomize.py"
+)
+
+
+def _save_patch_targets():
+ """Snapshot every global the shim patches, so tests can restore them.
+
+ On Python < 3.11 the shim also repoints ``pathlib._NormalAccessor.open``
+ (pathlib captured the original io.open at import there); the accessor is
+ absent on 3.11+, so the snapshot skips it.
+ """
+ accessor = getattr(pathlib, "_NormalAccessor", None)
+ return (
+ (builtins.open, io.open, os.open, os.makedirs, os.mkdir, pathlib.Path.mkdir),
+ accessor,
+ accessor.open if accessor is not None else None,
+ )
+
+
+def _restore_patch_targets(saved):
+ """Undo _save_patch_targets so the test process stays clean."""
+ globals_tuple, accessor, accessor_open = saved
+ (builtins.open, io.open, os.open, os.makedirs, os.mkdir, pathlib.Path.mkdir) = globals_tuple
+ if accessor is not None:
+ accessor.open = accessor_open
+
+
+def _load_shim():
+ """Import the shim without leaving its open()/mkdir patches installed."""
+ saved = _save_patch_targets()
+ spec = importlib.util.spec_from_file_location("_sandbox_sitecustomize_under_test", _SHIM)
+ mod = importlib.util.module_from_spec(spec)
+ try:
+ spec.loader.exec_module(mod) # runs _install(), patching the globals
+ finally:
+ # Undo the process-wide patch so the test process stays clean.
+ _restore_patch_targets(saved)
+ mod._notified = True # silence the one-shot stderr notice in tests
+ return mod
+
+
+def test_always_remap_prefixes_map_into_cwd(monkeypatch, tmp_path):
+ mod = _load_shim()
+ monkeypatch.chdir(tmp_path)
+ cwd = os.getcwd()
+ assert mod._remap("/mnt/data/out.txt") == os.path.join(cwd, "out.txt")
+ assert mod._remap("/mnt/data") == cwd
+ # Unrelated absolute and relative paths pass straight through.
+ assert mod._remap("/etc/passwd") == "/etc/passwd"
+ assert mod._remap("relative.txt") == "relative.txt"
+
+
+def test_prefix_remap_contains_parent_traversal_inside_cwd(monkeypatch, tmp_path):
+ # A hallucinated habit path can carry '..' in its suffix. The remapped target
+ # must stay under the per-conversation CWD, never climbing into a sibling
+ # session's directory: '..' components are dropped, the rest of the subpath kept.
+ mod = _load_shim()
+ workdir = tmp_path / "session_current" / "work"
+ workdir.mkdir(parents = True)
+ monkeypatch.chdir(workdir)
+ cwd = os.getcwd()
+
+ for escaping in (
+ "/mnt/data/../other_session/file",
+ "/mnt/data/../../secrets.txt",
+ "/mnt/data/a/../../b/c.txt",
+ "/mnt/data/./sub/./x.txt",
+ ):
+ mapped = mod._remap(escaping)
+ # Never escapes the CWD subtree.
+ assert mapped == cwd or mapped.startswith(cwd + os.sep), (escaping, mapped)
+ assert os.path.realpath(mapped).startswith(os.path.realpath(cwd))
+ # '../other_session/file' collapses to CWD/other_session/file.
+ assert mod._remap("/mnt/data/../other_session/file") == os.path.join(
+ cwd, "other_session", "file"
+ )
+ # A bare '/mnt/data/..' with nothing left maps onto the CWD itself.
+ assert mod._remap("/mnt/data/..") == cwd
+
+
+def test_write_fallback_refuses_dotdot_basename(monkeypatch, tmp_path):
+ # basename('/no/such/tree/..') == '..'; joining that onto the CWD would target
+ # its parent (outside the sandbox). The fallback must refuse such non-filename
+ # basenames and return the path unchanged so the real open raises.
+ mod = _load_shim()
+ workdir = tmp_path / "work"
+ workdir.mkdir()
+ monkeypatch.chdir(workdir)
+ for escaping in ("/no/such/tree/..", "/no/such/tree/.", "/no/such/tree/"):
+ assert mod._remap_open(escaping, "w") == escaping
+
+
+def test_write_fallback_remaps_hallucinated_absolute_path(monkeypatch, tmp_path):
+ # Models invent absolute paths from their CWD (e.g. /home/ubuntu/Sandbox/x.html),
+ # which prefix lists cannot enumerate. A write/create-mode open on an absolute
+ # path outside the CWD whose parent is missing is redirected to the basename in the CWD.
+ mod = _load_shim()
+ workdir = tmp_path / "workdir"
+ workdir.mkdir()
+ monkeypatch.chdir(workdir)
+ cwd = os.getcwd()
+ hallucinated = "/home/ubuntu/Sandbox/flappy_bird.html"
+ for mode in ("w", "a", "x", "w+"):
+ assert mod._remap_open(hallucinated, mode) == os.path.join(cwd, "flappy_bird.html")
+ # A nested missing tree collapses to just the basename in the CWD.
+ assert mod._remap_open("/no/such/tree/report.txt", "w") == os.path.join(cwd, "report.txt")
+
+
+def test_write_fallback_never_touches_read_modes(monkeypatch, tmp_path):
+ # Reading a real (or genuinely missing) file must succeed/fail truthfully --
+ # the fallback is write-only.
+ mod = _load_shim()
+ monkeypatch.chdir(tmp_path)
+ for mode in ("r", "rb", "r+"):
+ assert mod._remap_open("/etc/definitely_missing_xyz.conf", mode) == (
+ "/etc/definitely_missing_xyz.conf"
+ )
+
+
+def test_write_fallback_passes_through_existing_external_dir(monkeypatch, tmp_path):
+ # A write to an absolute path whose parent dir exists is a deliberate, working
+ # target and must NOT be redirected.
+ mod = _load_shim()
+ external = tmp_path / "external"
+ external.mkdir()
+ workdir = tmp_path / "workdir"
+ workdir.mkdir()
+ monkeypatch.chdir(workdir)
+ target = str(external / "out.txt")
+ assert mod._remap_open(target, "w") is target
+
+
+def test_write_fallback_never_clobbers_same_basename(monkeypatch, tmp_path):
+ # A same-named CWD file is an unrelated persistent conversation file.
+ # Redirecting an invented absolute path (missing parent) onto it would clobber
+ # data the model never asked to touch, so the fallback refuses on collision for
+ # every create mode: it returns the original path and the real open() raises.
+ mod = _load_shim()
+ monkeypatch.chdir(tmp_path)
+
+ existing = tmp_path / "report.txt"
+ existing.write_text("KEEP-ME")
+
+ requested = "/definitely_missing_parent_7083/report.txt"
+ for mode in ("w", "a", "x", "w+", "a+"):
+ # Refused: returns the original absolute path unchanged (no redirect).
+ assert mod._remap_open(requested, mode) == requested
+
+ # And opening the refused path really does raise, leaving the file intact.
+ with pytest.raises(FileNotFoundError):
+ open(mod._remap_open(requested, "w"), "w")
+ assert existing.read_text() == "KEEP-ME"
+
+ # No collision -> still healed into the working directory as before.
+ fresh = "/definitely_missing_parent_7083/brand_new.txt"
+ assert mod._remap_open(fresh, "w") == os.path.join(os.getcwd(), "brand_new.txt")
+
+
+def test_write_fallback_reserves_same_target_on_repeated_writes(monkeypatch, tmp_path):
+ # Iterative overwrite of the SAME invented path must keep landing on the CWD
+ # target the fallback first healed it to. Once ./app.html exists, a naive
+ # anti-clobber guard would return the original (parent-missing) path and every
+ # regenerate would raise; the fallback must recognise its own prior remap and re-serve it.
+ mod = _load_shim()
+ monkeypatch.chdir(tmp_path)
+ cwd = os.getcwd()
+ invented = "/home/ubuntu/Sandbox/app.html"
+ target = os.path.join(cwd, "app.html")
+
+ # First write: healed into the CWD, and create the file so the collision guard
+ # would trigger on the next call without the fix.
+ assert mod._remap_open(invented, "w") == target
+ with open(mod._remap_open(invented, "w"), "w") as fh:
+ fh.write("v1")
+
+ # Repeated overwrites of the same invented path stay on the same target.
+ for _ in range(3):
+ assert mod._remap_open(invented, "w") == target
+ with open(mod._remap_open(invented, "w"), "w") as fh:
+ fh.write("v2")
+ assert Path(target).read_text() == "v2"
+
+ # A DIFFERENT invented source colliding on basename is still refused, so it can
+ # never clobber the artifact the first path owns.
+ other = "/opt/other/app.html"
+ assert mod._remap_open(other, "w") == other
+
+
+def test_write_fallback_reserves_healed_target_across_separate_runs(monkeypatch, tmp_path):
+ # Each tool call is a FRESH subprocess, so the in-process remap map is empty on
+ # the next run while the healed file persists in the working directory. A second
+ # run overwriting the SAME invented path (whose healed basename now exists) must
+ # still re-serve that target via the on-disk sidecar, else the model could never
+ # overwrite last turn's artifact. Each _load_shim() simulates a brand-new interpreter.
+ monkeypatch.chdir(tmp_path)
+ cwd = os.getcwd()
+ invented = "/home/ubuntu/Sandbox/app.html"
+ target = os.path.join(cwd, "app.html")
+
+ # Run 1: heal the invented path, create the file, persist source->target to the sidecar.
+ run1 = _load_shim()
+ assert run1._remap_open(invented, "w") == target
+ with open(run1._remap_open(invented, "w"), "w") as fh:
+ fh.write("v1")
+
+ # Run 2: brand-new interpreter, nothing in memory -- still recognises its prior
+ # heal from the sidecar and re-serves it, even though ./app.html now exists
+ # (which without the sidecar would trip the anti-clobber guard and raise).
+ run2 = _load_shim()
+ assert run2._remapped_writes == {}
+ assert run2._remap_open(invented, "w") == target
+ with open(run2._remap_open(invented, "w"), "w") as fh:
+ fh.write("v2")
+ assert Path(target).read_text() == "v2"
+
+ # A DIFFERENT invented source colliding only on basename is still refused across
+ # runs: the sidecar records solely the source it healed, so an unrelated path
+ # can never adopt/clobber the artifact.
+ other = "/opt/other/app.html"
+ assert run2._remap_open(other, "w") == other
+
+ # A foreign CWD file (created directly, never healed) stays protected in a later
+ # run from an invented path sharing its basename.
+ (tmp_path / "notes.txt").write_text("KEEP-ME")
+ run3 = _load_shim()
+ assert run3._remap_open("/some/missing/notes.txt", "w") == "/some/missing/notes.txt"
+ with pytest.raises(FileNotFoundError):
+ open(run3._remap_open("/some/missing/notes.txt", "w"), "w")
+ assert (tmp_path / "notes.txt").read_text() == "KEEP-ME"
+
+
[email protected]("mode", ["r+", "rb+"])
+def test_read_update_modes_never_redirected_even_with_missing_parent(monkeypatch, tmp_path, mode):
+ # r+ / rb+ REQUIRE the target to exist and never create; a "+" must not qualify
+ # as creation, or a missing absolute path would be redirected onto a same-basename
+ # workspace file and corrupt it. The parent is missing, so only the mode predicate
+ # protects the victim.
+ mod = _load_shim()
+ monkeypatch.chdir(tmp_path)
+
+ victim = tmp_path / "victim.txt"
+ victim.write_text("original")
+
+ requested = "/definitely_missing_parent_xyz/victim.txt"
+ assert mod._remap_open(requested, mode) == requested
+ with pytest.raises(FileNotFoundError):
+ open(mod._remap_open(requested, mode), mode)
+ assert victim.read_text() == "original"
+
+
+def test_existing_convention_prefix_is_not_shadowed(monkeypatch, tmp_path):
+ # A convention prefix (/mnt/data etc.) is remapped ONLY while absent. If a real
+ # host directory exists there it must pass through so its own filesystem semantics
+ # apply: a real read succeeds, and a missing file under it is created there by a
+ # write, never shadowed by a CWD file.
+ mod = _load_shim()
+ external = tmp_path / "real_prefix"
+ external.mkdir()
+ (external / "data.txt").write_text("real external content")
+
+ workdir = tmp_path / "conversation"
+ workdir.mkdir()
+ monkeypatch.chdir(workdir)
+ monkeypatch.setattr(mod, "_PREFIXES", (str(external),))
+ monkeypatch.setattr(mod, "_CONDITIONAL_PREFIXES", ())
+
+ target = str(external / "data.txt")
+ # Prefix exists -> pass through for read and write.
+ assert mod._remap(target) == target
+ assert mod._remap_open(target, "r") == target
+ assert mod._remap_open(target, "w") == target
+ # A missing file under the EXISTING real prefix is left alone (parent exists),
+ # so the real directory creates it -- not a CWD shadow.
+ missing = str(external / "new.txt")
+ assert mod._remap_open(missing, "w") == missing
+
+ # Remove the prefix directory -> healing resumes (absent prefix).
+ (external / "data.txt").unlink()
+ external.rmdir()
+ assert mod._remap(target) == os.path.join(os.getcwd(), "data.txt")
+
+
+def test_os_open_and_path_touch_remap_convention_path(monkeypatch, tmp_path):
+ # Path.touch() and other low-level creators go through os.open, not builtins/io.open.
+ # Keep the shim's patches installed under a chdir into tmp_path so os.open is
+ # patched, and confirm a convention path is healed into the CWD instead of raising.
+ saved = _save_patch_targets()
+ spec = importlib.util.spec_from_file_location("_sandbox_sitecustomize_osopen", _SHIM)
+ mod = importlib.util.module_from_spec(spec)
+ monkeypatch.chdir(tmp_path)
+ cwd = os.getcwd()
+ try:
+ spec.loader.exec_module(mod) # installs the os.open patch
+ mod._notified = True
+ pathlib.Path("/mnt/data/touched.txt").touch()
+ assert os.path.isfile(os.path.join(cwd, "touched.txt"))
+ # Direct os.open with create flags is healed too.
+ fd = os.open("/mnt/data/via_os_open.txt", os.O_CREAT | os.O_WRONLY, 0o600)
+ os.close(fd)
+ assert os.path.isfile(os.path.join(cwd, "via_os_open.txt"))
+ finally:
+ _restore_patch_targets(saved)
+
+
+def test_path_write_read_text_remap_convention_path(monkeypatch, tmp_path):
+ # Path.open / write_text / read_text route through io.open (3.11+) or the captured
+ # accessor open (< 3.11). Keep the patches installed under a chdir into tmp_path
+ # and confirm a convention path is healed into the CWD on every version. This is
+ # the hermetic guard for the 3.10 accessor path a plain io.open patch misses.
+ saved = _save_patch_targets()
+ spec = importlib.util.spec_from_file_location("_sandbox_sitecustomize_writetext", _SHIM)
+ mod = importlib.util.module_from_spec(spec)
+ monkeypatch.chdir(tmp_path)
+ cwd = os.getcwd()
+ try:
+ spec.loader.exec_module(mod) # installs the io.open / accessor patch
+ mod._notified = True
+ pathlib.Path("/mnt/data/note.txt").write_text("pathlib remap")
+ assert os.path.isfile(os.path.join(cwd, "note.txt"))
+ # read_text goes through the same mapped path and sees what was written.
+ assert pathlib.Path("/mnt/data/note.txt").read_text() == "pathlib remap"
+ # A real absolute path passes through both patches untouched.
+ real = tmp_path / "real.txt"
+ pathlib.Path(str(real)).write_text("verbatim")
+ assert real.read_text() == "verbatim"
+ finally:
+ _restore_patch_targets(saved)
+
+
+def test_write_fallback_leaves_relative_and_bytes_paths(monkeypatch, tmp_path):
+ mod = _load_shim()
+ monkeypatch.chdir(tmp_path)
+ # Relative paths are already inside the CWD.
+ assert mod._remap_open("out.txt", "w") == "out.txt"
+ # Bytes paths are left untouched (prefix remap skips non-str).
+ assert mod._remap_open(b"/no/such/tree/x.bin", "w") == b"/no/such/tree/x.bin"
+
+
+def test_remap_open_still_applies_prefix_remaps(monkeypatch, tmp_path):
+ # The prefix remap runs first and preserves subpaths. A write heals onto the CWD
+ # unconditionally; the write-mode fallback is only the last resort.
+ mod = _load_shim()
+ monkeypatch.chdir(tmp_path)
+ cwd = os.getcwd()
+ assert mod._remap_open("/mnt/data/sub/out.txt", "w") == os.path.join(cwd, "sub", "out.txt")
+ # A read whose mapped target does NOT exist keeps the original path: a missing
+ # input stays truthful, not silently redirected into the CWD.
+ assert mod._remap_open("/mnt/data/sub/out.txt", "r") == "/mnt/data/sub/out.txt"
+
+
+def test_prefix_read_heals_only_when_mapped_target_exists(monkeypatch, tmp_path):
+ # A convention-prefix READ must not redirect onto the CWD when the mapped target
+ # is absent -- that masks a genuine missing-input error and could serve an
+ # unrelated same-basename workdir file. It heals only when the mapped CWD target
+ # exists, so re-reading an artifact an earlier write produced still works.
+ mod = _load_shim()
+ monkeypatch.chdir(tmp_path)
+ cwd = os.getcwd()
+
+ # Mapped target absent: read keeps the original path (truthful miss).
+ assert mod._remap_open("/mnt/data/input.csv", "r") == "/mnt/data/input.csv"
+ with pytest.raises(FileNotFoundError):
+ open(mod._remap_open("/mnt/data/input.csv", "r"))
+
+ # r+ (never creates) behaves the same: no redirect while absent.
+ assert mod._remap_open("/mnt/data/input.csv", "r+") == "/mnt/data/input.csv"
+
+ # A write heals onto the CWD and creates the artifact...
+ mapped = mod._remap_open("/mnt/data/input.csv", "w")
+ assert mapped == os.path.join(cwd, "input.csv")
+ with open(mapped, "w") as fh:
+ fh.write("col\n1\n")
+
+ # ...and now a READ of the same convention path heals onto that existing artifact.
+ read_target = mod._remap_open("/mnt/data/input.csv", "r")
+ assert read_target == os.path.join(cwd, "input.csv")
+ with open(read_target) as fh:
+ assert fh.read() == "col\n1\n"
+
+
+def test_prefix_boundary_not_matched_by_similar_paths(monkeypatch, tmp_path):
+ # The prefix match is anchored on a segment boundary (prefix or prefix + '/'), so
+ # a sibling merely sharing the textual prefix must NOT be remapped: /workspace2
+ # is not /workspace, /mnt/database is not /mnt/data.
+ mod = _load_shim()
+ monkeypatch.chdir(tmp_path)
+ for unrelated in ("/workspace2/file.txt", "/mnt/database/x", "/home/sandboxed/y"):
+ assert mod._remap(unrelated) == unrelated
+ # And through open() for a read too (no silent redirect).
+ assert mod._remap_open(unrelated, "r") == unrelated
+
+
+def test_tmp_outputs_is_a_conditional_prefix():
+ mod = _load_shim()
+ assert "/tmp/outputs" in mod._CONDITIONAL_PREFIXES
+ # NOT in the always-remap set: /tmp exists on the host, so an unconditional remap
+ # could shadow a real /tmp/outputs the user code made.
+ assert "/tmp/outputs" not in mod._PREFIXES
+
+
+def test_tmp_outputs_remapped_only_while_absent(monkeypatch, tmp_path):
+ mod = _load_shim()
+ monkeypatch.chdir(tmp_path)
+ cwd = os.getcwd()
+ # Point the conditional prefix at a real temp location so we can toggle its
+ # existence on disk instead of mocking os.path.exists.
+ cond = str(tmp_path / "cond_outputs")
+ monkeypatch.setattr(mod, "_CONDITIONAL_PREFIXES", (cond,))
+
+ # Absent: heal the habit path into the working directory (preserved/served).
+ assert not os.path.exists(cond)
+ assert mod._remap(cond + "/plot.png") == os.path.join(cwd, "plot.png")
+ assert mod._remap(cond) == cwd
+
+ # Present (the user's own code created it): pass through, never shadowed.
+ os.makedirs(cond)
+ assert mod._remap(cond + "/plot.png") == cond + "/plot.png"
+ assert mod._remap(cond) == cond
+
+
+def test_pathlib_mkdir_parents_remaps_convention_path(monkeypatch, tmp_path):
+ # `Path('/mnt/data').mkdir(parents=True, exist_ok=True)` is a stock setup line.
+ # pathlib drives it through os.mkdir per component and Path.is_dir()/os.stat on
+ # FileExistsError, so the shim must patch os.mkdir AND Path.mkdir for the whole
+ # parents/exist_ok dance to land in the CWD instead of raising. Keeps the mkdir
+ # patches installed under a chdir into tmp_path and restores them in finally.
+ saved = _save_patch_targets()
+ spec = importlib.util.spec_from_file_location("_sandbox_sitecustomize_mkdir", _SHIM)
+ mod = importlib.util.module_from_spec(spec)
+ monkeypatch.chdir(tmp_path)
+ cwd = os.getcwd()
+ try:
+ spec.loader.exec_module(mod) # installs the os.mkdir / Path.mkdir patches
+ mod._notified = True
+ # Bare convention path maps onto the CWD, which already exists: exist_ok=True
+ # must be honoured against the mapped location, not raise.
+ pathlib.Path("/mnt/data").mkdir(parents = True, exist_ok = True)
+ # A nested convention path is created inside the CWD, parents and all.
+ pathlib.Path("/mnt/data/plots/run1").mkdir(parents = True, exist_ok = True)
+ assert os.path.isdir(os.path.join(cwd, "plots", "run1"))
+ # Idempotent: exist_ok is evaluated on the mapped path (which now exists),
+ # not the never-present /mnt/data.
+ pathlib.Path("/mnt/data/plots/run1").mkdir(parents = True, exist_ok = True)
+
+ # Passthrough: real paths are created verbatim through both patches,
+ # never remapped into the CWD.
+ real_dir = tmp_path / "real_via_path"
+ pathlib.Path(str(real_dir)).mkdir()
+ assert real_dir.is_dir()
+ real_os = tmp_path / "real_via_os"
+ os.mkdir(str(real_os))
+ assert real_os.is_dir()
+ finally:
+ _restore_patch_targets(saved)
+
+
+def test_read_of_missing_prefix_path_emits_no_notice(monkeypatch, tmp_path, capsys):
+ # A read of a missing convention path keeps the original path and must not spend
+ # the one-shot notice; a genuine remap afterward still notifies.
+ mod = _load_shim()
+ monkeypatch.chdir(tmp_path)
+ mod._notified = False # re-arm the one-shot notice for this test
+ # Read of a missing prefixed path: original kept, no notice, flag unspent.
+ assert mod._remap_open("/mnt/data/missing.csv", "r") == "/mnt/data/missing.csv"
+ assert mod._notified is False
+ assert "does not exist" not in capsys.readouterr().err
+ # A committed write then heals and fires the notice exactly once.
+ assert mod._remap_open("/mnt/data/out.txt", "w") == os.path.join(os.getcwd(), "out.txt")
+ assert mod._notified is True
+ assert "/mnt/data does not exist in this sandbox" in capsys.readouterr().err
+
+
+def test_os_open_trunc_without_creat_missing_stays_truthful(monkeypatch, tmp_path):
+ # O_TRUNC / O_APPEND without O_CREAT cannot create a missing file, so the shim
+ # treats them as a read: a missing convention path stays truthful (the error
+ # names the caller's path) and nothing is created in the CWD.
+ saved = _save_patch_targets()
+ spec = importlib.util.spec_from_file_location("_sandbox_sitecustomize_trunc", _SHIM)
+ mod = importlib.util.module_from_spec(spec)
+ monkeypatch.chdir(tmp_path)
+ try:
+ spec.loader.exec_module(mod)
+ mod._notified = True
+ with pytest.raises(FileNotFoundError) as exc:
+ os.open("/mnt/data/missing_xyz.bin", os.O_WRONLY | os.O_TRUNC)
+ assert exc.value.filename == "/mnt/data/missing_xyz.bin"
+ assert not os.path.exists(os.path.join(os.getcwd(), "missing_xyz.bin"))
+ finally:
+ _restore_patch_targets(saved)
diff --git a/studio/backend/tests/test_sandbox_tools.py b/studio/backend/tests/test_sandbox_tools.py
index 24b1da17728..2970b1a6bbf 100644
--- a/studio/backend/tests/test_sandbox_tools.py
+++ b/studio/backend/tests/test_sandbox_tools.py
@@ -294,11 +294,16 @@ class TestSandboxEnvIsolation:
"LANG",
"TERM",
"PYTHONIOENCODING",
+ "PYTHONPATH",
"VIRTUAL_ENV",
"SystemRoot",
}
extras = set(env.keys()) - allowed
assert not extras, f"sandbox env added unexpected keys: {extras}"
+ # PYTHONPATH is whitelist-built, never inherited: only the sandbox
+ # sitecustomize shim dir (code-interpreter path remap).
+ assert env["PYTHONPATH"].endswith("sandbox_site")
+ assert "leak-me" not in env["PYTHONPATH"]
def test_home_points_at_sandbox_workdir(self, tmp_path):
from core.inference.tools import _build_safe_env
@@ -315,6 +320,23 @@ class TestSandboxEnvIsolation:
env = _build_safe_env(str(tmp_path))
assert env["TERM"] == "dumb"
+ def test_bypass_env_installs_sitecustomize_path_shim(self, tmp_path):
+ # Bypass mode must install the same /mnt/data path-remap shim as the safe
+ # env (finding 17), else /mnt/data writes work only in normal mode.
+ from core.inference.tools import _SANDBOX_SITE_DIR, _build_bypass_env
+ env = _build_bypass_env(str(tmp_path))
+ assert _SANDBOX_SITE_DIR in env["PYTHONPATH"].split(os.pathsep)
+
+ def test_bypass_env_prepends_shim_and_keeps_inherited_pythonpath(self, monkeypatch, tmp_path):
+ from core.inference.tools import _SANDBOX_SITE_DIR, _build_bypass_env
+
+ monkeypatch.setenv("PYTHONPATH", "/operator/libs")
+ env = _build_bypass_env(str(tmp_path))
+ parts = env["PYTHONPATH"].split(os.pathsep)
+ # Shim first so its open()/makedirs remap wins, operator entries kept.
+ assert parts[0] == _SANDBOX_SITE_DIR
+ assert "/operator/libs" in parts
+
class TestSandboxCpuRlimitDefault:
"""Pin the default so a regression below 600s without opt-in is caught."""
diff --git a/studio/backend/tests/test_tool_output_streaming.py b/studio/backend/tests/test_tool_output_streaming.py
new file mode 100644
index 00000000000..28bd79cc6ef
--- /dev/null
+++ b/studio/backend/tests/test_tool_output_streaming.py
@@ -0,0 +1,1234 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Live tool-output streaming and heartbeats for server-side tool execution.
+
+Covers three invariants:
+
+* ``stream_tool_execution`` yields incremental ``tool_output`` events and
+ ``heartbeat`` events while a tool blocks, and returns the tool's result
+ byte-identical to a direct call;
+* ``_python_exec`` / ``_bash_exec`` produce the same result string with and
+ without an ``output_callback`` (the final tool message the model sees is
+ untouched by streaming);
+* the GGUF agentic loop emits ``tool_output`` between ``tool_start`` and
+ ``tool_end`` and feeds the model the same ``role=tool`` message as before.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+import threading
+import time
+from pathlib import Path
+
+import pytest
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+_TESTS_DIR = str(Path(__file__).resolve().parent)
+if _TESTS_DIR not in sys.path:
+ sys.path.insert(0, _TESTS_DIR)
+
+from core.inference.tool_stream_exec import (
+ TOOL_OUTPUT_STREAM_MAX_CHARS,
+ stream_tool_execution,
+)
+from core.inference.tools import _bash_exec, _python_exec
+
+from test_llama_cpp_tool_loop import _done, _make_backend, _sse
+
+
+def _run_stream(invoke, **kwargs):
+ """Drive the wrapper generator; return (events, result)."""
+ gen = stream_tool_execution(invoke, **kwargs)
+ events = []
+ while True:
+ try:
+ events.append(next(gen))
+ except StopIteration as stop:
+ return events, stop.value
+
+
+# ── stream_tool_execution ────────────────────────────────────────
+
+
+def test_result_returned_verbatim_without_output():
+ events, result = _run_stream(
+ lambda _cb: "final result",
+ tool_name = "web_search",
+ )
+ assert result == "final result"
+ assert [e for e in events if e["type"] == "tool_output"] == []
+
+
+def test_incremental_output_streams_as_tool_output_events():
+ def tool(callback):
+ callback("line 1\n")
+ callback("line 2\n")
+ return "line 1\nline 2\n"
+
+ events, result = _run_stream(tool, tool_name = "python", tool_call_id = "call_1")
+ assert result == "line 1\nline 2\n"
+ outputs = [e for e in events if e["type"] == "tool_output"]
+ assert outputs, "expected tool_output events"
+ assert "".join(e["text"] for e in outputs) == "line 1\nline 2\n"
+ assert all(e["tool_name"] == "python" for e in outputs)
+ assert all(e["tool_call_id"] == "call_1" for e in outputs)
+
+
+def test_heartbeats_emitted_while_tool_blocks():
+ release = threading.Event()
+
+ def tool(_cb):
+ release.wait(timeout = 5)
+ return "done"
+
+ gen = stream_tool_execution(
+ tool,
+ tool_name = "web_search",
+ heartbeat_interval_s = 0.04,
+ poll_interval_s = 0.02,
+ )
+ events = []
+ result = None
+ try:
+ while True:
+ event = next(gen)
+ events.append(event)
+ if len([e for e in events if e["type"] == "heartbeat"]) >= 2:
+ release.set()
+ except StopIteration as stop:
+ result = stop.value
+ assert result == "done"
+ assert len([e for e in events if e["type"] == "heartbeat"]) >= 2
+
+
+def test_output_resets_heartbeat_pacing():
+ # A steady output stream means no heartbeats are needed.
+ def tool(callback):
+ for i in range(5):
+ callback(f"tick {i}\n")
+ time.sleep(0.01)
+ return "ok"
+
+ events, result = _run_stream(
+ tool,
+ tool_name = "python",
+ heartbeat_interval_s = 10.0,
+ poll_interval_s = 0.02,
+ )
+ assert result == "ok"
+ assert [e for e in events if e["type"] == "heartbeat"] == []
+
+
+def test_tool_exception_propagates_after_stream():
+ def tool(_cb):
+ raise RuntimeError("boom")
+
+ gen = stream_tool_execution(tool, tool_name = "python")
+ try:
+ while True:
+ next(gen)
+ except RuntimeError as exc:
+ assert str(exc) == "boom"
+ else:
+ raise AssertionError("expected RuntimeError")
+
+
+def test_output_before_worker_raises_is_preserved():
+ # Output streamed before the worker raises survives; the exception still propagates.
+ def tool(callback):
+ callback("partial before crash\n")
+ time.sleep(0.02)
+ raise RuntimeError("late boom")
+
+ gen = stream_tool_execution(tool, tool_name = "python", poll_interval_s = 0.01)
+ events = []
+ with pytest.raises(RuntimeError, match = "late boom"):
+ while True:
+ events.append(next(gen))
+ streamed = "".join(e["text"] for e in events if e["type"] == "tool_output")
+ assert "partial before crash" in streamed
+
+
+def test_generator_close_cancels_observing_tool():
+ # gen.close() (SSE client disconnect) sets the shared cancel_event, so a
+ # cancel-observing tool returns at once.
+ cancel_event = threading.Event()
+ started = threading.Event()
+ returned = threading.Event()
+
+ def tool(_cb):
+ started.set()
+ cancel_event.wait(timeout = 5) # cancel-observing: unblocks on cancel
+ returned.set()
+ return "cancelled cleanly"
+
+ gen = stream_tool_execution(
+ tool,
+ tool_name = "web_search",
+ cancel_event = cancel_event,
+ heartbeat_interval_s = 0.02,
+ poll_interval_s = 0.01,
+ )
+ next(gen) # prime the worker; returns a heartbeat while the tool blocks
+ assert started.wait(timeout = 2)
+ gen.close() # GeneratorExit -> sets cancel_event, then bounded join
+ assert cancel_event.is_set()
+ assert returned.wait(timeout = 2) # the tool actually observed cancellation
+
+
+def test_generator_close_is_bounded_for_cancel_ignoring_tool(monkeypatch):
+ # A tool that ignores cancel_event must not stall teardown: gen.close() waits
+ # at most the bounded join, not the tool's full runtime.
+ monkeypatch.setattr("core.inference.tool_stream_exec._WORKER_JOIN_TIMEOUT_S", 0.2)
+ release = threading.Event()
+
+ def tool(_cb):
+ # Ignores cancel_event; stands in for a web_search/MCP call that never polls it.
+ release.wait(timeout = 30)
+ return "slow"
+
+ gen = stream_tool_execution(
+ tool,
+ tool_name = "web_search",
+ cancel_event = threading.Event(),
+ heartbeat_interval_s = 0.02,
+ poll_interval_s = 0.01,
+ )
+ next(gen)
+ started = time.monotonic()
+ gen.close()
+ elapsed = time.monotonic() - started
+ release.set() # let the daemon worker finish so no sleeper lingers
+ assert elapsed < 2.0 # bounded by _WORKER_JOIN_TIMEOUT_S, not the 30s tool
+
+
+def test_cancel_event_not_set_on_clean_finish():
+ # cancel_event is shared across a turn; a clean finish must leave it unset so
+ # the next tool in the same turn is not aborted.
+ cancel_event = threading.Event()
+
+ def tool(_cb):
+ return "ok"
+
+ events, result = _run_stream(
+ tool,
+ tool_name = "python",
+ cancel_event = cancel_event,
+ )
+ assert result == "ok"
+ assert not cancel_event.is_set()
+
+
+def test_no_worker_thread_leak_under_repeated_close(monkeypatch):
+ # Repeated start-then-close must not leak worker threads: each cancel-observing
+ # worker exits once close() signals it.
+ monkeypatch.setattr("core.inference.tool_stream_exec._WORKER_JOIN_TIMEOUT_S", 0.2)
+
+ def _live_tool_workers():
+ return [t for t in threading.enumerate() if t.name.startswith("tool-exec-")]
+
+ for _ in range(50): # let workers from earlier tests drain
+ if not _live_tool_workers():
+ break
+ time.sleep(0.02)
+ baseline = len(_live_tool_workers())
+
+ for _ in range(60):
+ cancel_event = threading.Event()
+
+ def tool(_cb, _ev = cancel_event):
+ _ev.wait(timeout = 5)
+ return "done"
+
+ gen = stream_tool_execution(
+ tool,
+ tool_name = "soak",
+ cancel_event = cancel_event,
+ heartbeat_interval_s = 0.02,
+ poll_interval_s = 0.01,
+ )
+ next(gen)
+ gen.close() # sets cancel_event -> tool returns -> worker exits
+
+ for _ in range(100):
+ if len(_live_tool_workers()) <= baseline:
+ break
+ time.sleep(0.02)
+ assert len(_live_tool_workers()) <= baseline
+
+
+def test_streamed_output_is_capped_but_result_is_not():
+ big = "x" * (TOOL_OUTPUT_STREAM_MAX_CHARS + 5000)
+
+ def tool(callback):
+ callback(big)
+ return big
+
+ events, result = _run_stream(tool, tool_name = "python")
+ assert result == big # final result untouched by the stream cap
+ streamed = "".join(e["text"] for e in events if e["type"] == "tool_output")
+ assert len(streamed) < len(big)
+ assert "further live output not streamed" in streamed
+
+
+def test_heartbeats_continue_while_capped_output_flows():
+ # After the cap, discarded chunks must not starve the keepalive: a chatty tool
+ # keeps the queue non-empty, so without the fix no heartbeat fires and the SSE
+ # stream stays silent past proxy idle timeouts.
+ release = threading.Event()
+
+ def tool(callback):
+ callback("x" * (TOOL_OUTPUT_STREAM_MAX_CHARS + 10)) # trip the cap
+ while not release.is_set():
+ callback("post-cap spam")
+ time.sleep(0.005)
+ return "done"
+
+ # Watchdog: on regressed code next(gen) blocks forever while spam flows; the
+ # timer ends the tool, turning that hang into a clean assertion failure.
+ watchdog = threading.Timer(8.0, release.set)
+ watchdog.start()
+ gen = stream_tool_execution(
+ tool,
+ tool_name = "python",
+ heartbeat_interval_s = 0.04,
+ poll_interval_s = 0.02,
+ )
+ events = []
+ result = None
+ try:
+ while True:
+ event = next(gen)
+ events.append(event)
+ if len([e for e in events if e["type"] == "heartbeat"]) >= 2:
+ release.set()
+ except StopIteration as stop:
+ result = stop.value
+ finally:
+ release.set()
+ watchdog.cancel()
+ assert result == "done"
+ assert len([e for e in events if e["type"] == "heartbeat"]) >= 2
+ streamed = "".join(e["text"] for e in events if e["type"] == "tool_output")
+ assert "further live output not streamed" in streamed
+ assert "post-cap spam" not in streamed # cap still enforced
+
+
+def test_drain_queue_bounds_the_over_cap_batch():
+ # _drain_queue stops concatenating once the cap is first exceeded and discards
+ # the rest in place, so a chatty tool's huge backlog never defeats the memory ceiling.
+ import queue as _queue
+
+ from core.inference.tool_stream_exec import _drain_queue
+
+ q: _queue.Queue = _queue.Queue()
+ sentinel = object()
+ chunk = "z" * 1000
+ for _ in range(5000): # 5 MB queued ahead of the drain
+ q.put(chunk)
+ q.put(sentinel)
+ text, hit_sentinel = _drain_queue(q, sentinel, max_chars = 100)
+ assert hit_sentinel is True
+ # At most cap + one chunk is joined, not the full 5 MB backlog.
+ assert len(text) <= 100 + len(chunk)
+ assert q.empty() # surplus still drained so completion is detected
+
+
+def test_drain_queue_does_not_materialize_surplus_crossing_chunk():
+ # The single chunk that first crosses the cap must not be materialized in full
+ # (a tool can emit one multi-megabyte line). Keep just one char past the budget
+ # to preserve the overflow signal and byte-identical truncation, even when the
+ # budget is already met (max_chars <= 0).
+ import queue as _queue
+
+ from core.inference.tool_stream_exec import _drain_queue
+
+ sentinel = object()
+ huge = "z" * 1_000_000
+
+ # Budget already met (non-positive): keep one char, a true prefix.
+ for cap in (0, -500):
+ q: _queue.Queue = _queue.Queue()
+ q.put(huge)
+ q.put("more")
+ q.put(sentinel)
+ text, hit_sentinel = _drain_queue(q, sentinel, max_chars = cap)
+ assert hit_sentinel is True
+ assert len(text) == 1
+ assert huge.startswith(text)
+ assert q.empty()
+
+ # Positive cap crossed by one huge chunk: bounded to cap + 1, prefix kept.
+ q = _queue.Queue()
+ q.put(huge)
+ q.put(sentinel)
+ text, hit_sentinel = _drain_queue(q, sentinel, max_chars = 100)
+ assert len(text) == 101
+ assert text == huge[:101]
+
+
+def test_drain_queue_unbounded_joins_everything():
+ # Without a cap the join is complete and ordered (the sub-cap path streams
+ # every chunk verbatim on this).
+ import queue as _queue
+
+ from core.inference.tool_stream_exec import _drain_queue
+
+ q: _queue.Queue = _queue.Queue()
+ sentinel = object()
+ for i in range(3):
+ q.put(f"c{i}")
+ q.put(sentinel)
+ text, hit_sentinel = _drain_queue(q, sentinel, max_chars = None)
+ assert hit_sentinel is True
+ assert text == "c0c1c2"
+
+
+def test_over_cap_crossing_batch_streams_capped_output():
+ # End-to-end: a burst crossing the cap in one drain still yields a capped live
+ # stream and an untouched final result.
+ chunk = "z" * 1000
+
+ def tool(callback):
+ for _ in range(3000): # ~3 MB, well past the cap, in one burst
+ callback(chunk)
+ return "final"
+
+ events, result = _run_stream(tool, tool_name = "python")
+ assert result == "final"
+ streamed = "".join(e["text"] for e in events if e["type"] == "tool_output")
+ assert len(streamed) <= TOOL_OUTPUT_STREAM_MAX_CHARS + len(
+ "\n... (further live output not streamed)\n"
+ )
+ assert "further live output not streamed" in streamed
+
+
+# ── python / terminal executors ──────────────────────────────────
+
+_PY_CODE = "for i in range(5):\n print('row', i)\n"
+
+
+def test_python_exec_result_identical_with_streaming():
+ baseline = _python_exec(_PY_CODE, timeout = 60)
+ chunks: list[str] = []
+ streamed = _python_exec(_PY_CODE, timeout = 60, output_callback = chunks.append)
+ assert streamed == baseline
+ assert "".join(chunks) == "".join(f"row {i}\n" for i in range(5))
+
+
+def test_python_exec_streams_lines_incrementally():
+ # The first of two sleep-separated prints must reach the callback well before exit.
+ code = (
+ "import time\n"
+ "print('first', flush=True)\n"
+ "time.sleep(1.0)\n"
+ "print('second', flush=True)\n"
+ )
+ first_seen_at: list[float] = []
+
+ def on_chunk(_text: str) -> None:
+ if not first_seen_at:
+ first_seen_at.append(time.monotonic())
+
+ started = time.monotonic()
+ result = _python_exec(code, timeout = 60, output_callback = on_chunk)
+ finished = time.monotonic()
+ assert "first" in result and "second" in result
+ assert first_seen_at, "callback never invoked"
+ # First line arrived before the sleep completed (margin for slow interpreter start).
+ assert first_seen_at[0] - started < finished - started - 0.5
+
+
+def test_python_exec_unflushed_print_streams_live_and_result_identical():
+ # A bare print() WITHOUT flush=True then a sleep. -u forces the child's stdout
+ # unbuffered so the line reaches the callback before exit (else CPython
+ # block-buffers the pipe and the live pane stays empty). -u changes timing only,
+ # so the joined result stays byte-identical to the non-streaming run.
+ code = (
+ "import time\n"
+ "print('progress')\n" # no flush=True
+ "time.sleep(1.0)\n"
+ "print('done')\n"
+ )
+ first_seen_at: list[float] = []
+
+ def on_chunk(_text: str) -> None:
+ if not first_seen_at:
+ first_seen_at.append(time.monotonic())
+
+ baseline = _python_exec(code, timeout = 60)
+ started = time.monotonic()
+ streamed = _python_exec(code, timeout = 60, output_callback = on_chunk)
+ finished = time.monotonic()
+ assert streamed == baseline
+ assert "progress" in streamed and "done" in streamed
+ assert first_seen_at, "callback never invoked for unflushed print"
+ # Unflushed line arrived before the sleep finished: streamed live, not at exit.
+ assert first_seen_at[0] - started < finished - started - 0.5
+
+
+def test_python_exec_error_exit_identical_with_streaming():
+ code = "print('before')\nraise SystemExit(3)\n"
+ baseline = _python_exec(code, timeout = 60)
+ streamed = _python_exec(code, timeout = 60, output_callback = lambda _t: None)
+ assert streamed == baseline
+ assert streamed.startswith("Exit code 3:")
+
+
+def test_python_exec_timeout_message_identical_with_streaming():
+ code = "import time\ntime.sleep(30)\n"
+ baseline = _python_exec(code, timeout = 1)
+ streamed = _python_exec(code, timeout = 1, output_callback = lambda _t: None)
+ assert streamed == baseline == "Execution timed out after 1 seconds."
+
+
+def test_python_exec_callback_errors_do_not_break_execution():
+ def bad_callback(_text: str) -> None:
+ raise ValueError("observer bug")
+
+ result = _python_exec("print('ok')", timeout = 60, output_callback = bad_callback)
+ assert result.strip() == "ok"
+
+
+def test_bash_exec_result_identical_with_streaming():
+ command = "echo one; echo two"
+ baseline = _bash_exec(command, timeout = 60)
+ chunks: list[str] = []
+ streamed = _bash_exec(command, timeout = 60, output_callback = chunks.append)
+ assert streamed == baseline
+ assert "".join(chunks) == "one\ntwo\n"
+
+
+def test_bash_exec_invalid_utf8_identical_with_streaming():
+ # Invalid UTF-8 must not kill either path: the pipe decodes with
+ # errors="replace", so the streaming reader thread cannot die on the
+ # UnicodeDecodeError readline raises, and both paths return the same replaced text.
+ command = "printf 'ok\\377bad\\n'" # \377 = 0xFF, invalid UTF-8
+ baseline = _bash_exec(command, timeout = 60)
+ chunks: list[str] = []
+ streamed = _bash_exec(command, timeout = 60, output_callback = chunks.append)
+ assert streamed == baseline
+ assert not baseline.startswith("Execution error")
+ assert "ok" in baseline and "bad" in baseline
+ assert "�" in baseline # replacement character, not a crash
+ assert "".join(chunks) == "ok�bad\n"
+
+
+def test_bash_exec_unlimited_timeout_waits_for_grandchild_output():
+ # A background grandchild holds the pipe open past the shell's exit and writes
+ # ~7s later. With timeout=None the drain must wait for EOF like
+ # communicate(timeout=None), so the late output is included.
+ command = "( sleep 7; echo late-grandchild-output ) & echo parent-done"
+ chunks: list[str] = []
+ result = _bash_exec(command, timeout = None, output_callback = chunks.append)
+ assert "parent-done" in result
+ assert "late-grandchild-output" in result
+ assert "late-grandchild-output" in "".join(chunks)
+
+
+def test_bash_exec_finite_timeout_kills_grandchild_holding_stdout(tmp_path):
+ # A backgrounded grandchild holds the pipe open past the finite timeout, then
+ # would write a sentinel. The parent shell has already exited, so killing only
+ # the reaped parent leaves the grandchild running; the drain must kill the
+ # process group captured before the wait so the grandchild never writes.
+ sentinel = tmp_path / "grandchild_ran"
+ command = f"( sleep 3; touch '{sentinel}' ) & echo parent-done"
+ result = _bash_exec(command, timeout = 1, output_callback = lambda _t: None)
+ assert "timed out" in result
+ time.sleep(4.0) # past the grandchild's 3s sleep
+ assert not sentinel.exists(), "grandchild survived the timeout process-group kill"
+
+
[email protected](sys.platform == "win32", reason = "POSIX process groups")
+def test_bash_exec_nonstreaming_timeout_kills_grandchild(tmp_path):
+ # The NON-streaming path (communicate() + _kill_process_tree) short-circuits
+ # once the reaped leader has exited, so a stdout-holding grandchild survives
+ # unless the group captured right after spawn is killed too. Must match the
+ # streaming path's exited-leader handling.
+ sentinel = tmp_path / "grandchild_ran"
+ command = f"( sleep 3; touch '{sentinel}' ) & echo parent-done"
+ result = _bash_exec(command, timeout = 1) # no output_callback -> communicate path
+ assert "timed out" in result
+ time.sleep(4.0)
+ assert not sentinel.exists(), "non-streaming timeout leaked a stdout-holding grandchild"
+
+
[email protected](sys.platform == "win32", reason = "POSIX process groups")
+def test_python_exec_nonstreaming_timeout_kills_grandchild(tmp_path):
+ sentinel = tmp_path / "grandchild_ran"
+ code = (
+ "import subprocess\n"
+ f"subprocess.Popen(['bash', '-c', \"sleep 3; touch '{sentinel}'\"])\n"
+ "print('parent-done')\n"
+ "import time; time.sleep(30)\n"
+ )
+ result = _python_exec(code, timeout = 1) # no output_callback -> communicate path
+ assert "timed out" in result
+ time.sleep(4.0)
+ assert not sentinel.exists(), "non-streaming timeout leaked a stdout-holding grandchild"
+
+
+def test_drain_process_output_without_posix_process_group_apis(monkeypatch):
+ # On Windows os.getpgid / os.killpg are absent; _drain_process_output must not
+ # raise AttributeError before reading the child's output. Removing the APIs and
+ # flipping os.name: the child still runs and is captured, only the group kill is skipped.
+ import subprocess as _sp
+
+ from core.inference.tools import _drain_process_output
+
+ monkeypatch.delattr(os, "getpgid", raising = False)
+ monkeypatch.delattr(os, "killpg", raising = False)
+ monkeypatch.setattr(os, "name", "nt")
+
+ proc = _sp.Popen(
+ [sys.executable, "-c", "print('ok-no-pgid')"],
+ stdout = _sp.PIPE,
+ stderr = _sp.STDOUT,
+ text = True,
+ )
+ output, timed_out = _drain_process_output(proc, 10, lambda _t: None)
+ assert not timed_out
+ assert "ok-no-pgid" in output
+
+
[email protected](sys.platform == "win32", reason = "POSIX process groups")
+def test_captured_group_survives_fast_leader_reap(tmp_path):
+ # Capture the group after spawn, reap the leader first (as a polling cancel
+ # watcher would), then drain: the pre-captured pgid must still reap the
+ # stdout-holding grandchild even though os.getpgid(pid) would now fail.
+ import subprocess as _sp
+
+ from core.inference.tools import _capture_process_group, _drain_process_output
+
+ sentinel = tmp_path / "grandchild_ran"
+ proc = _sp.Popen(
+ ["bash", "-c", f"( sleep 3; touch '{sentinel}' ) & echo parent-done"],
+ stdout = _sp.PIPE,
+ stderr = _sp.STDOUT,
+ text = True,
+ preexec_fn = os.setsid,
+ )
+ pgid = _capture_process_group(proc)
+ assert pgid is not None
+ proc.wait() # reap the leader before draining
+
+ output, timed_out = _drain_process_output(proc, 0.5, None, pgid = pgid)
+ assert timed_out
+ assert "parent-done" in output
+ time.sleep(4.0)
+ assert not sentinel.exists(), "pre-captured group failed to reap the grandchild"
+
+
[email protected](sys.platform == "win32", reason = "POSIX process groups")
+def test_finite_drain_honors_cancel_after_leader_exit(tmp_path):
+ # Once the leader exits the cancel watcher (which loops on proc.poll()) is gone,
+ # so the finite-timeout drain itself must honor cancellation: a mid-drain
+ # cancel_event must break the drain promptly and kill the process group instead
+ # of draining a chatty grandchild for the whole large budget.
+ import subprocess as _sp
+ import threading as _th
+
+ from core.inference.tools import _capture_process_group, _drain_process_output
+
+ sentinel = tmp_path / "grandchild_late"
+ # Grandchild holds the pipe open, streams every 0.2s, and touches the sentinel
+ # only after 10s -- well past the cancel. The leader exits immediately, so the
+ # drain enters the finite branch with a live, chatty reader.
+ proc = _sp.Popen(
+ [
+ "bash",
+ "-c",
+ "( for i in $(seq 1 100); do echo tick-$i; sleep 0.2; done; "
+ f"touch '{sentinel}' ) & echo parent-done",
+ ],
+ stdout = _sp.PIPE,
+ stderr = _sp.STDOUT,
+ text = True,
+ preexec_fn = os.setsid,
+ )
+ pgid = _capture_process_group(proc)
+ assert pgid is not None
+ proc.wait() # leader exits at once; the cancel watcher would now be gone
+
+ cancel_event = _th.Event()
+ _th.Timer(0.6, cancel_event.set).start() # cancel shortly into the drain
+
+ started = time.monotonic()
+ # Large finite timeout (30s); without the cancel poll the drain keeps reading
+ # the grandchild until the pipe closes ~20s later.
+ output, timed_out = _drain_process_output(proc, 30, lambda _t: None, cancel_event, pgid = pgid)
+ elapsed = time.monotonic() - started
+ assert elapsed < 5.0, f"finite drain ignored cancel_event (took {elapsed:.1f}s)"
+ # Cancellation is not a timeout: the budget never elapsed.
+ assert not timed_out
+ assert "parent-done" in output
+ time.sleep(11.0) # past the grandchild's 10s sentinel write
+ assert not sentinel.exists(), "cancel did not kill the stdout-holding grandchild group"
+
+
[email protected](sys.platform == "win32", reason = "POSIX process groups")
+def test_streamed_wait_timeout_kills_grandchild_when_leader_reaped(tmp_path, monkeypatch):
+ # The proc.wait() timeout branch normally kills the group via _kill_process_tree.
+ # But the leader can exit before _kill_process_tree samples its pgid, which then
+ # short-circuits on the reaped leader and leaves a stdout-holding grandchild.
+ # Model that race with _kill_process_tree as a no-op; the captured-pgid kill in
+ # the timeout branch must still reap the grandchild, matching non-streaming.
+ import subprocess as _sp
+
+ from core.inference import tools as _tools_mod
+ from core.inference.tools import _capture_process_group, _drain_process_output
+
+ monkeypatch.setattr(_tools_mod, "_kill_process_tree", lambda proc: None)
+
+ sentinel = tmp_path / "grandchild_ran"
+ # Leader sleeps past the timeout so proc.wait() genuinely times out; a same-group
+ # grandchild holds stdout and would touch the sentinel unless the group is killed.
+ proc = _sp.Popen(
+ ["bash", "-c", f"( sleep 3; touch '{sentinel}' ) & sleep 30"],
+ stdout = _sp.PIPE,
+ stderr = _sp.STDOUT,
+ text = True,
+ preexec_fn = os.setsid,
+ )
+ pgid = _capture_process_group(proc)
+ assert pgid is not None
+
+ output, timed_out = _drain_process_output(proc, 0.5, None, pgid = pgid)
+ assert timed_out
+ time.sleep(4.0) # past the grandchild's 3s sleep
+ assert not sentinel.exists(), (
+ "streamed wait timeout leaked a stdout-holding grandchild when the "
+ "process-tree kill short-circuited on the reaped leader"
+ )
+
+
+# ── GGUF loop regression: model-visible messages unchanged ───────
+
+
+def _run_gguf_tool_turn(monkeypatch, fake_execute_tool):
+ tool_stream = [
+ _sse(
+ {
+ "tool_calls": [
+ {
+ "id": "call_1",
+ "index": 0,
+ "function": {
+ "name": "python",
+ "arguments": json.dumps({"code": "print('hi')"}),
+ },
+ }
+ ]
+ }
+ ),
+ _done(),
+ ]
+ final_stream = [_sse({"content": "All done."}), _done()]
+ payloads: list[dict] = []
+ backend = _make_backend(monkeypatch, [tool_stream, final_stream], payloads)
+ monkeypatch.setattr("core.inference.tools.execute_tool", fake_execute_tool)
+ events = list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "run it"}],
+ tools = [{"type": "function", "function": {"name": "python"}}],
+ max_tool_iterations = 1,
+ )
+ )
+ return events, payloads
+
+
+def test_gguf_loop_final_tool_message_unchanged_by_streaming(monkeypatch):
+ result_text = "hi\nline 2\n"
+
+ def plain_tool(name, arguments, **_kwargs):
+ return result_text
+
+ def streaming_tool(
+ name,
+ arguments,
+ output_callback = None,
+ **_kwargs,
+ ):
+ if output_callback is not None:
+ output_callback("hi\n")
+ output_callback("line 2\n")
+ return result_text
+
+ events_plain, payloads_plain = _run_gguf_tool_turn(monkeypatch, plain_tool)
+ events_streaming, payloads_streaming = _run_gguf_tool_turn(monkeypatch, streaming_tool)
+
+ def _tool_messages(payloads):
+ return [
+ msg for payload in payloads for msg in payload["messages"] if msg.get("role") == "tool"
+ ]
+
+ # The role=tool message fed to the model is byte-identical: streaming is purely
+ # observational and must not perturb parsing/nudging/healing.
+ assert _tool_messages(payloads_streaming) == _tool_messages(payloads_plain)
+ assert _tool_messages(payloads_streaming) == [
+ {
+ "role": "tool",
+ "name": "python",
+ "content": result_text,
+ "tool_call_id": "call_1",
+ }
+ ]
+
+ # tool_end results match too.
+ ends_plain = [e for e in events_plain if e["type"] == "tool_end"]
+ ends_streaming = [e for e in events_streaming if e["type"] == "tool_end"]
+ assert [e["result"] for e in ends_streaming] == [e["result"] for e in ends_plain]
+
+
+def test_gguf_loop_emits_tool_output_between_start_and_end(monkeypatch):
+ def streaming_tool(
+ name,
+ arguments,
+ output_callback = None,
+ **_kwargs,
+ ):
+ if output_callback is not None:
+ output_callback("progress 1\n")
+ output_callback("progress 2\n")
+ return "progress 1\nprogress 2\n"
+
+ events, _payloads = _run_gguf_tool_turn(monkeypatch, streaming_tool)
+ types = [e["type"] for e in events]
+ assert "tool_output" in types
+ start_idx = types.index("tool_start")
+ end_idx = types.index("tool_end")
+ output_indices = [i for i, t in enumerate(types) if t == "tool_output"]
+ assert all(start_idx < i < end_idx for i in output_indices)
+ streamed = "".join(e["text"] for e in events if e["type"] == "tool_output")
+ assert streamed == "progress 1\nprogress 2\n"
+ for e in events:
+ if e["type"] == "tool_output":
+ assert e["tool_name"] == "python"
+ assert e["tool_call_id"] == "call_1"
+
+
+def test_gguf_loop_plain_tool_yields_no_tool_output(monkeypatch):
+ def plain_tool(name, arguments, **_kwargs):
+ return "quiet"
+
+ events, _payloads = _run_gguf_tool_turn(monkeypatch, plain_tool)
+ assert [e for e in events if e["type"] == "tool_output"] == []
+
+
+# ── result truncation notice, env cap, missing-path healing ──────
+
+import os as _os
+import uuid as _uuid
+
+from core.inference.tools import (
+ PYTHON_TOOL,
+ TERMINAL_TOOL,
+ _MAX_OUTPUT_CHARS,
+ _env_int,
+ _missing_path_hint,
+ _truncate,
+ get_sandbox_workdir,
+)
+
+
+def test_truncate_notice_is_neutral_and_mentions_workdir():
+ out = _truncate("y" * 50, limit = 10)
+ assert out.startswith("y" * 10)
+ assert "truncated" in out and "50 chars total" in out
+ assert "persist in the working directory" in out
+ # The notice must NOT claim the user saw the output: this wrapper also serves
+ # non-streaming callers where no output_callback delivers anything.
+ assert "the user was shown the full output" not in out
+ assert "shown" not in out
+ # Under the limit: untouched.
+ assert _truncate("short", limit = 10) == "short"
+
+
+def test_truncated_result_identical_and_notice_neutral_with_streaming():
+ # The truncation notice must be byte-identical with and without an
+ # output_callback (the streaming vs non-streaming invariant a mode-dependent
+ # notice would break) and must not claim the user was shown the full output.
+ code = f"print('x' * {_MAX_OUTPUT_CHARS + 5000})"
+ baseline = _python_exec(code, timeout = 60)
+ streamed = _python_exec(code, timeout = 60, output_callback = lambda _t: None)
+ assert streamed == baseline
+ assert "truncated" in baseline
+ assert "the user was shown the full output" not in baseline
+ assert "persist in the working directory" in baseline
+
+
+def test_result_cap_env_override(monkeypatch):
+ monkeypatch.delenv("UNSLOTH_TOOL_RESULT_MAX_CHARS", raising = False)
+ assert _env_int("UNSLOTH_TOOL_RESULT_MAX_CHARS", 16000) == 16000
+ monkeypatch.setenv("UNSLOTH_TOOL_RESULT_MAX_CHARS", "50000")
+ assert _env_int("UNSLOTH_TOOL_RESULT_MAX_CHARS", 16000) == 50000
+ # Garbage and non-positive values fall back to the default.
+ monkeypatch.setenv("UNSLOTH_TOOL_RESULT_MAX_CHARS", "lots")
+ assert _env_int("UNSLOTH_TOOL_RESULT_MAX_CHARS", 16000) == 16000
+ monkeypatch.setenv("UNSLOTH_TOOL_RESULT_MAX_CHARS", "-5")
+ assert _env_int("UNSLOTH_TOOL_RESULT_MAX_CHARS", 16000) == 16000
+
+
+def test_missing_path_hint_detection():
+ err = "FileNotFoundError: [Errno 2] No such file or directory: '/mnt/data/x.html'"
+ hint = _missing_path_hint(err)
+ assert "working directory is writable" in hint
+ assert "relative path" in hint
+ # The hint echoes the actual failing path, not a canned example.
+ assert "'x.html', not '/mnt/data/x.html'" in hint
+ # A failure on a local path gets no hint.
+ assert _missing_path_hint("FileNotFoundError: 'local.txt'") == ""
+ # Mentioning /mnt/data without a file error gets no hint.
+ assert _missing_path_hint("saved to /mnt/data, all good") == ""
+ assert _missing_path_hint("") == ""
+
+
+def test_missing_path_hint_generalizes_beyond_convention_prefixes():
+ # A hallucinated absolute path outside the enumerated prefixes still earns the
+ # hint, echoing that path.
+ err = (
+ "FileNotFoundError: [Errno 2] No such file or directory: "
+ "'/home/ubuntu/Sandbox/flappy_bird.html'"
+ )
+ hint = _missing_path_hint(err)
+ assert "working directory is writable" in hint
+ assert "'flappy_bird.html', not '/home/ubuntu/Sandbox/flappy_bird.html'" in hint
+ # A bash-style error on an absolute path outside the workdir is echoed too.
+ bash_err = "cat: /var/data/report.csv: No such file or directory"
+ assert "'report.csv', not '/var/data/report.csv'" in _missing_path_hint(bash_err)
+
+
+def test_missing_path_hint_respects_project_workdir():
+ # Project-backed sessions run under a root OUTSIDE ~/studio_sandbox. A legitimate
+ # miss INSIDE that project workspace must not be misclassified as an external
+ # habit path and flattened to its basename; judged against the real workdir it
+ # gets no hint. The fabricated paths carry no convention prefix, so only the
+ # workdir judgement decides.
+ workdir = "/srv/projroot/session_area"
+ missing = "/srv/projroot/session_area/data/missing.csv"
+ output = f"FileNotFoundError: [Errno 2] No such file or directory: '{missing}'"
+ # Against the static sandbox root (no workdir) it looks external and wrongly earns the hint.
+ assert "working directory is writable" in _missing_path_hint(output)
+ # Against the real project workdir it is local -> no hint.
+ assert _missing_path_hint(output, workdir) == ""
+ # A path genuinely outside the project workdir still earns the hint.
+ outside_err = "FileNotFoundError: [Errno 2] No such file or directory: '/srv/other/x.html'"
+ assert "working directory is writable" in _missing_path_hint(outside_err, workdir)
+
+
+def test_missing_path_hint_project_workdir_under_convention_prefix():
+ # A project workdir can live under a convention prefix like /workspace (common in
+ # containers). A genuine miss INSIDE it carries the "/workspace" substring but is
+ # a real local path, not a habit path: the convention fast path must not fire and
+ # flatten it to a bare basename (which would drop the project subdirectory).
+ workdir = "/workspace/proj"
+ nested = "/workspace/proj/sub/data.csv"
+ output = f"FileNotFoundError: [Errno 2] No such file or directory: '{nested}'"
+ # Against the real project workdir the miss is local -> no hint, so
+ # /workspace/proj/sub is not flattened away.
+ assert _missing_path_hint(output, workdir) == ""
+ # A miss at the project root itself is likewise local.
+ at_root = "/workspace/proj/data.csv"
+ root_output = f"FileNotFoundError: [Errno 2] No such file or directory: '{at_root}'"
+ assert _missing_path_hint(root_output, workdir) == ""
+ # A convention path genuinely outside the project workdir still earns the
+ # hint (e.g. a /mnt/data habit path with a /workspace-rooted project).
+ outside = "FileNotFoundError: [Errno 2] No such file or directory: '/mnt/data/x.html'"
+ assert "'x.html', not '/mnt/data/x.html'" in _missing_path_hint(outside, workdir)
+ # Without an explicit workdir the default sandbox root applies, so a
+ # /workspace path is out of sandbox and keeps the habit-path hint.
+ assert "working directory is writable" in _missing_path_hint(root_output)
+
+
+def test_missing_path_hint_convention_scoped_to_failing_line():
+ # A convention prefix appearing only OUTSIDE the failing-path line (a traceback
+ # frame under /workspace, or the user's code printing /mnt/data) must not trigger
+ # the hint when the actual miss was a relative / in-workdir path.
+ frame_err = (
+ "Traceback (most recent call last):\n"
+ ' File "/workspace/proj/script.py", line 5, in <module>\n'
+ " open('data.csv')\n"
+ "FileNotFoundError: [Errno 2] No such file or directory: 'data.csv'"
+ )
+ assert _missing_path_hint(frame_err) == ""
+ printed_err = (
+ "outputs go to /mnt/data normally\n"
+ "FileNotFoundError: [Errno 2] No such file or directory: 'notes.txt'"
+ )
+ assert _missing_path_hint(printed_err) == ""
+ # But a convention path ON the error line still earns the hint.
+ on_line = "FileNotFoundError: [Errno 2] No such file or directory: '/mnt/data/x.html'"
+ assert "'x.html', not '/mnt/data/x.html'" in _missing_path_hint(on_line)
+
+
+def test_code_tool_descriptions_mention_relative_paths():
+ for tool in (PYTHON_TOOL, TERMINAL_TOOL):
+ description = tool["function"]["description"]
+ assert "relative paths" in description
+ assert "/mnt/data" in description
+
+
+def test_python_exec_mnt_data_open_is_remapped_into_workdir():
+ # The shim remaps open()/os.makedirs() on /mnt/data into the sandbox CWD and
+ # prints a one-line stderr notice, identically with and without streaming.
+ fname = f"remap_{_uuid.uuid4().hex}.txt"
+ code = (
+ "import os\n"
+ "os.makedirs('/mnt/data', exist_ok=True)\n"
+ f"with open('/mnt/data/{fname}', 'w') as f:\n"
+ " f.write('hello remap')\n"
+ f"print(open('/mnt/data/{fname}').read())\n"
+ )
+ target = _os.path.join(get_sandbox_workdir(), fname)
+ try:
+ baseline = _python_exec(code, timeout = 60)
+ assert _os.path.isfile(target), baseline
+ with open(target) as f:
+ assert f.read() == "hello remap"
+ assert "hello remap" in baseline
+ assert "/mnt/data does not exist in this sandbox" in baseline
+ _os.remove(target)
+ streamed = _python_exec(code, timeout = 60, output_callback = lambda _t: None)
+ assert streamed == baseline
+ assert _os.path.isfile(target)
+ finally:
+ if _os.path.exists(target):
+ _os.remove(target)
+
+
+def test_python_exec_pathlib_write_text_is_remapped_into_workdir():
+ # pathlib.Path.open / write_text / read_text call io.open directly,
+ # bypassing the builtins.open patch, so the shim must remap io.open too.
+ fname = f"remap_{_uuid.uuid4().hex}.txt"
+ code = (
+ "from pathlib import Path\n"
+ f"p = Path('/mnt/data/{fname}')\n"
+ "p.write_text('pathlib remap')\n"
+ "print(p.read_text())\n"
+ )
+ target = _os.path.join(get_sandbox_workdir(), fname)
+ try:
+ baseline = _python_exec(code, timeout = 60)
+ assert _os.path.isfile(target), baseline
+ with open(target) as f:
+ assert f.read() == "pathlib remap"
+ assert "pathlib remap" in baseline
+ assert "/mnt/data does not exist in this sandbox" in baseline
+ _os.remove(target)
+ streamed = _python_exec(code, timeout = 60, output_callback = lambda _t: None)
+ assert streamed == baseline
+ assert _os.path.isfile(target)
+ finally:
+ if _os.path.exists(target):
+ _os.remove(target)
+
+
+def test_python_exec_hallucinated_absolute_write_is_remapped_into_workdir():
+ # The model invents an absolute path outside the enumerated prefixes and opens
+ # it for writing; the write-mode fallback redirects it to the basename in the
+ # sandbox workdir instead of dying with FileNotFoundError.
+ fname = f"remap_{_uuid.uuid4().hex}.html"
+ hallucinated = f"/nonexistent_root_xyz/Sandbox/{fname}"
+ # Read-back goes through the mapped basename: reads are never redirected, only
+ # the write is healed.
+ code = (
+ f"with open('{hallucinated}', 'w') as f:\n"
+ " f.write('hello fallback')\n"
+ f"print(open('{fname}').read())\n"
+ )
+ target = _os.path.join(get_sandbox_workdir(), fname)
+ try:
+ baseline = _python_exec(code, timeout = 60)
+ assert _os.path.isfile(target), baseline
+ with open(target) as f:
+ assert f.read() == "hello fallback"
+ assert "hello fallback" in baseline
+ assert "does not exist in this sandbox" in baseline
+ _os.remove(target)
+ streamed = _python_exec(code, timeout = 60, output_callback = lambda _t: None)
+ assert streamed == baseline
+ assert _os.path.isfile(target)
+ finally:
+ if _os.path.exists(target):
+ _os.remove(target)
+
+
+def test_python_exec_unremapped_mnt_data_failure_gets_hint():
+ # os.listdir is deliberately not remapped: the failure carries the retry hint
+ # instead, identically with and without streaming.
+ import re as _re
+
+ code = "import os\nos.listdir('/mnt/data/nonexistent_dir_xyz')\n"
+ baseline = _python_exec(code, timeout = 60)
+ assert "FileNotFoundError" in baseline
+ assert "working directory is writable" in baseline
+ streamed = _python_exec(code, timeout = 60, output_callback = lambda _t: None)
+
+ # Normalize each run's random temp filename (byte-identity is per-execution).
+ def normalize(text: str) -> str:
+ return _re.sub(r"studio_exec_\w+\.py", "studio_exec.py", text)
+
+ assert normalize(streamed) == normalize(baseline)
+
+
+def test_bash_exec_missing_path_hint():
+ baseline = _bash_exec("cat /mnt/data/definitely_missing.txt", timeout = 60)
+ assert "No such file or directory" in baseline
+ assert "working directory is writable" in baseline
+ streamed = _bash_exec(
+ "cat /mnt/data/definitely_missing.txt", timeout = 60, output_callback = lambda _t: None
+ )
+ assert streamed == baseline
+
+
+def test_bash_exec_local_failure_gets_no_hint():
+ result = _bash_exec("cat definitely_missing_local_file.txt", timeout = 60)
+ assert "No such file or directory" in result
+ assert "working directory is writable" not in result
+
+
+def test_producer_queue_is_bounded_under_tight_print_loop(monkeypatch):
+ # The consumer-side cap only bounds the concatenated stream; a fast worker can
+ # still enqueue unboundedly while the SSE consumer is backpressured. The producer
+ # boundary now discards callbacks past the cap so the queue cannot grow without
+ # limit (finding 12).
+ import queue as _queue
+
+ from core.inference import tool_stream_exec
+
+ observed = []
+
+ class _TrackingQueue(_queue.Queue):
+ def put(self, *args, **kwargs):
+ result = super().put(*args, **kwargs)
+ observed.append(self.qsize())
+ return result
+
+ monkeypatch.setattr(tool_stream_exec.queue, "Queue", _TrackingQueue)
+
+ def tool(callback):
+ for _ in range(200_000):
+ callback("x")
+ return "done"
+
+ events, result = _run_stream(tool, tool_name = "python")
+ assert result == "done"
+ # At most cap + 1 chars enter the queue, so 1-char items cannot exceed that
+ # regardless of consumer lag.
+ assert observed
+ assert max(observed) <= TOOL_OUTPUT_STREAM_MAX_CHARS + 2
+
+
+def test_continuous_over_cap_output_does_not_starve_heartbeats():
+ # Once the cap is tripped, a continuously producing tool must not spin the drain
+ # forever with no heartbeat: callbacks past the budget never enter the queue, so
+ # the idle heartbeat path resumes (finding 13).
+ release = threading.Event()
+
+ def tool(callback):
+ callback("x" * (TOOL_OUTPUT_STREAM_MAX_CHARS + 10)) # trip the cap
+ while not release.is_set():
+ callback("spam") # discarded at the producer boundary
+ return "done"
+
+ watchdog = threading.Timer(8.0, release.set)
+ watchdog.start()
+ gen = stream_tool_execution(
+ tool,
+ tool_name = "python",
+ heartbeat_interval_s = 0.04,
+ poll_interval_s = 0.02,
+ )
+ events = []
+ result = None
+ try:
+ while True:
+ event = next(gen)
+ events.append(event)
+ if len([e for e in events if e["type"] == "heartbeat"]) >= 2:
+ release.set()
+ except StopIteration as stop:
+ result = stop.value
+ finally:
+ release.set()
+ watchdog.cancel()
+ assert result == "done"
+ assert len([e for e in events if e["type"] == "heartbeat"]) >= 2
+
+
+def test_accepts_output_callback_signature_detection():
+ from core.inference.tool_stream_exec import accepts_output_callback
+
+ def legacy(
+ name,
+ arguments,
+ cancel_event = None,
+ timeout = None,
+ ):
+ return "ok"
+
+ def modern(
+ name,
+ arguments,
+ output_callback = None,
+ ):
+ return "ok"
+
+ def kwargs_only(name, arguments, **kw):
+ return "ok"
+
+ assert accepts_output_callback(legacy) is False
+ assert accepts_output_callback(modern) is True
+ assert accepts_output_callback(kwargs_only) is True
+ # Uninspectable callables (e.g. some builtins) fall back to not-supported.
+ assert accepts_output_callback(len) is False
+
+
[email protected](sys.platform == "win32", reason = "POSIX process groups")
+def test_bash_exec_nonstreaming_cancel_kills_grandchild_after_leader_exit(tmp_path):
+ # NON-streaming cancellation: the leader exits at once while a grandchild holds
+ # stdout. The cancel watcher loops on the leader's poll() and is gone, so before
+ # the fix communicate() blocked until the grandchild finished. The unified drain
+ # kills the captured group on cancel instead.
+ sentinel = tmp_path / "grandchild_ran"
+ command = f"( sleep 3; touch '{sentinel}' ) & echo parent-done"
+ cancel_event = threading.Event()
+ timer = threading.Timer(0.5, cancel_event.set)
+ timer.start()
+ started = time.monotonic()
+ try:
+ result = _bash_exec(command, cancel_event = cancel_event, timeout = 30)
+ finally:
+ timer.cancel()
+ assert time.monotonic() - started < 2.5
+ assert result == "Execution cancelled."
+ time.sleep(3.5)
+ assert not sentinel.exists(), "non-streaming cancel leaked a stdout-holding grandchild"
+
+
[email protected](sys.platform == "win32", reason = "POSIX process groups")
+def test_python_exec_nonstreaming_cancel_kills_grandchild_after_leader_exit(tmp_path):
+ sentinel = tmp_path / "grandchild_ran"
+ code = (
+ "import subprocess\n"
+ f"subprocess.Popen(['bash', '-c', \"sleep 3; touch '{sentinel}'\"])\n"
+ "print('parent-done')\n"
+ )
+ cancel_event = threading.Event()
+ timer = threading.Timer(0.5, cancel_event.set)
+ timer.start()
+ started = time.monotonic()
+ try:
+ result = _python_exec(code, cancel_event = cancel_event, timeout = 30)
+ finally:
+ timer.cancel()
+ assert time.monotonic() - started < 2.5
+ assert result == "Execution cancelled."
+ time.sleep(3.5)
+ assert not sentinel.exists(), "non-streaming cancel leaked a stdout-holding grandchild"
diff --git a/studio/backend/tests/test_tool_stream_generator_drain.py b/studio/backend/tests/test_tool_stream_generator_drain.py
new file mode 100644
index 00000000000..e1d751ab095
--- /dev/null
+++ b/studio/backend/tests/test_tool_stream_generator_drain.py
@@ -0,0 +1,83 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Regression tests for generator-close cleanup in the tool-streaming routes.
+
+Tool streams run ``next(gen)`` in an ``asyncio.to_thread`` worker. Closing the
+generator while that worker is still inside ``next`` raises ``ValueError:
+generator already executing`` and skips the generator's ``finally`` (tool
+cleanup); the routes drain the pending task first (``_drain_pending_next_task``),
+which these tests exercise.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import threading
+
+import pytest
+
+from routes.inference import _drain_pending_next_task
+
+
+def test_drain_before_close_avoids_generator_already_executing():
+ cancel_event = threading.Event()
+ entered = threading.Event()
+ finally_ran = threading.Event()
+
+ def blocking_gen():
+ try:
+ entered.set()
+ # Blocking call inside next(gen) that respects the cancel flag.
+ cancel_event.wait()
+ yield "value"
+ finally:
+ finally_ran.set()
+
+ async def scenario():
+ gen = blocking_gen()
+ next_task = asyncio.create_task(asyncio.to_thread(next, gen, object()))
+ await asyncio.to_thread(entered.wait) # worker now inside next(gen)
+
+ # Closing mid-next races and raises, leaving the finally unrun.
+ with pytest.raises(ValueError):
+ gen.close()
+ assert not finally_ran.is_set()
+
+ # Draining sets the cancel flag so the worker returns; then close is
+ # clean and the generator's finally runs.
+ await _drain_pending_next_task(next_task, cancel_event)
+ gen.close()
+ return
+
+ asyncio.run(scenario())
+ assert finally_ran.is_set()
+
+
+def test_drain_pending_next_task_is_noop_without_task():
+ # None (task already consumed): draining is a no-op, cancel flag untouched.
+ cancel_event = threading.Event()
+
+ asyncio.run(_drain_pending_next_task(None, cancel_event))
+ assert not cancel_event.is_set()
+
+
+def test_drain_pending_next_task_returns_when_worker_finishes():
+ # A worker finishing on its own drains without error; the cancel flag stays
+ # set (the caller is tearing the stream down).
+ cancel_event = threading.Event()
+ release = threading.Event()
+
+ def gen():
+ release.wait()
+ yield "done"
+
+ async def scenario():
+ g = gen()
+ task = asyncio.create_task(asyncio.to_thread(next, g, object()))
+ release.set() # let the worker complete before draining
+ await _drain_pending_next_task(task, cancel_event)
+ assert task.done()
+
+ asyncio.run(scenario())
+ assert cancel_event.is_set()
diff --git a/studio/backend/tests/test_web_fetch_extraction.py b/studio/backend/tests/test_web_fetch_extraction.py
new file mode 100644
index 00000000000..b794ee3e819
--- /dev/null
+++ b/studio/backend/tests/test_web_fetch_extraction.py
@@ -0,0 +1,1196 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Main-content extraction and boilerplate stripping for the web fetch tool.
+
+The HTML fixtures below snapshot the relevant fragments of a real GitHub repo
+page (github.com/unslothai/unsloth, fetched 2026-07): the ``hidden``
+client-side error placeholders ("Uh oh! There was an error while loading."),
+the skip-link / nav / footer furniture, and the README rendered inside
+``<article class="markdown-body">``. No network access is required.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+from core.inference._html_to_md import html_to_markdown
+from core.inference.tools import (
+ _fetch_page_text,
+ _fetch_url_raw,
+ _github_repo_readme_api_url,
+ _looks_like_html,
+)
+
+
+# ── Fixtures: snapshot of GitHub repo page fragments ─────────────
+
+# GitHub ships client-side error placeholders behind the `hidden` attribute (JS
+# reveals them on a failed fetch); a text converter must not surface them.
+_GITHUB_HIDDEN_ERROR_BLOCK = """
+<div data-show-on-forbidden-error hidden>
+ <div class="Box">
+ <div class="blankslate-container">
+ <h3 class="blankslate-heading">Uh oh!</h3>
+ <p class="blankslate-description">
+ <p class="color-fg-muted my-2 mb-2 ws-normal">There was an error while loading.
+ <a class="Link--inTextBlock" href="" aria-label="Please reload this page">Please reload this page</a>.</p>
+ </p>
+ </div>
+ </div>
+</div>
+"""
+
+_GITHUB_PAGE = f"""<!DOCTYPE html>
+<html lang="en">
+<head><title>unslothai/unsloth</title></head>
+<body>
+<a class="px-2 py-4" href="#start-of-content">Skip to content</a>
+<header class="Header-old">
+ <div class="AppHeader-globalBar">
+ <a href="/login">Sign in</a>
+ <a href="/signup">Sign up</a>
+ </div>
+</header>
+<div class="js-notification-shelf"></div>
+<div hidden>
+ You signed in with another tab or window. Reload to refresh your session.
+ You signed out in another tab or window. Reload to refresh your session.
+ You switched accounts on another tab or window. Reload to refresh your session.
+ Dismiss alert
+</div>
+<template>{{{{ message }}}}</template>
+{_GITHUB_HIDDEN_ERROR_BLOCK}
+<main id="js-repo-pjax-container">
+ {_GITHUB_HIDDEN_ERROR_BLOCK}
+ <div id="repository-container-header">
+ <a href="/unslothai">unslothai</a> / <a href="/unslothai/unsloth">unsloth</a>
+ <a href="/login?return_to=%2Funslothai%2Funsloth">Notifications</a>
+ You must be signed in to change notification settings
+ </div>
+ <div class="repository-content">
+ <table aria-labelledby="folders-and-files">
+ <tr><th>Name</th><th>Last commit message</th></tr>
+ <tr><td><a href="/unslothai/unsloth/tree/main/unsloth">unsloth</a></td><td></td></tr>
+ </table>
+ <article class="markdown-body entry-content container-lg" itemprop="text">
+ <h1>Unsloth Studio</h1>
+ <p>Unsloth Studio lets you run and train models locally. Fine-tune and
+ run LLMs on Windows, Linux and macOS with a single install command,
+ then export to GGUF, Ollama, vLLM or Hugging Face when you are done.</p>
+ <h2>Install</h2>
+ <pre>curl -fsSL https://unsloth.ai/install.sh | sh</pre>
+ <p>See the <a href="https://unsloth.ai/docs">documentation</a> for
+ quickstarts, notebooks, and fine-tuning guides for every major model
+ family including Llama, Gemma, Qwen and DeepSeek.</p>
+ </article>
+ </div>
+ <div class="Layout-sidebar">
+ <h2>Languages</h2>
+ <ul>
+ <li><a href="/unslothai/unsloth/search?l=javascript">JavaScript 89.3%</a></li>
+ <li><a href="/unslothai/unsloth/search?l=python">Python 9.7%</a></li>
+ </ul>
+ </div>
+</main>
+<footer>
+ <a href="https://docs.github.com">Docs</a>
+ <a href="https://github.com/contact">Contact</a>
+</footer>
+<div aria-live="polite" aria-hidden="true">You can't perform that action at this time.</div>
+</body>
+</html>
+"""
+
+
+# ── html_to_markdown: hidden elements ────────────────────────────
+
+
+def test_hidden_attribute_subtree_is_dropped():
+ html = "<body><p>visible</p><div hidden><p>secret error text</p></div><p>after</p></body>"
+ out = html_to_markdown(html)
+ assert "visible" in out
+ assert "after" in out
+ assert "secret error text" not in out
+
+
+def test_aria_hidden_true_subtree_is_dropped():
+ html = '<body><p>keep</p><span aria-hidden="true">decoration</span></body>'
+ out = html_to_markdown(html)
+ assert "keep" in out
+ assert "decoration" not in out
+
+
+def test_aria_hidden_false_subtree_is_kept():
+ html = '<body><span aria-hidden="false">still here</span></body>'
+ assert "still here" in html_to_markdown(html)
+
+
+def test_inline_style_display_none_subtree_is_dropped():
+ # Error/loading blocks are often hidden with inline CSS rather than the
+ # ``hidden`` attribute; browsers do not render them, so they must not leak.
+ html = (
+ "<body><p>visible</p>"
+ '<div style="display:none">secret loading block</div>'
+ "<p>after</p></body>"
+ )
+ out = html_to_markdown(html)
+ assert "visible" in out
+ assert "after" in out
+ assert "secret loading block" not in out
+
+
+def test_inline_style_visibility_hidden_subtree_is_dropped():
+ html = '<body><p>keep</p><span style="visibility:hidden">ghost</span></body>'
+ out = html_to_markdown(html)
+ assert "keep" in out
+ assert "ghost" not in out
+
+
+def test_inline_style_display_none_important_is_dropped():
+ # The !important flag must not defeat the display:none detection.
+ html = '<body><p>keep</p><div style="display:none !important">gone</div></body>'
+ out = html_to_markdown(html)
+ assert "keep" in out
+ assert "gone" not in out
+
+
+def test_inline_style_display_none_among_other_declarations():
+ html = (
+ "<body><p>keep</p>" '<div style="color: red; display : none ; margin:0">gone</div></body>'
+ )
+ out = html_to_markdown(html)
+ assert "keep" in out
+ assert "gone" not in out
+
+
+def test_inline_style_visible_display_is_kept():
+ # Over-strip guard: display:block / visibility:visible render, and a value or
+ # URL merely containing the substring "none" must not trigger the hidden path.
+ html = (
+ "<body>"
+ '<div style="display:block">block kept</div>'
+ '<div style="visibility:visible">visible kept</div>'
+ '<a style="background:url(none.png)">link kept</a>'
+ "</body>"
+ )
+ out = html_to_markdown(html)
+ assert "block kept" in out
+ assert "visible kept" in out
+ assert "link kept" in out
+
+
+def test_hidden_recovers_from_omitted_close_tags():
+ # <p hidden> is never closed; the parent </div> must still end the hidden region.
+ html = "<body><div><p hidden>gone</div><p>kept</p></body>"
+ out = html_to_markdown(html)
+ assert "gone" not in out
+ assert "kept" in out
+
+
+def test_nested_hidden_regions():
+ html = "<body><div hidden><div hidden>inner</div>outer</div><p>ok</p></body>"
+ out = html_to_markdown(html)
+ assert "inner" not in out
+ assert "outer" not in out
+ assert "ok" in out
+
+
+def test_hidden_false_is_still_hidden():
+ # ``hidden`` is enumerated: the spec maps invalid/empty values to the Hidden
+ # state, so hidden="false" is NOT rendered and must not reach the Markdown.
+ html = '<body><p>keep</p><div hidden="false">not rendered</div></body>'
+ out = html_to_markdown(html)
+ assert "keep" in out
+ assert "not rendered" not in out
+
+
+def test_hidden_paragraph_omitted_close_does_not_swallow_siblings():
+ # HTML5 optional end tags: a sibling <p> start tag implicitly closes an open
+ # <p hidden>, so the hidden region ends there instead of swallowing siblings.
+ html = (
+ "<body><div><p hidden>secret"
+ "<p>visible one</p><p>visible two</p></div><p>after</p></body>"
+ )
+ out = html_to_markdown(html)
+ assert "secret" not in out
+ assert "visible one" in out
+ assert "visible two" in out
+ assert "after" in out
+
+
+def test_hidden_list_item_omitted_close_keeps_following_items():
+ # <li hidden> without </li> is implicitly closed by the next <li>.
+ html = "<body><ul><li hidden>secret<li>shown A</li><li>shown B</li></ul></body>"
+ out = html_to_markdown(html)
+ assert "secret" not in out
+ assert "shown A" in out
+ assert "shown B" in out
+
+
+def test_hr_implicitly_closes_hidden_paragraph():
+ # Void elements also imply closes: <hr> ends an open <p hidden>.
+ html = "<body><p hidden>secret<hr>kept text</body>"
+ out = html_to_markdown(html)
+ assert "secret" not in out
+ assert "kept text" in out
+
+
+def test_skipped_tag_implicitly_closes_hidden_paragraph():
+ # A skipped block (<nav>/<footer>) also closes an open <p>. The optional-close
+ # bookkeeping must run before the skip, or the never-closed <p hidden> keeps its
+ # hidden mark and swallows every following sibling.
+ for skipped in ("nav", "footer"):
+ html = f"<body><p hidden>secret<{skipped}>chrome</{skipped}>VISIBLE</body>"
+ out = html_to_markdown(html)
+ assert "secret" not in out
+ assert "chrome" not in out
+ assert "VISIBLE" in out
+
+
+def test_hidden_void_element_is_suppressed():
+ # A hidden void element (<hr>/<br>) never joins the open-element stack, so it
+ # must be suppressed inline rather than emitting its markup.
+ html = '<body><p>before</p><hr aria-hidden="true"><p>after</p></body>'
+ out = html_to_markdown(html)
+ assert "before" in out
+ assert "after" in out
+ assert "---" not in out
+
+
+def test_hidden_void_br_emits_no_break():
+ html = "<body><p>one<br hidden>two</p></body>"
+ out = html_to_markdown(html)
+ assert "one" in out
+ assert "two" in out
+ # The hidden <br> must not inject a newline between the two runs.
+ assert "one\ntwo" not in out
+
+
+def test_visible_void_hr_still_renders():
+ # Guard: the suppression must not affect non-hidden void elements.
+ html = "<body><p>a</p><hr><p>b</p></body>"
+ out = html_to_markdown(html)
+ assert "---" in out
+
+
+# ── html_to_markdown: main-content scoping ───────────────────────
+
+
+def test_github_page_main_content_keeps_readme_only():
+ out = html_to_markdown(_GITHUB_PAGE, main_content = True)
+ # README content survives.
+ assert "Unsloth Studio" in out
+ assert "install.sh" in out
+ assert "documentation" in out
+ # Client-side error placeholders and page furniture are gone.
+ assert "Uh oh!" not in out
+ assert "There was an error while loading" not in out
+ assert "Please reload this page" not in out
+ assert "You can't perform that action at this time" not in out
+ assert "Skip to content" not in out
+ assert "Sign in" not in out
+ assert "Reload to refresh your session" not in out
+ assert "JavaScript 89.3%" not in out
+ assert "Languages" not in out
+ assert "Last commit message" not in out
+
+
+def test_main_scope_used_when_no_article():
+ html = """
+ <body>
+ <header><a href="/login">Sign in</a></header>
+ <main><h1>Doc title</h1><p>%s</p></main>
+ <footer>footer junk</footer>
+ </body>
+ """ % ("Body text. " * 40)
+ out = html_to_markdown(html, main_content = True)
+ assert "Doc title" in out
+ assert "Body text." in out
+ assert "Sign in" not in out
+ assert "footer junk" not in out
+
+
+def test_main_content_falls_back_to_full_document():
+ # No article/main and a tiny body: the unscoped conversion is returned.
+ html = "<body><h1>Tiny</h1><p>Just a short page.</p></body>"
+ out = html_to_markdown(html, main_content = True)
+ assert "Tiny" in out
+ assert "Just a short page." in out
+
+
+def test_tiny_article_stub_does_not_hijack_scope():
+ # An <article> with negligible text must not swallow the real content.
+ body_text = "Real content paragraph. " * 30
+ html = f"<body><article>ad</article><main><p>{body_text}</p></main></body>"
+ out = html_to_markdown(html, main_content = True)
+ assert "Real content paragraph." in out
+
+
+def test_sibling_articles_do_not_leak_after_main_selected():
+ # The size gate picks the largest single <article> and renders only that
+ # subtree: sibling articles (related-post cards, comment threads) must not leak
+ # in just because the real article cleared the threshold.
+ real = "Main article body content for selection. " * 20
+ card = "Unrelated related-post card teaser blurb. " * 3
+ cards = "".join(f"<article><p>{card}</p></article>" for _ in range(5))
+ html = f"<body><article><h1>Real</h1><p>{real}</p></article>{cards}</body>"
+ out = html_to_markdown(html, main_content = True)
+ assert "Main article body content" in out
+ assert "Unrelated related-post" not in out
+
+
+def test_default_conversion_unscoped_and_unstripped():
+ # Without main_content the whole document converts (backwards compatible),
+ # boilerplate included; only hidden subtrees are dropped.
+ html = "<body><p>Skip to content</p><div hidden>gone</div><main><p>hello</p></main></body>"
+ out = html_to_markdown(html)
+ assert "Skip to content" in out
+ assert "hello" in out
+ assert "gone" not in out
+
+
+def test_boilerplate_filter_preserves_phrase_inside_real_prose():
+ # The furniture filter once matched by substring, deleting a real sentence that
+ # merely CONTAINS a fragment ("we use cookies"). It must drop only lines COMPOSED
+ # of furniture, keeping real prose that quotes one.
+ body = (
+ "<article><h1>Authentication</h1>"
+ "<p>We use cookies to authenticate API requests and keep sessions safe.</p>"
+ "<p>%s</p></article>"
+ ) % ("Additional documentation content to select the article. " * 8)
+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)
+ assert "We use cookies to authenticate API requests" in out
+
+
+def test_boilerplate_filter_still_drops_standalone_and_stacked_furniture():
+ # A line that is purely furniture is dropped, as is one stacking several
+ # furniture phrases (as GitHub renders them).
+ body = (
+ "<article>"
+ "<p>Skip to content</p>"
+ "<p>You signed in with another tab or window. Reload to refresh your session.</p>"
+ "<p>Real README body. %s</p>"
+ "</article>"
+ ) % ("Genuine documentation text. " * 8)
+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)
+ assert "Real README body." in out
+ assert "Skip to content" not in out
+ assert "Reload to refresh your session" not in out
+
+
+def test_boilerplate_not_stripped_inside_code_fences():
+ html = (
+ "<body><article><p>%s</p>"
+ "<pre>assert 'There was an error while loading' in page</pre>"
+ "</article></body>" % ("Prose. " * 40)
+ )
+ out = html_to_markdown(html, main_content = True)
+ assert "There was an error while loading" in out
+
+
+def test_aside_callout_inside_article_is_kept():
+ # Docs render notes/warnings as <aside> callouts. An aside inside the selected
+ # article/main scope is real content and must survive; dropping it unconditionally
+ # loses page text.
+ body = (
+ "<article><h1>Guide</h1>"
+ "<p>%s</p>"
+ "<aside class='admonition warning'><strong>Warning:</strong> "
+ "This operation is destructive and cannot be undone.</aside>"
+ "<p>Trailing paragraph.</p></article>"
+ ) % ("Documentation body text to select the article scope. " * 6)
+ out = html_to_markdown(f"<body>{body}</body>", main_content = True)
+ assert "This operation is destructive and cannot be undone." in out
+ assert "Warning:" in out
+ # Also kept in the unscoped (backwards-compatible) conversion.
+ out_full = html_to_markdown(f"<body>{body}</body>")
+ assert "This operation is destructive and cannot be undone." in out_full
+
+
+# ── GitHub README rewrite ────────────────────────────────────────
+
+
+def test_github_repo_url_maps_to_readme_api():
+ assert (
+ _github_repo_readme_api_url("https://github.com/unslothai/unsloth")
+ == "https://api.github.com/repos/unslothai/unsloth/readme"
+ )
+ assert (
+ _github_repo_readme_api_url("https://github.com/unslothai/unsloth/")
+ == "https://api.github.com/repos/unslothai/unsloth/readme"
+ )
+ assert (
+ _github_repo_readme_api_url("http://www.github.com/owner/repo.git")
+ == "https://api.github.com/repos/owner/repo/readme"
+ )
+
+
+def test_github_non_repo_urls_are_not_rewritten():
+ for url in (
+ "https://github.com/unslothai/unsloth/tree/main/studio",
+ "https://github.com/unslothai/unsloth/issues/123",
+ "https://github.com/topics/llm",
+ "https://github.com/orgs/unslothai/repositories",
+ "https://github.com/login/oauth",
+ "https://github.com/unslothai",
+ "https://example.com/owner/repo",
+ "https://raw.githubusercontent.com/owner/repo/main/README.md",
+ ):
+ assert _github_repo_readme_api_url(url) is None, url
+
+
+def test_fetch_page_text_prefers_github_readme(monkeypatch):
+ calls = []
+
+ def fake_fetch(
+ url,
+ timeout = 30,
+ extra_headers = None,
+ deadline = None,
+ cancel_event = None,
+ ):
+ calls.append((url, extra_headers))
+ assert url == "https://api.github.com/repos/unslothai/unsloth/readme"
+ return None, "# Unsloth\n\nFine-tune LLMs faster.", "text/plain"
+
+ monkeypatch.setattr("core.inference.tools._fetch_url_raw", fake_fetch)
+ out = _fetch_page_text("https://github.com/unslothai/unsloth")
+ assert "Fine-tune LLMs faster." in out
+ assert "README of https://github.com/unslothai/unsloth" in out
+ assert len(calls) == 1
+ assert calls[0][1]["Accept"] == "application/vnd.github.raw+json"
+
+
+def test_fetch_page_text_keeps_html_readme_from_api(monkeypatch):
+ # A repo whose README is HTML returns HTML from the README API with a 200. That
+ # success is authoritative: convert to Markdown and keep it, never discard it in
+ # favour of the repo root page's UI chrome.
+ html_readme = (
+ "<!doctype html><html><body>"
+ "<h1>Project Title</h1>"
+ "<p>Install with the one-line script and read the docs.</p>"
+ "</body></html>"
+ )
+ calls = []
+
+ def fake_fetch(
+ url,
+ timeout = 30,
+ extra_headers = None,
+ deadline = None,
+ cancel_event = None,
+ ):
+ calls.append(url)
+ assert url == "https://api.github.com/repos/unslothai/unsloth/readme"
+ return None, html_readme, "text/html"
+
+ monkeypatch.setattr("core.inference.tools._fetch_url_raw", fake_fetch)
+ out = _fetch_page_text("https://github.com/unslothai/unsloth")
+ # The successful README is converted and returned; no fallback fetch fires.
+ assert "README of https://github.com/unslothai/unsloth" in out
+ assert "Project Title" in out
+ assert "Install with the one-line script" in out
+ assert "<html" not in out
+ assert len(calls) == 1
+
+
+def test_fetch_page_text_falls_back_to_html_when_readme_api_fails(monkeypatch):
+ def fake_fetch(
+ url,
+ timeout = 30,
+ extra_headers = None,
+ deadline = None,
+ cancel_event = None,
+ ):
+ if url.startswith("https://api.github.com/"):
+ return "Failed to fetch URL: HTTP 403 rate limited", "", ""
+ return None, _GITHUB_PAGE, "text/html"
+
+ monkeypatch.setattr("core.inference.tools._fetch_url_raw", fake_fetch)
+ out = _fetch_page_text("https://github.com/unslothai/unsloth")
+ # Fallback converts the HTML page with the main-content heuristic.
+ assert "Unsloth Studio" in out
+ assert "Uh oh!" not in out
+ assert "There was an error while loading" not in out
+
+
+def test_fetch_page_text_non_html_returned_raw(monkeypatch):
+ raw = "line one\n indented code\nline three"
+
+ def fake_fetch(
+ url,
+ timeout = 30,
+ extra_headers = None,
+ deadline = None,
+ cancel_event = None,
+ ):
+ return None, raw, "text/plain"
+
+ monkeypatch.setattr("core.inference.tools._fetch_url_raw", fake_fetch)
+ out = _fetch_page_text("https://raw.githubusercontent.com/o/r/main/file.txt")
+ # Whitespace preserved: the HTML renderer would have collapsed it.
+ assert " indented code" in out
+
+
+def test_fetch_page_text_html_conversion(monkeypatch):
+ def fake_fetch(
+ url,
+ timeout = 30,
+ extra_headers = None,
+ deadline = None,
+ cancel_event = None,
+ ):
+ return None, _GITHUB_PAGE, "text/html"
+
+ monkeypatch.setattr("core.inference.tools._fetch_url_raw", fake_fetch)
+ out = _fetch_page_text("https://github.com/unslothai/unsloth/tree/main")
+ assert "Unsloth Studio" in out
+ assert "Uh oh!" not in out
+
+
+def test_fetch_page_text_propagates_fetch_errors(monkeypatch):
+ def fake_fetch(
+ url,
+ timeout = 30,
+ extra_headers = None,
+ deadline = None,
+ cancel_event = None,
+ ):
+ return "Failed to fetch URL: HTTP 404 Not Found", "", ""
+
+ monkeypatch.setattr("core.inference.tools._fetch_url_raw", fake_fetch)
+ assert _fetch_page_text("https://example.com/missing") == (
+ "Failed to fetch URL: HTTP 404 Not Found"
+ )
+
+
+def test_looks_like_html():
+ assert _looks_like_html("<!DOCTYPE html><html></html>")
+ assert _looks_like_html("\n <HTML lang='en'>")
+ assert not _looks_like_html("# Markdown README\n\n<h1>embedded html later</h1>")
+ assert not _looks_like_html("plain text")
+
+
+def test_looks_like_html_markdown_with_leading_fenced_example_stays_markdown():
+ # A Markdown README OPENING with a fenced HTML example must not be sniffed as
+ # HTML just because a doctype/tag appears in the first 256 chars; html_to_markdown
+ # would corrupt the fences and prose.
+ fenced = (
+ "```html\n<!DOCTYPE html>\n<html><body><div>hi</div></body></html>\n```\n\n# Real README\n"
+ )
+ assert not _looks_like_html(fenced)
+ # Prose that mentions a tag inline, and a centered-logo README that opens
+ # with <p align>/<div align>/<h1 align>, also stay Markdown.
+ assert not _looks_like_html("Use the <html> element to start a page.")
+ assert not _looks_like_html('<p align="center"><img src="logo.png"></p>\n\n# Project\n')
+ assert not _looks_like_html('<div align="center">\n\n# Project\n\n</div>\n')
+ assert not _looks_like_html('<h1 align="center">Project</h1>\n\nMarkdown body.\n')
+ # An autolink is not a tag opener.
+ assert not _looks_like_html("<https://example.com> is the homepage")
+
+
+def test_looks_like_html_detects_bare_fragments():
+ # A body that is a bare HTML fragment (no <html>/doctype) must still be
+ # recognized so it is converted to Markdown.
+ assert _looks_like_html("<body><p>hello</p></body>")
+ assert _looks_like_html("\n<article><h1>Title</h1><p>Body</p></article>")
+ assert _looks_like_html("<section>content</section>")
+
+
+def test_looks_like_html_leading_table_stays_markdown():
+ # Markdown READMEs routinely open with a raw HTML <table> badge row or logo
+ # layout, then continue in Markdown. Sniffing that as HTML would collapse the
+ # Markdown body, so a leading <table> (and its row/cell children) must stay
+ # Markdown, like the excluded <div align>/<p align> layout headers.
+ assert not _looks_like_html("<table><tr><td>cell</td></tr></table>")
+ assert not _looks_like_html(
+ '<table align="center"><tr><td><img src="logo.png"></td></tr></table>\n\n# Project\n'
+ )
+ assert not _looks_like_html("<tr><td>cell</td></tr>")
+
+
+def test_fetch_page_text_keeps_markdown_readme_with_html_example(monkeypatch):
+ # A Markdown README opening with a fenced HTML snippet must be served verbatim,
+ # never run through html_to_markdown (which would drop the fences/tags).
+ md_readme = (
+ "```html\n"
+ "<!DOCTYPE html>\n"
+ "<html><body><h1>Demo</h1></body></html>\n"
+ "```\n\n"
+ "# My Project\n\nInstall and run.\n"
+ )
+
+ def fake_fetch(
+ url,
+ timeout = 30,
+ extra_headers = None,
+ deadline = None,
+ cancel_event = None,
+ ):
+ assert url == "https://api.github.com/repos/unslothai/unsloth/readme"
+ return None, md_readme, "text/plain"
+
+ monkeypatch.setattr("core.inference.tools._fetch_url_raw", fake_fetch)
+ out = _fetch_page_text("https://github.com/unslothai/unsloth")
+ assert "README of https://github.com/unslothai/unsloth" in out
+ # Markdown preserved verbatim: the fence and literal tags survive.
+ assert "```html" in out
+ assert "<!DOCTYPE html>" in out
+ assert "# My Project" in out
+
+
+def test_fetch_page_text_keeps_markdown_readme_with_leading_table(monkeypatch):
+ # A README opening with a raw HTML <table> badge/layout row then continuing in
+ # Markdown must be served verbatim, never run through html_to_markdown (which
+ # would collapse the list/fence/heading body onto one line).
+ md_readme = (
+ '<table align="center">\n'
+ '<tr><td><img src="logo.png"></td><td>Badges</td></tr>\n'
+ "</table>\n\n"
+ "# My Project\n\n"
+ "- feature one\n"
+ "- feature two\n\n"
+ "```python\nprint('hi')\n```\n"
+ )
+
+ def fake_fetch(
+ url,
+ timeout = 30,
+ extra_headers = None,
+ deadline = None,
+ cancel_event = None,
+ ):
+ assert url == "https://api.github.com/repos/unslothai/unsloth/readme"
+ return None, md_readme, "text/plain"
+
+ monkeypatch.setattr("core.inference.tools._fetch_url_raw", fake_fetch)
+ out = _fetch_page_text("https://github.com/unslothai/unsloth")
+ assert "README of https://github.com/unslothai/unsloth" in out
+ # Markdown body verbatim: list, fence and heading survive on their own lines.
+ assert "- feature one\n- feature two" in out
+ assert "```python" in out
+ assert "# My Project" in out
+
+
+def test_fetch_url_raw_missing_content_type_reported_empty(monkeypatch):
+ # Message.get_content_type() falls back to the RFC 2045 "text/plain" default
+ # when the header is absent; _fetch_url_raw must report "" instead so the HTML
+ # sniffing fallback can fire.
+ import email
+ import urllib.request
+
+ class _FakeResp:
+ headers = email.message_from_string("")
+
+ def __init__(self):
+ self._body = b"<html><body>hello</body></html>"
+
+ def read(self, n = -1):
+ # Hand back the body once, then EOF, so the chunked reader terminates.
+ body, self._body = self._body, b""
+ return body
+
+ class _FakeOpener:
+ def open(
+ self,
+ req,
+ timeout = None,
+ ):
+ return _FakeResp()
+
+ monkeypatch.setattr(
+ "core.inference.tools._validate_and_resolve_host",
+ lambda host, port: (True, "", "203.0.113.7"),
+ )
+ monkeypatch.setattr(urllib.request, "build_opener", lambda *handlers: _FakeOpener())
+ err, body, content_type = _fetch_url_raw("https://example.com/")
+ assert err is None
+ assert "hello" in body
+ assert content_type == ""
+
+
+def test_fetch_page_text_missing_content_type_html_sniffed(monkeypatch):
+ # A header-less server returning an HTML body must still be converted.
+ def fake_fetch(
+ url,
+ timeout = 30,
+ extra_headers = None,
+ deadline = None,
+ cancel_event = None,
+ ):
+ return None, _GITHUB_PAGE, ""
+
+ monkeypatch.setattr("core.inference.tools._fetch_url_raw", fake_fetch)
+ out = _fetch_page_text("https://example.com/no-content-type")
+ assert "Unsloth Studio" in out
+ assert "<html" not in out
+ assert "Uh oh!" not in out
+
+
+def test_fetch_page_text_missing_content_type_fragment_converted(monkeypatch):
+ # A header-less server returning a bare HTML fragment (no <html>/doctype) must
+ # still be sniffed as HTML and converted, not served as raw markup.
+ fragment = "<article><h1>Doc Title</h1><p>Readable fragment body.</p></article>"
+
+ def fake_fetch(
+ url,
+ timeout = 30,
+ extra_headers = None,
+ deadline = None,
+ cancel_event = None,
+ ):
+ return None, fragment, ""
+
+ monkeypatch.setattr("core.inference.tools._fetch_url_raw", fake_fetch)
+ out = _fetch_page_text("https://example.com/fragment")
+ assert "Doc Title" in out
+ assert "Readable fragment body." in out
+ assert "<article" not in out
+
+
+def test_fetch_page_text_missing_content_type_plain_text_raw(monkeypatch):
+ # A header-less server returning plain text stays raw (whitespace kept).
+ raw = "line one\n indented code\nline three"
+
+ def fake_fetch(
+ url,
+ timeout = 30,
+ extra_headers = None,
+ deadline = None,
+ cancel_event = None,
+ ):
+ return None, raw, ""
+
+ monkeypatch.setattr("core.inference.tools._fetch_url_raw", fake_fetch)
+ out = _fetch_page_text("https://example.com/no-content-type.txt")
+ assert " indented code" in out
+
+
+def test_fetch_page_text_mislabeled_text_plain_html_converted(monkeypatch):
+ # An explicit text/plain header on an HTML body is sniffed and converted, like
+ # the pre-extraction behavior of always converting HTML pages.
+ def fake_fetch(
+ url,
+ timeout = 30,
+ extra_headers = None,
+ deadline = None,
+ cancel_event = None,
+ ):
+ return None, _GITHUB_PAGE, "text/plain"
+
+ monkeypatch.setattr("core.inference.tools._fetch_url_raw", fake_fetch)
+ out = _fetch_page_text("https://example.com/mislabeled")
+ assert "Unsloth Studio" in out
+ assert "<html" not in out
+
+
+# ── implicit-close past unclosed inline descendants (finding 14) ──
+
+
+def test_hidden_paragraph_with_inline_child_implicitly_closed_by_block():
+ # A browser closes an open <p> when a <div> arrives, even with an unclosed
+ # <span> on top of it. The hidden region must end there, not swallow the
+ # following visible blocks.
+ html = "<body><p hidden><span>secret<div>visible div</div><p>visible paragraph</body>"
+ out = html_to_markdown(html)
+ assert "secret" not in out
+ assert "visible div" in out
+ assert "visible paragraph" in out
+
+
+def test_hidden_list_item_with_inline_child_closed_by_next_item():
+ html = "<body><ul><li hidden><span>secret<li>visible item</ul><p>after</p></body>"
+ out = html_to_markdown(html)
+ assert "secret" not in out
+ assert "visible item" in out
+ assert "after" in out
+
+
+# ── nested hidden list/table contents must stay suppressed ──
+
+
+def test_nested_hidden_list_does_not_leak_child_items():
+ # The nested <ul> re-scopes the item, so the inner <li> is a DESCENDANT of the
+ # hidden outer <li>, not an optional-close sibling. Optional-end-tag recovery
+ # must not cross the intervening <ul>, or the outer li's hidden mark is popped
+ # and the nested text leaks.
+ html = (
+ "<body><ul>"
+ "<li hidden>parent<ul><li>secret child</li></ul></li>"
+ "<li>visible sibling</li>"
+ "</ul></body>"
+ )
+ out = html_to_markdown(html)
+ assert "parent" not in out
+ assert "secret child" not in out
+ assert "visible sibling" in out
+
+
+def test_nested_hidden_list_with_omitted_closes_stays_suppressed():
+ # Same leak, doubly nested with omitted </li>/</ul>. Every hidden descendant
+ # stays gone; the following visible sibling (which implicitly closes the hidden
+ # outer <li>) still renders.
+ html = (
+ "<body><ul>"
+ "<li hidden>parent<ul><li>secret child<ul><li>deeper secret</ul></li></ul>"
+ "<li>visible sibling"
+ "</ul></body>"
+ )
+ out = html_to_markdown(html)
+ assert "parent" not in out
+ assert "secret child" not in out
+ assert "deeper secret" not in out
+ assert "visible sibling" in out
+
+
+def test_nested_hidden_table_does_not_leak_inner_cells():
+ # A nested <table> re-scopes <tr>/<td>: an inner <td> must not be an
+ # optional-close sibling of a hidden outer <td> across the nested table.
+ html = (
+ "<body><table><tr>"
+ "<td hidden>outer<table><tr><td>secret cell</td></tr></table></td>"
+ "<td>visible cell</td>"
+ "</tr></table></body>"
+ )
+ out = html_to_markdown(html)
+ assert "secret cell" not in out
+ assert "visible cell" in out
+
+
+# ── aggregate tiny <article> cards must not displace <main> (finding 15) ──
+
+
+def test_many_tiny_articles_do_not_displace_substantial_main():
+ cards = "".join(
+ f"<article><h2>Teaser {i}</h2><p>Advertisement card blurb.</p></article>" for i in range(12)
+ )
+ main_body = "Authoritative main documentation content. " * 30
+ html = f"<body>{cards}<main><h1>Real page</h1><p>{main_body}</p></main></body>"
+ out = html_to_markdown(html, main_content = True)
+ assert "Authoritative main documentation content." in out
+ assert "Advertisement card blurb." not in out
+
+
+def test_single_substantial_article_still_preferred_over_main():
+ # GitHub-README case: one substantial <article> inside <main> must still win
+ # over sibling <main> furniture.
+ article_body = "Real README documentation body text. " * 20
+ html = (
+ "<body><main>"
+ f"<article><h1>Guide</h1><p>{article_body}</p></article>"
+ "<div><h2>Languages</h2><p>JavaScript 89.3%</p></div>"
+ "</main></body>"
+ )
+ out = html_to_markdown(html, main_content = True)
+ assert "Real README documentation body text." in out
+ assert "JavaScript 89.3%" not in out
+
+
+# ── truncated (unclosed) main-content scopes must still be scored ──
+
+
+def test_truncated_open_article_scope_is_scored_and_preferred():
+ # _fetch_url_raw caps large pages, so the download can end before the closing
+ # </article>. The scope is still the main content and must be preferred over the
+ # whole document (which re-leaks the page chrome).
+ chrome = "<nav>Skip to content</nav><div>Repository file tree and page chrome.</div>"
+ article_body = "Real README documentation body text. " * 20
+ # No closing </article> / </body> -- the fetch cap truncated the page.
+ html = f"<body>{chrome}<article><h1>Guide</h1><p>{article_body}</p>"
+ out = html_to_markdown(html, main_content = True)
+ assert "Real README documentation body text." in out
+ assert "Repository file tree and page chrome." not in out
+
+
+def test_truncated_open_main_scope_is_scored_and_preferred():
+ chrome = "<nav>Skip to content</nav><div>Repository file tree and page chrome.</div>"
+ main_body = "Authoritative main documentation content. " * 30
+ html = f"<body>{chrome}<main><h1>Doc</h1><p>{main_body}</p>"
+ out = html_to_markdown(html, main_content = True)
+ assert "Authoritative main documentation content." in out
+ assert "Repository file tree and page chrome." not in out
+
+
+# ── overall fetch deadline + cancellation (no per-hop timeout blowup) ──
+
+
+def test_fetch_url_raw_overall_deadline_aborts_across_redirects(monkeypatch):
+ # Each hop advances a fake clock by 5s; an 8s overall budget is exhausted on the
+ # third hop even though every hop stays within its own socket timeout. Without
+ # the deadline this would redirect until the 5-hop cap, so the "timed out" error
+ # proves the overall budget aborted it, not the hop cap.
+ import urllib.request
+ from urllib.error import HTTPError
+
+ import core.inference.tools as tools_mod
+
+ clock = {"t": 1000.0}
+ monkeypatch.setattr(tools_mod.time, "monotonic", lambda: clock["t"])
+
+ hops = {"n": 0}
+
+ class _RedirectingOpener:
+ def open(
+ self,
+ req,
+ timeout = None,
+ ):
+ clock["t"] += 5.0
+ hops["n"] += 1
+ raise HTTPError(
+ req.full_url,
+ 302,
+ "Found",
+ {"Location": "https://example.com/next"},
+ None,
+ )
+
+ monkeypatch.setattr(
+ tools_mod,
+ "_validate_and_resolve_host",
+ lambda host, port: (True, "", "203.0.113.7"),
+ )
+ monkeypatch.setattr(urllib.request, "build_opener", lambda *handlers: _RedirectingOpener())
+
+ err, body, content_type = tools_mod._fetch_url_raw(
+ "https://example.com/start",
+ timeout = 30,
+ deadline = clock["t"] + 8.0,
+ )
+ assert err == "Failed to fetch URL: timed out."
+ assert body == ""
+ assert hops["n"] < 5
+
+
+def test_fetch_url_raw_cancel_event_aborts_before_network(monkeypatch):
+ # A set cancel_event (client disconnected) stops the fetch before it opens any
+ # socket, so a dropped stream cannot leave a tool blocking on the wire.
+ import threading
+ import urllib.request
+
+ import core.inference.tools as tools_mod
+
+ ev = threading.Event()
+ ev.set()
+ opened = {"n": 0}
+
+ class _Opener:
+ def open(
+ self,
+ req,
+ timeout = None,
+ ):
+ opened["n"] += 1
+ raise AssertionError("network must not be touched after cancel")
+
+ monkeypatch.setattr(
+ tools_mod,
+ "_validate_and_resolve_host",
+ lambda host, port: (True, "", "203.0.113.7"),
+ )
+ monkeypatch.setattr(urllib.request, "build_opener", lambda *handlers: _Opener())
+
+ err, body, content_type = tools_mod._fetch_url_raw(
+ "https://example.com/",
+ cancel_event = ev,
+ )
+ assert err == "Failed to fetch URL: cancelled."
+ assert opened["n"] == 0
+
+
+def test_fetch_page_text_shares_one_deadline_across_readme_and_fallback(monkeypatch):
+ # The README API attempt and its HTML fallback must draw from ONE budget: a
+ # failed API call cannot hand the fallback a fresh full timeout.
+ seen_deadlines = []
+
+ def fake_fetch(
+ url,
+ timeout = 30,
+ extra_headers = None,
+ deadline = None,
+ cancel_event = None,
+ ):
+ seen_deadlines.append(deadline)
+ # Fail the README API so the HTML fallback also runs.
+ return "Failed to fetch URL: HTTP 429 rate limited", "", ""
+
+ monkeypatch.setattr("core.inference.tools._fetch_url_raw", fake_fetch)
+ out = _fetch_page_text("https://github.com/unslothai/unsloth", timeout = 30)
+ assert out == "Failed to fetch URL: HTTP 429 rate limited"
+ # Both attempts ran and shared the same, single deadline value.
+ assert len(seen_deadlines) == 2
+ assert seen_deadlines[0] is not None
+ assert seen_deadlines[0] == seen_deadlines[1]
+
+
+# -- overall deadline reaches the body read, the resolver, and the query path --
+
+
+def test_fetch_url_raw_deadline_aborts_slow_body(monkeypatch):
+ # A server dribbling the body must not stretch the read past the overall
+ # deadline: the body is read in chunks with the budget re-checked between them,
+ # so a single slow resp.read cannot outlast the fetch budget.
+ import email
+ import urllib.request
+
+ import core.inference.tools as tools_mod
+
+ clock = {"t": 1000.0}
+ monkeypatch.setattr(tools_mod.time, "monotonic", lambda: clock["t"])
+
+ class _DrippingResp:
+ headers = email.message_from_string("")
+
+ def read(self, n = -1):
+ # One chunk, then jump the clock past the deadline so the next
+ # between-chunk budget check aborts instead of reading forever.
+ clock["t"] += 10.0
+ return b"x" * 16
+
+ def close(self):
+ pass
+
+ class _Opener:
+ def open(
+ self,
+ req,
+ timeout = None,
+ ):
+ return _DrippingResp()
+
+ monkeypatch.setattr(
+ tools_mod,
+ "_validate_and_resolve_host",
+ lambda host, port: (True, "", "203.0.113.7"),
+ )
+ monkeypatch.setattr(urllib.request, "build_opener", lambda *handlers: _Opener())
+
+ err, body, content_type = tools_mod._fetch_url_raw(
+ "https://example.com/",
+ timeout = 30,
+ deadline = clock["t"] + 5.0,
+ )
+ assert err == "Failed to fetch URL: timed out."
+ assert body == ""
+
+
+def test_resolve_with_budget_aborts_on_slow_resolver(monkeypatch):
+ # getaddrinfo has no deadline of its own; a resolver slower than the budget must
+ # abort on time instead of blocking the whole fetch.
+ import threading
+
+ import core.inference.tools as tools_mod
+
+ clock = {"t": 1000.0}
+ monkeypatch.setattr(tools_mod.time, "monotonic", lambda: clock["t"])
+
+ release = threading.Event()
+
+ def slow_resolve(host, port):
+ release.wait(5.0) # block until released; the budget should abort first
+ return True, "", "203.0.113.7"
+
+ monkeypatch.setattr(tools_mod, "_validate_and_resolve_host", slow_resolve)
+
+ def advance_past_deadline():
+ import time as _t
+ _t.sleep(0.1)
+ clock["t"] += 100.0
+
+ t = threading.Thread(target = advance_past_deadline, daemon = True)
+ t.start()
+ try:
+ ok, reason, ip = tools_mod._resolve_with_budget(
+ "example.com",
+ 443,
+ 1005.0,
+ None,
+ )
+ finally:
+ release.set()
+ assert ok is False
+ assert reason == "Failed to fetch URL: timed out."
+
+
+def test_web_search_query_cancelled_skips_search(monkeypatch):
+ # A pre-set cancel_event (client disconnected) skips the blocking DDGS query,
+ # matching the direct-URL path's cancellation.
+ import sys
+ import threading
+ import types
+
+ import core.inference.tools as tools_mod
+
+ ev = threading.Event()
+ ev.set()
+ called = {"n": 0}
+
+ class _DDGS:
+ def __init__(self, *a, **k):
+ called["n"] += 1
+
+ def text(self, *a, **k):
+ called["n"] += 1
+ return []
+
+ fake_mod = types.ModuleType("ddgs")
+ fake_mod.DDGS = _DDGS
+ monkeypatch.setitem(sys.modules, "ddgs", fake_mod)
+
+ out = tools_mod._web_search("some query", cancel_event = ev)
+ assert out == "Search cancelled."
+ assert called["n"] == 0
+
+
+def test_fetch_page_text_markdown_readme_with_leading_block_tag_stays_markdown(monkeypatch):
+ # A raw-Markdown README that OPENS with an HTML block tag (<blockquote>, <ul>,
+ # <pre>, ...) must not be run through html_to_markdown, which would collapse its
+ # headings/list/fence. Only a real HTML document (doctype / <html>) is converted.
+ md_readme = (
+ "<blockquote>Note: pre-release.</blockquote>\n\n"
+ "# My Project\n\n"
+ "Install:\n\n"
+ "- step one\n"
+ "- step two\n\n"
+ "```bash\npip install myproject\n```\n"
+ )
+
+ def fake_fetch(
+ url,
+ timeout = 30,
+ extra_headers = None,
+ deadline = None,
+ cancel_event = None,
+ ):
+ assert url == "https://api.github.com/repos/unslothai/unsloth/readme"
+ return None, md_readme, "text/plain"
+
+ monkeypatch.setattr("core.inference.tools._fetch_url_raw", fake_fetch)
+ out = _fetch_page_text("https://github.com/unslothai/unsloth")
+ assert "README of https://github.com/unslothai/unsloth" in out
+ # Markdown structure survives verbatim (heading, list, fenced code).
+ assert "# My Project" in out
+ assert "- step one" in out
+ assert "```bash" in out
+
+
+def test_looks_like_html_document_only_matches_real_documents():
+ from core.inference.tools import _looks_like_html_document
+
+ assert _looks_like_html_document("<!doctype html><html><body>x</body></html>")
+ assert _looks_like_html_document("\n <HTML lang='en'>")
+ assert _looks_like_html_document("<body><h1>x</h1></body>")
+ # Block tags a Markdown README can open with are NOT full documents.
+ for frag in (
+ "<blockquote>q</blockquote>",
+ "<ul><li>x</li></ul>",
+ "<pre>x</pre>",
+ "<dl><dt>x</dt></dl>",
+ ):
+ assert not _looks_like_html_document(frag), frag
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index 93cf162ca7f..11d91cc9524 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -3444,8 +3444,18 @@ const ComposerRightControls: FC<{
const MessageError: FC = () => {
return (
<MessagePrimitive.Error>
- <ErrorPrimitive.Root className="aui-message-error-root mt-2 rounded-md bg-destructive/10 p-3 text-destructive text-sm dark:bg-destructive/5 dark:text-red-200">
- <ErrorPrimitive.Message className="aui-message-error-message line-clamp-2" />
+ <ErrorPrimitive.Root className="aui-message-error-root mt-2 flex flex-wrap items-center gap-x-3 gap-y-2 rounded-md bg-destructive/10 p-3 text-destructive text-sm dark:bg-destructive/5 dark:text-red-200">
+ <ErrorPrimitive.Message className="aui-message-error-message line-clamp-2 min-w-0 flex-1" />
+ {/* Recovery path for interrupted/failed turns: regenerate in place. */}
+ <ActionBarPrimitive.Reload asChild={true}>
+ <button
+ type="button"
+ className="aui-message-error-retry inline-flex shrink-0 items-center gap-1.5 rounded-md border border-destructive/40 px-2.5 py-1 text-xs font-medium transition-colors hover:bg-destructive/15"
+ >
+ <RefreshCwIcon strokeWidth={1.75} className="size-3.5" />
+ Retry
+ </button>
+ </ActionBarPrimitive.Reload>
</ErrorPrimitive.Root>
</MessagePrimitive.Error>
);
diff --git a/studio/frontend/src/components/assistant-ui/tool-group.tsx b/studio/frontend/src/components/assistant-ui/tool-group.tsx
index 74b5e023818..469c449a700 100644
--- a/studio/frontend/src/components/assistant-ui/tool-group.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-group.tsx
@@ -10,6 +10,7 @@ import {
} from "react";
import { useAuiState } from "@assistant-ui/react";
import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
+import { toolOutputKey, useToolPaneScope } from "@/features/chat";
import { ChevronDownIcon } from "lucide-react";
import { Wrench01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
@@ -235,13 +236,29 @@ const ToolGroupImpl: FC<
const messageRunning = useAuiState(
({ message }) => message.status?.type === "running",
);
- // Keep the group open once a confirmation forced it open, so answering an
- // allow/deny doesn't snap it shut between sequential tool calls. It reverts
- // to the default collapsed state once the turn finishes.
+ // Force the group open when any call is receiving tool_output events.
+ const toolLiveOutput = useChatRuntimeStore((s) => s.toolLiveOutput);
+ const paneScope = useToolPaneScope();
+ const hasLiveOutput = useAuiState(({ message }) =>
+ message.parts
+ .slice(startIndex, endIndex + 1)
+ .some(
+ (part) =>
+ part.type === "tool-call" &&
+ Object.prototype.hasOwnProperty.call(
+ toolLiveOutput,
+ toolOutputKey(paneScope, part.toolCallId),
+ ),
+ ),
+ );
+ // Keep the group open once a confirmation or live output forced it (so an
+ // allow/deny doesn't snap it shut between calls); reverts once the turn ends.
const forcedOpenRef = useRef(false);
- if (hasPendingConfirmation) forcedOpenRef.current = true;
+ if (hasPendingConfirmation || hasLiveOutput) forcedOpenRef.current = true;
const forceOpen =
- hasPendingConfirmation || (forcedOpenRef.current && messageRunning);
+ hasPendingConfirmation ||
+ (hasLiveOutput && messageRunning) ||
+ (forcedOpenRef.current && messageRunning);
// Render single tool calls and canvases directly so cards never hide in a
// collapsed group.
diff --git a/studio/frontend/src/components/assistant-ui/tool-live-output.tsx b/studio/frontend/src/components/assistant-ui/tool-live-output.tsx
new file mode 100644
index 00000000000..3434783f0a1
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/tool-live-output.tsx
@@ -0,0 +1,63 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"use client";
+
+import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
+import { toolOutputKey, useToolPaneScope } from "@/features/chat";
+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
+ * the transient `toolLiveOutput` map fed by `tool_output` SSE events. Renders
+ * nothing until the first chunk, then follows the tail. Mounted only while
+ * running; the finished card shows the persisted result instead.
+ */
+export function ToolLiveOutput({ toolCallId }: { toolCallId: string }) {
+ const paneScope = useToolPaneScope();
+ const output = useChatRuntimeStore(
+ (s) => s.toolLiveOutput[toolOutputKey(paneScope, toolCallId)] ?? "",
+ );
+ 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]);
+
+ const handleScroll = () => {
+ const el = scrollRef.current;
+ if (!el) {
+ return;
+ }
+ // Within 40px of the bottom counts as pinned (tolerates small nudges).
+ pinnedToBottom.current =
+ el.scrollHeight - el.scrollTop - el.clientHeight < 40;
+ };
+
+ useEffect(() => {
+ const el = scrollRef.current;
+ if (el && pinnedToBottom.current) {
+ el.scrollTop = el.scrollHeight;
+ }
+ }, [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>
+ <pre
+ ref={scrollRef}
+ onScroll={handleScroll}
+ className="mt-1 max-h-60 overflow-auto whitespace-pre-wrap break-words font-mono text-xs"
+ >
+ {visible}
+ </pre>
+ </div>
+ );
+}
diff --git a/studio/frontend/src/components/assistant-ui/tool-result-output.tsx b/studio/frontend/src/components/assistant-ui/tool-result-output.tsx
new file mode 100644
index 00000000000..45f72ed96c8
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/tool-result-output.tsx
@@ -0,0 +1,63 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"use client";
+
+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"
+ * toggle so a large output stays scrollable without janking the DOM. Copy
+ * buttons still copy the FULL text (owned by the caller), not the tail.
+ */
+export function ToolResultOutput({ text }: { text: string }) {
+ const [showAll, setShowAll] = useState(false);
+ const tail = useMemo(() => tailText(text), [text]);
+ const truncated = !showAll && (tail.hiddenLines > 0 || tail.hiddenChars > 0);
+
+ return (
+ <>
+ {truncated && (
+ <button
+ type="button"
+ onClick={() => setShowAll(true)}
+ className="mt-1 rounded px-1.5 py-0.5 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
+ >
+ {tail.hiddenLines > 0
+ ? `Show all (${tail.hiddenLines.toLocaleString()} earlier lines hidden)`
+ : `Show all (${tail.hiddenChars.toLocaleString()} earlier chars hidden)`}
+ </button>
+ )}
+ <pre className="mt-1 max-h-60 overflow-auto whitespace-pre-wrap break-words font-mono text-xs">
+ {showAll ? text : tail.visible}
+ </pre>
+ </>
+ );
+}
diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx
index 1afffaed7d1..1b3dd22000e 100644
--- a/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-ui-python.tsx
@@ -6,6 +6,7 @@
import { copyToClipboard } from "@/lib/copy-to-clipboard";
import { getAuthToken } from "@/features/auth/session";
import type { ToolCallMessagePartComponent } from "@assistant-ui/react";
+import { useToolArgsStatus } from "@assistant-ui/react";
import { code as codePlugin } from "@streamdown/code";
import { CodeIcon, CopyIcon } from "lucide-react";
import { Tick02Icon } from "@/lib/tick-icon";
@@ -18,6 +19,14 @@ import {
ToolFallbackRoot,
ToolFallbackTrigger,
} from "./tool-fallback";
+import { ToolLiveOutput } from "./tool-live-output";
+import { ToolResultOutput } from "./tool-result-output";
+import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
+import {
+ preferFullToolOutput,
+ toolOutputKey,
+ useToolPaneScope,
+} from "@/features/chat";
interface StructuredResult {
text: string;
@@ -105,6 +114,7 @@ function isStructuredResult(val: unknown): val is StructuredResult {
}
const PythonToolUIImpl: ToolCallMessagePartComponent = ({
+ toolCallId,
args,
result,
status,
@@ -112,6 +122,9 @@ const PythonToolUIImpl: ToolCallMessagePartComponent = ({
const code = (args as { code?: string })?.code ?? "";
const firstLine = code.split("\n")[0]?.slice(0, 60) ?? "";
const isRunning = status?.type === "running";
+ // Args still streaming = the model is WRITING the code, not running it yet.
+ const { propStatus } = useToolArgsStatus();
+ const isWritingCode = isRunning && propStatus.code === "streaming";
let output: string;
let images: string[] = [];
@@ -129,10 +142,19 @@ const PythonToolUIImpl: ToolCallMessagePartComponent = ({
output = "";
}
+ // Show the fuller live stream over a truncated result, keeping its exit
+ // status. Session-transient: after a reload only the result remains.
+ const paneScope = useToolPaneScope();
+ const fullOutput = useChatRuntimeStore(
+ (s) => s.toolFullOutput[toolOutputKey(paneScope, toolCallId)] ?? "",
+ );
+ const displayOutput = preferFullToolOutput(fullOutput, output);
+
const authToken = getAuthToken();
return (
- <ToolFallbackRoot>
+ // Open when mounted mid-run so live output shows; collapsed from history.
+ <ToolFallbackRoot defaultOpen={isRunning}>
<ToolFallbackTrigger
toolName={firstLine ? `Python: ${firstLine}` : "Python"}
status={status}
@@ -150,19 +172,21 @@ const PythonToolUIImpl: ToolCallMessagePartComponent = ({
{/* Output */}
{isRunning ? (
- <div className="mt-2 flex items-center gap-2 text-sm text-muted-foreground">
- <Spinner className="size-3.5" />
- <span>Running&hellip;</span>
- </div>
- ) : output ? (
+ <>
+ <div className="mt-2 flex items-center gap-2 text-sm text-muted-foreground">
+ <Spinner className="size-3.5" />
+ <span>{isWritingCode ? "Writing code…" : "Running…"}</span>
+ </div>
+ {/* Live stdout streamed via tool_output SSE events. */}
+ <ToolLiveOutput toolCallId={toolCallId} />
+ </>
+ ) : displayOutput ? (
<div className="mt-2 border-t border-dashed pt-2">
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-muted-foreground">output</span>
- <CopyBtn text={output} />
+ <CopyBtn text={displayOutput} />
</div>
- <pre className="mt-1 max-h-60 overflow-auto whitespace-pre-wrap break-words font-mono text-xs">
- {truncate(output)}
- </pre>
+ <ToolResultOutput text={displayOutput} />
</div>
) : null}
diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx
index c088d5cf987..17ae26d3888 100644
--- a/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-ui-terminal.tsx
@@ -5,6 +5,7 @@
import { copyToClipboard } from "@/lib/copy-to-clipboard";
import type { ToolCallMessagePartComponent } from "@assistant-ui/react";
+import { useToolArgsStatus } from "@assistant-ui/react";
import { CopyIcon, TerminalIcon } from "lucide-react";
import { Tick02Icon } from "@/lib/tick-icon";
import { HugeiconsIcon } from "@hugeicons/react";
@@ -15,16 +16,17 @@ import {
ToolFallbackRoot,
ToolFallbackTrigger,
} from "./tool-fallback";
+import { ToolLiveOutput } from "./tool-live-output";
+import { ToolResultOutput } from "./tool-result-output";
+import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";
+import {
+ preferFullToolOutput,
+ toolOutputKey,
+ useToolPaneScope,
+} from "@/features/chat";
-const MAX_DISPLAY = 10_000;
const COPY_RESET_MS = 2000;
-function truncate(text: string): string {
- return text.length <= MAX_DISPLAY
- ? text
- : `${text.slice(0, MAX_DISPLAY)}\n... (truncated)`;
-}
-
function CopyBtn({ text }: { text: string }) {
const [copied, setCopied] = useState(false);
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -65,12 +67,16 @@ function CopyBtn({ text }: { text: string }) {
}
const TerminalToolUIImpl: ToolCallMessagePartComponent = ({
+ toolCallId,
args,
result,
status,
}) => {
const command = (args as { command?: string })?.command ?? "";
const isRunning = status?.type === "running";
+ // 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
@@ -78,8 +84,17 @@ const TerminalToolUIImpl: ToolCallMessagePartComponent = ({
? JSON.stringify(result, null, 2)
: "";
+ // Show the fuller live stream over a truncated result, keeping its exit
+ // status. Session-transient: after a reload only the result remains.
+ const paneScope = useToolPaneScope();
+ const fullOutput = useChatRuntimeStore(
+ (s) => s.toolFullOutput[toolOutputKey(paneScope, toolCallId)] ?? "",
+ );
+ const displayOutput = preferFullToolOutput(fullOutput, output);
+
return (
- <ToolFallbackRoot>
+ // Open when mounted mid-run so live output shows; collapsed from history.
+ <ToolFallbackRoot defaultOpen={isRunning}>
<ToolFallbackTrigger
toolName={command ? `$ ${command.slice(0, 60)}` : "Terminal"}
status={status}
@@ -88,19 +103,21 @@ const TerminalToolUIImpl: ToolCallMessagePartComponent = ({
<ToolFallbackContent>
<div className="border-l-2 border-muted-foreground/20 pl-2">
{isRunning ? (
- <div className="flex items-center gap-2 text-sm text-muted-foreground">
- <Spinner className="size-3.5" />
- <span>Running&hellip;</span>
- </div>
- ) : output ? (
+ <>
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <Spinner className="size-3.5" />
+ <span>{isWritingCommand ? "Writing command…" : "Running…"}</span>
+ </div>
+ {/* Live stdout streamed via tool_output SSE events. */}
+ <ToolLiveOutput toolCallId={toolCallId} />
+ </>
+ ) : displayOutput ? (
<div>
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-muted-foreground">output</span>
- <CopyBtn text={output} />
+ <CopyBtn text={displayOutput} />
</div>
- <pre className="mt-1 max-h-60 overflow-auto whitespace-pre-wrap break-words font-mono text-xs">
- {truncate(output)}
- </pre>
+ <ToolResultOutput text={displayOutput} />
</div>
) : null}
</div>
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index c7dd6372aa1..0bf46e7343c 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -12,6 +12,7 @@ import { parseParamCountB } from "@/lib/model-size";
import { toast } from "@/lib/toast";
import type { MessageTiming, ToolCallMessagePart } from "@assistant-ui/core";
import type { ChatModelAdapter } from "@assistant-ui/react";
+import { parsePartialJsonObject } from "assistant-stream/utils";
import {
getExternalProviderApiKey,
isCustomProviderType,
@@ -51,6 +52,11 @@ import {
useChatRuntimeStore,
} from "../stores/chat-runtime-store";
import { useExternalProvidersStore } from "../stores/external-providers-store";
+import {
+ shouldPreserveFullOutput,
+ toolOutputKey,
+ toolPaneScope,
+} from "../tool-output-scope";
import type { ModelType } from "../types";
import { isMultimodalResponse } from "../types/api";
import type {
@@ -85,6 +91,7 @@ import {
listGgufVariants,
loadModel,
streamChatCompletions,
+ StreamInterruptedError,
validateModel,
} from "./chat-api";
import {
@@ -228,6 +235,49 @@ function wait(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
+/**
+ * Best-effort partial parse of a live tool_args stream into a tool part's
+ * `args`, so cards render the payload while the model is still writing it. The
+ * structured path streams raw arguments JSON; the text path wraps it in call
+ * markup, unwrapped here. Returns null until something parses; never throws.
+ */
+function parseLiveToolArgs(
+ raw: string,
+): { args: Record<string, unknown>; argsText: string } | null {
+ let candidate = raw.trimStart();
+ if (!candidate.startsWith("{")) {
+ const brace = candidate.indexOf("{");
+ if (brace < 0) return null;
+ candidate = candidate.slice(brace);
+ }
+ const parsed = parsePartialJsonObject(candidate) as
+ | Record<string, unknown>
+ | undefined;
+ if (!parsed || typeof parsed !== "object") return null;
+ // Call envelope from the text path: unwrap to the arguments payload.
+ const inner = parsed.arguments ?? parsed.parameters;
+ if (typeof parsed.name === "string" && inner !== undefined) {
+ if (typeof inner === "string") {
+ // Stringified arguments: partial-parse the inner JSON string.
+ const innerParsed = parsePartialJsonObject(inner) as
+ | Record<string, unknown>
+ | undefined;
+ if (innerParsed && typeof innerParsed === "object") {
+ return { args: innerParsed, argsText: inner };
+ }
+ return null;
+ }
+ if (inner && typeof inner === "object" && !Array.isArray(inner)) {
+ return {
+ args: inner as Record<string, unknown>,
+ argsText: JSON.stringify(inner),
+ };
+ }
+ return null;
+ }
+ return { args: parsed, argsText: candidate };
+}
+
function parseSystemVariablesMap(raw: string): Record<string, unknown> {
if (!raw.trim()) {
return {};
@@ -1877,6 +1927,16 @@ export function createOpenAIStreamAdapter(
? `${sandboxSessionId || "_default"}:${resolvedThreadId}`
: sandboxSessionId || "_default";
const toolConfirmationIdsByBackendId = new Map<string, string>();
+ // Store keys are pane-scoped since local tool ids ("call_0") repeat across
+ // turns and concurrent panes (compare mode). Track this run's keys so
+ // cleanup can't wipe another pane's.
+ const toolOutputPaneScope = toolPaneScope(
+ options.modelType,
+ options.pairId,
+ );
+ const scopedToolOutputKey = (id: string) =>
+ toolOutputKey(toolOutputPaneScope, id);
+ const runToolLiveOutputKeys = new Set<string>();
const resolvedThreadKey = resolvedThreadId ?? null;
const pendingImageEditReferenceForRun = runtime.pendingImageEditReference;
const selectedImageEditReference =
@@ -2426,6 +2486,34 @@ export function createOpenAIStreamAdapter(
};
// Tool call parts, cumulative; result lands on tool_end.
const toolCallParts: PositionedToolCallPart[] = [];
+ // Raw tool_args accumulator per card: the backend forwards arguments while
+ // the model is still WRITING them, and the partial parse below feeds the
+ // card's args so the code renders live.
+ const liveArgsTextById = new Map<string, string>();
+ // Backend tool ids ("call_0", ...) restart every response, so a bare id as
+ // store key lets a later turn's stream overwrite the preserved output an
+ // earlier still-mounted finished card reads (the tool_start stale-clear
+ // only guards the forward direction). Mint one per-run-unique part id per
+ // backend id (confirmation ids already synthesize their own) so each card
+ // key is unique; every tool_start/output/args/end resolves the same id via
+ // this map, dropped at tool_end.
+ const toolPartIdByBackendId = new Map<string, string>();
+ const resolveToolPartId = (backendToolCallId: string): string => {
+ if (!backendToolCallId) {
+ return toolCallParts[toolCallParts.length - 1]?.toolCallId ?? "";
+ }
+ const confirmationId =
+ toolConfirmationIdsByBackendId.get(backendToolCallId);
+ if (confirmationId) {
+ return confirmationId;
+ }
+ let partId = toolPartIdByBackendId.get(backendToolCallId);
+ if (!partId) {
+ partId = `${backendToolCallId}:${crypto.randomUUID()}`;
+ toolPartIdByBackendId.set(backendToolCallId, partId);
+ }
+ return partId;
+ };
// Latest Gemini text-part thoughtSignature; pinned onto the final
// text MessagePart so next-turn replay carries it.
let latestTextThoughtSignature: string | undefined;
@@ -3160,6 +3248,66 @@ export function createOpenAIStreamAdapter(
anthropicRefusalSeen = true;
continue;
}
+ if (toolEvent.type === "tool_output") {
+ // Incremental stdout from a running tool: append to the live
+ // store so the card renders it while the spinner runs. Final
+ // result arrives via tool_end.
+ const backendToolCallId =
+ (toolEvent.tool_call_id as string) || "";
+ const liveId = resolveToolPartId(backendToolCallId);
+ const liveText =
+ typeof toolEvent.text === "string" ? toolEvent.text : "";
+ if (liveId && liveText) {
+ const liveKey = scopedToolOutputKey(liveId);
+ runToolLiveOutputKeys.add(liveKey);
+ useChatRuntimeStore
+ .getState()
+ .appendToolLiveOutput(liveKey, liveText);
+ }
+ continue;
+ }
+ if (toolEvent.type === "tool_args") {
+ // The model is still WRITING this call's arguments: accumulate
+ // the raw stream and feed a partial parse into the part's args
+ // so the card shows the code live. tool_start later replaces
+ // args with the authoritative parse.
+ const backendToolCallId =
+ (toolEvent.tool_call_id as string) || "";
+ const liveId = resolveToolPartId(backendToolCallId);
+ const fragment =
+ typeof toolEvent.text === "string" ? toolEvent.text : "";
+ if (liveId && fragment) {
+ const accum =
+ (liveArgsTextById.get(liveId) ?? "") + fragment;
+ liveArgsTextById.set(liveId, accum);
+ const partial = parseLiveToolArgs(accum);
+ const idx = toolCallParts.findIndex(
+ (p) => p.toolCallId === liveId,
+ );
+ if (partial && idx !== -1) {
+ const existing = toolCallParts[
+ idx
+ ] as PositionedToolCallPart;
+ toolCallParts[idx] = {
+ ...existing,
+ args: partial.args as ToolCallMessagePart["args"],
+ argsText: partial.argsText,
+ };
+ yield {
+ content: buildAssistantContent(cumulativeText),
+ metadata: {
+ timing: buildTiming(
+ streamStartTime,
+ totalChunks,
+ firstTokenTime,
+ ),
+ custom: { reasoningDuration },
+ },
+ };
+ }
+ }
+ continue;
+ }
closeReasoningContent();
const toolProvenance = parseToolProvenance(
toolEvent.provenance,
@@ -3173,12 +3321,18 @@ export function createOpenAIStreamAdapter(
const id =
awaitingConfirmation && approvalId
? `${toolConfirmationScopeId}:${approvalId}`
- : backendToolCallId ||
- approvalId ||
- `${toolEvent.tool_name}_${Date.now()}`;
+ : backendToolCallId
+ ? resolveToolPartId(backendToolCallId)
+ : approvalId ||
+ `${toolEvent.tool_name}_${Date.now()}`;
if (awaitingConfirmation && backendToolCallId) {
toolConfirmationIdsByBackendId.set(backendToolCallId, id);
}
+ // "call_0" restarts every response: drop stale live/preserved
+ // output under this key, else the card shows the previous call's.
+ const staleKey = scopedToolOutputKey(id);
+ useChatRuntimeStore.getState().clearToolLiveOutput(staleKey);
+ useChatRuntimeStore.getState().clearToolFullOutput(staleKey);
const toolArgs = (toolEvent.arguments ??
{}) as ToolCallMessagePart["args"];
const idx = toolCallParts.findIndex(
@@ -3222,17 +3376,35 @@ export function createOpenAIStreamAdapter(
} else if (toolEvent.type === "tool_end") {
const backendToolCallId =
(toolEvent.tool_call_id as string) || "";
- const id =
- (backendToolCallId
- ? toolConfirmationIdsByBackendId.get(backendToolCallId)
- : undefined) ||
- backendToolCallId ||
- toolCallParts[toolCallParts.length - 1]?.toolCallId ||
- "";
+ const id = resolveToolPartId(backendToolCallId);
if (backendToolCallId) {
toolConfirmationIdsByBackendId.delete(backendToolCallId);
+ toolPartIdByBackendId.delete(backendToolCallId);
}
useChatRuntimeStore.getState().clearToolConfirmation(id);
+ // The result replaces the live output, but if the stream
+ // captured MORE than the truncated result, preserve it so the
+ // finished card keeps everything. Uses the shared predicate,
+ // not a length compare (footer / "Exit code N:" / __IMAGES__
+ // tail can make the result longer by byte).
+ const liveKey = scopedToolOutputKey(id);
+ const liveOutput =
+ useChatRuntimeStore.getState().toolLiveOutput[liveKey] ??
+ "";
+ if (
+ id &&
+ shouldPreserveFullOutput(
+ liveOutput,
+ (toolEvent.result as string) ?? "",
+ )
+ ) {
+ useChatRuntimeStore
+ .getState()
+ .setToolFullOutput(liveKey, liveOutput);
+ }
+ useChatRuntimeStore.getState().clearToolLiveOutput(liveKey);
+ runToolLiveOutputKeys.delete(liveKey);
+ liveArgsTextById.delete(id);
const idx = toolCallParts.findIndex(
(p) => p.toolCallId === id,
);
@@ -3797,7 +3969,16 @@ export function createOpenAIStreamAdapter(
);
if (!abortSignal.aborted) {
const msg = err instanceof Error ? err.message : String(err);
- if (isContextLimitError(msg)) {
+ if (err instanceof StreamInterruptedError) {
+ // Connection dropped mid-turn: surface it explicitly (the rethrow
+ // below also marks the message with an inline error + Retry).
+ toast.error("Response interrupted", {
+ description:
+ "The connection dropped before the model finished. " +
+ "The partial answer is kept. Use Retry to regenerate.",
+ duration: 8000,
+ });
+ } else if (isContextLimitError(msg)) {
// llama-server runs with --no-context-shift, returning a hard
// error instead of silently dropping old KV-cache turns. Point
// the user at the control that raises the ceiling.
@@ -3823,6 +4004,19 @@ export function createOpenAIStreamAdapter(
}
runtime.setGeneratingStatus(null);
runtime.setToolStatus(null);
+ // Clear only this run's live keys (a concurrent pane owns its own). A
+ // key still here streamed stdout but never reached tool_end (SSE drop or
+ // cancel), so promote it to full output first, else the partial
+ // diagnostics the user was watching vanish from the card.
+ for (const liveKey of runToolLiveOutputKeys) {
+ const store = useChatRuntimeStore.getState();
+ const liveOutput = store.toolLiveOutput[liveKey] ?? "";
+ if (liveOutput) {
+ store.setToolFullOutput(liveKey, liveOutput);
+ }
+ store.clearToolLiveOutput(liveKey);
+ }
+ runToolLiveOutputKeys.clear();
// Drop the transient denoising canvas so the finished bubble shows only
// the committed markdown answer (cancellation/error included).
runtime.setActiveDiffusionCanvas(null);
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 8195d895286..ebf94611727 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -29,6 +29,21 @@ import type {
export const CHAT_HISTORY_UPDATED_EVENT = "unsloth-chat-history-updated";
+/**
+ * Thrown when the chat SSE stream ends without a terminal signal (`[DONE]` or a
+ * finish_reason chunk): the connection dropped mid-generation. The adapter
+ * surfaces it as an explicit interrupted state instead of ending the turn.
+ */
+export class StreamInterruptedError extends Error {
+ constructor() {
+ super(
+ "Response interrupted: the connection dropped before the model finished. " +
+ "Use Retry to regenerate.",
+ );
+ this.name = "StreamInterruptedError";
+ }
+}
+
export function notifyChatHistoryUpdated(): void {
if (typeof window !== "undefined") {
window.dispatchEvent(new Event(CHAT_HISTORY_UPDATED_EVENT));
@@ -851,12 +866,18 @@ export async function* streamChatCompletions(
const decoder = new TextDecoder();
let buffer = "";
let completed = false;
+ // EOF without `[DONE]` or a finish_reason chunk means the stream was cut
+ // mid-generation: surface as interrupted, not silent success.
+ let sawTerminalSignal = false;
try {
while (true) {
const { done, value } = await reader.read();
if (done) {
completed = true;
+ if (!sawTerminalSignal) {
+ throw new StreamInterruptedError();
+ }
break;
}
@@ -877,6 +898,7 @@ export async function* streamChatCompletions(
const dataText = dataLines.join("\n");
if (dataText === "[DONE]") {
completed = true;
+ sawTerminalSignal = true;
return;
}
@@ -903,10 +925,14 @@ export async function* streamChatCompletions(
separatorIndex = buffer.search(/\r?\n\r?\n/);
continue;
}
- // Tool start/end events carry full input/output for the tool outputs panel
+ // tool_start/end carry full input/output; tool_output streams
+ // incremental stdout and tool_args streams the call arguments live.
if (
"type" in parsed &&
- (parsed.type === "tool_start" || parsed.type === "tool_end")
+ (parsed.type === "tool_start" ||
+ parsed.type === "tool_end" ||
+ parsed.type === "tool_output" ||
+ parsed.type === "tool_args")
) {
yield { _toolEvent: parsed } as unknown as OpenAIChatChunk;
separatorIndex = buffer.search(/\r?\n\r?\n/);
@@ -925,6 +951,16 @@ export async function* streamChatCompletions(
separatorIndex = buffer.search(/\r?\n\r?\n/);
continue;
}
+ // finish_reason is a valid terminal signal for providers that close
+ // the stream without an explicit [DONE] sentinel.
+ const finishReason = (
+ parsed as {
+ choices?: Array<{ finish_reason?: string | null }>;
+ }
+ ).choices?.[0]?.finish_reason;
+ if (finishReason) {
+ sawTerminalSignal = true;
+ }
yield parsed as OpenAIChatChunk;
separatorIndex = buffer.search(/\r?\n\r?\n/);
}
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index 7e894bb92ea..a8b5fc23ad9 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -17,6 +17,11 @@ export {
type Preset,
} from "./chat-settings-sheet";
export { useChatRuntimeStore } from "./stores/chat-runtime-store";
+export {
+ preferFullToolOutput,
+ toolOutputKey,
+ useToolPaneScope,
+} from "./tool-output-scope";
export { PermissionModeDropdown } from "./permission-mode-select";
export { useChatSearchStore } from "./stores/chat-search-store";
export { usePinnedChatsStore } from "./stores/pinned-chats-store";
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsx
index 20fc9797779..019d0bfd8ad 100644
--- a/studio/frontend/src/features/chat/runtime-provider.tsx
+++ b/studio/frontend/src/features/chat/runtime-provider.tsx
@@ -54,6 +54,7 @@ import {
} from "./open-document";
import { AudioAttachmentAdapter } from "./audio-attachment-adapter";
import { useChatRuntimeStore } from "./stores/chat-runtime-store";
+import { ToolPaneScopeContext, toolPaneScope } from "./tool-output-scope";
import type { MessageRecord, ModelType, ThreadRecord } from "./types";
import {
deleteStoredChatThreads,
@@ -1347,26 +1348,33 @@ export function ChatRuntimeProvider({
return (
<AssistantRuntimeProvider runtime={runtime} aui={aui}>
- <ActiveThreadSync
- enabled={
- modelType === "base" && !pairId && !newThreadNonce && !initialThreadId
- }
- />
- <ThreadBackendAutosave modelType={modelType} pairId={pairId} />
- <CancelRegistrar />
- {initialThreadId && (
- <ThreadAutoSwitch
- threadId={initialThreadId}
- syncActiveThreadId={syncActiveThreadId}
+ {/* Pane identity for the tool-output store maps: the adapter prefixes its
+ keys with this scope so concurrent panes with colliding tool ids
+ ("call_0") can't bleed live output into each other's cards. */}
+ <ToolPaneScopeContext.Provider value={toolPaneScope(modelType, pairId)}>
+ <ActiveThreadSync
+ enabled={
+ modelType === "base" &&
+ !pairId &&
+ !newThreadNonce &&
+ !initialThreadId
+ }
/>
- )}
- {!initialThreadId && newThreadNonce && (
- <ThreadNewChatSwitch nonce={newThreadNonce} />
- )}
- {/* The view stays mounted (only CSS-hidden by RootLayout) while off-route
- so assistant-ui keeps the run attached and the stream alive. Unmounting
- it here aborts the in-flight generation. */}
- {children}
+ <ThreadBackendAutosave modelType={modelType} pairId={pairId} />
+ <CancelRegistrar />
+ {initialThreadId && (
+ <ThreadAutoSwitch
+ threadId={initialThreadId}
+ syncActiveThreadId={syncActiveThreadId}
+ />
+ )}
+ {!initialThreadId && newThreadNonce && (
+ <ThreadNewChatSwitch nonce={newThreadNonce} />
+ )}
+ {/* The view stays mounted (only CSS-hidden) while off-route so the run
+ stays attached and the stream alive; unmounting aborts generation. */}
+ {children}
+ </ToolPaneScopeContext.Provider>
</AssistantRuntimeProvider>
);
}
diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
index b70d2fbeab0..2a81fe6ea89 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -701,6 +701,13 @@ type ChatRuntimeStore = {
*/
webFetchToolsEnabled: boolean;
toolStatus: string | null;
+ /** Live stdout/stderr from running tools, keyed by toolCallId. Transient:
+ * appended by tool_output, cleared on tool_end or run end. */
+ toolLiveOutput: Record<string, string>;
+ /** Full live output of finished tools whose result was truncated for the
+ * model, keyed by toolCallId. Set from tool_end; finished cards prefer it
+ * over the truncated result. Session-transient. */
+ toolFullOutput: Record<string, string>;
generatingStatus: string | null;
autoHealToolCalls: boolean;
nudgeToolCalls: boolean;
@@ -836,6 +843,13 @@ type ChatRuntimeStore = {
setRagOcrScanned: (enabled: boolean) => void;
setRagCaptionFigures: (enabled: boolean) => void;
setToolStatus: (status: string | null) => void;
+ appendToolLiveOutput: (toolCallId: string, text: string) => void;
+ /** Clear one tool's live output, or all when no id is given. */
+ clearToolLiveOutput: (toolCallId?: string) => void;
+ /** Preserve a finished tool's full live-streamed output for display. */
+ setToolFullOutput: (toolCallId: string, text: string) => void;
+ /** Drop a stale preserved full output (a new run is reusing the id). */
+ clearToolFullOutput: (toolCallId: string) => void;
setGeneratingStatus: (status: string | null) => void;
setActiveDiffusionCanvas: (canvas: DiffusionCanvasFrame | null) => void;
setAutoHealToolCalls: (enabled: boolean) => void;
@@ -1166,6 +1180,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
ragOcrScanned: loadBool(CHAT_RAG_OCR_KEY, DEFAULT_RAG_OCR),
ragCaptionFigures: loadBool(CHAT_RAG_CAPTION_KEY, DEFAULT_RAG_CAPTION),
toolStatus: null,
+ toolLiveOutput: {},
+ toolFullOutput: {},
generatingStatus: null,
activeDiffusionCanvas: null,
autoHealToolCalls: true,
@@ -1415,6 +1431,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
// Only the per-session enable pill resets; source/mode/top_k persist.
ragEnabled: false,
toolStatus: null,
+ toolLiveOutput: {},
+ toolFullOutput: {},
activeDiffusionCanvas: null,
kvCacheDtype: null,
loadedKvCacheDtype: null,
@@ -1638,6 +1656,43 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
return { ragCaptionFigures };
}),
setToolStatus: (toolStatus) => set({ toolStatus }),
+ appendToolLiveOutput: (toolCallId, text) =>
+ set((state) => ({
+ toolLiveOutput: {
+ ...state.toolLiveOutput,
+ [toolCallId]: (state.toolLiveOutput[toolCallId] ?? "") + text,
+ },
+ })),
+ setToolFullOutput: (toolCallId, text) =>
+ set((state) => ({
+ toolFullOutput: {
+ ...state.toolFullOutput,
+ [toolCallId]: text,
+ },
+ })),
+ clearToolFullOutput: (toolCallId) =>
+ set((state) => {
+ if (!(toolCallId in state.toolFullOutput)) {
+ return {};
+ }
+ const next = { ...state.toolFullOutput };
+ delete next[toolCallId];
+ return { toolFullOutput: next };
+ }),
+ clearToolLiveOutput: (toolCallId) =>
+ set((state) => {
+ if (toolCallId === undefined) {
+ return Object.keys(state.toolLiveOutput).length
+ ? { toolLiveOutput: {} }
+ : {};
+ }
+ if (!(toolCallId in state.toolLiveOutput)) {
+ return {};
+ }
+ const next = { ...state.toolLiveOutput };
+ delete next[toolCallId];
+ return { toolLiveOutput: next };
+ }),
setActiveDiffusionCanvas: (activeDiffusionCanvas) =>
set({ activeDiffusionCanvas }),
setGeneratingStatus: (generatingStatus) => set({ generatingStatus }),
diff --git a/studio/frontend/src/features/chat/tool-output-scope.ts b/studio/frontend/src/features/chat/tool-output-scope.ts
new file mode 100644
index 00000000000..a7885a39167
--- /dev/null
+++ b/studio/frontend/src/features/chat/tool-output-scope.ts
@@ -0,0 +1,95 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"use client";
+
+import { createContext, useContext } from "react";
+import type { ModelType } from "./types";
+
+/**
+ * Pane scope prefix for the transient tool-output store keys.
+ *
+ * Local GGUF tool ids are only unique within one response ("call_0", "call_1",
+ * ...), and panes stream concurrently (compare mode mounts two runtimes; the
+ * main view stays CSS-hidden off-route), so a bare id would let one pane's
+ * stdout bleed into another's same-id card. Derived from static props
+ * (`modelType` + `pairId`) shared by writer (adapter) and reader (components)
+ * via one `ChatRuntimeProvider`, so they can never disagree.
+ */
+export function toolPaneScope(modelType?: ModelType, pairId?: string): string {
+ return `${modelType ?? "base"}\u0000${pairId ?? ""}`;
+}
+
+export const ToolPaneScopeContext = createContext<string>(toolPaneScope());
+
+export function useToolPaneScope(): string {
+ return useContext(ToolPaneScopeContext);
+}
+
+/** Store key for the live/full tool output maps: pane scope + tool call id. */
+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, so it distinguishes "just truncated" from "carries
+// failure/exit status the stream never produced".
+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
+ * (retain?) and reader (display?) so they agree.
+ *
+ * True when the result is truncated, OR the stream is longer. Truncation can't
+ * fall back to length: a truncated result may be longer by byte count once its
+ * footer / `Exit code N:` / `__IMAGES__` blob is appended, yet the stream still
+ * holds more stdout. Also true when a short stream is absent from the result: a
+ * timed-out/cancelled tool returns only a status line, so length alone would
+ * drop the partial stdout the stream captured.
+ */
+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/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/exit
+ * text that never reached stdout ("Exit code N: ...", timeouts), so show the
+ * stream when the result is just a truncated prefix of it, else append the
+ * result so its status survives (and the copy button copies both).
+ */
+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:\n",
+ // so `full.startsWith(core)` above misses and a plain append would duplicate
+ // the stdout. Re-attach just the exit prefix (and any missing-path hint) to
+ // the fuller stream so the status survives without duplicating stdout.
+ 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}`;
+}