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.

OpenAI stream: gate UI control frames behind X-Unsloth-Events opt-in (#10362)

Denys Bushuliakf47547b6f295
diff --git a/.github/workflows/studio-inference-smoke.yml b/.github/workflows/studio-inference-smoke.yml
index 769b42b8424..9acf500645a 100644
--- a/.github/workflows/studio-inference-smoke.yml
+++ b/.github/workflows/studio-inference-smoke.yml
@@ -566,6 +566,11 @@ jobs:
headers = {
"Authorization": f"Bearer {KEY}",
"Content-Type": "application/json",
+ # A server-side tool leaves no OpenAI-spec trace, so the
+ # tool_start/tool_end envelopes _tool_invoked looks for are
+ # Unsloth control frames, sent only to a caller that asks.
+ # This helper exists to prove the tool path ran, so it asks.
+ "X-Unsloth-Events": "1",
},
)
for attempt in range(retries + 1):
diff --git a/.github/workflows/studio-mac-ui-smoke.yml b/.github/workflows/studio-mac-ui-smoke.yml
index f337b1fbd02..32804639c57 100644
--- a/.github/workflows/studio-mac-ui-smoke.yml
+++ b/.github/workflows/studio-mac-ui-smoke.yml
@@ -986,6 +986,10 @@ jobs:
headers = {
"Authorization": f"Bearer {KEY}",
"Content-Type": "application/json",
+ # The tool loop's frames, and the confirm gate's prompt, only
+ # go to a caller that asks, as the Studio UI does. Ask, so this
+ # probe exercises the same path a user takes.
+ "X-Unsloth-Events": "1",
},
)
for attempt in range(retries + 1):
diff --git a/.github/workflows/studio-windows-inference-smoke.yml b/.github/workflows/studio-windows-inference-smoke.yml
index 276477b1651..8b8d66d188c 100644
--- a/.github/workflows/studio-windows-inference-smoke.yml
+++ b/.github/workflows/studio-windows-inference-smoke.yml
@@ -766,6 +766,10 @@ jobs:
headers = {
"Authorization": f"Bearer {KEY}",
"Content-Type": "application/json",
+ # The tool loop's frames, and the confirm gate's prompt, only
+ # go to a caller that asks, as the Studio UI does. Ask, so this
+ # probe exercises the same path a user takes.
+ "X-Unsloth-Events": "1",
},
)
for attempt in range(retries + 1):
diff --git a/studio/backend/core/inference/chat_generation_runs.py b/studio/backend/core/inference/chat_generation_runs.py
index ce9da8a6b71..dfaa3bf0b72 100644
--- a/studio/backend/core/inference/chat_generation_runs.py
+++ b/studio/backend/core/inference/chat_generation_runs.py
@@ -76,7 +76,11 @@ def _background_request(app: Any, run_id: str, cancel_event: threading.Event) ->
"path": "/api/inference/chat-runs/producer",
"raw_path": b"/api/inference/chat-runs/producer",
"query_string": b"",
- "headers": [(b"x-unsloth-generation-run", run_id.encode("ascii", "ignore"))],
+ "headers": [
+ (b"x-unsloth-generation-run", run_id.encode("ascii", "ignore")),
+ # Durable runs replay their event log to the UI, which needs the Unsloth control frames (see routes.inference).
+ (b"x-unsloth-events", b"1"),
+ ],
"client": ("127.0.0.1", 0),
"server": ("127.0.0.1", 0),
"app": app,
diff --git a/studio/backend/core/inference/sse_control_frames.py b/studio/backend/core/inference/sse_control_frames.py
index f565930ede0..b783db1ba0b 100644
--- a/studio/backend/core/inference/sse_control_frames.py
+++ b/studio/backend/core/inference/sse_control_frames.py
@@ -29,8 +29,8 @@ import json
from typing import Any
-# Top-level "type" values the chat client routes away from the transcript. Anything here paints UI on the user's behalf,
-# so only this server may send it.
+# Top-level "type" values the client routes away from the transcript: they paint UI on the user's behalf, so only this
+# server may send them.
_CONTROL_TYPES = frozenset(
{
"tool_start",
@@ -43,13 +43,10 @@ _CONTROL_TYPES = frozenset(
}
)
-# unsloth extensions, in no provider's wire format, read with the same trust as the frames above
-# Unsloth extensions carried inside a chunk. Not part of any provider's wire format, and read by the client with the
-# same trust as the frames above.
+# Unsloth extensions carried inside a chunk: in no provider's wire format, read with the same trust as the frames above.
_CONTROL_KEYS = ("_toolEvent", "_toolStatus", "_diffusionFrame", "_reasoningDurationMs")
-# a stripped frame is only worth relaying if it still says something in the provider's vocabulary
-# What is left of a stripped frame is only worth relaying if it still says something in the provider's own vocabulary.
+# A stripped frame is only worth relaying if it still says something in the provider's own vocabulary.
_SUBSTANTIVE_KEYS = ("choices", "usage", "error")
@@ -72,8 +69,7 @@ def _normalize_reasoning_deltas(payload: dict[str, Any]) -> bool:
isinstance(part, dict) and isinstance(part.get("text"), str) and part["text"]
for part in details
):
- # OpenRouter repeats the thought in reasoning_details and the client concatenates both; details carrying no
- # text are not a second copy.
+ # OpenRouter repeats the thought in reasoning_details and the client concatenates both.
continue
canonical = delta.get("reasoning_content")
if canonical is not None and (not isinstance(canonical, str) or canonical.strip()):
@@ -116,7 +112,262 @@ def sanitize_provider_sse_line(line: str) -> str | None:
if key not in forged_keys and not (forged_type and key == "type")
}
if not any(key in cleaned for key in _SUBSTANTIVE_KEYS):
- # A pure control frame with the control stripped out is an empty envelope; relaying it would only make the
- # client parse nothing.
+ # A pure control frame with the control stripped out is an empty envelope.
return None
return "data: " + json.dumps(cleaned, separators = (",", ":"))
+
+
+def _sse_payload(line: str) -> dict[str, Any] | None:
+ """The JSON object a ``data:`` line carries, or None if it carries none."""
+ if not line.startswith("data:"):
+ return None
+ raw = line[5:].strip()
+ if not raw or raw == "[DONE]":
+ return None
+ try:
+ payload = json.loads(raw)
+ except (TypeError, ValueError, json.JSONDecodeError):
+ return None
+ return payload if isinstance(payload, dict) else None
+
+
+def is_ui_control_sse_line(line: str) -> bool:
+ """Whether ``line`` is a frame no OpenAI client can route, rather than a chunk.
+
+ Read by the OpenAI-compatible route to hold these back from a caller that did not opt
+ in: with no ``choices`` they fail schema validation mid-stream. Structural rather than
+ a name list, because ``_CONTROL_TYPES`` answers a different question -- what a
+ PROVIDER must not forge -- and the tool loop also writes bare ``status`` frames around
+ a RAG autoinjection, which are just as unroutable without being forgeable. ``usage``
+ and ``error`` keep a frame: those are the provider's own vocabulary and a client reads
+ them. A chunk that merely carries a ``_toolEvent``-style key has ``choices`` and stays.
+ """
+ payload = _sse_payload(line)
+ if payload is None:
+ return False
+ # isinstance first: the sanitizer passes a non-string `type` through, and an unhashable one raises on `in`.
+ if not isinstance(payload.get("type"), str):
+ return False
+ return not any(key in payload for key in _SUBSTANTIVE_KEYS)
+
+
+def strip_server_executed_tool_call(line: str, pending_call: bool = False) -> str | None:
+ """Hold a call the server runs itself back from a caller that did not opt in.
+
+ ``stream_with_studio_tools`` relays the provider's own ``delta.tool_calls`` and the
+ ``finish_reason: "tool_calls"`` that ends that turn, for a call Unsloth then executes
+ and answers in a later turn. Its catalogue is Unsloth's own, never the caller's, so a
+ client reading those chunks is told to run a tool that is already running here: an
+ agent may run it a second time, or stop at the finish_reason and never read the real
+ answer. Returns the line with the call and that finish_reason removed, or None when
+ nothing worth relaying was left.
+
+ ``pending_call`` says a call was already withheld earlier in this turn, which makes a
+ ``finish_reason: "stop"`` on this line just as misleading as "tool_calls": llama.cpp
+ and vLLM routinely end a perfectly good tool call on "stop" and the loop deliberately
+ runs those (see studio_tool_loop's ``truncated`` rule), so the turn has not finished
+ either. Callers that track the turn use ``ServerToolCallStripper`` rather than passing
+ this by hand. It also covers the legacy "function_call", which a gateway may still use
+ to close a turn it streamed modern ``delta.tool_calls`` for. "length" and
+ "content_filter" are left alone on purpose: those are the two the loop refuses to run,
+ so that turn really is the last one.
+
+ Only for the Unsloth-tool-loop path. On a plain proxy the calls are the caller's own
+ and must pass through untouched.
+ """
+ payload = _sse_payload(line)
+ choices = payload.get("choices") if payload else None
+ if not isinstance(choices, list) or not choices:
+ return line
+
+ not_really_final = ("tool_calls", "stop", "function_call") if pending_call else ("tool_calls",)
+ changed = False
+ kept_choices = []
+ for choice in choices:
+ if not isinstance(choice, dict):
+ kept_choices.append(choice)
+ continue
+ choice = dict(choice)
+ withheld = False
+ for src_key in ("delta", "message"):
+ src = choice.get(src_key)
+ # tool_calls only: the loop reads no other form, so a legacy function_call is the caller's to run.
+ if isinstance(src, dict) and "tool_calls" in src:
+ src = {k: v for k, v in src.items() if k != "tool_calls"}
+ choice[src_key] = src
+ withheld = True
+ if choice.get("finish_reason") in not_really_final:
+ # Blanked, not renamed: the turn has not finished, the loop answers in the next
+ # one. Cannot be keyed on a call withheld on this line, since the arguments
+ # arrived in earlier chunks and this delta is usually empty.
+ #
+ # "function_call" only counts once a call is pending, for the gateway that
+ # streams modern delta.tool_calls then closes on the legacy reason (LocalAI does
+ # whenever the client sent no tools). A genuine legacy call never sets pending
+ # (_line_offers_tool_call keys on "tool_calls" alone), so it keeps its reason.
+ choice["finish_reason"] = None
+ withheld = True
+ changed = changed or withheld
+ kept_choices.append(choice)
+
+ if not changed:
+ return line
+ payload = {**payload, "choices": kept_choices}
+ if not _choices_say_anything(kept_choices) and "usage" not in payload:
+ return None
+ return "data: " + json.dumps(payload, separators = (",", ":"))
+
+
+def _line_offers_tool_call(line: str) -> bool:
+ """Whether this line carries a ``tool_calls`` fragment at all.
+
+ Keyed on the key being present, not on it being truthy, so it reads the same
+ condition the strip itself does: a line whose only evidence is an empty list is
+ still stripped, and the two must not disagree about whether a call was withheld.
+ """
+ payload = _sse_payload(line)
+ choices = payload.get("choices") if payload else None
+ if not isinstance(choices, list):
+ return False
+ for choice in choices:
+ if not isinstance(choice, dict):
+ continue
+ for src_key in ("delta", "message"):
+ src = choice.get(src_key)
+ if isinstance(src, dict) and "tool_calls" in src:
+ return True
+ return False
+
+
+class ServerToolCallStripper:
+ """``strip_server_executed_tool_call`` with the one bit of turn state it needs.
+
+ A turn whose calls this server runs is not over when the provider says it is, and the
+ provider does not always say "tool_calls": llama.cpp and vLLM finish a structured call
+ on "stop", which the loop runs anyway. Stripping only the call then leaves a caller
+ holding an empty chunk marked ``finish_reason: "stop"``, and a client that ends the
+ turn there never reads the answer the loop is about to stream -- the same lost reply
+ the control-frame gate exists to prevent, arrived at from the other side.
+
+ So remember, per stream, that a call was withheld and no reply has followed it, and
+ treat the "stop" that closes that turn the way "tool_calls" is already treated. The
+ next turn opens with the flag clear, so its own finish_reason is relayed untouched.
+
+ The flag is raised BEFORE the strip reads it, because a provider may co-emit the call
+ and the finish_reason on one line (any non-streamed upstream relayed as a single line
+ does), and the turn boundary is read on every line, because that same line both opens
+ and closes the turn. Getting either wrong leaks the empty "stop" this exists to hold
+ back, or swallows a later turn's legitimate one.
+
+ Blanking the last finish_reason of a stream would leave the caller none at all --
+ openai-node raises "missing finish_reason for choice 0" outright -- so the withheld
+ ones are counted and ``owed_terminal_chunk`` mints a replacement when the loop ends
+ without opening the turn it promised (a spent tool budget, a discarded call, a
+ provider that failed mid-loop).
+
+ One instance per request. The state is per line, not per choice index, which is exact
+ here because the loop reads choice 0 only and this path rejects n > 1 upstream.
+ """
+
+ def __init__(self) -> None:
+ self._pending_call = False
+ self._owes_finish = False
+ self._last_envelope: dict[str, Any] | None = None
+
+ def arm(self) -> None:
+ """Withhold the next turn-ending reason for a call that never reached the wire.
+
+ A text-form ``<tool_call>`` healed out of ordinary content is executed by the loop
+ but is invisible here: the markup is removed from the content it arrived in, and no
+ ``tool_calls`` key ever appears, so ``_line_offers_tool_call`` cannot see it. The
+ loop knows, and says so by calling this before it releases the chunk that closes
+ that turn. Everything after is the structured path's behaviour exactly, debt
+ included.
+ """
+ self._pending_call = True
+ self._owes_finish = True
+
+ def end_turn(self) -> None:
+ """The loop finished a provider turn, whatever the provider said to close it.
+
+ A turn boundary is normally read off the finish_reason on the wire, but a provider
+ may close on ``[DONE]`` alone and the loop consumes that sentinel before this ever
+ sees it, leaving the withheld-call flag raised into the next turn. The next turn's
+ reasons are its own: a legacy ``function_call`` there belongs to the caller, and
+ stripping it as though it closed the previous call means the caller never dispatches
+ it. The debt is deliberately left alone -- it is still owed until a real terminal
+ reaches the caller.
+ """
+ self._pending_call = False
+
+ def strip(self, line: str) -> str | None:
+ pending = self._pending_call or _line_offers_tool_call(line)
+ out = strip_server_executed_tool_call(line, pending_call = pending)
+ ends_turn = _line_ends_turn(line)
+ # Turn closed: whatever the loop does next opens a turn whose finish_reason is the caller's to read.
+ self._pending_call = pending and not ends_turn
+ if pending or (ends_turn and (out is None or not _line_ends_turn(out))):
+ # Armed as soon as a call is withheld, not only where a finish_reason was
+ # removed: a provider closing the turn on [DONE] alone never offers one to
+ # remove. Settled below the moment a real terminal is relayed.
+ #
+ # The second clause is the reverse: a reason removed with no call ever seen. A
+ # provider reporting "tool_calls" for a call its own parser failed to emit
+ # (open llama.cpp and vLLM bugs) gives `pending` nothing to latch onto, so the
+ # reason is blanked and no debt recorded, leaving no finish_reason at all.
+ self._owes_finish = True
+ if out is not None and _line_ends_turn(out):
+ self._owes_finish = False
+ self._remember_envelope(line)
+ return out
+
+ def _remember_envelope(self, line: str) -> None:
+ """Keep the last chunk's identity, so a minted finish matches the stream."""
+ payload = _sse_payload(line)
+ if not payload or "choices" not in payload:
+ return
+ envelope = {
+ key: payload[key] for key in ("id", "object", "created", "model") if key in payload
+ }
+ if envelope:
+ self._last_envelope = envelope
+
+ def owed_terminal_chunk(self) -> str | None:
+ """A finish chunk to send before [DONE], or None when the caller already has one.
+
+ finish_reason is a required key in the OpenAI chunk schema, so a stream that ends
+ without one is not merely unhelpful: openai-node raises, and openai-python hands
+ back a parsed completion whose finish_reason is None in a field its own type
+ declares non-nullable. Mirrors the GGUF passthrough's _synthetic_finish_line.
+ """
+ if not self._owes_finish:
+ return None
+ self._owes_finish = False
+ payload = dict(self._last_envelope or {})
+ payload["choices"] = [{"index": 0, "delta": {}, "finish_reason": "stop"}]
+ return "data: " + json.dumps(payload, separators = (",", ":"))
+
+
+def _line_ends_turn(line: str) -> bool:
+ """Whether this line carries any finish_reason, i.e. closes the provider's turn."""
+ payload = _sse_payload(line)
+ choices = payload.get("choices") if payload else None
+ if not isinstance(choices, list):
+ return False
+ return any(
+ isinstance(choice, dict) and choice.get("finish_reason") is not None for choice in choices
+ )
+
+
+def _choices_say_anything(choices: list[Any]) -> bool:
+ """Whether anything survived the strip that a client would act on."""
+ for choice in choices:
+ if not isinstance(choice, dict):
+ return True
+ if choice.get("finish_reason") is not None:
+ return True
+ for src_key in ("delta", "message"):
+ src = choice.get(src_key)
+ if isinstance(src, dict) and any(value for value in src.values()):
+ return True
+ return False
diff --git a/studio/backend/core/inference/studio_tool_loop.py b/studio/backend/core/inference/studio_tool_loop.py
index 2aa4d61d28a..68aecb9d12d 100644
--- a/studio/backend/core/inference/studio_tool_loop.py
+++ b/studio/backend/core/inference/studio_tool_loop.py
@@ -50,7 +50,7 @@ import json
import threading
from dataclasses import dataclass, field
-from collections.abc import AsyncIterator
+from collections.abc import AsyncIterator, Callable
from typing import Any, Protocol
from core.inference import tools as tools_module
@@ -374,6 +374,12 @@ class ToolLoopPolicy:
auto_heal: bool | None = None
# None follows UNSLOTH_TOOL_CALL_NUDGE; explicit booleans win.
nudge_tool_calls: bool | None = None
+ # Called before relaying the chunk that ends a turn a text-form call was healed out of. Headerless relay only, to arm
+ # its ServerToolCallStripper for a call that never reached the wire as a tool_calls key.
+ on_withheld_tool_call: Callable[[], None] | None = None
+ # Called when a provider turn ends, however it ended. Headerless only: clears the stripper's withheld-call flag,
+ # which the wire cannot always close because a turn may end on [DONE] alone.
+ on_provider_turn_end: Callable[[], None] | None = None
def _reject_json_constant(name: str) -> Any:
@@ -1016,6 +1022,33 @@ def _rewrite_content(payload: dict[str, Any], choice: dict[str, Any], text: str)
return _sse(new_payload)
+def _split_turn_end(
+ payload: dict[str, Any], choice: dict[str, Any], delta: dict[str, Any]
+) -> tuple[str | None, str]:
+ """Separate a turn-ending chunk into what can be sent now and the reason to hold.
+
+ Only the finish_reason has to wait for the healer to resolve; the content on that same
+ chunk does not, and holding it too would let residue flushed by ``finalize`` overtake
+ it and reverse the text on the wire. So the content goes out in place and a bare
+ finish-only chunk is what gets parked.
+ """
+ now_choice = {key: value for key, value in choice.items() if key != "finish_reason"}
+ now_choice["delta"] = delta
+ now_payload = {key: value for key, value in payload.items() if key != "choices"}
+ now_payload["choices"] = [now_choice] + list(payload.get("choices", [])[1:])
+ now = _sse(now_payload) if (delta or len(now_payload["choices"]) > 1) else None
+
+ held_payload = {key: value for key, value in payload.items() if key != "choices"}
+ held_payload["choices"] = [
+ {
+ "index": choice.get("index", 0),
+ "delta": {},
+ "finish_reason": choice.get("finish_reason"),
+ }
+ ]
+ return now, _sse(held_payload)
+
+
def _unrun_provenance(tool_name: str, round_id: int) -> dict[str, Any]:
"""Provenance for a hand-built unrun card; carries the MCP display name so a
budget-exhausted or truncated MCP call never shows the internal server id."""
@@ -1275,6 +1308,12 @@ async def stream_with_studio_tools(
provider_turns += 1
turn = _Turn(round = provider_turns)
healer = StreamToolCallHealer(heal_names, tools) if heal_names else None
+ # A healed text-form call never reaches the wire as a tool_calls key, so a headerless caller's stripper cannot
+ # tell this turn ends in a call the loop is about to run rather than in an answer. Hold the turn-ending chunk
+ # until finalize() says whether anything was promoted, then arm the stripper before releasing it. Arming at
+ # promotion time is too late for unterminated markup, which only promotes in finalize(), after the provider's
+ # "stop" has gone out.
+ held_final: str | None = None
active_tools = controller.active_tools()
tools_available = (
@@ -1347,6 +1386,13 @@ async def stream_with_studio_tools(
turn.note_hosted_tool_event(payload.get("_toolEvent"))
if isinstance(choice.get("finish_reason"), str):
turn.finish_reason = choice["finish_reason"]
+ # Only a live healer can still promote a call this turn; once dormant, the wire already carries the
+ # tool_calls key the stripper arms on.
+ hold_final = (
+ isinstance(choice.get("finish_reason"), str)
+ and healer is not None
+ and not healer.dormant
+ )
if isinstance(raw_calls, list) and raw_calls:
if healer is not None and not healer.dormant:
@@ -1362,7 +1408,12 @@ async def stream_with_studio_tools(
plain = _delta_text(content)
if plain:
turn.text.append(plain)
- yield line
+ if hold_final:
+ now, held_final = _split_turn_end(payload, choice, delta)
+ if now is not None:
+ yield now
+ else:
+ yield line
continue
released: list[str] = []
@@ -1377,12 +1428,27 @@ async def stream_with_studio_tools(
turn.text.append(visible)
if visible == content:
# Nothing was held back, the case for almost every chunk of ordinary prose
- yield line
+ if hold_final:
+ now, held_final = _split_turn_end(payload, choice, delta)
+ if now is not None:
+ yield now
+ else:
+ yield line
continue
# Withholding everything is normal mid-block. Only drop the chunk when it carries nothing else worth
# relaying.
if visible or turn.finish_reason is not None or len(delta) > 1:
- yield _rewrite_content(payload, choice, visible)
+ if hold_final:
+ healed_delta = {
+ key: value for key, value in delta.items() if key != "content"
+ }
+ if visible:
+ healed_delta["content"] = visible
+ now, held_final = _split_turn_end(payload, choice, healed_delta)
+ if now is not None:
+ yield now
+ else:
+ yield _rewrite_content(payload, choice, visible)
if healer is not None:
for kind, value in healer.finalize():
@@ -1393,6 +1459,23 @@ async def stream_with_studio_tools(
elif kind == "tool_call":
turn.healed.append(value)
+ # The turn ended in a call this loop is about to run, so the provider's reason is not the end of the
+ # response. Arming blanks it for headerless callers and records the debt, so owed_terminal_chunk() still
+ # mints a terminal if the loop stops before a later turn supplies one. A truncated turn is the exception: it
+ # refuses to run the call, so its reason really is final.
+ #
+ # Deliberately not conditioned on held_final: a provider that closes on [DONE] alone while a healed call is
+ # promoted would leave the debt unarmed, ending the stream with no finish_reason, which openai-node rejects.
+ if (
+ turn.healed
+ and turn.finish_reason not in ("length", "content_filter")
+ and policy.on_withheld_tool_call is not None
+ ):
+ policy.on_withheld_tool_call()
+ if held_final is not None:
+ yield held_final
+ held_final = None
+
finally:
# Release the upstream response now rather than leaving it to the async-generator finalisation hook, which
# runs a tick or more after the route has already closed this loop.
@@ -1403,6 +1486,11 @@ async def stream_with_studio_tools(
except (RuntimeError, GeneratorExit):
pass
+ # The provider turn is over, whichever way it ended. Said explicitly because a turn closed on [DONE] alone
+ # carries no finish_reason for the stripper to read the boundary off, and the loop consumes that sentinel.
+ if policy.on_provider_turn_end is not None:
+ policy.on_provider_turn_end()
+
# Both mean the turn ended before the model finished Both of these mean the turn ended before the model finished
# saying what it wanted: "length" hit the token ceiling, "content_filter" had the output cut by the provider's
# own filter. Either way a call collected so far may be half-written, so it is described rather than run. "stop"
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 0a2fcad9b5d..a87c6ad1e71 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -3234,6 +3234,10 @@ from core.inference.providers import (
)
from core.inference.external_provider import ExternalProviderClient
from core.inference.external_tool_transport import OAICompatTransport
+from core.inference.sse_control_frames import (
+ is_ui_control_sse_line,
+ ServerToolCallStripper,
+)
from core.inference.studio_tool_loop import (
ToolLoopPolicy,
ToolLoopRun,
@@ -3705,6 +3709,25 @@ def _tools_on_by_launcher_default_only(payload) -> bool:
)
+def _request_states_no_tool_flag(payload) -> bool:
+ """True when the request set no tool flag of its own, so something else turned tools on.
+
+ The wider sibling of _tools_on_by_launcher_default_only, which reads the same two
+ request fields but additionally insists the process installed no CLI override. That
+ extra condition is right where the question is "may the launcher DEFAULT answer for
+ this request", and wrong where it is "did this caller ask for anything the gate could
+ hold it to": `unsloth studio run --enable-tools` fills the override slot rather than
+ the default one, so under it every ordinary OpenAI stream -- `unsloth chat`'s own
+ included -- states no tool intent, inherits the full catalogue, and would be refused
+ for a gate it never asked to open. Which slot the operator used is not something the
+ caller can see or act on, so it must not decide whether the caller is served.
+
+ Named for what it tests rather than for the conclusion drawn from it: on a plain
+ `unsloth studio` process, where tools are on for nobody, this is still true.
+ """
+ return payload.enable_tools is None and not getattr(payload, "mcp_enabled", False)
+
+
def _request_states_tool_intent(payload) -> bool:
"""True when a request states its own tool intent through the standard
OpenAI fields: a `tool_choice: "none"` withdrawal, its own tool catalog,
@@ -3913,7 +3936,18 @@ def _permission_mode_confirm(payload) -> bool:
return bool(getattr(payload, "stream", False))
-def _confirm_gate_needs_stream(payload) -> bool:
+def _catalog_names(tools) -> list[str]:
+ """Tool names out of a resolved catalogue, for the confirm-gate classifier."""
+ names = []
+ for tool in tools or []:
+ function = tool.get("function") if isinstance(tool, dict) else None
+ name = function.get("name") if isinstance(function, dict) else None
+ if isinstance(name, str) and name:
+ names.append(name)
+ return names
+
+
+def _confirm_gate_needs_stream(payload, selected_names = None) -> bool:
"""Whether Unsloth's local tool-loop confirm gate still requires stream=true.
The gate can only prompt while streaming, so a non-streaming request that will
@@ -3923,6 +3957,12 @@ def _confirm_gate_needs_stream(payload) -> bool:
always-safe (web_search / RAG) never prompts and needs no stream. ask,
an explicit confirm flag, MCP tools, and an unrestricted or unsafe selection
still require streaming.
+
+ ``selected_names`` is the RESOLVED catalogue, for the callers that have one. It
+ answers the selection and mcp_enabled together, and more accurately: an MCP ask that
+ discovery filtered down to nothing leaves only always-safe built-ins, which cannot
+ prompt. Without it the request's own fields are read, which is all the pre-switch and
+ non-streaming callers have.
"""
if not _permission_mode_confirm(payload):
return False
@@ -3930,9 +3970,12 @@ def _confirm_gate_needs_stream(payload) -> bool:
return True
if payload.confirm_tool_calls is True:
return True
- if getattr(payload, "mcp_enabled", False):
+ if selected_names is not None:
+ enabled = list(selected_names)
+ elif getattr(payload, "mcp_enabled", False):
return True
- enabled = getattr(payload, "enabled_tools", None)
+ else:
+ enabled = getattr(payload, "enabled_tools", None)
if enabled is None:
return True # omitted enabled_tools resolves to ALL tools (incl. terminal/python)
if not enabled:
@@ -3947,6 +3990,162 @@ def _confirm_gate_needs_stream(payload) -> bool:
return not all(is_always_safe_tool(t) and t != "web_search" for t in enabled)
+class _AutoPermissionMode:
+ """``payload`` with its unset permission_mode read as "auto", the loop's own default.
+
+ Applied only when the mode really is unset: an explicit ask must never be softened
+ into auto's leniency.
+ """
+
+ permission_mode = "auto"
+
+ def __init__(self, payload) -> None:
+ self._payload = payload
+
+ def __getattr__(self, name):
+ return getattr(self._payload, name)
+
+
+def _tool_calls_are_disabled(payload) -> bool:
+ """True when no tool call can happen, so no confirm prompt can either.
+
+ stream_with_studio_tools withdraws the catalogue for a turn unless tool_choice is not
+ "none" and the per-message budget is unspent, and discards a call a provider emits
+ under "none" anyway. The selector does not read either field, so a catalogue can be
+ non-empty while nothing in it is reachable.
+
+ A `--disable-tools` process policy is the third way: it vetoes even an explicit
+ enable_tools (see _explicit_studio_tool_loop_requested), so no loop opens and nothing
+ can prompt. The per-backend branches already guard on that, but this predicate is
+ about whether a prompt CAN fire, and under that policy it cannot.
+ """
+ from state.tool_policy import get_tool_policy
+
+ if get_tool_policy() is False:
+ return True
+ if getattr(payload, "tool_choice", None) == "none":
+ return True
+ return getattr(payload, "max_tool_calls_per_message", None) == 0
+
+
+def _confirm_gate_has_no_channel(
+ payload,
+ ui_events: bool,
+ selected_names = None,
+) -> bool:
+ """Whether a confirm gate that will prompt has no way to ask this caller.
+
+ Two ways to have nowhere to ask. The gate writes its prompt to the stream, so a
+ non-streaming request cannot be asked (the case _confirm_gate_needs_stream was
+ written for). And the approval_id only ever reaches the caller inside the tool_start
+ control frame (see state.tool_approvals), so a stream that opted out of those frames
+ cannot be asked either: it would park in wait_tool_decision for the full decision
+ timeout on a prompt nobody was shown, holding the decode slot the whole hour.
+
+ A streaming request is only ever refused over a prompt that can actually fire: tool
+ calls must be reachable at all, and an unset permission_mode is read as "auto", the
+ way the loop itself defaults it, so an always-safe selection (deep research sends
+ enabled_tools: []) passes. Non-streaming keeps the reading it has always had.
+ """
+ if not getattr(payload, "stream", False):
+ # Bypass suppresses the gate in the loop, so it never prompts and needs no channel to
+ # prompt on. Each guard this replaced paired the stream requirement with the same flag;
+ # dropping it would 400 full-access non-streaming tool runs that work today.
+ if getattr(payload, "bypass_permissions", False):
+ return False
+ return _confirm_gate_needs_stream(payload)
+ if ui_events:
+ return False
+ if _request_states_no_tool_flag(payload):
+ # The request never asked for tools, so it cannot be asked to know about the
+ # header either. `unsloth studio run` turns tools on for the process -- as a
+ # default, or as an override under --enable-tools -- and refusing here would 400
+ # every ordinary OpenAI request on that launcher, `unsloth chat`'s own included.
+ # Tools are withdrawn for this caller instead (see _launcher_tool_default_applies),
+ # so the loop it could not be prompted for never opens. The external-provider
+ # sites never reach this line: both gate on _explicit_studio_tool_loop_requested,
+ # which is this predicate's exact complement.
+ return False
+ return _confirm_gate_would_prompt(payload, selected_names)
+
+
+def _confirm_gate_would_prompt(payload, selected_names = None) -> bool:
+ """Whether the confirm gate would actually stop and ask on this streaming request.
+
+ The one question behind both the refusal and the withdrawal, so that the two stay
+ complements of each other: a caller is refused only over a prompt that can really
+ fire, and only such a caller has the tools taken away instead. Tool calls must be
+ reachable at all, and an unset permission_mode is read as "auto", the way the loop
+ itself defaults it, so an always-safe selection (deep research sends enabled_tools:
+ []) and an explicit off/full both pass without ever being asked.
+ """
+ if getattr(payload, "bypass_permissions", False):
+ return False
+ if _tool_calls_are_disabled(payload):
+ return False
+ if getattr(payload, "permission_mode", None) is None:
+ payload = _AutoPermissionMode(payload)
+ return _confirm_gate_needs_stream(payload, selected_names)
+
+
+def _launcher_tool_default_applies(payload, ui_events: bool) -> bool:
+ """Whether a tools-on default the request did not ask for still answers it.
+
+ It answers a request that said nothing about tools. A request that stated its own
+ intent has already answered (the sibling rule at the safetensors and GGUF branches),
+ and so, now, has a stream that cannot be prompted: the confirm gate asks over the
+ control frames, so running a default nobody asked for behind a gate nobody can
+ answer would park the caller in wait_tool_decision on the first high-risk call.
+ Plain chat is what such a request asked for and what it gets.
+
+ Withdrawn only from a stream the gate would really have stopped, which is what keeps
+ this the exact complement of the refusal above. A frameless caller that sent
+ permission_mode "off" or bypass_permissions is never asked anything, so it keeps the
+ tools the operator turned on: trading a refusal it would not have got for a silent
+ loss of capability would be the worse half of both.
+ """
+ if not _request_states_no_tool_flag(payload):
+ return True
+ if _request_states_tool_intent(payload):
+ return False
+ if not (getattr(payload, "stream", False) and not ui_events):
+ return True
+ return not _confirm_gate_would_prompt(payload)
+
+
+def _reject_confirm_gate_without_channel(
+ payload,
+ ui_events: bool,
+ monitor_id = None,
+ selected_names = None,
+) -> None:
+ """Refuse a request whose confirm gate would have nowhere to ask.
+
+ Called with the SELECTED catalog in hand, never on intent: mcp_enabled with no MCP
+ tools enabled, or a selection filtered down to nothing, leaves the loop skipped, and
+ refusing there would 400 a request that proxies straight through.
+
+ ``monitor_id`` closes an entry the caller already opened. The stream generator that
+ would otherwise finish it is never reached from here, and a running entry is exempt
+ from trimming, so leaving it open strands /api/inference/monitor in `generating`.
+ """
+ if not _confirm_gate_has_no_channel(payload, ui_events, selected_names):
+ return
+ if monitor_id is not None:
+ api_monitor.fail(monitor_id, "confirm_tool_calls requires an event channel")
+ raise HTTPException(
+ status_code = 400,
+ detail = openai_error_body(
+ "confirm_tool_calls requires stream=true and the X-Unsloth-Events: 1 "
+ 'header for local tool execution; set permission_mode to "off" to '
+ "run tools without confirmation.",
+ status = 400,
+ code = "invalid_request_error",
+ param = "confirm_tool_calls",
+ ),
+ )
+
+
def _anthropic_reasoning_args(payload) -> dict:
"""Reasoning kwargs for /v1/messages generators.
@@ -19953,6 +20152,11 @@ async def _proxy_to_external_provider(
and not _selects_only_provider_hosted_tools(payload, provider_type)
)
codex_studio_tool_loop = studio_tool_loop and provider_type == "openai_codex"
+ # The loop relays the same control frames the local routes gate (see UI_STREAM_EVENTS_HEADER).
+ _ui_events = _ui_stream_events_enabled(request)
+ _drop_keepalive = _DroppedFrameKeepalive()
+ # One per request: carries the withheld-call state across the lines of a turn.
+ _tool_call_stripper = ServerToolCallStripper()
# Unsloth's UI asks for the gate by permission_mode, not by confirm_tool_calls,
# so reading the raw flag admits the exact request the local routes reject: a
# non-streaming permission_mode="ask" with the flag omitted proxies through
@@ -20186,6 +20390,12 @@ async def _proxy_to_external_provider(
tools_on = _effective_enable_tools(payload) is True,
mcp_allowed = bool(payload.mcp_enabled),
)
+ if studio_tool_payloads:
+ # The loop runs iff the catalog is non-empty, and its approval handshake
+ # rides the control frames.
+ _reject_confirm_gate_without_channel(
+ payload, _ui_events, selected_names = _catalog_names(studio_tool_payloads)
+ )
# The Unsloth loop owns its schemas. Do not also expose a caller-supplied
# catalog: Codex would return calls that this server is not authorized to run.
tool_payloads = studio_tool_payloads
@@ -20325,7 +20535,26 @@ async def _proxy_to_external_provider(
if cancel_event.is_set() or await request.is_disconnected():
await generator.aclose()
break
+ if not _ui_events and is_ui_control_sse_line(line):
+ if _drop_keepalive.due():
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
+ continue
+ if not _ui_events and policy is not None:
+ # policy is set only when the loop owns the catalogue, so a call
+ # here is one this server runs, not one to hand to the caller.
+ line = _tool_call_stripper.strip(line)
+ if line is None:
+ # A long argument stream drops every fragment here and, like a
+ # gated frame, holds off the loop's stall timer.
+ if _drop_keepalive.due():
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
+ continue
yield f"{line}\n\n"
+ # The loop can end without opening the turn a withheld call promised, and the
+ # reason removed with that call was this stream's last one.
+ _owed = _tool_call_stripper.owed_terminal_chunk()
+ if _owed is not None:
+ yield f"{_owed}\n\n"
yield "data: [DONE]\n\n"
except asyncio.CancelledError:
raise
@@ -20502,6 +20731,12 @@ async def _proxy_to_external_provider(
mcp_allowed = bool(payload.mcp_enabled),
)
run_studio_tool_loop = bool(external_studio_tools)
+ if run_studio_tool_loop:
+ # Only once the catalog is known: mcp_enabled with no MCP tools enabled leaves this
+ # empty and skips the loop, so there is no prompt to find a channel for.
+ _reject_confirm_gate_without_channel(
+ payload, _ui_events, monitor_id, _catalog_names(external_studio_tools)
+ )
chat_messages = _prepend_current_date_to_messages(
chat_messages,
request,
@@ -20597,6 +20832,10 @@ async def _proxy_to_external_provider(
rag_scope = payload.rag_scope,
auto_heal = payload.auto_heal_tool_calls,
nudge_tool_calls = payload.nudge_tool_calls,
+ # Matches the strip below: only a headerless caller has its calls
+ # withheld, so only it needs a healed one the wire never carried flagged.
+ on_withheld_tool_call = (None if _ui_events else _tool_call_stripper.arm),
+ on_provider_turn_end = (None if _ui_events else _tool_call_stripper.end_turn),
),
cancel_event = cancel_event,
)
@@ -20634,12 +20873,30 @@ async def _proxy_to_external_provider(
# choices: [] chunk. Same rule _cmpl_stream_event_out applies locally.
if not _wants_stream_usage(payload) and _is_openai_usage_only_sse(line):
continue
+ if not _ui_events and is_ui_control_sse_line(line):
+ if _drop_keepalive.due():
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
+ continue
+ if not _ui_events and run_studio_tool_loop:
+ # Only inside the loop: on a plain proxy the calls are the caller's own.
+ line = _tool_call_stripper.strip(line)
+ if line is None:
+ if _drop_keepalive.due():
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
+ continue
yield f"{line}\n\n"
# Parsed from the line itself, not from monitor_event: with the
# monitor disabled the helper returns None for every line, and
# trusting it would append a second [DONE] after the provider's.
if _is_openai_sse_done(line):
sent_done = True
+ # The loop can end without opening the turn a withheld call promised, and the
+ # reason removed with that call was this stream's last one. Before [DONE], where
+ # the GGUF passthrough places its own synthetic finish.
+ _owed = _tool_call_stripper.owed_terminal_chunk()
+ if _owed is not None and not stream_failed:
+ _monitor_openai_sse_line(monitor_id, _owed)
+ yield f"{_owed}\n\n"
if not sent_done:
if not stream_failed:
_monitor_openai_sse_line(monitor_id, "data: [DONE]")
@@ -20976,6 +21233,51 @@ def _chat_cancel_event(request: Request) -> threading.Event:
return event if event is not None else threading.Event()
+# Unsloth multiplexes its own UI control frames (tool_start / tool_end / tool_output /
+# tool_args / tool_status / reasoning_summary / diffusion_frame) onto the SSE stream of
+# /v1/chat/completions. They carry no `choices`, so strict OpenAI clients -- openai-python,
+# the Vercel AI SDK, opencode -- fail schema validation mid-stream and drop the response
+# (the Anthropic route already drops these events for the same reason). So the default is a
+# clean OpenAI stream and the Studio UI opts back in with this header.
+UI_STREAM_EVENTS_HEADER = "X-Unsloth-Events"
+
+
+def _ui_stream_events_enabled(request: Optional[Request]) -> bool:
+ """Whether this request opted into Unsloth's UI control frames on an OpenAI stream."""
+ if request is None:
+ return False
+ headers = getattr(request, "headers", None)
+ if headers is None:
+ return False
+ try:
+ value = headers.get(UI_STREAM_EVENTS_HEADER)
+ except Exception:
+ return False
+ return (value or "").strip() == "1"
+
+
+class _DroppedFrameKeepalive:
+ """Paces an SSE keepalive comment in place of dropped UI control frames.
+
+ A stall keepalive is only written while the generator is silent, and a control frame
+ is not silence: it restarts that wait but, once gated off, puts nothing on the wire.
+ A tool streaming stdout emits `tool_output` continuously, which also resets
+ tool_stream_exec's own heartbeat, so a non-opt-in caller would see no bytes for the
+ whole tool run and a Cloudflare quick tunnel drops the stream at ~100s idle. The
+ Anthropic route pays the same cost on the same events; this is its `_last_drop_keepalive`.
+ """
+
+ def __init__(self, now: Optional[float] = None) -> None:
+ self._last = time.monotonic() if now is None else now
+
+ def due(self, now: Optional[float] = None) -> bool:
+ current = time.monotonic() if now is None else now
+ if current - self._last < _LOCAL_TOOL_STREAM_STALL_KEEPALIVE_S:
+ return False
+ self._last = current
+ return True
+
+
@router.post("/chat/completions")
async def openai_chat_completions(
payload: ChatCompletionRequest,
@@ -21025,6 +21327,11 @@ async def produce_openai_chat_completions(
request,
cancel_on_disconnect = cancel_on_disconnect,
)
+ # Opt-in per request (see UI_STREAM_EVENTS_HEADER); captured once so every stream
+ # generator below shares one answer.
+ _ui_events = _ui_stream_events_enabled(request)
+ # Seeded at stream start, so a tool already chatty past the window still gets a keepalive.
+ _drop_keepalive = _DroppedFrameKeepalive()
# OpenAI's newer "developer" role is equivalent to "system". Normalize it
# before provider routing so external providers (which may not accept the
@@ -21178,6 +21485,11 @@ async def produce_openai_chat_completions(
_studio_local_tool_loop = bool(_use_tools_intent) and (
_explicit_studio_tool_loop_requested(payload) or not _client_tool_passthrough
)
+ # Non-streaming only: this runs before the model switch, so it has only the request's
+ # intent, and mcp_enabled with no MCP tools enabled selects an empty catalogue and
+ # skips the loop. The per-backend guards below refuse a frameless stream with the
+ # selection in hand; a switch before that refusal beats 400ing a request that would
+ # have run.
if (
not payload.bypass_permissions
and not payload.stream
@@ -21189,7 +21501,9 @@ async def produce_openai_chat_completions(
raise HTTPException(
status_code = 400,
detail = openai_error_body(
- "confirm_tool_calls requires stream=true for local tool execution.",
+ "confirm_tool_calls requires stream=true and the X-Unsloth-Events: 1 "
+ 'header for local tool execution; set permission_mode to "off" to '
+ "run tools without confirmation.",
status = 400,
code = "invalid_request_error",
param = "confirm_tool_calls",
@@ -21809,6 +22123,9 @@ async def produce_openai_chat_completions(
# the epoch is replayed from the boundary, so the thread never recovers on its
# own. Measured on a non-streaming request with permission_mode ask, and equally
# on auto and on a bare confirm_tool_calls, which the validator folds to ask.
+ # Non-streaming only, deliberately: a stream that merely hid the control frames is
+ # refused by the tool branch alone, and widening this would change what a plain
+ # request is handed (tools_withheld).
or (
_confirm_gate_needs_stream(payload)
and not payload.bypass_permissions
@@ -22022,6 +22339,8 @@ async def produce_openai_chat_completions(
_cli_policy = _get_tool_policy_g()
_tools_on = False if _client_disabled_tool_calls else _effective_enable_tools(payload)
+ if _tools_on and not _launcher_tool_default_applies(payload, _ui_events):
+ _tools_on = False
_mcp_allowed = (
not _client_disabled_tool_calls
and bool(payload.mcp_enabled)
@@ -22094,15 +22413,13 @@ async def produce_openai_chat_completions(
# (the gate needs streaming to prompt) no longer applies. auto with an
# always-safe-only selection never prompts, so it needs no stream even
# though _effective_confirm stays true for the loop's per-call gate.
- if (
- _confirm_gate_needs_stream(payload)
- and not payload.bypass_permissions
- and not payload.stream
- ):
+ if _confirm_gate_has_no_channel(payload, _ui_events, _catalog_names(tools_to_use)):
raise _reject(
400,
openai_error_body(
- "confirm_tool_calls requires stream=true for local tool execution.",
+ "confirm_tool_calls requires stream=true and the X-Unsloth-Events: 1 "
+ 'header for local tool execution; set permission_mode to "off" to '
+ "run tools without confirmation.",
status = 400,
code = "invalid_request_error",
param = "confirm_tool_calls",
@@ -22405,7 +22722,10 @@ async def produce_openai_chat_completions(
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"
+ if _ui_events:
+ yield f"data: {json.dumps(event)}\n\n"
+ elif _drop_keepalive.due():
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
continue
if event["type"] == "status":
@@ -22420,21 +22740,27 @@ async def produce_openai_chat_completions(
reasoning_extractor = _new_chat_reasoning_extractor()
# Emit tool status as a custom SSE event (including
# empty ones to clear UI badges)
- status_data = json.dumps(
- {
- "type": "tool_status",
- "content": event["text"],
- }
- )
- yield f"data: {status_data}\n\n"
+ if _ui_events:
+ status_data = json.dumps(
+ {
+ "type": "tool_status",
+ "content": event["text"],
+ }
+ )
+ yield f"data: {status_data}\n\n"
+ elif _drop_keepalive.due():
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
continue
if event["type"] in ("tool_start", "tool_end"):
if event["type"] == "tool_start":
# Tool card is client-visible output; stamp the turn here.
# Not decoded output: the tool run (or a human confirming
- # it) before the next turn is not decoding time.
- api_monitor.mark_first_token(monitor_id, decoded = False)
+ # it) before the next turn is not decoding time. Gated with
+ # the card, since the stamp is set once: a caller that cannot
+ # see it would report the tool run as its TTFT.
+ if _ui_events:
+ api_monitor.mark_first_token(monitor_id, decoded = False)
for chunk in _flush_reasoning_extractor():
yield chunk
prev_text = ""
@@ -22442,7 +22768,10 @@ async def produce_openai_chat_completions(
# Yielded just before the loop blocks on the user.
await _park_admission(bool(event.get("awaiting_confirmation")))
approval_flush_pending = bool(event.get("awaiting_confirmation"))
- yield f"data: {json.dumps(event)}\n\n"
+ if _ui_events:
+ yield f"data: {json.dumps(event)}\n\n"
+ elif _drop_keepalive.due():
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
continue
if event["type"] == "metadata":
@@ -22453,7 +22782,10 @@ async def produce_openai_chat_completions(
if event["type"] == "reasoning_summary":
# Forward server-side reasoning timing to the UI.
- yield f"data: {json.dumps(event)}\n\n"
+ if _ui_events:
+ yield f"data: {json.dumps(event)}\n\n"
+ elif _drop_keepalive.due():
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
continue
if event["type"] == "context_truncated":
@@ -23063,7 +23395,10 @@ async def produce_openai_chat_completions(
elif cumulative.get("type") == "diffusion_frame":
# Diffusion frame (per-step canvas): pass through as a raw SSE line on the
# tool_status channel. No assistant text, so it never enters the cumulative diff.
- yield f"data: {json.dumps(cumulative)}\n\n"
+ if _ui_events:
+ yield f"data: {json.dumps(cumulative)}\n\n"
+ elif _drop_keepalive.due():
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
elif cumulative.get("type") == "context_truncated":
yield _context_truncated_sse_chunk(
completion_id,
@@ -23684,20 +24019,42 @@ async def produce_openai_chat_completions(
# _client_disabled_tool_calls and _takes_tool_passthrough; an explicit
# enable_tools/mcp_enabled ask, or a CLI --enable-tools, still claims the
# request as before.
- if (
- _sf_tools_on
- and _tools_on_by_launcher_default_only(payload)
- and _request_states_tool_intent(payload)
- ):
+ if _sf_tools_on and not _launcher_tool_default_applies(payload, _ui_events):
+ _sf_tools_on = False
+ # tool_choice: "none" withdraws the catalogue outright, as the GGUF loop does at its
+ # controller. Nothing below reads the field (not _sf_use_tools, not
+ # _select_request_tools, and generate_chat_completion_with_tools is never passed it), so
+ # without this the loop renders the full built-in catalogue for a request that asked for
+ # no call at all. It is also what _tool_calls_are_disabled promises the confirm gate:
+ # otherwise a headerless stream is admitted on the strength of "none", the model calls
+ # anyway, and the tool_start carrying the approval_id is dropped while the generator
+ # blocks in wait_tool_decision for the full hour.
+ if payload.tool_choice == "none":
_sf_tools_on = False
- _sf_mcp_allowed = bool(payload.mcp_enabled) and _sf_cli_policy is not False
+ _sf_mcp_allowed = (
+ payload.tool_choice != "none" and bool(payload.mcp_enabled) and _sf_cli_policy is not False
+ )
# Named templates may expose native reasoning only in their ``tool_use``
# branch. Use a truthy placeholder for Unsloth-managed tools, whose concrete
# schemas are selected below, and the request schemas for client passthrough.
- _sf_server_tool_intent = bool(_sf_tools_on or _explicit_studio_tool_loop_requested(payload))
- _sf_template_tools = payload.tools if payload.tool_choice != "none" else None
- if not _sf_template_tools and _sf_server_tool_intent:
+ # A withdrawn catalogue renders plain here too, so the probe and the completion agree on
+ # which branch the conversation is in.
+ _sf_server_tool_intent = payload.tool_choice != "none" and bool(
+ _sf_tools_on or _explicit_studio_tool_loop_requested(payload)
+ )
+ # Detection only: this picks which branch of a named template is READ, never what is
+ # rendered (the catalogue is withdrawn above and in _sf_tools_to_use), so it must not
+ # follow tool_choice. A conversation carrying client tools or tool history is a tool
+ # conversation whatever the field says, and reading the plain branch for it turns off
+ # _sf_client_tools, which is what routes the history through
+ # _structured_tool_history_for_local_template. Without that, _extract_content_parts drops
+ # the assistant's tool_calls and the result's correlation fields, exactly when "none" is
+ # used to ask for the final answer.
+ _sf_template_tools = payload.tools or None
+ if not _sf_template_tools and (
+ _sf_server_tool_intent or any(m.role == "tool" or m.tool_calls for m in payload.messages)
+ ):
_sf_template_tools = ({},)
# What the prefill probe renders, built to match what generation renders: a template may
@@ -23834,15 +24191,13 @@ async def produce_openai_chat_completions(
# (the gate needs streaming to prompt) no longer applies. auto with an
# always-safe-only selection never prompts, so it needs no stream even
# though _sf_effective_confirm stays true for the loop's per-call gate.
- if (
- _confirm_gate_needs_stream(payload)
- and not payload.bypass_permissions
- and not payload.stream
- ):
+ if _confirm_gate_has_no_channel(payload, _ui_events, _catalog_names(_sf_tools_to_use)):
raise _reject(
400,
openai_error_body(
- "confirm_tool_calls requires stream=true for local tool execution.",
+ "confirm_tool_calls requires stream=true and the X-Unsloth-Events: 1 "
+ 'header for local tool execution; set permission_mode to "off" to '
+ "run tools without confirmation.",
status = 400,
code = "invalid_request_error",
param = "confirm_tool_calls",
@@ -24036,7 +24391,10 @@ async def produce_openai_chat_completions(
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"
+ if _ui_events:
+ yield f"data: {json.dumps(event)}\n\n"
+ elif _drop_keepalive.due():
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
continue
if event["type"] == "status":
@@ -24046,26 +24404,34 @@ async def produce_openai_chat_completions(
yield _c
prev_text = ""
reasoning_extractor = _new_sf_reasoning_extractor()
- status_data = json.dumps(
- {
- "type": "tool_status",
- "content": event["text"],
- }
- )
- yield f"data: {status_data}\n\n"
+ if _ui_events:
+ status_data = json.dumps(
+ {
+ "type": "tool_status",
+ "content": event["text"],
+ }
+ )
+ yield f"data: {status_data}\n\n"
+ elif _drop_keepalive.due():
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
continue
if event["type"] in ("tool_start", "tool_end"):
if event["type"] == "tool_start":
- # Same as the GGUF loop: visible output, but not decoded.
- api_monitor.mark_first_token(monitor_id, decoded = False)
+ # Same as the GGUF loop, gated with the card for the same reason:
+ # the stamp is set once.
+ if _ui_events:
+ api_monitor.mark_first_token(monitor_id, decoded = False)
# Flush reasoning before tool_start so the thinking block closes ahead of the card.
for _c in _sf_flush_reasoning():
yield _c
prev_text = ""
reasoning_extractor = _new_sf_reasoning_extractor()
approval_flush_pending = bool(event.get("awaiting_confirmation"))
- yield f"data: {json.dumps(event)}\n\n"
+ if _ui_events:
+ yield f"data: {json.dumps(event)}\n\n"
+ elif _drop_keepalive.due():
+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
continue
# Diff cumulative cleaned text against last snapshot.
@@ -29384,22 +29750,38 @@ async def _mlx_count_chat_tokens(payload, request = None) -> Optional[JSONRespon
_tools_on = bool(_effective_enable_tools(payload))
# The launcher's default answers a request that said nothing about tools; one that
- # stated its intent goes to the passthrough, not the tool loop.
- if (
- _tools_on
- and _tools_on_by_launcher_default_only(payload)
- and _request_states_tool_intent(payload)
+ # stated its intent goes to the passthrough, not the tool loop. Called rather than
+ # restated, so a count cannot price the tool_use branch of a template the completion
+ # renders plain: the same helper decides it at the safetensors and GGUF branches.
+ if _tools_on and not _launcher_tool_default_applies(
+ payload, _ui_stream_events_enabled(request)
):
_tools_on = False
- _mcp_on = bool(getattr(payload, "mcp_enabled", False)) and _get_tool_policy_mlx() is not False
+ # "none" withdraws the catalogue on the completion's safetensors branch, so neither the
+ # schemas nor the MCP discovery 503 belong in a count for it.
+ if getattr(payload, "tool_choice", None) == "none":
+ _tools_on = False
+ _mcp_on = (
+ getattr(payload, "tool_choice", None) != "none"
+ and bool(getattr(payload, "mcp_enabled", False))
+ and _get_tool_policy_mlx() is not False
+ )
# Classified from the template the way the completion classifies it. A named template
# exposes tool markup only in its tool_use branch, and which branch is read depends on
# the tools handed in -- so hand it a placeholder for the schemas selected below.
# Without them it reads the plain branch and prices away the whole catalog.
_tpl = (entry.get("chat_template_info") or {}).get("template")
- _template_tools = payload.tools if getattr(payload, "tool_choice", None) != "none" else None
- if not _template_tools and (_tools_on or _explicit_studio_tool_loop_requested(payload)):
+ # Detection only, exactly as the completion draws it: which branch is read, never what is
+ # rendered, so it must not follow tool_choice. A count reading the plain branch for a tool
+ # conversation loses the assistant's calls and the result correlation fields to
+ # _extract_content_parts, and prices a history the completion keeps.
+ _template_tools = payload.tools or None
+ if not _template_tools and (
+ _tools_on
+ or _explicit_studio_tool_loop_requested(payload)
+ or any(m.role == "tool" or m.tool_calls for m in payload.messages)
+ ):
_template_tools = ({},)
_takes_tools = bool(
_detect_safetensors_features(backend, _tpl, tools = _template_tools).get(
diff --git a/studio/backend/tests/test_external_confirm_gate_and_saved_keys.py b/studio/backend/tests/test_external_confirm_gate_and_saved_keys.py
index 0e3ebeabb87..afeeab3c622 100644
--- a/studio/backend/tests/test_external_confirm_gate_and_saved_keys.py
+++ b/studio/backend/tests/test_external_confirm_gate_and_saved_keys.py
@@ -52,8 +52,12 @@ def _request(authorization = None):
async def is_disconnected():
return False
+ headers = {"X-Unsloth-Events": "1"}
+ if authorization:
+ headers["authorization"] = authorization
return SimpleNamespace(
- headers = {"authorization": authorization} if authorization else {},
+ # The confirm gate can only ask over these frames.
+ headers = headers,
state = SimpleNamespace(skip_api_monitor = True),
is_disconnected = is_disconnected,
)
diff --git a/studio/backend/tests/test_external_hosted_tool_passthrough.py b/studio/backend/tests/test_external_hosted_tool_passthrough.py
index 4a05b79e7d4..8f1ab910485 100644
--- a/studio/backend/tests/test_external_hosted_tool_passthrough.py
+++ b/studio/backend/tests/test_external_hosted_tool_passthrough.py
@@ -68,7 +68,8 @@ def _request():
return False
return SimpleNamespace(
- headers = {},
+ # These cases drive the tool loop, whose confirm gate asks over these frames.
+ headers = {"X-Unsloth-Events": "1"},
state = SimpleNamespace(skip_api_monitor = True),
is_disconnected = is_disconnected,
)
@@ -333,6 +334,95 @@ def test_a_codex_declares_no_hosted_tools():
# ── Task 1: what an omitted permission_mode means ────────────────────
+def test_mcp_intent_with_no_tools_is_not_refused_for_a_prompt_it_can_never_show(monkeypatch):
+ """mcp_enabled arms the confirm gate on intent, but with no MCP tool enabled the
+ selection is empty and the loop is skipped, so a headerless stream has no prompt to
+ find a channel for. Refusing on intent would 400 a request that proxies straight
+ through, so the check waits for the selected catalog."""
+ monkeypatch.setattr(
+ "core.inference.tools.get_enabled_mcp_tools",
+ lambda: _noop_mcp(),
+ )
+ inf = _install(monkeypatch, "openai")
+ payload = _payload(mcp_enabled = True)
+
+ async def is_disconnected():
+ return False
+
+ headerless = SimpleNamespace(
+ headers = {},
+ state = SimpleNamespace(skip_api_monitor = True),
+ is_disconnected = is_disconnected,
+ )
+
+ async def go():
+ resp = await inf._proxy_to_external_provider(payload, headerless, current_subject = "t")
+ return [chunk async for chunk in resp.body_iterator]
+
+ # No LoopEntered and no HTTPException: the request proxies through.
+ assert _drive(go())
+
+
+def test_tool_choice_none_is_not_refused_for_a_prompt_it_can_never_show(monkeypatch):
+ """The catalogue is non-empty here, but stream_with_studio_tools withdraws it every
+ turn under tool_choice "none", so no call and no approval prompt can happen. A
+ headerless stream must still get its clean text answer."""
+ inf = _install(monkeypatch, "openai")
+ payload = _payload(enable_tools = True, enabled_tools = ["python"], tool_choice = "none")
+
+ async def is_disconnected():
+ return False
+
+ headerless = SimpleNamespace(
+ headers = {},
+ state = SimpleNamespace(skip_api_monitor = True),
+ is_disconnected = is_disconnected,
+ )
+
+ async def go():
+ resp = await inf._proxy_to_external_provider(payload, headerless, current_subject = "t")
+ return [chunk async for chunk in resp.body_iterator]
+
+ # Reaches the loop rather than being refused; the loop then withdraws the catalogue per
+ # turn (tools_available), so the request answers as plain text.
+ with pytest.raises(LoopEntered):
+ _drive(go())
+
+
+def test_a_refused_request_does_not_strand_a_running_monitor_entry(monkeypatch):
+ """The refusal lands after api_monitor.start and before the stream generator that
+ would finish it, and a running entry is exempt from trimming, so leaving it open
+ strands /api/inference/monitor in `generating` for good."""
+ from core.inference.api_monitor import ApiMonitor
+ from fastapi import HTTPException
+
+ inf = _install(monkeypatch, "openai")
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf, "api_monitor", monitor)
+ payload = _payload(enable_tools = True, enabled_tools = ["python"])
+
+ async def is_disconnected():
+ return False
+
+ headerless = SimpleNamespace(
+ headers = {},
+ state = SimpleNamespace(),
+ url = SimpleNamespace(path = "/v1/chat/completions"),
+ method = "POST",
+ is_disconnected = is_disconnected,
+ )
+
+ async def go():
+ return await inf._proxy_to_external_provider(payload, headerless, current_subject = "t")
+
+ with pytest.raises(HTTPException) as exc:
+ _drive(go())
+ assert exc.value.status_code == 400
+ assert monitor.active_count() == 0
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "error"
+
+
def test_b_an_omitted_permission_mode_arms_the_auto_gate(monkeypatch):
"""`permission_mode` unset on a streaming request resolves to "auto" with
the confirm gate ON, so high-risk calls still prompt."""
diff --git a/studio/backend/tests/test_external_hosted_tool_selection.py b/studio/backend/tests/test_external_hosted_tool_selection.py
index 911fb3996a7..aa8dd4be2a9 100644
--- a/studio/backend/tests/test_external_hosted_tool_selection.py
+++ b/studio/backend/tests/test_external_hosted_tool_selection.py
@@ -52,7 +52,8 @@ def _request():
return False
return SimpleNamespace(
- headers = {},
+ # These cases drive the tool loop, whose confirm gate asks over these frames.
+ headers = {"X-Unsloth-Events": "1"},
state = SimpleNamespace(skip_api_monitor = True),
is_disconnected = is_disconnected,
)
diff --git a/studio/backend/tests/test_gguf_tool_non_streaming.py b/studio/backend/tests/test_gguf_tool_non_streaming.py
index 126828a895c..bbc7bbd9678 100644
--- a/studio/backend/tests/test_gguf_tool_non_streaming.py
+++ b/studio/backend/tests/test_gguf_tool_non_streaming.py
@@ -92,8 +92,13 @@ def test_non_streaming_tool_call_returns_single_json(monkeypatch):
def test_streaming_tool_call_still_streams(monkeypatch):
- # The parallel path is untouched: stream:true keeps returning SSE.
- response = _client(monkeypatch).post("/chat/completions", json = _payload(stream = True))
+ # The parallel path is untouched: stream:true keeps returning SSE. An unrestricted
+ # enable_tools arms the confirm gate, which asks over the control frames.
+ response = _client(monkeypatch).post(
+ "/chat/completions",
+ json = _payload(stream = True),
+ headers = {"X-Unsloth-Events": "1"},
+ )
assert response.status_code == 200
assert response.headers["content-type"].startswith("text/event-stream")
diff --git a/studio/backend/tests/test_healed_tool_call_stop.py b/studio/backend/tests/test_healed_tool_call_stop.py
new file mode 100644
index 00000000000..c19a074bf64
--- /dev/null
+++ b/studio/backend/tests/test_healed_tool_call_stop.py
@@ -0,0 +1,361 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A healed text-form tool call must withhold its turn's finish_reason, like a structured one.
+
+A provider that writes ``<tool_call>...</tool_call>`` as ordinary content instead of
+``delta.tool_calls`` -- the small self-hosted GGUF models ``heals_text_tool_calls`` exists
+for -- has that markup healed into a real call and executed by the loop. But the call never
+reaches the wire as a ``tool_calls`` key, so ``ServerToolCallStripper`` cannot see it, and
+the turn's ``finish_reason: "stop"`` used to reach a headerless caller intact. A client that
+ends on the first finish reason then returns the sentence before the tool ran and never
+reads the answer, which is the exact failure the control-frame gate exists to prevent.
+
+These drive the real loop and the real stripper in the route's relay order, because the bug
+lives in the interleaving: the loop must flag the call while the stripper is still upstream
+of the chunk that closes the turn.
+"""
+
+import asyncio
+import json
+import threading
+
+import pytest
+
+import core.inference.studio_tool_loop as loop_mod
+from core.inference.sse_control_frames import ServerToolCallStripper, is_ui_control_sse_line
+from core.inference.studio_tool_loop import (
+ ToolLoopPolicy,
+ ToolLoopRun,
+ stream_with_studio_tools,
+)
+
+
+_DONE = "data: [DONE]"
+
+WEB_SEARCH = {
+ "type": "function",
+ "function": {
+ "name": "web_search",
+ "description": "",
+ "parameters": {
+ "type": "object",
+ "properties": {"query": {"type": "string"}},
+ "required": ["query"],
+ },
+ },
+}
+
+
+def _sse(delta = None, finish = None):
+ choice = {"index": 0, "delta": delta if delta is not None else {}}
+ if finish is not None:
+ choice["finish_reason"] = finish
+ return "data: " + json.dumps({"choices": [choice]}, ensure_ascii = False)
+
+
+_ANSWER_TURN = [_sse({"content": "The answer is 42."}), _sse(finish = "stop"), _DONE]
+
+# The call arrives as content, closed tag: the healer promotes it during feed().
+_TEXT_FORM_TURN = [
+ _sse({"content": "Let me look that up. "}),
+ _sse({"content": '<tool_call>{"name": "web_search", '}),
+ _sse({"content": '"arguments": {"query": "42"}}</tool_call>'}),
+ _sse(finish = "stop"),
+ _DONE,
+]
+
+# Same call with the closing tag missing: promotion happens only in finalize(), after the
+# provider already sent its finish_reason. Arming at promotion time would be too late here,
+# which is why the loop holds the chunk back instead.
+_UNTERMINATED_TURN = [
+ _sse({"content": "Let me look that up. "}),
+ _sse({"content": '<tool_call>{"name": "web_search", '}),
+ _sse({"content": '"arguments": {"query": "42"}}'}),
+ _sse(finish = "stop"),
+ _DONE,
+]
+
+# The control: the same call in the structured shape the stripper already handled.
+_STRUCTURED_TURN = [
+ _sse({"content": "Let me look that up. "}),
+ _sse(
+ {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "c1",
+ "function": {"name": "web_search", "arguments": '{"query":"42"}'},
+ }
+ ]
+ }
+ ),
+ _sse(finish = "stop"),
+ _DONE,
+]
+
+
+class _HealingTransport:
+ """An OAI-compatible transport, i.e. one that heals text-form calls."""
+
+ heals_text_tool_calls = True
+
+ def __init__(self, turns):
+ self._turns = [list(turn) for turn in turns]
+
+ def stream(self, *, messages, tools, tool_choice, cancel_event):
+ lines = self._turns.pop(0) if self._turns else [_DONE]
+
+ async def _generate():
+ for line in lines:
+ yield line
+
+ return _generate()
+
+
+def loop_env(monkeypatch):
+ """Run tools inline and keep RAG and the risk check out of the way."""
+ executed: list[str] = []
+ monkeypatch.setattr(
+ loop_mod,
+ "execute_tool",
+ lambda name, arguments, **kwargs: (executed.append(name), f"RESULT<{name}>")[1],
+ )
+ monkeypatch.setattr(loop_mod, "build_rag_autoinject", lambda *a, **k: None)
+ monkeypatch.setattr(loop_mod, "is_high_risk_tool_call", lambda name, args: False)
+ return executed
+
+
+def _relay(turns, *, ui_events):
+ """The route's relay for one request: drop control frames, then strip, lazily.
+
+ Laziness matters. Draining the loop and stripping afterwards would let the loop's flag
+ arrive before any line was stripped, which passes even when the fix is absent.
+ """
+
+ async def _run():
+ stripper = ServerToolCallStripper()
+ generator = stream_with_studio_tools(
+ _HealingTransport(turns),
+ run = ToolLoopRun(
+ messages = [{"role": "user", "content": "hi"}],
+ session_id = "s1",
+ thread_id = "t1",
+ ),
+ policy = ToolLoopPolicy(
+ tools = [WEB_SEARCH],
+ max_calls = 25,
+ timeout = 300,
+ permission_mode = "off",
+ confirm_calls = False,
+ bypass_permissions = False,
+ rag_scope = None,
+ on_withheld_tool_call = None if ui_events else stripper.arm,
+ on_provider_turn_end = None if ui_events else stripper.end_turn,
+ ),
+ cancel_event = threading.Event(),
+ )
+ seen: list[str] = []
+ async for line in generator:
+ if not ui_events:
+ if is_ui_control_sse_line(line):
+ continue
+ line = stripper.strip(line)
+ if line is None:
+ continue
+ seen.append(line)
+ if not ui_events:
+ owed = stripper.owed_terminal_chunk()
+ if owed:
+ seen.append(owed)
+ return seen
+
+ return asyncio.run(asyncio.wait_for(_run(), timeout = 30.0))
+
+
+def _finish_reasons(lines):
+ reasons = []
+ for line in lines:
+ if not line.startswith("data: ") or line == _DONE:
+ continue
+ try:
+ payload = json.loads(line[len("data: ") :])
+ except ValueError:
+ continue
+ for choice in payload.get("choices") or []:
+ if isinstance(choice, dict) and isinstance(choice.get("finish_reason"), str):
+ reasons.append(choice["finish_reason"])
+ return reasons
+
+
+def _text(lines):
+ out = []
+ for line in lines:
+ if not line.startswith("data: ") or line == _DONE:
+ continue
+ try:
+ payload = json.loads(line[len("data: ") :])
+ except ValueError:
+ continue
+ for choice in payload.get("choices") or []:
+ if isinstance(choice, dict):
+ content = (choice.get("delta") or {}).get("content")
+ if isinstance(content, str):
+ out.append(content)
+ return "".join(out)
+
+
+ "turns, label",
+ [
+ (_TEXT_FORM_TURN, "closed tag, promoted in feed()"),
+ (_UNTERMINATED_TURN, "unterminated, promoted in finalize()"),
+ ],
+)
+def test_a_healed_call_does_not_leak_its_turns_stop(loop_env, turns, label):
+ lines = _relay([turns, _ANSWER_TURN], ui_events = False)
+
+ assert loop_env == ["web_search"], f"the tool must actually run ({label})"
+ # Exactly one finish_reason, and it arrives last: a client ending on the first one still
+ # reads the post-tool answer.
+ assert _finish_reasons(lines) == ["stop"], label
+ assert "The answer is 42." in _text(lines), label
+ assert _finish_reasons(lines[:-1]) == [], f"the terminal must be last ({label})"
+
+
+def test_a_structured_call_behaves_the_same_way(loop_env):
+ """The shape that already worked, as the reference the healed ones must match."""
+ lines = _relay([_STRUCTURED_TURN, _ANSWER_TURN], ui_events = False)
+
+ assert loop_env == ["web_search"]
+ assert _finish_reasons(lines) == ["stop"]
+ assert "The answer is 42." in _text(lines)
+
+
+def test_the_opt_in_stream_still_sees_both_turns_reasons(loop_env):
+ """Nothing is withheld from the Studio UI: it reads the cards and needs the real turns."""
+ lines = _relay([_TEXT_FORM_TURN, _ANSWER_TURN], ui_events = True)
+
+ assert loop_env == ["web_search"]
+ assert _finish_reasons(lines) == ["stop", "stop"]
+ assert any(is_ui_control_sse_line(line) for line in lines), "tool cards must survive"
+
+
+def test_a_turn_with_no_call_keeps_its_only_finish_reason(loop_env):
+ """The healer is live on every turn here, so the ordinary path must be untouched."""
+ plain = [_sse({"content": "Just an answer."}), _sse(finish = "stop"), _DONE]
+ lines = _relay([plain], ui_events = False)
+
+ assert loop_env == []
+ assert _finish_reasons(lines) == ["stop"]
+ assert _text(lines) == "Just an answer."
+
+
+def test_a_healed_call_owes_a_terminal_even_with_no_finish_chunk(loop_env):
+ """A provider may close a turn on [DONE] alone, sending no finish_reason at all.
+
+ Nothing is held back in that case, but the call is still promoted and run, so the debt
+ has to be armed anyway. Otherwise a loop that then ends without a genuine terminal --
+ here the second pass says nothing -- closes the stream on [DONE] carrying no
+ finish_reason, which openai-node rejects with "missing finish_reason for choice 0".
+ """
+ no_finish = [
+ _sse({"content": "Let me look that up. "}),
+ _sse({"content": '<tool_call>{"name": "web_search", '}),
+ _sse({"content": '"arguments": {"query": "42"}}</tool_call>'}),
+ _DONE,
+ ]
+ lines = _relay([no_finish, [_DONE]], ui_events = False)
+
+ assert loop_env == ["web_search"], "the tool must actually run"
+ assert _finish_reasons(lines) == ["stop"], "a terminal must be minted"
+
+
+def test_holding_the_turn_end_does_not_reorder_the_text(loop_env):
+ """Only the finish_reason waits for healing; the content on that chunk goes out in place.
+
+ The healer withholds any trailing run that could still become a tool marker, so a final
+ delta ending in "<to" releases its prose and buffers the rest. Parking that whole chunk
+ let the residue flushed by finalize() overtake the prose and reverse it on the wire --
+ "Comparing: <tothe value " -- even though the conversation replay stayed correct. No
+ tool call is involved: any healing turn whose last delta ends in "<" hits this.
+ """
+ trailing_marker = [
+ _sse({"content": "Comparing: "}),
+ _sse({"content": "the value <to"}, finish = "stop"),
+ _DONE,
+ ]
+ lines = _relay([trailing_marker], ui_events = False)
+
+ assert loop_env == [], "no tool call in this stream"
+ assert _text(lines) == "Comparing: the value <to"
+ assert _finish_reasons(lines) == ["stop"]
+ # The reason is last, so a client reading in order sees the whole turn before it ends.
+ assert _finish_reasons(lines[:-1]) == []
+
+
+def test_the_opt_in_stream_keeps_that_order_too(loop_env):
+ """The reordering happened inside the loop, upstream of the stripper, so it hit both."""
+ trailing_marker = [
+ _sse({"content": "Comparing: "}),
+ _sse({"content": "the value <to"}, finish = "stop"),
+ _DONE,
+ ]
+ lines = _relay([trailing_marker], ui_events = True)
+
+ assert _text(lines) == "Comparing: the value <to"
+
+
+def test_the_next_turns_legacy_call_keeps_its_own_reason(loop_env):
+ """A withheld call must not reach past the turn it belonged to.
+
+ The wire is not always enough to close a turn: a provider can end one on [DONE] alone,
+ and the loop eats that sentinel rather than relaying it, so the withheld-call flag stayed
+ raised into the next turn. A legacy delta.function_call there is the caller's own to
+ dispatch, and it dispatches on the finish_reason, so stripping that reason as though it
+ closed the previous call means the call never runs.
+ """
+ server_call_then_done = [
+ _sse({"content": "looking. "}),
+ _sse(
+ {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "c1",
+ "function": {"name": "web_search", "arguments": '{"query":"42"}'},
+ }
+ ]
+ }
+ ),
+ _DONE,
+ ]
+ legacy_offer = [
+ _sse({"content": "now yours: "}),
+ _sse({"function_call": {"name": "caller_tool", "arguments": '{"x":1}'}}),
+ _sse(finish = "function_call"),
+ _DONE,
+ ]
+ lines = _relay([server_call_then_done, legacy_offer], ui_events = False)
+
+ assert loop_env == ["web_search"], "only the server call runs; the legacy one is the caller's"
+ assert "function_call" in _text(lines) or any(
+ '"function_call"' in line for line in lines
+ ), "the legacy call itself must reach the caller"
+ # Its own reason, not a minted stop: the caller dispatches on this.
+ assert _finish_reasons(lines) == ["function_call"]
+
+
+def test_a_truncated_turn_keeps_its_reason(loop_env):
+ """ "length" cut the call off half-written, so the loop refuses to run it.
+
+ Nothing follows, so that reason is genuinely the end of the response and withholding it
+ would leave the caller with none at all.
+ """
+ truncated = list(_TEXT_FORM_TURN)
+ truncated[-2] = _sse(finish = "length")
+ lines = _relay([truncated, _ANSWER_TURN], ui_events = False)
+
+ assert loop_env == [], "a truncated call must not run"
+ assert _finish_reasons(lines) == ["length"]
diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.py
index 9fb5c6effa1..2343008f6ef 100644
--- a/studio/backend/tests/test_openai_tool_passthrough.py
+++ b/studio/backend/tests/test_openai_tool_passthrough.py
@@ -3881,6 +3881,10 @@ class TestGgufVisionToolRouting:
url = SimpleNamespace(path = "/v1/chat/completions")
method = "POST"
+ def __init__(self, ui_events = False):
+ # Tool cards and the approval handshake ride these frames.
+ self.headers = {"X-Unsloth-Events": "1"} if ui_events else {}
+
async def is_disconnected(self):
return False
@@ -4024,7 +4028,9 @@ class TestGgufVisionToolRouting:
)
response = self._drive(
- openai_chat_completions(payload, request = self._Request(), current_subject = "test")
+ openai_chat_completions(
+ payload, request = self._Request(ui_events = True), current_subject = "test"
+ )
)
self._consume_response(response)
@@ -4071,7 +4077,9 @@ class TestGgufVisionToolRouting:
)
response = self._drive(
- openai_chat_completions(payload, request = self._Request(), current_subject = "test")
+ openai_chat_completions(
+ payload, request = self._Request(ui_events = True), current_subject = "test"
+ )
)
self._consume_response(response)
@@ -4277,6 +4285,105 @@ class TestGgufVisionToolRouting:
# Neither site may leave a row running.
assert monitor.active_count() == 0
+ def test_streaming_confirm_gate_refuses_a_caller_that_hid_the_frames(self, monkeypatch):
+ # A stream without X-Unsloth-Events has nowhere to be asked, so the loop would park
+ # in wait_tool_decision for the full timeout (_confirm_gate_has_no_channel).
+ import routes.inference as inf_mod
+
+ reset_tool_policy()
+
+ def _tools(**_kwargs):
+ raise AssertionError("the tool loop must not start with nowhere to confirm")
+
+ backend = SimpleNamespace(
+ is_loaded = True,
+ is_vision = False,
+ supports_tools = True,
+ supports_reasoning = True,
+ reasoning_always_on = True,
+ _is_audio = False,
+ model_identifier = "test-gguf",
+ context_length = 4096,
+ generate_chat_completion = lambda **_kwargs: "unused",
+ generate_chat_completion_with_tools = _tools,
+ )
+ monkeypatch.setattr(inf_mod, "get_llama_cpp_backend", lambda: backend)
+ monkeypatch.setattr(inf_mod, "api_monitor", ApiMonitor(max_entries = 3))
+
+ payload = ChatCompletionRequest(
+ model = "default",
+ enable_tools = True,
+ enabled_tools = ["terminal"],
+ stream = True,
+ messages = [{"role": "user", "content": "run something"}],
+ )
+ with pytest.raises(HTTPException) as exc:
+ self._drive(
+ openai_chat_completions(payload, request = self._Request(), current_subject = "test")
+ )
+ assert exc.value.status_code == 400
+ message = exc.value.detail["error"]["message"]
+ assert "X-Unsloth-Events" in message
+ # Names the way out, or a client that cannot render a prompt is stuck.
+ assert "permission_mode" in message
+
+ def test_streaming_confirm_gate_admits_a_caller_that_opted_in(self, monkeypatch):
+ # Same request with the frames on runs the loop: the guard refuses no one else.
+ def _tools(**_kwargs):
+ yield {"type": "content", "text": "done"}
+ yield {
+ "type": "metadata",
+ "usage": {"prompt_tokens": 3, "completion_tokens": 2, "total_tokens": 5},
+ "finish_reason": "stop",
+ }
+
+ result = self._run_gguf_case(
+ monkeypatch,
+ tool_generate = _tools,
+ payload_kwargs = {
+ "stream": True,
+ "enable_tools": True,
+ "enabled_tools": ["terminal"],
+ "messages": [{"role": "user", "content": "run something"}],
+ },
+ request = self._Request(ui_events = True),
+ )
+ deltas = [p["choices"][0].get("delta", {}) for p in result.payloads if p.get("choices")]
+ assert "".join(d.get("content", "") for d in deltas) == "done"
+
+ def test_an_empty_selection_is_not_refused_for_a_prompt_it_can_never_show(self, monkeypatch):
+ # mcp_enabled arms _confirm_gate_needs_stream on intent, but discovery finds no MCP
+ # tool here, so the selection is empty and the loop is skipped. Refusing on intent
+ # would 400 a request that answers fine without ever prompting.
+ import routes.inference as inf_mod
+
+ reset_tool_policy()
+
+ async def _no_tools(*_args, **_kwargs):
+ return []
+
+ monkeypatch.setattr(inf_mod, "_select_request_tools", _no_tools)
+
+ def _generate(**_kwargs):
+ yield "hi"
+ yield {
+ "type": "metadata",
+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
+ "finish_reason": "stop",
+ }
+
+ result = self._run_gguf_case(
+ monkeypatch,
+ generate = _generate,
+ payload_kwargs = {
+ "stream": True,
+ "mcp_enabled": True,
+ "messages": [{"role": "user", "content": "hi"}],
+ },
+ )
+ deltas = [p["choices"][0].get("delta", {}) for p in result.payloads if p.get("choices")]
+ assert "".join(d.get("content", "") for d in deltas) == "hi"
+
def test_standard_gguf_stream_splits_reasoning_content(self, monkeypatch):
def _generate(**_kwargs):
yield "<thi"
@@ -4533,7 +4640,7 @@ class TestGgufVisionToolRouting:
)
response = await openai_chat_completions(
payload,
- request = Request(),
+ request = Request(ui_events = True),
current_subject = "test",
)
iterator = response.body_iterator
@@ -4617,7 +4724,8 @@ class TestGgufVisionToolRouting:
)
response = await openai_chat_completions(
payload,
- request = self._Request(),
+ # A gateable request has to opt in: tool_start carries the approval_id.
+ request = self._Request(ui_events = True),
current_subject = "test",
)
iterator = response.body_iterator
@@ -4694,7 +4802,7 @@ class TestGgufVisionToolRouting:
)
response = await openai_chat_completions(
payload,
- request = self._Request(),
+ request = self._Request(ui_events = True),
current_subject = "test",
)
iterator = response.body_iterator
@@ -5101,6 +5209,8 @@ class TestGgufVisionToolRouting:
"enabled_tools": ["terminal"],
"messages": [{"role": "user", "content": "list files"}],
},
+ # terminal is confirmable, so the gate needs the frames it asks on.
+ request = self._Request(ui_events = True),
)
deltas = [p["choices"][0].get("delta", {}) for p in result.payloads if p.get("choices")]
@@ -5130,6 +5240,8 @@ class TestGgufVisionToolRouting:
"enabled_tools": ["terminal"],
"messages": [{"role": "user", "content": "say literal"}],
},
+ # terminal is confirmable, so the gate needs the frames it asks on.
+ request = self._Request(ui_events = True),
)
deltas = [p["choices"][0].get("delta", {}) for p in result.payloads if p.get("choices")]
diff --git a/studio/backend/tests/test_research_internal_call_tool_gate.py b/studio/backend/tests/test_research_internal_call_tool_gate.py
index 76eda221dc8..c4d09251ece 100644
--- a/studio/backend/tests/test_research_internal_call_tool_gate.py
+++ b/studio/backend/tests/test_research_internal_call_tool_gate.py
@@ -76,7 +76,11 @@ def _entry_point(monkeypatch, *, policy, opt_out):
if policy is not None:
set_tool_policy(policy)
response = _client(monkeypatch, backend).post(
- "/chat/completions", json = _research_payload(opt_out)
+ "/chat/completions",
+ json = _research_payload(opt_out),
+ # Unrestricted without the opt-out, so the confirm gate arms and needs a channel.
+ # Research sends enabled_tools: [] and never arms it.
+ headers = {"X-Unsloth-Events": "1"},
)
assert response.status_code == 200
assert "the answer" in response.text
diff --git a/studio/backend/tests/test_sf_client_tools_passthrough.py b/studio/backend/tests/test_sf_client_tools_passthrough.py
index 3a2a0a9f4c5..a9d69fa094e 100644
--- a/studio/backend/tests/test_sf_client_tools_passthrough.py
+++ b/studio/backend/tests/test_sf_client_tools_passthrough.py
@@ -53,6 +53,8 @@ class _Request:
url = SimpleNamespace(path = "/v1/chat/completions")
method = "POST"
scope: dict = {}
+ # These cases drive the tool loop, whose confirm gate asks over these frames.
+ headers = {"X-Unsloth-Events": "1"}
async def is_disconnected(self):
return False
diff --git a/studio/backend/tests/test_sf_tool_choice_none_history.py b/studio/backend/tests/test_sf_tool_choice_none_history.py
new file mode 100644
index 00000000000..a7ddf7c9ca5
--- /dev/null
+++ b/studio/backend/tests/test_sf_tool_choice_none_history.py
@@ -0,0 +1,174 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Probe: tool_choice "none" on a named-template model must keep tool history."""
+
+import asyncio
+import json
+from types import SimpleNamespace
+
+import pytest
+
+from models.inference import ChatCompletionRequest, ChatMessage
+from routes.inference import openai_chat_completions
+from core.inference.api_monitor import ApiMonitor
+
+
+LOOKUP_TOOL = {
+ "type": "function",
+ "function": {
+ "name": "lookup",
+ "description": "Look something up",
+ "parameters": {
+ "type": "object",
+ "properties": {"q": {"type": "string"}},
+ "required": ["q"],
+ },
+ },
+}
+
+# A named-template model: tool support lives ONLY in the tool_use branch.
+DEFAULT_BODY = (
+ "{% for m in messages %}<|im_start|>{{ m.role }}\n{{ m.content }}<|im_end|>\n{% endfor %}"
+)
+TOOL_USE_BODY = (
+ "{% if tools %}tools available{% endif %}"
+ "{% for m in messages %}<|im_start|>{{ m.role }}\n{{ m.content }}"
+ "<tool_call>{{ m.tool_calls }}</tool_call><|im_end|>\n{% endfor %}"
+)
+NAMED_TEMPLATE = {"default": DEFAULT_BODY, "tool_use": TOOL_USE_BODY}
+
+
+class _Request:
+ state = SimpleNamespace()
+ url = SimpleNamespace(path = "/v1/chat/completions")
+ method = "POST"
+ scope: dict = {}
+ headers = {"X-Unsloth-Events": "1"}
+
+ async def is_disconnected(self):
+ return False
+
+
+class _ScriptedBackend:
+ active_model_name = "sf-model"
+
+ def __init__(self):
+ self.models = {
+ "sf-model": {
+ "chat_template_info": {"template": NAMED_TEMPLATE},
+ "context_length": 2048,
+ }
+ }
+ self.calls: list = []
+ self.reset_count = 0
+
+ def generate_chat_response(
+ self,
+ *,
+ messages,
+ tools = None,
+ stats_holder = None,
+ **kwargs,
+ ):
+ self.calls.append({"messages": messages, "tools": tools, **kwargs})
+ yield "the weather is sunny"
+
+ def generate_chat_completion_with_tools(
+ self,
+ *,
+ messages,
+ tools = None,
+ **kwargs,
+ ):
+ self.calls.append({"loop": True, "messages": messages, "tools": tools, **kwargs})
+ yield {"type": "content", "text": "the weather is sunny"}
+
+ def reset_generation_state(self, caller_cancel_event = None):
+ self.reset_count += 1
+
+ def resize_image(self, image):
+ return image
+
+
+def _llama_stub():
+ return SimpleNamespace(
+ is_loaded = False, supports_tools = False, is_vision = False, context_length = None
+ )
+
+
+def _install(monkeypatch, backend):
+ import routes.inference as inf
+ from state.tool_policy import reset_tool_policy
+
+ reset_tool_policy()
+ monkeypatch.setattr(inf, "api_monitor", ApiMonitor(max_entries = 8))
+ monkeypatch.setattr(inf, "get_llama_cpp_backend", lambda: _llama_stub())
+ monkeypatch.setattr(inf, "get_inference_backend", lambda: backend)
+
+
+def _continued_exchange(**extra):
+ base = dict(
+ model = "default",
+ messages = [
+ ChatMessage(role = "user", content = "weather in SF?"),
+ ChatMessage(
+ role = "assistant",
+ content = None,
+ tool_calls = [
+ {
+ "id": "call_abc",
+ "type": "function",
+ "function": {"name": "lookup", "arguments": '{"q": "sf weather"}'},
+ }
+ ],
+ ),
+ ChatMessage(role = "tool", tool_call_id = "call_abc", name = "lookup", content = "sunny"),
+ ],
+ tools = [LOOKUP_TOOL],
+ tool_choice = "none",
+ enable_tools = True,
+ stream = False,
+ )
+ base.update(extra)
+ return ChatCompletionRequest(**base)
+
+
+def _run(payload, monkeypatch, backend):
+ _install(monkeypatch, backend)
+
+ async def _go():
+ return await openai_chat_completions(payload, request = _Request(), current_subject = "u")
+
+ return asyncio.run(_go())
+
+
+def test_tool_history_survives_tool_choice_none(monkeypatch):
+ backend = _ScriptedBackend()
+ _run(_continued_exchange(), monkeypatch, backend)
+
+ assert backend.calls, "generator never ran"
+ msgs = backend.calls[0]["messages"]
+ print("\nMESSAGES HANDED TO BACKEND:\n" + json.dumps(msgs, indent = 2, default = str))
+ print("TOOLS HANDED TO BACKEND:", backend.calls[0]["tools"])
+
+ assistant = [m for m in msgs if (m.get("role") if isinstance(m, dict) else None) == "assistant"]
+ tool_msgs = [m for m in msgs if (m.get("role") if isinstance(m, dict) else None) == "tool"]
+ assert assistant, "assistant tool-call turn dropped entirely"
+ assert assistant[0].get("tool_calls"), "assistant tool_calls dropped"
+ assert tool_msgs, "tool result dropped"
+ assert tool_msgs[0].get("tool_call_id") == "call_abc", "tool_call_id dropped"
+ assert backend.calls[0]["tools"] is None, "tool_choice none must advertise no tools"
+
+
+def test_tool_history_survives_plain_openai_client(monkeypatch):
+ """The common shape: an OpenAI client that never sets Unsloth's enable_tools."""
+ backend = _ScriptedBackend()
+ _run(_continued_exchange(enable_tools = None), monkeypatch, backend)
+
+ msgs = backend.calls[0]["messages"]
+ print("\nPLAIN CLIENT MESSAGES:\n" + json.dumps(msgs, indent = 2, default = str))
+ assistant = [m for m in msgs if isinstance(m, dict) and m.get("role") == "assistant"]
+ tool_msgs = [m for m in msgs if isinstance(m, dict) and m.get("role") == "tool"]
+ assert assistant and assistant[0].get("tool_calls"), "assistant tool_calls dropped"
+ assert tool_msgs and tool_msgs[0].get("tool_call_id") == "call_abc", "tool_call_id dropped"
diff --git a/studio/backend/tests/test_studio_api.py b/studio/backend/tests/test_studio_api.py
index 13dfccde203..c707bd9166d 100644
--- a/studio/backend/tests/test_studio_api.py
+++ b/studio/backend/tests/test_studio_api.py
@@ -251,6 +251,9 @@ def test_curl_with_tools(base_url: str, api_key: str):
"stream": True,
"enable_tools": True,
"enabled_tools": ["python"],
+ # The shape the API keys tab hands out. The confirm gate only asks over the
+ # opt-in X-Unsloth-Events frames, so this says the tools run unprompted.
+ "permission_mode": "off",
"session_id": "test-session",
},
headers = {"Authorization": f"Bearer {api_key}"},
@@ -259,8 +262,11 @@ def test_curl_with_tools(base_url: str, api_key: str):
assert status == 200, f"Expected 200, got {status}"
assert len(chunks) > 0, "No SSE chunks received for tools request"
- # Check that at least one chunk has the expected shape
- has_valid_chunk = any("choices" in c or "type" in c for c in chunks)
+ # Only `choices`: this sends the documented snippet shape, which does not take
+ # X-Unsloth-Events, so a bare `type` frame can no longer arrive and accepting one would
+ # read as coverage this no longer has. Frame-level proof that the tool ran lives in the
+ # CI smokes, which opt in so their tool_start/tool_end assertions keep a witness.
+ has_valid_chunk = any("choices" in c for c in chunks)
assert has_valid_chunk, "No valid chunks in tools response"
full = _collect_streamed_content(chunks)
print(f" PASS curl with tools: {len(chunks)} chunks, {len(full)} chars content")
diff --git a/studio/backend/tests/test_ui_stream_events_gate.py b/studio/backend/tests/test_ui_stream_events_gate.py
new file mode 100644
index 00000000000..aaa5f92129b
--- /dev/null
+++ b/studio/backend/tests/test_ui_stream_events_gate.py
@@ -0,0 +1,808 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Unsloth's UI control frames are opt-in on OpenAI-compatible streams.
+
+Frames like ``tool_status`` / ``reasoning_summary`` carry no ``choices``, so
+strict OpenAI clients (openai-python, the Vercel AI SDK, opencode) fail schema
+validation mid-stream when they arrive. /v1/chat/completions therefore emits a
+clean OpenAI stream by default; the Studio UI opts in with X-Unsloth-Events: 1,
+and durable runs (whose event log is replayed to that UI) opt in internally.
+"""
+
+from __future__ import annotations
+
+import ast
+import inspect
+import json
+import threading
+
+from pathlib import Path
+from types import SimpleNamespace
+from unittest import mock
+
+from core.inference.sse_control_frames import (
+ ServerToolCallStripper,
+ is_ui_control_sse_line,
+ strip_server_executed_tool_call,
+)
+from routes.inference import (
+ _LOCAL_TOOL_STREAM_STALL_KEEPALIVE_S,
+ UI_STREAM_EVENTS_HEADER,
+ _DroppedFrameKeepalive,
+ _confirm_gate_has_no_channel,
+ _launcher_tool_default_applies,
+ _proxy_to_external_provider,
+ _ui_stream_events_enabled,
+ produce_openai_chat_completions,
+)
+
+
+def _request(headers: list[tuple[bytes, bytes]]):
+ from starlette.requests import Request
+
+ scope = {
+ "type": "http",
+ "asgi": {"version": "3.0", "spec_version": "2.3"},
+ "http_version": "1.1",
+ "method": "POST",
+ "scheme": "http",
+ "path": "/v1/chat/completions",
+ "raw_path": b"/v1/chat/completions",
+ "query_string": b"",
+ "headers": headers,
+ "client": ("127.0.0.1", 0),
+ "server": ("127.0.0.1", 0),
+ "state": {},
+ }
+
+ async def receive():
+ return {"type": "http.request", "body": b"", "more_body": False}
+
+ return Request(scope, receive)
+
+
+def test_no_header_means_clean_openai_stream():
+ assert _ui_stream_events_enabled(_request([])) is False
+
+
+def test_header_opts_in():
+ req = _request([(UI_STREAM_EVENTS_HEADER.lower().encode(), b"1")])
+ assert _ui_stream_events_enabled(req) is True
+
+
+def test_other_header_values_do_not_opt_in():
+ for value in (b"0", b"true", b"yes", b"", b" 1x"):
+ req = _request([(UI_STREAM_EVENTS_HEADER.lower().encode(), value)])
+ assert _ui_stream_events_enabled(req) is False, value
+
+
+def test_none_request_is_refused():
+ assert _ui_stream_events_enabled(None) is False
+
+
+def test_background_generation_run_opts_into_control_frames():
+ # Durable runs replay the producer's SSE lines (tool cards included) to the Studio UI,
+ # so their synthetic request must carry the opt-in.
+ from core.inference.chat_generation_runs import _background_request
+ req = _background_request(app = None, run_id = "run-1", cancel_event = threading.Event())
+ assert _ui_stream_events_enabled(req) is True
+
+
+def test_openai_stream_control_yields_are_gated():
+ # Every raw control-frame yield must sit behind the per-request opt-in; keepalive and
+ # error chunks are plain SSE and exempt.
+ src = inspect.getsource(produce_openai_chat_completions)
+ lines = src.splitlines()
+ control_yields = (
+ 'yield f"data: {json.dumps(event)}',
+ 'yield f"data: {json.dumps(cumulative)}',
+ 'yield f"data: {status_data}',
+ )
+ candidate_lines = {
+ i + 1
+ for i, line in enumerate(lines)
+ if any(line.strip().startswith(p) for p in control_yields)
+ }
+ assert candidate_lines, "control-frame yields disappeared from the producer"
+
+ guarded: set[int] = set()
+ for node in ast.walk(ast.parse(src)):
+ if isinstance(node, ast.If) and "_ui_events" in ast.dump(node.test):
+ guarded.update(range(node.lineno, (node.end_lineno or node.lineno) + 1))
+
+ ungated = sorted(candidate_lines - guarded)
+ assert not ungated, f"ungated control-frame yields at producer lines {ungated}"
+
+
+def test_dropped_frames_still_pace_a_keepalive():
+ # A gated-off frame writes nothing but still restarts the stall-keepalive wait and
+ # tool_stream_exec's heartbeat, so an unpaced stream is silent for the whole tool run
+ # and a Cloudflare quick tunnel drops it at ~100s idle.
+ keepalive = _DroppedFrameKeepalive(now = 0.0)
+ assert keepalive.due(now = _LOCAL_TOOL_STREAM_STALL_KEEPALIVE_S - 0.01) is False
+ assert keepalive.due(now = _LOCAL_TOOL_STREAM_STALL_KEEPALIVE_S) is True
+ # Paced, not per-frame: the window restarts from the one just written.
+ assert keepalive.due(now = _LOCAL_TOOL_STREAM_STALL_KEEPALIVE_S + 0.01) is False
+ assert keepalive.due(now = 2 * _LOCAL_TOOL_STREAM_STALL_KEEPALIVE_S) is True
+
+
+def test_every_gated_frame_falls_back_to_a_keepalive():
+ # Dropping a frame must never mean writing nothing, so each opt-in branch carries the
+ # paced keepalive on its else side.
+ src = inspect.getsource(produce_openai_chat_completions)
+ gates = [
+ node
+ for node in ast.walk(ast.parse(src))
+ if isinstance(node, ast.If)
+ and "_ui_events" in ast.dump(node.test)
+ # Frame-emitting gates only; the opt-in also guards bookkeeping that writes nothing.
+ and any(isinstance(child, ast.Yield) for child in ast.walk(ast.Module(node.body, [])))
+ ]
+ assert gates, "the per-request control-frame gate disappeared from the producer"
+
+ missing = [
+ node.lineno
+ for node in gates
+ if not (
+ len(node.orelse) == 1
+ and isinstance(node.orelse[0], ast.If)
+ and "_drop_keepalive" in ast.dump(node.orelse[0].test)
+ )
+ ]
+ assert not missing, f"gated frames dropped with no keepalive at producer lines {missing}"
+
+
+def test_control_frame_lines_are_recognised_by_type():
+ # The vocabulary lives in sse_control_frames so the passthrough relay and the local gate
+ # cannot drift apart when a frame type is added.
+ for frame in (
+ "tool_start",
+ "tool_end",
+ "tool_output",
+ "tool_args",
+ "tool_status",
+ "diffusion_frame",
+ "reasoning_summary",
+ ):
+ assert is_ui_control_sse_line('data: {"type": "%s"}' % frame) is True, frame
+
+
+def test_ordinary_chunks_and_sse_scaffolding_are_not_control_frames():
+ for line in (
+ 'data: {"choices": [{"delta": {"content": "hi"}}]}',
+ # An Unsloth extension stamped inside a real chunk still carries choices.
+ 'data: {"choices": [], "usage": {}, "_toolEvent": {"type": "tool_end"}}',
+ "data: [DONE]",
+ ": keep-alive",
+ "event: message",
+ "data: not json",
+ ):
+ assert is_ui_control_sse_line(line) is False, line
+
+
+def _gate_payload(**kwargs):
+ fields = {
+ "stream": True,
+ "bypass_permissions": False,
+ "confirm_tool_calls": None,
+ "permission_mode": None,
+ "mcp_enabled": False,
+ "enabled_tools": None,
+ "tool_choice": None,
+ "max_tool_calls_per_message": None,
+ # Explicit, so the launcher-default branch is not what is under test here.
+ "enable_tools": True,
+ # Read by _request_states_tool_intent when the launcher default is in play.
+ "tools": None,
+ "messages": [],
+ "response_format": None,
+ }
+ fields.update(kwargs)
+ return SimpleNamespace(**fields)
+
+
+def test_confirm_gate_needs_both_a_stream_and_the_frames():
+ # Either channel missing means the gate has nowhere to ask.
+ assert _confirm_gate_has_no_channel(_gate_payload(), False) is True
+ assert _confirm_gate_has_no_channel(_gate_payload(), True) is False
+ # Non-streaming keeps its old reading: an unset mode stays lenient (a health check must
+ # not 400), an explicit one has nowhere to prompt.
+ assert _confirm_gate_has_no_channel(_gate_payload(stream = False), True) is False
+ assert (
+ _confirm_gate_has_no_channel(_gate_payload(stream = False, permission_mode = "ask"), True)
+ is True
+ )
+ # An explicit opt-out of the gate needs no channel at all.
+ assert _confirm_gate_has_no_channel(_gate_payload(bypass_permissions = True), False) is False
+ assert _confirm_gate_has_no_channel(_gate_payload(permission_mode = "off"), False) is False
+
+
+def test_a_streaming_request_that_can_never_prompt_is_not_refused():
+ # An unset permission_mode is read as auto on a stream, the way the loop defaults it, so
+ # an always-safe selection is not refused over a prompt that can never fire. Deep research
+ # drives its own /v1/chat/completions this way (enabled_tools: []).
+ assert _confirm_gate_has_no_channel(_gate_payload(enabled_tools = []), False) is False
+ # A selection that can prompt still is.
+ assert _confirm_gate_has_no_channel(_gate_payload(enabled_tools = ["terminal"]), False) is True
+ # As is an omitted selection, which resolves to every built-in tool.
+ assert _confirm_gate_has_no_channel(_gate_payload(enabled_tools = None), False) is True
+ # An explicit ask never converges on auto's leniency.
+ assert (
+ _confirm_gate_has_no_channel(_gate_payload(permission_mode = "ask", enabled_tools = []), False)
+ is True
+ )
+
+
+def test_a_request_that_can_run_no_tool_is_not_refused():
+ # stream_with_studio_tools withdraws the catalogue unless tool_choice is not "none" and
+ # the budget is unspent, so neither shape can reach a prompt. The selector reads neither
+ # field, so the catalogue alone cannot answer this.
+ assert _confirm_gate_has_no_channel(_gate_payload(tool_choice = "none"), False) is False
+ assert _confirm_gate_has_no_channel(_gate_payload(max_tool_calls_per_message = 0), False) is False
+ # An unspent budget is not a disabled one.
+ assert _confirm_gate_has_no_channel(_gate_payload(max_tool_calls_per_message = 1), False) is True
+ # Non-streaming keeps its own reading; this only narrows the stream refusal.
+ assert (
+ _confirm_gate_has_no_channel(
+ _gate_payload(stream = False, permission_mode = "ask", tool_choice = "none"), True
+ )
+ is True
+ )
+
+
+_USAGE_EXAMPLES = (
+ Path(__file__).resolve().parents[2]
+ / "frontend/src/features/settings/components/usage-examples.tsx"
+)
+
+
+_LIVE_SMOKE = Path(__file__).resolve().parent / "test_studio_api.py"
+
+
+def test_the_live_tool_smoke_sends_the_shape_the_examples_hand_out():
+ # Example 4 in the live smoke is the same curl the API keys tab shows, so it has to stay
+ # runnable in the same way.
+ src = _LIVE_SMOKE.read_text(encoding = "utf-8")
+ body = src[src.index("def test_curl_with_tools") :]
+ body = body[: body.index("\ndef ")]
+ assert '"enable_tools": True' in body
+ assert '"permission_mode": "off"' in body
+
+
+def test_the_bundled_api_examples_are_still_runnable():
+ # The API keys tab's copy-paste snippets stream with python and terminal enabled and
+ # deliberately do not take the control frames, so without an explicit mode the confirm
+ # gate would refuse every one of them before generation.
+ src = _USAGE_EXAMPLES.read_text(encoding = "utf-8")
+ tool_branches = src.count("enable_tools")
+ assert tool_branches, "the tool variants disappeared from the examples"
+ assert (
+ src.count('permission_mode": "off"')
+ + src.count('permission_mode = "off"')
+ + src.count('permission_mode: "off"')
+ == tool_branches
+ ), "every example that enables tools must pick a permission mode"
+
+ # And the shape they now send is one the gate admits.
+ example = _gate_payload(
+ enabled_tools = ["web_search", "python", "terminal"],
+ permission_mode = "off",
+ )
+ assert _confirm_gate_has_no_channel(example, False) is False
+ # Without the mode it would not be, which is what the snippets guard against.
+ assert (
+ _confirm_gate_has_no_channel(
+ _gate_payload(enabled_tools = ["web_search", "python", "terminal"]), False
+ )
+ is True
+ )
+
+
+def test_a_structured_type_field_does_not_crash_the_relay():
+ # sanitize_provider_sse_line passes a non-string `type` through, and a frozenset
+ # membership test on an unhashable value raises, so a custom provider could end an
+ # otherwise relayable stream with a server error.
+ for value in ('{"a": 1}', "[1, 2]", "3", "null", "true"):
+ line = 'data: {"type": %s, "choices": []}' % value
+ assert is_ui_control_sse_line(line) is False, line
+
+
+def test_the_loops_bare_status_frames_are_held_back_too():
+ # build_synthetic_search_exchange brackets a RAG autoinjection with {"type": "status"}
+ # frames, written straight onto the relayed stream. "status" is not in the
+ # provider-forgery vocabulary, but it carries no choices, so a strict client fails on it
+ # exactly like a tool card.
+ assert is_ui_control_sse_line('data: {"type": "status", "text": "Searching: x"}') is True
+ assert is_ui_control_sse_line('data: {"type": "status", "text": ""}') is True
+ # usage and error are the provider's own vocabulary; a client reads them.
+ assert is_ui_control_sse_line('data: {"type": "error", "error": {"message": "x"}}') is False
+ assert is_ui_control_sse_line('data: {"type": "x", "usage": {"total_tokens": 3}}') is False
+ # A context_truncated chunk keeps its choices, so it is a chunk, not a frame.
+ assert is_ui_control_sse_line('data: {"choices": [], "context_truncated": {}}') is False
+
+
+def test_a_call_the_server_runs_itself_is_not_offered_to_the_caller():
+ # The loop relays the provider's delta.tool_calls and the finish_reason ending that turn,
+ # for a call Unsloth runs and answers later. The catalogue is Unsloth's own, so a client
+ # acting on those chunks runs the tool twice, or stops before the real answer arrives.
+ assert (
+ strip_server_executed_tool_call(
+ 'data: {"choices": [{"index": 0, "delta": {"tool_calls": [{"id": "c1"}]}}]}'
+ )
+ is None
+ )
+ assert (
+ strip_server_executed_tool_call(
+ 'data: {"choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}]}'
+ )
+ is None
+ )
+ # A chunk that also carries prose keeps the prose.
+ kept = strip_server_executed_tool_call(
+ 'data: {"choices": [{"index": 0, "delta": {"content": "hi", "tool_calls": [{"id": "c"}]}}]}'
+ )
+ assert kept is not None and "tool_calls" not in kept and '"content":"hi"' in kept
+ # Everything else passes through byte-for-byte.
+ for line in (
+ 'data: {"choices": [{"index": 0, "delta": {"content": "hi"}}]}',
+ 'data: {"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}',
+ 'data: {"choices": [], "usage": {"total_tokens": 3}}',
+ "data: [DONE]",
+ ": keep-alive",
+ ):
+ assert strip_server_executed_tool_call(line) == line, line
+
+
+def test_the_relay_only_strips_calls_the_loop_owns():
+ # On a plain proxy the calls are the caller's own, so the strip is gated on the loop
+ # running: policy on the Codex branch, run_studio_tool_loop on the other.
+ src = inspect.getsource(_proxy_to_external_provider)
+ assert "if not _ui_events and policy is not None:" in src
+ assert "if not _ui_events and run_studio_tool_loop:" in src
+ assert src.count("_tool_call_stripper.strip(line)") == 2
+
+
+def test_a_legacy_function_call_is_left_for_the_caller():
+ # The loop reads delta.tool_calls and nothing else, so a legacy function_call is one it
+ # never executes: stripping it would drop a call the caller is meant to run, and its
+ # matching finish_reason would arrive with no name or arguments behind it.
+ for line in (
+ 'data: {"choices": [{"index": 0, "delta": {"function_call": {"name": "f"}}}]}',
+ 'data: {"choices": [{"index": 0, "delta": {}, "finish_reason": "function_call"}]}',
+ ):
+ assert strip_server_executed_tool_call(line) == line, line
+ # And a finish_reason with no call withheld beside it is the caller's own turn ending.
+ plain = 'data: {"choices": [{"index": 0, "delta": {"content": "x"}, "finish_reason": "stop"}]}'
+ assert strip_server_executed_tool_call(plain) == plain
+
+
+def test_a_stop_that_only_looks_final_is_held_back_too():
+ # llama.cpp and vLLM finish a perfectly good structured tool call on "stop", and the loop
+ # deliberately runs those (studio_tool_loop keeps "stop" out of `truncated`). Stripping
+ # only the call leaves an empty chunk marked finish_reason "stop", so a client ending on
+ # the first finish_reason never reads the answer the loop is about to stream.
+ stripper = ServerToolCallStripper()
+ call = (
+ 'data: {"choices": [{"index": 0, "delta": {"tool_calls": [{"index": 0, '
+ '"id": "c1", "type": "function", "function": {"name": "python", '
+ '"arguments": "{}"}}]}, "finish_reason": null}]}'
+ )
+ end = 'data: {"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}'
+
+ # The call chunk carries nothing else, so it drops entirely, as it already did.
+ assert stripper.strip(call) is None
+ # So does the "stop" that closes that turn: otherwise the caller gets an empty chunk
+ # marked finish_reason "stop" and ends the turn there.
+ assert stripper.strip(end) is None
+ # The loop's next turn is the caller's to read, finish_reason and all.
+ answer = 'data: {"choices": [{"index": 0, "delta": {"content": "56088"}}]}'
+ assert stripper.strip(answer) == answer
+ assert stripper.strip(end) == end
+
+
+def test_a_stop_the_loop_will_not_run_past_stays_final():
+ # "length" and "content_filter" are the two the loop refuses to run (a call cut off at the
+ # token ceiling may be half-written), so that turn really is the last one.
+ for reason in ("length", "content_filter"):
+ stripper = ServerToolCallStripper()
+ call = (
+ 'data: {"choices": [{"index": 0, "delta": {"tool_calls": [{"index": 0, '
+ '"id": "c1", "type": "function", "function": {"name": "python"}}]}}]}'
+ )
+ stripper.strip(call)
+ end = 'data: {"choices": [{"index": 0, "delta": {}, "finish_reason": "%s"}]}' % reason
+ assert json.loads(stripper.strip(end)[5:])["choices"][0]["finish_reason"] == reason
+
+
+def _call_chunk(delta, finish = None):
+ return "data: " + json.dumps(
+ {
+ "id": "x",
+ "object": "chat.completion.chunk",
+ "created": 1,
+ "model": "m",
+ "choices": [{"index": 0, "delta": delta, "finish_reason": finish}],
+ }
+ )
+
+
+_ONE_CALL = [
+ {"index": 0, "id": "c1", "type": "function", "function": {"name": "python", "arguments": "{}"}}
+]
+
+
+def test_a_call_co_emitted_with_its_finish_reason_is_still_held_back():
+ # A provider may put the call and the reason that ends its turn on ONE line; any
+ # non-streamed upstream relayed as a single line does. So the withheld-call flag has to be
+ # raised before the strip reads it, or this leaks the empty "stop" the gate exists to
+ # prevent and then eats the real one that follows.
+ for reason in ("stop", "tool_calls"):
+ stripper = ServerToolCallStripper()
+ assert stripper.strip(_call_chunk({"tool_calls": _ONE_CALL}, reason)) is None
+ answer = _call_chunk({"content": "56088"})
+ assert json.loads(stripper.strip(answer)[5:])["choices"][0]["delta"]["content"] == "56088"
+ # The loop's own turn ends normally, and that reason is the caller's to read.
+ end = _call_chunk({}, "stop")
+ assert json.loads(stripper.strip(end)[5:])["choices"][0]["finish_reason"] == "stop"
+ assert stripper.owed_terminal_chunk() is None
+
+
+def test_a_withheld_call_the_loop_never_runs_still_ends_the_stream():
+ # The loop can close without opening the turn a withheld call promised: a spent tool
+ # budget, a discarded call, a provider that failed mid-loop. The reason removed with that
+ # call was then the stream's last one, and finish_reason is required -- openai-node raises
+ # "missing finish_reason for choice 0".
+ stripper = ServerToolCallStripper()
+ assert stripper.strip(_call_chunk({"tool_calls": _ONE_CALL})) is None
+ assert stripper.strip(_call_chunk({}, "stop")) is None
+ owed = stripper.owed_terminal_chunk()
+ assert owed is not None
+ payload = json.loads(owed[5:])
+ assert payload["choices"][0]["finish_reason"] == "stop"
+ # Minted in the stream's own envelope, not a bare choices list.
+ assert payload["object"] == "chat.completion.chunk"
+ assert (payload["id"], payload["model"]) == ("x", "m")
+ # Owed once, not on every later poll.
+ assert stripper.owed_terminal_chunk() is None
+
+
+def test_an_empty_tool_calls_entry_counts_as_a_withheld_call():
+ # The strip removes the key whether or not it is truthy, so the flag must read the same
+ # condition; otherwise the line drops without arming the turn and the next "stop" leaks.
+ stripper = ServerToolCallStripper()
+ stripper.strip(_call_chunk({"tool_calls": []}))
+ assert stripper.strip(_call_chunk({}, "stop")) is None
+
+
+def test_both_relays_send_a_finish_the_stripper_still_owes():
+ # A blanked terminal reason is only safe if something replaces it before [DONE].
+ src = inspect.getsource(_proxy_to_external_provider)
+ assert src.count("_tool_call_stripper.owed_terminal_chunk()") == 2
+
+
+def test_a_turn_with_no_withheld_call_keeps_its_own_stop():
+ # The state is per turn, not per stream: an ordinary turn must be relayed untouched.
+ stripper = ServerToolCallStripper()
+ for line in (
+ 'data: {"choices": [{"index": 0, "delta": {"content": "hi"}}]}',
+ 'data: {"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}',
+ ):
+ assert stripper.strip(line) == line, line
+
+
+def test_a_process_wide_tools_on_flag_does_not_refuse_a_plain_request():
+ # `unsloth studio run --enable-tools` fills the tool-policy OVERRIDE slot, not the default
+ # one, so _tools_on_by_launcher_default_only stops answering for it. Reading that narrower
+ # predicate here would 400 every ordinary OpenAI stream on that launcher, `unsloth chat`'s
+ # own included, over a slot choice the caller cannot see or act on.
+ payload = _gate_payload(enable_tools = None, enabled_tools = None)
+ for policy in (None, True):
+ with mock.patch("state.tool_policy.get_tool_policy", return_value = policy):
+ assert _confirm_gate_has_no_channel(payload, False, ["python"]) is False
+ # Tools are withdrawn for that stream instead, so the loop it could not be
+ # prompted for never opens.
+ assert _launcher_tool_default_applies(payload, False) is False
+ # A request that asked for tools itself is still refused: it can be told about the header.
+ asked = _gate_payload(enable_tools = True, enabled_tools = ["python"])
+ for policy in (None, True):
+ with mock.patch("state.tool_policy.get_tool_policy", return_value = policy):
+ assert _confirm_gate_has_no_channel(asked, False, ["python"]) is True
+
+
+def test_a_disabled_tool_policy_can_never_prompt():
+ # --disable-tools vetoes even an explicit enable_tools, so no loop opens and nothing
+ # can prompt. Refusing there would 400 a request that would have run fine.
+ asked = _gate_payload(enable_tools = True, enabled_tools = ["python"])
+ with mock.patch("state.tool_policy.get_tool_policy", return_value = False):
+ assert _confirm_gate_has_no_channel(asked, False, ["python"]) is False
+
+
+def test_the_selected_catalog_beats_a_stale_mcp_flag():
+ # mcp_enabled arms the classifier on the flag alone. The resolved catalogue answers
+ # better: an MCP ask discovery filtered to nothing leaves only always-safe built-ins.
+ payload = _gate_payload(mcp_enabled = True, enabled_tools = ["search_knowledge_base"])
+ assert _confirm_gate_has_no_channel(payload, False) is True
+ assert _confirm_gate_has_no_channel(payload, False, ["search_knowledge_base"]) is False
+ # A catalogue that kept something confirmable still needs the channel.
+ assert _confirm_gate_has_no_channel(payload, False, ["python"]) is True
+ # An MCP tool that survived is not an always-safe built-in, so it still does.
+ assert _confirm_gate_has_no_channel(payload, False, ["mcp__server__do_thing"]) is True
+
+
+def test_a_stripped_call_still_paces_a_keepalive():
+ # Same trap as the gated frames: a long argument stream drops every fragment and holds off
+ # the loop's stall timer, so the relay must write something.
+ src = inspect.getsource(_proxy_to_external_provider)
+ assert src.count("_tool_call_stripper.strip(line)") == 2
+ # Each strip that drops the line pairs with the paced keepalive before continuing.
+ assert src.count("if line is None:") == 2
+ stripped_blocks = src.count("_drop_keepalive.due()")
+ assert stripped_blocks == 4, (
+ f"expected a paced keepalive on both control-frame and stripped-call drops, "
+ f"found {stripped_blocks}"
+ )
+
+
+def test_the_launcher_default_does_not_claim_a_stream_it_cannot_prompt(monkeypatch):
+ # `unsloth studio run` installs a tools-on default, but a request that never mentions
+ # tools cannot be expected to know about the header either. Putting it behind a confirm
+ # gate would 400 every ordinary OpenAI call on that launcher, or park it in
+ # wait_tool_decision on the first high-risk call. It asked for plain chat.
+ from state import tool_policy
+
+ monkeypatch.setattr(tool_policy, "get_tool_policy", lambda: None)
+ silent = _gate_payload(enable_tools = None, enabled_tools = None)
+ assert _launcher_tool_default_applies(silent, False) is False
+ assert _confirm_gate_has_no_channel(silent, False) is False
+ # The Studio UI takes the frames, so the default keeps answering for it.
+ assert _launcher_tool_default_applies(silent, True) is True
+ # A request that asked for tools itself is not the launcher's default and still needs the
+ # channel; so does one that stated its intent through the standard fields.
+ asked = _gate_payload(enable_tools = True, enabled_tools = None)
+ assert _launcher_tool_default_applies(asked, False) is True
+ assert _confirm_gate_has_no_channel(asked, False) is True
+ assert (
+ _launcher_tool_default_applies(_gate_payload(enable_tools = None, tool_choice = "none"), False)
+ is False
+ )
+
+
+def test_both_local_branches_consult_the_launcher_default_rule():
+ # The suppression has to happen where tools are switched on, or the loop still opens.
+ src = inspect.getsource(produce_openai_chat_completions)
+ assert src.count("_launcher_tool_default_applies(payload, _ui_events)") == 2
+
+
+def test_the_mlx_counter_honours_tool_choice_none():
+ # The safetensors completion withdraws the catalogue outright for tool_choice "none", so a
+ # count that still prices the schemas, or trips the MCP discovery 503, no longer describes
+ # the prompt generation renders. The MLX branch of the rule the GGUF counter already draws
+ # with _client_disabled_tool_calls.
+ from routes import inference as inf
+
+ src = inspect.getsource(inf._mlx_count_chat_tokens)
+ assert 'tool_choice", None) == "none"' in src
+ assert 'tool_choice", None) != "none"' in src
+
+
+def test_tool_choice_none_withdraws_the_catalogue_but_not_the_capability():
+ # _sf_template_tools decides which branch of a named template is READ, not what is
+ # rendered. Following tool_choice there reads the plain branch for a tool conversation,
+ # turning off _sf_client_tools and dropping the assistant's tool_calls and the result's
+ # correlation fields, exactly when "none" asks for the final answer. The withdrawal
+ # belongs to _sf_tools_on and _sf_tools_to_use instead.
+ src = inspect.getsource(produce_openai_chat_completions)
+ detect = src[src.index("_sf_template_tools = ") :][:400]
+ assert 'payload.tool_choice != "none"' not in detect
+ assert 'm.role == "tool" or m.tool_calls' in detect
+ # The catalogue itself is still withdrawn for "none".
+ assert 'if payload.tool_choice == "none":\n _sf_tools_on = False' in src
+
+
+def test_a_withheld_call_always_leaves_the_caller_a_finish_reason():
+ # A provider closing the turn on [DONE] alone offers no finish_reason to remove, so arming
+ # the debt only where one was removed left the caller holding a stream whose only chunk
+ # was withheld. finish_reason is required in the chunk schema: openai-node raises without.
+ stripper = ServerToolCallStripper()
+ call = 'data: {"id": "c", "choices": [{"index": 0, "delta": {"tool_calls": [{"id": "x"}]}}]}'
+ assert stripper.strip(call) is None
+ owed = stripper.owed_terminal_chunk()
+ assert owed is not None and '"finish_reason":"stop"' in owed
+ # Minted once, not on every call.
+ assert stripper.owed_terminal_chunk() is None
+
+
+def test_a_removed_reason_owes_a_terminal_even_with_no_call_to_latch_onto():
+ # A provider can report finish_reason "tool_calls" for a call its own parser failed to
+ # emit (open llama.cpp and vLLM bugs). Nothing is there for the withheld-call flag to
+ # latch onto, so the reason was blanked with no debt recorded and the stream ended with no
+ # finish_reason at all, the openai-node failure the minting exists to prevent.
+ stripper = ServerToolCallStripper()
+ stripper.strip('data: {"id": "c", "choices": [{"index": 0, "delta": {"content": "hi"}}]}')
+ stripper.strip(
+ 'data: {"id": "c", "choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}]}'
+ )
+ owed = stripper.owed_terminal_chunk()
+ assert owed is not None and '"finish_reason":"stop"' in owed
+
+ # The reasons the strip leaves alone are still genuinely final, so nothing is owed.
+ for reason in ("stop", "length", "content_filter"):
+ kept = ServerToolCallStripper()
+ kept.strip('data: {"id": "c", "choices": [{"index": 0, "delta": {"content": "hi"}}]}')
+ kept.strip(
+ 'data: {"id": "c", "choices": [{"index": 0, "delta": {},'
+ ' "finish_reason": "%s"}]}' % reason
+ )
+ assert kept.owed_terminal_chunk() is None, reason
+
+
+def test_a_legacy_finish_after_a_structured_call_is_withheld_too():
+ # A gateway may stream modern delta.tool_calls and still close the turn on the legacy
+ # "function_call" (LocalAI picks it whenever the client sent no tools, litellm relays it
+ # verbatim). The loop runs such a call, so relaying the reason ends the caller's turn
+ # early.
+ stripper = ServerToolCallStripper()
+ call = 'data: {"id": "c", "choices": [{"index": 0, "delta": {"tool_calls": [{"id": "x"}]}}]}'
+ assert stripper.strip(call) is None
+ out = stripper.strip(
+ 'data: {"id": "c", "choices": [{"index": 0, "delta": {},'
+ ' "finish_reason": "function_call"}]}'
+ )
+ assert out is None or '"function_call"' not in out
+
+ # A genuine legacy call is the caller's own to run and keeps its delta and its reason:
+ # pending is keyed on "tool_calls", which a function_call delta never sets.
+ legacy = ServerToolCallStripper()
+ passed = legacy.strip(
+ 'data: {"id": "c", "choices": [{"index": 0, "delta": {"function_call":'
+ ' {"name": "f", "arguments": "{}"}}}]}'
+ )
+ assert passed is not None and "function_call" in passed
+ ended = legacy.strip(
+ 'data: {"id": "c", "choices": [{"index": 0, "delta": {},'
+ ' "finish_reason": "function_call"}]}'
+ )
+ assert ended is not None and '"function_call"' in ended
+
+
+def test_bypass_still_exempts_a_non_streaming_request():
+ # Losing the bypass conjunct here would 400 full-access non-streaming tool runs that work
+ # today. Both shapes the validator can produce: it folds permission_mode "full" and
+ # bypass_permissions into each other, and an explicit confirm_tool_calls survives the fold.
+ for extra in ({}, {"permission_mode": "full"}):
+ payload = _gate_payload(
+ stream = False, bypass_permissions = True, confirm_tool_calls = True, **extra
+ )
+ assert _confirm_gate_has_no_channel(payload, False) is False, extra
+
+ # Without bypass the non-streaming refusal stands: the gate would prompt and cannot.
+ for extra in ({"confirm_tool_calls": True}, {"permission_mode": "ask"}):
+ payload = _gate_payload(stream = False, **extra)
+ assert _confirm_gate_has_no_channel(payload, False) is True, extra
+
+
+def test_a_stream_that_kept_its_own_terminal_is_owed_nothing():
+ # No spurious extra chunk when the caller already has a real finish_reason, whether or not
+ # a call was withheld earlier in the stream.
+ plain = ServerToolCallStripper()
+ plain.strip('data: {"id": "c", "choices": [{"index": 0, "delta": {"content": "hi"}}]}')
+ plain.strip(
+ 'data: {"id": "c", "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}'
+ )
+ assert plain.owed_terminal_chunk() is None
+
+ after_call = ServerToolCallStripper()
+ after_call.strip(
+ 'data: {"id": "c", "choices": [{"index": 0, "delta": {"tool_calls": [{"id": "x"}]},'
+ ' "finish_reason": "tool_calls"}]}'
+ )
+ after_call.strip('data: {"id": "c", "choices": [{"index": 0, "delta": {"content": "a"}}]}')
+ after_call.strip(
+ 'data: {"id": "c", "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}'
+ )
+ assert after_call.owed_terminal_chunk() is None
+
+
+def test_the_mlx_counter_keeps_capability_out_of_the_withdrawal_too():
+ # Same split the completion draws: the catalogue goes for tool_choice "none", the
+ # template branch used to read the history does not.
+ from routes import inference as inf
+
+ src = inspect.getsource(inf._mlx_count_chat_tokens)
+ detect = src[src.index("_template_tools = ") :][:400]
+ assert 'tool_choice", None) != "none"' not in detect
+ assert 'm.role == "tool" or m.tool_calls' in detect
+
+
+def test_external_provider_relay_drops_control_frames_too():
+ # The provider proxy returns before the local producer's per-yield gates and relays the
+ # loop's frames verbatim, so it filters the same vocabulary.
+ src = inspect.getsource(_proxy_to_external_provider)
+ relays = [line for line in src.splitlines() if line.strip() == 'yield f"{line}\\n\\n"']
+ assert relays, "the provider relay yields disappeared"
+ assert src.count("is_ui_control_sse_line(line)") == len(
+ relays
+ ), "every provider relay must hold control frames back from a non-opt-in caller"
+
+
+def test_a_safetensors_stream_that_disabled_tool_calls_opens_no_loop(monkeypatch):
+ # The gate exempts tool_choice: "none" from needing an event channel, on the promise that
+ # no call can happen. The safetensors/MLX branch had to be made to keep that promise:
+ # nothing on that path read the field (not _sf_use_tools, not _select_request_tools, and
+ # generate_chat_completion_with_tools is never passed it), so the loop opened with the
+ # full built-in catalogue for a headerless stream just admitted for being unable to call
+ # anything. The first high-risk call then wrote a tool_start the relay drops and blocked
+ # in wait_tool_decision for the hour.
+ import asyncio
+
+ from core.inference.api_monitor import ApiMonitor
+ from models.inference import ChatCompletionRequest, ChatMessage
+ import routes.inference as inf
+ from state.tool_policy import reset_tool_policy
+
+ opened_loop = []
+
+ class _Backend:
+ active_model_name = "sf-model"
+ models = {
+ "sf-model": {
+ "chat_template_info": {"template": "<tool_call> chatml"},
+ "context_length": 2048,
+ }
+ }
+
+ def generate_chat_response(
+ self,
+ *,
+ messages,
+ tools = None,
+ stats_holder = None,
+ **kw,
+ ):
+ yield "plain answer"
+
+ def generate_chat_completion_with_tools(self, **kwargs):
+ opened_loop.append(kwargs)
+ yield {"type": "content", "content": ""}
+
+ def reset_generation_state(self, caller_cancel_event = None):
+ pass
+
+ def resize_image(self, image):
+ return image
+
+ reset_tool_policy()
+ monkeypatch.setattr(inf, "api_monitor", ApiMonitor(max_entries = 8))
+ monkeypatch.setattr(
+ inf,
+ "get_llama_cpp_backend",
+ lambda: SimpleNamespace(
+ is_loaded = False, supports_tools = False, is_vision = False, context_length = None
+ ),
+ )
+ monkeypatch.setattr(inf, "get_inference_backend", lambda: _Backend())
+ monkeypatch.setattr(
+ inf, "_detect_safetensors_features", lambda *a, **k: {"supports_tools": True}
+ )
+
+ payload = ChatCompletionRequest(
+ model = "default",
+ messages = [ChatMessage(role = "user", content = "hi")],
+ stream = True,
+ enable_tools = True,
+ tool_choice = "none",
+ )
+
+ async def _run():
+ response = await inf.openai_chat_completions(
+ payload, request = _request([]), current_subject = "u"
+ )
+ return [chunk async for chunk in response.body_iterator]
+
+ body = "".join(c.decode() if isinstance(c, bytes) else str(c) for c in asyncio.run(_run()))
+ # No 400: the exemption still admits the request, which is the point of it.
+ assert "invalid_request_error" not in body
+ # And now it is telling the truth: no loop, so no prompt, so nothing to park on.
+ assert opened_loop == [], "tool_choice: 'none' still opened the safetensors tool loop"
+ assert "plain answer" in body
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 81c74d78e97..4d1a3062284 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -1515,7 +1515,12 @@ export async function* streamChatCompletions(
): AsyncGenerator<OpenAIChatChunk> {
const response = await authFetch("/v1/chat/completions", {
method: "POST",
- headers: { "Content-Type": "application/json" },
+ headers: {
+ "Content-Type": "application/json",
+ // Opt into Unsloth's UI control frames (tool cards, statuses, reasoning timing). The
+ // endpoint defaults to a clean OpenAI stream for external clients.
+ "X-Unsloth-Events": "1",
+ },
body: JSON.stringify(payload),
signal,
});
diff --git a/studio/frontend/src/features/settings/components/usage-examples.tsx b/studio/frontend/src/features/settings/components/usage-examples.tsx
index cf8cda50fd1..66d6bc34c4b 100644
--- a/studio/frontend/src/features/settings/components/usage-examples.tsx
+++ b/studio/frontend/src/features/settings/components/usage-examples.tsx
@@ -174,6 +174,10 @@ function bodyExtraLines(variant: Variant, indent: string): string[] {
if (variant !== "plain") {
lines.push(`${indent}"enable_tools": true,`);
lines.push(`${indent}"enabled_tools": [${toolsJson}],`);
+ // The gate only asks over the X-Unsloth-Events frames these snippets deliberately do
+ // not take, so say the tools run unprompted rather than hand out a request the server
+ // refuses.
+ lines.push(`${indent}"permission_mode": "off",`);
}
return lines;
}
@@ -205,6 +209,7 @@ function winBody(model: string, variant: Variant): string {
if (variant !== "plain") {
body.enable_tools = true;
body.enabled_tools = TOOLS;
+ body.permission_mode = "off";
}
body.stream = true;
return JSON.stringify(body, null, 2);
@@ -259,6 +264,8 @@ function pythonSnippet(
if (variant !== "plain") {
extra.push(` "enable_tools": True,`);
extra.push(` "enabled_tools": [${toolsJson}],`);
+ // biome-ignore lint/style/noUnusedTemplateLiteral: keep generated options visually uniform
+ extra.push(` "permission_mode": "off",`);
}
const extraBody = extra.length
? `
@@ -314,6 +321,8 @@ function javascriptSnippet(
// biome-ignore lint/style/noUnusedTemplateLiteral: keep generated options visually uniform
options.push(` enable_tools: true,`);
options.push(` enabled_tools: [${toolsJson}],`);
+ // biome-ignore lint/style/noUnusedTemplateLiteral: keep generated options visually uniform
+ options.push(` permission_mode: "off",`);
}
const trailingOptions = options.length ? `\n${options.join("\n")}` : "";