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: don't stop long running tool calls that print nothing (#11969)

Nilay1d8c891ca8f7
diff --git a/studio/backend/core/inference/chat_generation_runs.py b/studio/backend/core/inference/chat_generation_runs.py
index 6b136a3600f..d2bde61dead 100644
--- a/studio/backend/core/inference/chat_generation_runs.py
+++ b/studio/backend/core/inference/chat_generation_runs.py
@@ -395,6 +395,8 @@ _ADMISSION_WAIT_MARKER = ": admission-wait"
# Leaving the queue. Renewed unconditionally: wait renewals are rate limited, and the lease equals the first-token
# timeout, so any age carried in is negative margin.
_ADMISSION_DONE_MARKER = ": admission-done"
+# A server-side tool still running. Rate limited like the wait marker.
+_TOOL_HEARTBEAT_MARKER = ": tool-heartbeat"
def _minimum_lease_seconds() -> float:
@@ -800,7 +802,7 @@ class ChatGenerationSupervisor:
if _ADMISSION_DONE_MARKER in text:
last_keepalive = time.monotonic()
await self._try_touch_progress(run_id)
- elif _ADMISSION_WAIT_MARKER in text:
+ elif _ADMISSION_WAIT_MARKER in text or _TOOL_HEARTBEAT_MARKER in text:
now_s = time.monotonic()
if now_s - last_keepalive >= _renew_interval_seconds():
last_keepalive = now_s
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 8bee07dbf98..71fe484df3e 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -1768,6 +1768,8 @@ _LLAMA_STREAM_KEEPALIVE = _LlamaStreamKeepalive()
_OPENAI_ADMISSION_SSE_WAIT = ": admission-wait\n\n"
# Paired with the above: the slot is ours, so a suspended client clock starts now.
_OPENAI_ADMISSION_SSE_DONE = ": admission-done\n\n"
+# A server-side tool still running, unlike a stall keep-alive: durable runs renew their lease on it.
+_OPENAI_TOOL_HEARTBEAT_SSE = ": tool-heartbeat\n\n"
_OPENAI_LLAMA_ADMISSION_POLL_S = 0.25
# Cap on waiting for a cancelled teardown task. Request.is_disconnected() can swallow
# cancel() (#7617), so teardown abandons the task rather than hold the response, and
@@ -26920,7 +26922,7 @@ async def produce_openai_chat_completions(
if event["type"] == "heartbeat":
# Tool-wrapper heartbeat while a server-side tool blocks; keeps SSE alive.
- yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
+ yield _OPENAI_TOOL_HEARTBEAT_SSE
continue
if event["type"] in ("tool_output", "tool_args"):
@@ -28726,8 +28728,8 @@ async def produce_openai_chat_completions(
)
if event["type"] == "heartbeat":
- # Tool-execution wrapper heartbeat -> SSE keepalive.
- yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
+ # Tool-execution wrapper heartbeat -> SSE comment.
+ yield _OPENAI_TOOL_HEARTBEAT_SSE
continue
if event["type"] in ("tool_output", "tool_args"):
diff --git a/studio/backend/tests/test_chat_generation_lease_compat.py b/studio/backend/tests/test_chat_generation_lease_compat.py
index 3f26dcfd581..be82ee93011 100644
--- a/studio/backend/tests/test_chat_generation_lease_compat.py
+++ b/studio/backend/tests/test_chat_generation_lease_compat.py
@@ -704,8 +704,13 @@ def test_the_admission_marker_matches_the_route_that_emits_it():
assert inference_route._OPENAI_ADMISSION_SSE_WAIT.startswith(runs_mod._ADMISSION_WAIT_MARKER)
assert inference_route._OPENAI_ADMISSION_SSE_DONE.startswith(runs_mod._ADMISSION_DONE_MARKER)
- # And neither may match the stall keep-alive, which is the opposite signal.
- for marker in (runs_mod._ADMISSION_WAIT_MARKER, runs_mod._ADMISSION_DONE_MARKER):
+ assert inference_route._OPENAI_TOOL_HEARTBEAT_SSE.startswith(runs_mod._TOOL_HEARTBEAT_MARKER)
+ # And none may match the stall keep-alive, which is the opposite signal.
+ for marker in (
+ runs_mod._ADMISSION_WAIT_MARKER,
+ runs_mod._ADMISSION_DONE_MARKER,
+ runs_mod._TOOL_HEARTBEAT_MARKER,
+ ):
assert not inference_route._OPENAI_PASSTHROUGH_SSE_KEEPALIVE.startswith(marker)
# The two must stay distinct, or the done branch would swallow every wait.
assert not inference_route._OPENAI_ADMISSION_SSE_WAIT.startswith(
diff --git a/studio/backend/tests/test_chat_generation_supervisor.py b/studio/backend/tests/test_chat_generation_supervisor.py
index f8dcde4e1d5..afd2afb01ef 100644
--- a/studio/backend/tests/test_chat_generation_supervisor.py
+++ b/studio/backend/tests/test_chat_generation_supervisor.py
@@ -12,7 +12,7 @@ from unittest.mock import AsyncMock
import pytest
from starlette.requests import Request
-from core.inference import llama_keepwarm
+from core.inference import chat_generation_runs, llama_keepwarm
from core.inference.chat_generation_runs import (
_EVENT_FLUSH_SECONDS,
ChatGenerationSupervisor,
@@ -312,6 +312,38 @@ async def test_a_prefill_reporting_only_progress_renews_the_lease(durable_run, m
assert runs_db.get_run("run-1", "alice")["status"] == "completed"
+ "comment, reaped",
+ [("_OPENAI_TOOL_HEARTBEAT_SSE", []), ("_OPENAI_PASSTHROUGH_SSE_KEEPALIVE", ["run-1"])],
+)
+async def test_a_silent_tool_holds_the_lease_but_a_stalled_stream_does_not(
+ durable_run, monkeypatch, comment, reaped
+):
+ comment = getattr(inference, comment)
+ now = {"ms": runs_db.now_ms()}
+ monkeypatch.setattr(runs_db, "now_ms", lambda: now["ms"])
+ sampled = {}
+
+ async def body():
+ now["ms"] += 21 * 60_000
+ yield comment
+ # Asked for only once the producer has handled the comment before it.
+ yield comment
+ sampled["reaped"] = runs_db.reconcile_runs(stale_after_ms = 1_200_000)
+ yield "data: [DONE]\n\n"
+
+ async def fake(_payload, _request, _subject, *, cancel_on_disconnect):
+ # Preparation has already read its own interval; only the stream's rate limit is lifted.
+ monkeypatch.setattr(chat_generation_runs, "_renew_interval_seconds", lambda: 0.0)
+ return SimpleNamespace(status_code = 200, body_iterator = body())
+
+ monkeypatch.setattr(inference, "produce_openai_chat_completions", fake)
+ supervisor = ChatGenerationSupervisor(SimpleNamespace(state = SimpleNamespace()))
+ await supervisor._produce("run-1")
+ assert sampled["reaped"] == reaped
+
+
async def _subscriber_sequences(after = 0):
response = await run_routes.chat_generation_events(
"run-1",
diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.py
index 77214bd7de5..37045f7cd21 100644
--- a/studio/backend/tests/test_openai_tool_passthrough.py
+++ b/studio/backend/tests/test_openai_tool_passthrough.py
@@ -5042,6 +5042,29 @@ class TestGgufVisionToolRouting:
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_a_tool_heartbeat_is_not_sent_as_a_stall_keepalive(self, monkeypatch):
+ # Durable runs renew their lease on the tool heartbeat, never on `: keep-alive`.
+ import routes.inference as inf_mod
+
+ def _tools(**_kwargs):
+ yield {"type": "heartbeat"}
+ yield {"type": "content", "text": "done"}
+ yield _stop_metadata()
+
+ 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),
+ )
+ assert inf_mod._OPENAI_TOOL_HEARTBEAT_SSE in result.chunks
+ assert inf_mod._OPENAI_PASSTHROUGH_SSE_KEEPALIVE not in result.chunks
+
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
diff --git a/studio/backend/tests/test_sf_client_tools_passthrough.py b/studio/backend/tests/test_sf_client_tools_passthrough.py
index d76de9f13d7..c97d5abd7b3 100644
--- a/studio/backend/tests/test_sf_client_tools_passthrough.py
+++ b/studio/backend/tests/test_sf_client_tools_passthrough.py
@@ -806,6 +806,23 @@ def test_server_tool_streaming_invalid_event_is_error(monkeypatch):
assert errors == ["An internal error occurred."]
+def test_server_tool_heartbeat_is_not_sent_as_a_stall_keepalive(monkeypatch):
+ import routes.inference as inf
+
+ class _SilentToolBackend(_ScriptedBackend):
+ def __init__(self):
+ super().__init__(_fixed())
+
+ def generate_chat_completion_with_tools(self, **_kwargs):
+ yield {"type": "heartbeat"}
+ yield {"type": "content", "text": "done"}
+
+ payload = _request(tools = [LOOKUP_TOOL], enable_tools = True, stream = True)
+ chunks = _collect_sse(_call(payload, monkeypatch, _SilentToolBackend()))
+ assert inf._OPENAI_TOOL_HEARTBEAT_SSE in chunks
+ assert inf._OPENAI_PASSTHROUGH_SSE_KEEPALIVE not in chunks
+
+
def test_streaming_repeated_snapshot_no_duplicate_call(monkeypatch):
# Repeated then shrunk cumulative snapshots must not double-heal.
backend = _ScriptedBackend(_fixed(_CALL_XML, _CALL_XML, _CALL_XML[:5], _CALL_XML))