Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

studio: fix streamed tool calls in api monitor

Etherla11d9537bc7f
diff --git a/.github/workflows/studio-ui-smoke.yml b/.github/workflows/studio-ui-smoke.yml
index 0f3cabac18b..ba1a95152b5 100644
--- a/.github/workflows/studio-ui-smoke.yml
+++ b/.github/workflows/studio-ui-smoke.yml
@@ -634,6 +634,20 @@ jobs:
mkdir -p logs/playwright_image_cancel_retry_cold
python tests/studio/playwright_image_download_cancel_retry.py
+ - name: Tool activity collapse regression (Playwright)
+ if: matrix.shard == 'extra'
+ run: |
+ if [ ! -x studio/frontend/node_modules/.bin/vite ]; then
+ npm install -g npm@^11 --no-fund --no-audit
+ V=$(npm -v)
+ case "$V" in
+ 11.1[6-9].*|11.[2-9][0-9].*|1[2-9].*) echo "npm $V has allowScripts" ;;
+ *) echo "::error::npm $V lacks allowScripts (need >=11.16)"; exit 1 ;;
+ esac
+ npm --prefix studio/frontend ci --strict-allow-scripts --no-fund --no-audit
+ fi
+ python tests/studio/playwright_tool_activity.py --json
+
# The log budget in studio/backend/tests/log_budget compares two BACKEND files with
# each other: the suppression sets in loggers/handlers.py and the poll cadences in
# session.py. A pull request that adds a polling call site in the frontend edits
diff --git a/studio/backend/core/inference/api_monitor.py b/studio/backend/core/inference/api_monitor.py
index 6589c4d4069..9969a9b4d05 100644
--- a/studio/backend/core/inference/api_monitor.py
+++ b/studio/backend/core/inference/api_monitor.py
@@ -5,8 +5,10 @@
from __future__ import annotations
-import math
+import hashlib
+import json
import logging
+import math
import os
import threading
import time
@@ -32,6 +34,8 @@ _MAX_ENTRIES = 50
_MAX_PROMPT_CHARS = 12000
_MAX_REPLY_CHARS = 12000
_PREVIEW_CHARS = 360
+_MAX_STREAM_TOOL_CALLS = 64
+_MAX_STREAM_TOOL_FIELD_CHARS = 501
_MAX_DECODE_MS = 24 * 60 * 60 * 1000
# Far above any real context window; larger means a broken upstream payload.
_MAX_TOKEN_COUNT = 1 << 40
@@ -76,6 +80,90 @@ def _trim(text: Optional[str], limit: int) -> str:
return text[: limit - 3] + "..."
+@dataclass
+class _OpenAIStreamToolCall:
+ choice_index: int
+ tool_index: int
+ call_id: Optional[str] = None
+ name: str = ""
+ arguments: str = ""
+
+
+def _stream_tool_fragment(fragment: Any, *, serialize_json: bool = False) -> Optional[str]:
+ if fragment is None:
+ return None
+ if isinstance(fragment, str):
+ return fragment
+ return json.dumps(fragment, default = str) if serialize_json else str(fragment)
+
+
+def _append_stream_tool_field(
+ current: str,
+ fragment: Any,
+ budget: int,
+ *,
+ serialize_json: bool = False,
+) -> str:
+ if fragment is None or budget <= 0 or len(current) >= _MAX_STREAM_TOOL_FIELD_CHARS:
+ return current
+ fragment = _stream_tool_fragment(fragment, serialize_json = serialize_json)
+ if fragment is None:
+ return current
+ remaining = min(_MAX_STREAM_TOOL_FIELD_CHARS - len(current), budget)
+ return current + fragment[:remaining]
+
+
+def _merge_stream_tool_name(current: str, fragment: Any, budget: int) -> str:
+ fragment = _stream_tool_fragment(fragment)
+ if fragment is None:
+ return current
+ if fragment.startswith(current):
+ limit = min(_MAX_STREAM_TOOL_FIELD_CHARS, len(current) + max(0, budget))
+ return fragment[:limit]
+ return _append_stream_tool_field(current, fragment, budget)
+
+
+def _stream_tool_call_is_complete(state: _OpenAIStreamToolCall) -> bool:
+ if not state.name or not state.arguments:
+ return False
+ try:
+ arguments = json.loads(state.arguments)
+ except (TypeError, ValueError):
+ return False
+ return isinstance(arguments, (dict, list))
+
+
+def _stream_tool_call_preview(state: _OpenAIStreamToolCall) -> str:
+ name = state.name or "<unknown>"
+ if len(name) > 500:
+ name = name[:497] + "..."
+ if not state.arguments:
+ return f"Tool call: {name}"
+ arguments = state.arguments
+ if len(arguments) > 500:
+ arguments = arguments[:497] + "..."
+ return f"Tool call: {name}({arguments})"
+
+
+def _append_stream_tool_previews(
+ entry: ApiMonitorEntry, states: list[_OpenAIStreamToolCall]
+) -> None:
+ if not states:
+ return
+ text = "\n".join(_stream_tool_call_preview(state) for state in states)
+ if entry.reply and not entry.reply.endswith("\n"):
+ text = "\n" + text
+ entry.reply = _trim(entry.reply + text, _MAX_REPLY_CHARS)
+
+
+def _stream_tool_call_id(value: Any) -> Optional[str]:
+ if not isinstance(value, str) or not value:
+ return None
+ if len(value) <= _MAX_STREAM_TOOL_FIELD_CHARS:
+ return value
+ return "sha256:" + hashlib.sha256(value.encode("utf-8", errors = "replace")).hexdigest()
+
+
@dataclass
class ApiMonitorEntry:
id: str
@@ -123,6 +211,10 @@ class ApiMonitorEntry:
# Every finish reason seen so far. An n > 1 stream reports each choice in its own
# chunk, so agreement can only be judged across the whole request. Not serialized.
stop_reasons_seen: set[str] = field(default_factory = set)
+ # request-local preview state, omitted from snapshots and cleared on terminal paths.
+ openai_stream_tool_calls: list[_OpenAIStreamToolCall] = field(default_factory = list)
+ openai_stream_last_tool_indexes: dict[int, int] = field(default_factory = dict)
+ openai_stream_last_segment_was_tool: bool = False
def snapshot(
self,
@@ -382,6 +474,7 @@ class ApiMonitor:
text: str,
*,
stamp_first_token: bool = True,
+ separate_from_openai_tool: bool = False,
) -> None:
if not entry_id or not text:
return
@@ -389,6 +482,10 @@ class ApiMonitor:
entry = self._find_locked(entry_id)
if entry is None or entry.finished_at is not None:
return
+ if separate_from_openai_tool and entry.openai_stream_last_segment_was_tool:
+ if entry.reply and not entry.reply.endswith("\n"):
+ text = "\n" + text
+ entry.openai_stream_last_segment_was_tool = False
# Only a streaming delta stamps TTFT; a full-response append is end-to-end latency.
if stamp_first_token:
now = time.monotonic()
@@ -408,6 +505,147 @@ class ApiMonitor:
entry.reply = _trim(entry.reply + text, _MAX_REPLY_CHARS)
entry.updated_at = time.time()
+ def accumulate_openai_tool_call(
+ self,
+ entry_id: Optional[str],
+ *,
+ choice_index: int,
+ tool_index: Optional[int],
+ tool_index_explicit: bool = True,
+ call_id: Optional[str],
+ name_fragment: Any,
+ arguments_fragment: Any,
+ ) -> None:
+ """Merge one streamed OpenAI tool-call delta into its monitor row."""
+ if not entry_id:
+ return
+ call_id = _stream_tool_call_id(call_id)
+ with self._lock:
+ entry = self._find_locked(entry_id)
+ if entry is None or entry.finished_at is not None:
+ return
+ same_choice = [
+ state
+ for state in entry.openai_stream_tool_calls
+ if state.choice_index == choice_index
+ ]
+ if tool_index is None:
+ tool_index = entry.openai_stream_last_tool_indexes.get(choice_index, 0)
+ state = None
+ same_index = [
+ candidate for candidate in same_choice if candidate.tool_index == tool_index
+ ]
+ if tool_index_explicit:
+ state = next(
+ (
+ candidate
+ for candidate in reversed(same_index)
+ if candidate.call_id == call_id
+ ),
+ None,
+ )
+ if state is None and call_id is not None:
+ state = next(
+ (
+ candidate
+ for candidate in reversed(same_index)
+ if candidate.call_id is None
+ ),
+ None,
+ )
+ elif call_id is not None:
+ state = next(
+ (
+ candidate
+ for candidate in reversed(same_choice)
+ if candidate.call_id == call_id
+ ),
+ None,
+ )
+ if state is None and call_id is None:
+ state = same_index[-1] if same_index else None
+ if state is None:
+ pending_chars = sum(
+ len(candidate.name) + len(candidate.arguments)
+ for candidate in entry.openai_stream_tool_calls
+ )
+ if (
+ len(entry.openai_stream_tool_calls) >= _MAX_STREAM_TOOL_CALLS
+ or pending_chars >= _MAX_REPLY_CHARS
+ ):
+ return
+ state = _OpenAIStreamToolCall(
+ choice_index = choice_index,
+ tool_index = tool_index,
+ call_id = call_id,
+ )
+ entry.openai_stream_tool_calls.append(state)
+ elif call_id is not None and state.call_id is None:
+ state.call_id = call_id
+ entry.openai_stream_last_tool_indexes[choice_index] = tool_index
+ pending_chars = sum(
+ len(candidate.name) + len(candidate.arguments)
+ for candidate in entry.openai_stream_tool_calls
+ )
+ budget = _MAX_REPLY_CHARS - pending_chars
+ previous_name_length = len(state.name)
+ state.name = _merge_stream_tool_name(state.name, name_fragment, budget)
+ budget -= len(state.name) - previous_name_length
+ state.arguments = _append_stream_tool_field(
+ state.arguments,
+ arguments_fragment,
+ budget,
+ serialize_json = True,
+ )
+ now = time.monotonic()
+ if entry.first_token_monotonic is None:
+ entry.first_token_monotonic = now
+ if entry.first_decode_monotonic is None:
+ entry.first_decode_monotonic = now
+ entry.updated_at = time.time()
+
+ def take_openai_tool_calls(
+ self,
+ entry_id: Optional[str],
+ *,
+ choice_index: Optional[int] = None,
+ completed_only: bool = False,
+ ) -> tuple[list[tuple[str, str]], bool]:
+ """Remove and return completed preview calls in first-seen order."""
+ if not entry_id:
+ return [], False
+ with self._lock:
+ entry = self._find_locked(entry_id)
+ if entry is None or entry.finished_at is not None:
+ return [], False
+ selected = [
+ state
+ for state in entry.openai_stream_tool_calls
+ if (choice_index is None or state.choice_index == choice_index)
+ and (not completed_only or _stream_tool_call_is_complete(state))
+ ]
+ if not selected:
+ return [], False
+ separate = bool(entry.reply) and not entry.reply.endswith("\n")
+ entry.openai_stream_last_segment_was_tool = True
+ selected_ids = {id(state) for state in selected}
+ entry.openai_stream_tool_calls = [
+ state for state in entry.openai_stream_tool_calls if id(state) not in selected_ids
+ ]
+ remaining_indexes = {
+ state.choice_index: state.tool_index for state in entry.openai_stream_tool_calls
+ }
+ if choice_index is None:
+ entry.openai_stream_last_tool_indexes = remaining_indexes
+ elif choice_index not in remaining_indexes:
+ entry.openai_stream_last_tool_indexes.pop(choice_index, None)
+ else:
+ entry.openai_stream_last_tool_indexes[choice_index] = remaining_indexes[
+ choice_index
+ ]
+ entry.updated_at = time.time()
+ return [(state.name, state.arguments) for state in selected], separate
+
def mark_first_token(
self,
entry_id: Optional[str],
@@ -562,6 +800,10 @@ class ApiMonitor:
# already ran) must not move finished_*.
if entry.finished_at is not None:
return
+ _append_stream_tool_previews(entry, entry.openai_stream_tool_calls)
+ entry.openai_stream_tool_calls.clear()
+ entry.openai_stream_last_tool_indexes.clear()
+ entry.openai_stream_last_segment_was_tool = False
self._settle_stop_reason_locked(entry, status == "completed")
now = time.time()
entry.status = status
@@ -607,6 +849,10 @@ class ApiMonitor:
self._notify_terminal(notification)
def _fail_locked(self, entry: ApiMonitorEntry, error: str) -> None:
+ _append_stream_tool_previews(entry, entry.openai_stream_tool_calls)
+ entry.openai_stream_tool_calls.clear()
+ entry.openai_stream_last_tool_indexes.clear()
+ entry.openai_stream_last_segment_was_tool = False
self._settle_stop_reason_locked(entry, False)
now = time.time()
entry.status = "error"
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 15c13cbc157..7336028c8a7 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -5144,6 +5144,79 @@ def _monitor_tool_calls_text(tool_calls: Any) -> str:
return "\n".join(parts)
+def _monitor_stream_tool_call_deltas(
+ monitor_id: Optional[str], choice_index: int, tool_calls: Any
+) -> bool:
+ if not isinstance(tool_calls, list):
+ return False
+ accumulated = False
+ for position, tool_call in enumerate(tool_calls):
+ if not isinstance(tool_call, dict):
+ continue
+ function = tool_call.get("function") or {}
+ if not isinstance(function, dict):
+ function = {}
+ tool_index = tool_call.get("index")
+ tool_index_explicit = isinstance(tool_index, int) and not isinstance(tool_index, bool)
+ if not tool_index_explicit:
+ tool_index = position if len(tool_calls) > 1 else None
+ name = function.get("name")
+ if name is None:
+ name = tool_call.get("name")
+ arguments = function.get("arguments")
+ if arguments is None:
+ arguments = tool_call.get("arguments")
+ api_monitor.accumulate_openai_tool_call(
+ monitor_id,
+ choice_index = choice_index,
+ tool_index = tool_index,
+ tool_index_explicit = tool_index_explicit,
+ call_id = tool_call.get("id"),
+ name_fragment = name,
+ arguments_fragment = arguments,
+ )
+ accumulated = True
+ return accumulated
+
+
+def _monitor_stream_function_call_delta(
+ monitor_id: Optional[str], choice_index: int, function_call: Any
+) -> bool:
+ if not isinstance(function_call, dict):
+ return False
+ api_monitor.accumulate_openai_tool_call(
+ monitor_id,
+ choice_index = choice_index,
+ tool_index = 0,
+ call_id = None,
+ name_fragment = function_call.get("name"),
+ arguments_fragment = function_call.get("arguments"),
+ )
+ return True
+
+
+def _flush_monitor_stream_tool_calls(
+ monitor_id: Optional[str],
+ choice_index: Optional[int] = None,
+ *,
+ completed_only: bool = False,
+) -> None:
+ calls, separate = api_monitor.take_openai_tool_calls(
+ monitor_id,
+ choice_index = choice_index,
+ completed_only = completed_only,
+ )
+ if not calls:
+ return
+ parts = []
+ for name, arguments in calls:
+ if len(name) > 500:
+ name = name[:497] + "..."
+ parts.append(_monitor_call_text(name or "<unknown>", arguments))
+ prefix = "\n" if separate else ""
+ api_monitor.append_reply(monitor_id, prefix + "\n".join(parts), stamp_first_token = False)
+
+
def _monitor_openai_chunk(
monitor_id: Optional[str],
data: dict,
@@ -5172,6 +5245,7 @@ def _monitor_openai_chunk(
if not isinstance(choices, list) or not choices:
return
if isinstance(data, dict) and data.get("_toolEvent"):
+ _flush_monitor_stream_tool_calls(monitor_id)
# Tool cards ride the chunk beside choices with an empty delta; already seen.
# Not decoded output though: a tool run (or a human confirming one) between the
# card and the first token would otherwise be counted as decoding time.
@@ -5180,16 +5254,46 @@ def _monitor_openai_chunk(
for idx, choice in enumerate(choices):
if not isinstance(choice, dict):
continue
+ choice_index = choice.get("index")
+ if not isinstance(choice_index, int):
+ choice_index = idx
delta = choice.get("delta") or {}
message = choice.get("message") or {}
if isinstance(delta, dict) and delta.get("reasoning_content"):
api_monitor.mark_first_token(monitor_id)
+ streamed_tool_delta = False
+ if streaming and isinstance(delta, dict):
+ streamed_tool_delta = _monitor_stream_tool_call_deltas(
+ monitor_id,
+ choice_index,
+ delta.get("tool_calls"),
+ )
+ if not streamed_tool_delta:
+ streamed_tool_delta = _monitor_stream_function_call_delta(
+ monitor_id,
+ choice_index,
+ delta.get("function_call"),
+ )
content = delta.get("content") if isinstance(delta, dict) else None
if content:
- api_monitor.append_reply(monitor_id, content)
+ if streaming:
+ _flush_monitor_stream_tool_calls(
+ monitor_id,
+ choice_index,
+ completed_only = not bool(choice.get("finish_reason")),
+ )
+ api_monitor.append_reply(
+ monitor_id,
+ content,
+ separate_from_openai_tool = True,
+ )
continue
- if isinstance(delta, dict):
+ if streamed_tool_delta:
+ if choice.get("finish_reason"):
+ _flush_monitor_stream_tool_calls(monitor_id, choice_index)
+ continue
+ if not streaming and isinstance(delta, dict):
tool_text = _monitor_tool_calls_text(delta.get("tool_calls"))
if tool_text:
api_monitor.append_reply(monitor_id, tool_text)
@@ -5204,6 +5308,8 @@ def _monitor_openai_chunk(
tool_text = _monitor_tool_calls_text(message.get("tool_calls"))
if tool_text:
reply_parts.append((idx, tool_text))
+ if streaming and choice.get("finish_reason"):
+ _flush_monitor_stream_tool_calls(monitor_id, choice_index)
if not reply_parts:
return
if len(choices) == 1:
@@ -5251,6 +5357,7 @@ def _monitor_openai_sse_line(
return None
data_str = raw_line[5:].lstrip()
if data_str == "[DONE]":
+ _flush_monitor_stream_tool_calls(monitor_id)
api_monitor.finish(monitor_id)
return "done"
try:
@@ -17690,7 +17797,7 @@ async def _proxy_to_external_provider(
sent_done = True
if not sent_done:
if not stream_failed:
- api_monitor.finish(monitor_id)
+ _monitor_openai_sse_line(monitor_id, "data: [DONE]")
yield "data: [DONE]\n\n"
except asyncio.CancelledError:
api_monitor.finish(monitor_id, "cancelled")
diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.py
index 3de093a2a83..fcae77f27fd 100644
--- a/studio/backend/tests/test_openai_tool_passthrough.py
+++ b/studio/backend/tests/test_openai_tool_passthrough.py
@@ -5417,6 +5417,71 @@ class TestApiMonitorProviderAndCompletionStreams:
upstream_bodies = upstream_bodies,
)
+ @staticmethod
+ def _captured_tool_call_frames():
+ def _frame(delta, finish_reason = None):
+ return "data: " + json.dumps(
+ {
+ "id": "chatcmpl-captured",
+ "choices": [
+ {
+ "index": 0,
+ "delta": delta,
+ "finish_reason": finish_reason,
+ }
+ ],
+ },
+ separators = (",", ":"),
+ )
+
+ argument_fragments = [
+ "{",
+ '"command":"',
+ "echo",
+ " HER",
+ "MES",
+ "_UNS",
+ "LO",
+ "TH",
+ "_OK",
+ '"',
+ "}",
+ ]
+ frames = [_frame({"role": "assistant", "content": None})]
+ frames.append(
+ _frame(
+ {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "call-captured",
+ "type": "function",
+ "function": {
+ "name": "terminal",
+ "arguments": argument_fragments[0],
+ },
+ }
+ ]
+ }
+ )
+ )
+ frames.extend(
+ _frame(
+ {
+ "tool_calls": [
+ {
+ "index": 0,
+ "function": {"arguments": fragment},
+ }
+ ]
+ }
+ )
+ for fragment in argument_fragments[1:]
+ )
+ frames.extend([_frame({}, "tool_calls"), "data: [DONE]"])
+ assert len(frames) == 14
+ return frames
+
def test_passthrough_stream_preheader_dispatched_with_timeout(self, monkeypatch):
async def _run():
import routes.inference as inf_mod
@@ -6248,6 +6313,51 @@ class TestApiMonitorProviderAndCompletionStreams:
asyncio.run(_run())
+ def test_external_stream_clean_eof_flushes_pending_tool_monitor(self, monkeypatch):
+ async def _run():
+ import routes.inference as inf_mod
+
+ lines = [
+ 'data: {"choices":[{"index":0,"delta":{"tool_calls":['
+ '{"index":0,"id":"call-eof","function":{"name":"lookup",'
+ '"arguments":"{\\"query\\":"}}]}}]}',
+ 'data: {"choices":[{"index":0,"delta":{"tool_calls":['
+ '{"index":0,"function":{"arguments":"\\"weather\\"}"}}]}}]}',
+ ]
+
+ class DummyExternalClient:
+ def __init__(self, **_kwargs):
+ pass
+
+ async def stream_chat_completion(self, **_kwargs):
+ for line in lines:
+ yield line
+
+ async def close(self):
+ pass
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(inf_mod, "ExternalProviderClient", DummyExternalClient)
+ payload = ChatCompletionRequest(
+ model = "default",
+ external_model = "gpt-test",
+ provider_type = "openai",
+ provider_base_url = "https://api.openai.com/v1",
+ messages = [ChatMessage(role = "user", content = "hi")],
+ stream = True,
+ )
+
+ response = await _proxy_to_external_provider(payload, self._Request())
+ chunks = [chunk async for chunk in response.body_iterator]
+
+ assert chunks == [*(f"{line}\n\n" for line in lines), "data: [DONE]\n\n"]
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "completed"
+ assert entry["reply"] == 'Tool call: lookup({"query":"weather"})'
+
+ asyncio.run(_run())
+
def test_external_stream_cancel_finalizes_monitor(self, monkeypatch):
async def _run():
import routes.inference as inf_mod
@@ -6737,6 +6847,734 @@ class TestApiMonitorProviderAndCompletionStreams:
entry = monitor.get(monitor_id)
assert entry["reply"] == 'Tool call: lookup({"query":"weather"})'
+ def test_streamed_tool_monitor_reassembles_captured_frames_without_changing_sse(
+ self, monkeypatch
+ ):
+ async def _run():
+ frames = self._captured_tool_call_frames()
+ result = await self._run_passthrough_stream(monkeypatch, frames)
+
+ assert result.body == "".join(f"{frame}\n\n" for frame in frames)
+ [entry] = result.monitor.snapshot()
+ assert entry["status"] == "completed"
+ assert entry["stop_reason"] == "tool_calls"
+ assert entry["reply"] == ('Tool call: terminal({"command":"echo HERMES_UNSLOTH_OK"})')
+ assert entry["ttft_ms"] is not None
+
+ asyncio.run(_run())
+
+ def test_streamed_tool_monitor_joins_fragmented_name_and_arguments(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monitor_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "gguf",
+ prompt = "hi",
+ )
+ for tool_call in [
+ {
+ "index": 0,
+ "id": "call-fragmented",
+ "function": {"name": "ter", "arguments": '{"com'},
+ },
+ {"index": 0, "function": {"name": "min", "arguments": 'mand":'}},
+ {"index": 0, "function": {"name": "al", "arguments": '"echo"}'}},
+ ]:
+ _monitor_openai_chunk(
+ monitor_id,
+ {"choices": [{"index": 0, "delta": {"tool_calls": [tool_call]}}]},
+ streaming = True,
+ )
+ _monitor_openai_chunk(
+ monitor_id,
+ {"choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}]},
+ streaming = True,
+ )
+
+ assert monitor.get(monitor_id)["reply"] == 'Tool call: terminal({"command":"echo"})'
+
+ def test_streamed_tool_monitor_replaces_cumulative_names(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monitor_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "gguf",
+ prompt = "hi",
+ )
+ for name, arguments in [("web", None), ("web_search", "{}")]:
+ _monitor_openai_chunk(
+ monitor_id,
+ {
+ "choices": [
+ {
+ "index": 0,
+ "delta": {
+ "tool_calls": [
+ {
+ "index": 0,
+ "function": {"name": name, "arguments": arguments},
+ }
+ ]
+ },
+ }
+ ]
+ },
+ streaming = True,
+ )
+ _monitor_openai_chunk(
+ monitor_id,
+ {"choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}]},
+ streaming = True,
+ )
+
+ assert monitor.get(monitor_id)["reply"] == "Tool call: web_search({})"
+
+ def test_streamed_tool_monitor_serializes_structured_arguments(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monitor_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "gguf",
+ prompt = "hi",
+ )
+ _monitor_openai_chunk(
+ monitor_id,
+ {
+ "choices": [
+ {
+ "index": 0,
+ "delta": {
+ "tool_calls": [
+ {
+ "index": 0,
+ "function": {
+ "name": "lookup",
+ "arguments": {"query": "weather", "active": True},
+ },
+ }
+ ]
+ },
+ }
+ ]
+ },
+ streaming = True,
+ )
+ _monitor_openai_chunk(
+ monitor_id,
+ {"choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}]},
+ streaming = True,
+ )
+
+ assert monitor.get(monitor_id)["reply"] == (
+ 'Tool call: lookup({"query": "weather", "active": true})'
+ )
+
+ def test_streamed_legacy_function_monitor_joins_name_and_arguments(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monitor_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "gguf",
+ prompt = "hi",
+ )
+ for function_call in [
+ {"name": "look", "arguments": '{"query":'},
+ {"name": "up", "arguments": '"weather"}'},
+ ]:
+ _monitor_openai_chunk(
+ monitor_id,
+ {"choices": [{"index": 0, "delta": {"function_call": function_call}}]},
+ streaming = True,
+ )
+ _monitor_openai_chunk(
+ monitor_id,
+ {"choices": [{"index": 0, "delta": {}, "finish_reason": "function_call"}]},
+ streaming = True,
+ )
+
+ assert monitor.get(monitor_id)["reply"] == 'Tool call: lookup({"query":"weather"})'
+
+ def test_streamed_tool_monitor_keeps_interleaved_indexes_separate(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monitor_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "gguf",
+ prompt = "hi",
+ )
+ deltas = [
+ {"index": 0, "id": "call-a", "function": {"name": "alpha", "arguments": '{"a":'}},
+ {"index": 1, "id": "call-b", "function": {"name": "beta", "arguments": '{"b":'}},
+ {"index": 0, "function": {"arguments": "1}"}},
+ {"index": 1, "function": {"arguments": "2}"}},
+ ]
+ for tool_call in deltas:
+ _monitor_openai_chunk(
+ monitor_id,
+ {"choices": [{"index": 0, "delta": {"tool_calls": [tool_call]}}]},
+ streaming = True,
+ )
+ _monitor_openai_chunk(
+ monitor_id,
+ {"choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}]},
+ streaming = True,
+ )
+
+ assert monitor.get(monitor_id)["reply"] == (
+ 'Tool call: alpha({"a":1})\nTool call: beta({"b":2})'
+ )
+
+ def test_streamed_tool_monitor_routes_bare_fragments_to_latest_call(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monitor_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "gguf",
+ prompt = "hi",
+ )
+ deltas = [
+ {"index": 0, "function": {"name": "alpha", "arguments": '{"a":'}},
+ {"index": 1, "function": {"name": "beta", "arguments": '{"b":'}},
+ {"function": {"arguments": "2}"}},
+ {"index": 0, "function": {"arguments": "1"}},
+ {"function": {"arguments": "}"}},
+ ]
+ for tool_call in deltas:
+ _monitor_openai_chunk(
+ monitor_id,
+ {"choices": [{"index": 0, "delta": {"tool_calls": [tool_call]}}]},
+ streaming = True,
+ )
+ _monitor_openai_chunk(
+ monitor_id,
+ {"choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}]},
+ streaming = True,
+ )
+
+ assert monitor.get(monitor_id)["reply"] == (
+ 'Tool call: alpha({"a":1})\nTool call: beta({"b":2})'
+ )
+
+ def test_streamed_tool_monitor_keeps_choice_indexes_separate(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monitor_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "gguf",
+ prompt = "hi",
+ )
+ chunks = [
+ (0, {"index": 0, "id": "shared-id", "function": {"name": "alpha", "arguments": "{"}}),
+ (1, {"index": 0, "id": "shared-id", "function": {"name": "beta", "arguments": "{"}}),
+ (0, {"index": 0, "function": {"arguments": '"a":1}'}}),
+ (1, {"index": 0, "function": {"arguments": '"b":2}'}}),
+ ]
+ for choice_index, tool_call in chunks:
+ _monitor_openai_chunk(
+ monitor_id,
+ {
+ "choices": [
+ {
+ "index": choice_index,
+ "delta": {"tool_calls": [tool_call]},
+ }
+ ]
+ },
+ streaming = True,
+ )
+ for choice_index in (0, 1):
+ _monitor_openai_chunk(
+ monitor_id,
+ {
+ "choices": [
+ {
+ "index": choice_index,
+ "delta": {},
+ "finish_reason": "tool_calls",
+ }
+ ]
+ },
+ streaming = True,
+ )
+
+ assert monitor.get(monitor_id)["reply"] == (
+ 'Tool call: alpha({"a":1})\nTool call: beta({"b":2})'
+ )
+
+ def test_streamed_tool_monitor_uses_ids_when_indexes_are_reused_or_omitted(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monitor_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "gguf",
+ prompt = "hi",
+ )
+ deltas = [
+ {"index": 0, "id": "call-a", "function": {"name": "alpha", "arguments": '{"a":'}},
+ {"index": 0, "id": "call-b", "function": {"name": "beta", "arguments": '{"b":'}},
+ {"index": 0, "function": {"arguments": "2}"}},
+ {"id": "call-a", "function": {"arguments": "1}"}},
+ ]
+ for tool_call in deltas:
+ _monitor_openai_chunk(
+ monitor_id,
+ {"choices": [{"index": 0, "delta": {"tool_calls": [tool_call]}}]},
+ streaming = True,
+ )
+ _monitor_openai_chunk(
+ monitor_id,
+ {"choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}]},
+ streaming = True,
+ )
+
+ assert monitor.get(monitor_id)["reply"] == (
+ 'Tool call: alpha({"a":1})\nTool call: beta({"b":2})'
+ )
+
+ def test_streamed_tool_monitor_separates_duplicate_ids_by_explicit_index(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monitor_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "gguf",
+ prompt = "hi",
+ )
+ for tool_call in [
+ {
+ "index": 0,
+ "id": "duplicate",
+ "function": {"name": "alpha", "arguments": '{"a":1}'},
+ },
+ {
+ "index": 1,
+ "id": "duplicate",
+ "function": {"name": "beta", "arguments": '{"b":2}'},
+ },
+ ]:
+ _monitor_openai_chunk(
+ monitor_id,
+ {"choices": [{"index": 0, "delta": {"tool_calls": [tool_call]}}]},
+ streaming = True,
+ )
+ _monitor_openai_chunk(
+ monitor_id,
+ {"choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}]},
+ streaming = True,
+ )
+
+ assert monitor.get(monitor_id)["reply"] == (
+ 'Tool call: alpha({"a":1})\nTool call: beta({"b":2})'
+ )
+
+ @pytest.mark.parametrize("terminal", ["cancelled", "error", "eof"])
+ def test_streamed_tool_monitor_terminal_cleanup_is_request_local(self, monkeypatch, terminal):
+ import routes.inference as inf_mod
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ first_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "gguf",
+ prompt = "first",
+ )
+ _monitor_openai_chunk(
+ first_id,
+ {
+ "choices": [
+ {
+ "index": 0,
+ "delta": {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "call-first",
+ "function": {"name": "terminal", "arguments": "{"},
+ }
+ ]
+ },
+ }
+ ]
+ },
+ streaming = True,
+ )
+ if terminal == "error":
+ monitor.fail(first_id, "upstream failed")
+ else:
+ monitor.finish(first_id, "cancelled" if terminal == "cancelled" else "completed")
+
+ second_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "gguf",
+ prompt = "second",
+ )
+ _monitor_openai_chunk(
+ second_id,
+ {
+ "choices": [
+ {
+ "index": 0,
+ "delta": {
+ "tool_calls": [{"index": 0, "function": {"arguments": '{"b":2}'}}]
+ },
+ }
+ ]
+ },
+ streaming = True,
+ )
+ _monitor_openai_chunk(
+ second_id,
+ {"choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}]},
+ streaming = True,
+ )
+
+ assert monitor.get(first_id)["reply"] == "Tool call: terminal({)"
+ assert monitor.get(second_id)["reply"] == 'Tool call: <unknown>({"b":2})'
+
+ def test_streamed_non_tool_monitor_content_is_unchanged(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monitor_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "gguf",
+ prompt = "hi",
+ )
+ for content in ["hel", "lo"]:
+ _monitor_openai_chunk(
+ monitor_id,
+ {"choices": [{"index": 0, "delta": {"content": content}}]},
+ streaming = True,
+ )
+ _monitor_openai_chunk(
+ monitor_id,
+ {"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]},
+ streaming = True,
+ )
+
+ assert monitor.get(monitor_id)["reply"] == "hello"
+
+ @pytest.mark.parametrize(
+ ("tool_first", "expected"),
+ [
+ (False, "Checking:\nTool call: lookup({})"),
+ (True, "Tool call: lookup({})\nDone."),
+ ],
+ )
+ def test_streamed_tool_monitor_separates_mixed_text_segments(
+ self, monkeypatch, tool_first, expected
+ ):
+ import routes.inference as inf_mod
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monitor_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "gguf",
+ prompt = "hi",
+ )
+ text = "Done." if tool_first else "Checking:"
+ text_chunk = {"choices": [{"index": 0, "delta": {"content": text}}]}
+ tool_chunk = {
+ "choices": [
+ {
+ "index": 0,
+ "delta": {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "call-mixed",
+ "function": {"name": "lookup", "arguments": "{}"},
+ }
+ ]
+ },
+ }
+ ]
+ }
+ finish_chunk = {"choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}]}
+ if tool_first:
+ for chunk in (tool_chunk, finish_chunk, text_chunk):
+ _monitor_openai_chunk(monitor_id, chunk, streaming = True)
+ else:
+ for chunk in (text_chunk, tool_chunk, finish_chunk):
+ _monitor_openai_chunk(monitor_id, chunk, streaming = True)
+
+ assert monitor.get(monitor_id)["reply"] == expected
+
+ def test_streamed_tool_monitor_keeps_final_text_after_pending_tool(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monitor_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "gguf",
+ prompt = "hi",
+ )
+ _monitor_openai_chunk(
+ monitor_id,
+ {
+ "choices": [
+ {
+ "index": 0,
+ "delta": {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "call-final-text",
+ "function": {"name": "lookup", "arguments": "{}"},
+ }
+ ]
+ },
+ }
+ ]
+ },
+ streaming = True,
+ )
+ _monitor_openai_chunk(
+ monitor_id,
+ {
+ "choices": [
+ {
+ "index": 0,
+ "delta": {"content": "Done."},
+ }
+ ]
+ },
+ streaming = True,
+ )
+ _monitor_openai_chunk(
+ monitor_id,
+ {"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]},
+ streaming = True,
+ )
+
+ assert monitor.get(monitor_id)["reply"] == "Tool call: lookup({})\nDone."
+
+ def test_streamed_tool_monitor_flushes_scalar_call_before_terminal_content(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monitor_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "gguf",
+ prompt = "hi",
+ )
+ _monitor_openai_chunk(
+ monitor_id,
+ {
+ "choices": [
+ {
+ "index": 0,
+ "delta": {
+ "tool_calls": [
+ {
+ "index": 0,
+ "function": {"name": "lookup", "arguments": "1"},
+ }
+ ]
+ },
+ }
+ ]
+ },
+ streaming = True,
+ )
+ _monitor_openai_chunk(
+ monitor_id,
+ {
+ "choices": [
+ {
+ "index": 0,
+ "delta": {"content": "Done."},
+ "finish_reason": "stop",
+ }
+ ]
+ },
+ streaming = True,
+ )
+
+ assert monitor.get(monitor_id)["reply"] == "Tool call: lookup(1)\nDone."
+
+ def test_streamed_tool_monitor_keeps_incomplete_call_across_content(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monitor_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "gguf",
+ prompt = "hi",
+ )
+ chunks = [
+ {
+ "choices": [
+ {
+ "index": 0,
+ "delta": {
+ "tool_calls": [
+ {
+ "index": 0,
+ "function": {
+ "name": "lookup",
+ "arguments": '{"query":',
+ },
+ }
+ ]
+ },
+ }
+ ]
+ },
+ {"choices": [{"index": 0, "delta": {"content": "Checking."}}]},
+ {
+ "choices": [
+ {
+ "index": 0,
+ "delta": {
+ "tool_calls": [{"index": 0, "function": {"arguments": '"weather"}'}}]
+ },
+ }
+ ]
+ },
+ {"choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}]},
+ ]
+ for chunk in chunks:
+ _monitor_openai_chunk(monitor_id, chunk, streaming = True)
+
+ assert monitor.get(monitor_id)["reply"] == (
+ 'Checking.\nTool call: lookup({"query":"weather"})'
+ )
+
+ @pytest.mark.parametrize(
+ "arguments",
+ ["1", json.dumps({"query": "x" * 600})],
+ )
+ def test_streamed_tool_monitor_flushes_on_tool_event_boundary(self, monkeypatch, arguments):
+ import routes.inference as inf_mod
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monitor_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "gguf",
+ prompt = "hi",
+ )
+ chunks = [
+ {
+ "choices": [
+ {
+ "index": 0,
+ "delta": {
+ "tool_calls": [
+ {
+ "index": 0,
+ "function": {"name": "lookup", "arguments": arguments},
+ }
+ ]
+ },
+ }
+ ]
+ },
+ {
+ "choices": [{"index": 0, "delta": {}}],
+ "_toolEvent": {"type": "tool_start"},
+ },
+ {"choices": [{"index": 0, "delta": {"content": "Done."}}]},
+ ]
+ for chunk in chunks:
+ _monitor_openai_chunk(monitor_id, chunk, streaming = True)
+
+ reply = monitor.get(monitor_id)["reply"]
+ assert reply.startswith("Tool call: lookup(")
+ assert reply.endswith("\nDone.")
+
+ def test_streamed_tool_monitor_bounds_pending_preview_state(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monitor_id = monitor.start(
+ endpoint = "/v1/chat/completions",
+ method = "POST",
+ model = "gguf",
+ prompt = "hi",
+ )
+ for index in range(70):
+ _monitor_openai_chunk(
+ monitor_id,
+ {
+ "choices": [
+ {
+ "index": 0,
+ "delta": {
+ "tool_calls": [
+ {
+ "index": index,
+ "id": ("i" * 5000) + str(index),
+ "function": {
+ "name": "n" * 1000,
+ "arguments": "a" * 5000,
+ },
+ }
+ ]
+ },
+ }
+ ]
+ },
+ streaming = True,
+ )
+
+ [entry] = monitor._entries
+ assert len(entry.openai_stream_tool_calls) <= 64
+ assert all(
+ call.call_id is None or len(call.call_id) <= 501
+ for call in entry.openai_stream_tool_calls
+ )
+ assert all(len(call.name) <= 501 for call in entry.openai_stream_tool_calls)
+ assert all(len(call.arguments) <= 501 for call in entry.openai_stream_tool_calls)
+ assert (
+ sum(len(call.name) + len(call.arguments) for call in entry.openai_stream_tool_calls)
+ <= 12000
+ )
+ monitor.finish(monitor_id, "cancelled")
+ assert entry.openai_stream_tool_calls == []
+ assert entry.openai_stream_last_tool_indexes == {}
+
def test_embeddings_request_is_counted_active_and_completed(self, monkeypatch):
async def _run():
import routes.inference as inf_mod
diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-keys.ts b/studio/frontend/src/features/chat/stores/chat-runtime-keys.ts
new file mode 100644
index 00000000000..b8719326272
--- /dev/null
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-keys.ts
@@ -0,0 +1,5 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export const CHAT_SPECULATIVE_TYPE_KEY = "unsloth_chat_speculative_type";
+export const CHAT_GPU_MEMORY_MODE_KEY = "unsloth_chat_gpu_memory_mode";
diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
index 3ec4c56f1a6..231295bd15e 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -90,9 +90,18 @@ import {
import { shouldAdvanceQueuedSettingsEpoch } from "../utils/queued-settings-epoch";
import type { MmprojFallbackReason } from "../types/api";
import type { ResearchWebsitePolicy } from "../types/research";
+import {
+ CHAT_GPU_MEMORY_MODE_KEY,
+ CHAT_SPECULATIVE_TYPE_KEY,
+} from "./chat-runtime-keys";
import { useExternalProvidersStore } from "./external-providers-store";
import { PLUS_MENU_PINS_STORAGE_KEY } from "./plus-menu-prefs-store";
+export {
+ CHAT_GPU_MEMORY_MODE_KEY,
+ CHAT_SPECULATIVE_TYPE_KEY,
+} from "./chat-runtime-keys";
+
export const CHAT_REASONING_ENABLED_KEY = "unsloth_chat_reasoning_enabled";
export const CHAT_TOOLS_ENABLED_KEY = "unsloth_chat_tools_enabled";
export const CHAT_CODE_TOOLS_ENABLED_KEY = "unsloth_chat_code_tools_enabled";
@@ -144,9 +153,6 @@ export const CHAT_RAG_AUTOINJECT_MIN_SCORE_KEY =
"unsloth_chat_rag_autoinject_min_score";
export const CHAT_RAG_OCR_KEY = "unsloth_chat_rag_ocr_scanned";
export const CHAT_RAG_CAPTION_KEY = "unsloth_chat_rag_caption_figures";
-export const CHAT_SPECULATIVE_TYPE_KEY = "unsloth_chat_speculative_type";
-export const CHAT_GPU_MEMORY_MODE_KEY = "unsloth_chat_gpu_memory_mode";
-
// Persist only the model-agnostic intents (auto/ngram/off). The model-specific
// drafter modes (mtp/mtp+ngram/dspark/dflash) and spec_draft_n_max stay session-only:
// a persisted choice would silently no-op on a model with no MTP head or no
diff --git a/studio/frontend/src/hooks/use-model-memory.ts b/studio/frontend/src/hooks/use-model-memory.ts
index d780194b26e..9c94ca4e399 100644
--- a/studio/frontend/src/hooks/use-model-memory.ts
+++ b/studio/frontend/src/hooks/use-model-memory.ts
@@ -20,6 +20,8 @@ import { estimateKvCache } from "@/features/chat/api/chat-api";
import {
CHAT_GPU_MEMORY_MODE_KEY,
CHAT_SPECULATIVE_TYPE_KEY,
+} from "@/features/chat/stores/chat-runtime-keys";
+import {
readPersistedGpuMemoryMode,
readPersistedSpeculativeType,
useChatRuntimeStore,
diff --git a/studio/frontend/tests/module-scope-cycle-safety.test.ts b/studio/frontend/tests/module-scope-cycle-safety.test.ts
index a7653189ab4..7efbb62c3e6 100644
--- a/studio/frontend/tests/module-scope-cycle-safety.test.ts
+++ b/studio/frontend/tests/module-scope-cycle-safety.test.ts
@@ -133,17 +133,17 @@ test("the key is still read at module scope, so the guard above is load-bearing"
/**
* The same white screen, reached a second way.
*
- * `use-model-memory.ts` imported `CHAT_GPU_MEMORY_MODE_KEY` and friends from the
- * `@/features/chat` barrel, and the barrel reaches this file back:
+ * `use-model-memory.ts` read `CHAT_GPU_MEMORY_MODE_KEY` and friends from the
+ * chat runtime store, which reaches this file back:
*
* chat -> apply-inference-status-to-store -> model-picker -> model-selector
* -> pickers -> use-model-memory -> chat
*
* Under dev's unbundled ESM that ring evaluated `use-model-memory` before the chat
- * barrel had finished, and the module-scope const read threw "Cannot access
+ * store had finished, and the module-scope const read threw "Cannot access
* 'CHAT_GPU_MEMORY_MODE_KEY' before initialization". Measured on main: the page threw,
- * `#root` had 0 children and the body was empty. With the deep imports below there is
- * no page error and the app renders.
+ * `#root` had 0 children and the body was empty. Reading the keys from an import-free
+ * leaf module lets the app render regardless of entry-module order.
*
* Production builds never showed it. The bundler hoists these declarations into one
* module, so the ordering the dev server exposes stops existing, which is exactly the
@@ -151,6 +151,27 @@ test("the key is still read at module scope, so the guard above is load-bearing"
* server next.
*/
const MODEL_MEMORY = path.join(SRC, "hooks/use-model-memory.ts");
+const CHAT_RUNTIME_KEYS = path.join(
+ SRC,
+ "features/chat/stores/chat-runtime-keys.ts",
+);
+
+test("the chat runtime keys module imports nothing", async () => {
+ const text = await readFile(CHAT_RUNTIME_KEYS, "utf8");
+ assert.deepEqual(
+ staticSpecifiers(CHAT_RUNTIME_KEYS, text),
+ [],
+ "chat-runtime-keys.ts must not import anything",
+ );
+});
+
+test("the model memory hook reads runtime keys from the leaf module", async () => {
+ const text = await readFile(MODEL_MEMORY, "utf8");
+ assert.match(
+ text,
+ /CHAT_GPU_MEMORY_MODE_KEY,[\s\S]*CHAT_SPECULATIVE_TYPE_KEY,[\s\S]*from "@\/features\/chat\/stores\/chat-runtime-keys"/,
+ );
+});
test("the model memory hook imports no feature barrel", async () => {
const text = await readFile(MODEL_MEMORY, "utf8");
diff --git a/tests/studio/test_playwright_suites_run_in_ci.py b/tests/studio/test_playwright_suites_run_in_ci.py
index 9234f964c2a..b2995377085 100644
--- a/tests/studio/test_playwright_suites_run_in_ci.py
+++ b/tests/studio/test_playwright_suites_run_in_ci.py
@@ -176,6 +176,25 @@ def test_the_exemptions_are_still_exempt_and_still_exist():
)
+def test_tool_activity_install_enforces_the_script_allowlist():
+ document = yaml.safe_load(
+ (REPO / ".github" / "workflows" / "studio-ui-smoke.yml").read_text(encoding = "utf-8")
+ )
+ steps = document["jobs"]["ui-smoke"]["steps"]
+ run = next(
+ str(step["run"])
+ for step in steps
+ if step.get("name") == "Tool activity collapse regression (Playwright)"
+ )
+ upgrade = "npm install -g npm@^11"
+ version_gate = "11.1[6-9].*|11.[2-9][0-9].*|1[2-9].*"
+ install = "npm --prefix studio/frontend ci --strict-allow-scripts"
+ assert upgrade in run
+ assert version_gate in run
+ assert install in run
+ assert run.index(upgrade) < run.index(version_gate) < run.index(install)
+
+
def test_the_linux_job_still_drives_all_three_browser_engines():
"""The repo-wide check cannot see this job disappear.