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.

Desktop: flush gated tool approval cards immediately (#8628)

Maheswar Kumar2c058bfbdc21
diff --git a/studio/backend/core/inference/tool_stream_exec.py b/studio/backend/core/inference/tool_stream_exec.py
index 9cdb21bf8ae..041f7cb5a55 100644
--- a/studio/backend/core/inference/tool_stream_exec.py
+++ b/studio/backend/core/inference/tool_stream_exec.py
@@ -52,6 +52,9 @@ def accepts_output_callback(func: Callable[..., str]) -> bool:
# common proxy idle caps (Cloudflare ~100 s, nginx default 60 s).
TOOL_HEARTBEAT_INTERVAL_S = 10.0
+# delay before the first approval keepalive so it cannot coalesce with the gated card.
+TOOL_APPROVAL_FLUSH_DELAY_S = 0.05
+
# How often the wrapper wakes to poll for output / completion / cancellation.
_POLL_INTERVAL_S = 0.25
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 5fe18889b87..494c3fe8bef 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -69,6 +69,7 @@ from core.inference.llama_admission import (
llama_admission_config_from_env,
peek_llama_admission_snapshot,
)
+from core.inference.tool_stream_exec import TOOL_APPROVAL_FLUSH_DELAY_S
def _positive_int_or_none(value: Any) -> Optional[int]:
@@ -12935,6 +12936,7 @@ async def openai_chat_completions(
_stream_usage = None
_stream_timings = None
_stream_finish = None
+ approval_flush_pending = False
def _flush_reasoning_extractor():
final_reasoning, final_visible = reasoning_extractor.finish()
@@ -12967,15 +12969,23 @@ async def openai_chat_completions(
# Stall-timeout wait: keepalive while the generator stays
# silent (e.g. prefill between tool iterations). asyncio.wait
# never cancels next_task, matching the finally-drain shield.
+ wait_timeout = (
+ TOOL_APPROVAL_FLUSH_DELAY_S
+ if approval_flush_pending
+ else _LOCAL_TOOL_STREAM_STALL_KEEPALIVE_S
+ )
while True:
done_tasks, _ = await asyncio.wait(
{next_task},
- timeout = _LOCAL_TOOL_STREAM_STALL_KEEPALIVE_S,
+ timeout = wait_timeout,
)
if done_tasks:
break
yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
+ approval_flush_pending = False
+ wait_timeout = _LOCAL_TOOL_STREAM_STALL_KEEPALIVE_S
event = next_task.result()
+ approval_flush_pending = False
finally:
if next_task.done():
next_task = None
@@ -13033,6 +13043,7 @@ async def openai_chat_completions(
reasoning_extractor = _new_chat_reasoning_extractor()
# 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"
continue
@@ -14387,6 +14398,7 @@ async def openai_chat_completions(
gen = sf_generate_with_tools()
prev_text = ""
reasoning_extractor = _new_sf_reasoning_extractor()
+ approval_flush_pending = False
def _sf_flush_reasoning():
# Drain the extractor at turn/stream end (mirrors GGUF); only visible text hits the monitor.
@@ -14416,15 +14428,23 @@ async def openai_chat_completions(
_sf_next_task = asyncio.create_task(
asyncio.to_thread(next, gen, _sf_tool_sentinel)
)
+ wait_timeout = (
+ TOOL_APPROVAL_FLUSH_DELAY_S
+ if approval_flush_pending
+ else _LOCAL_TOOL_STREAM_STALL_KEEPALIVE_S
+ )
while True:
_sf_done, _ = await asyncio.wait(
{_sf_next_task},
- timeout = _LOCAL_TOOL_STREAM_STALL_KEEPALIVE_S,
+ timeout = wait_timeout,
)
if _sf_done:
break
yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
+ approval_flush_pending = False
+ wait_timeout = _LOCAL_TOOL_STREAM_STALL_KEEPALIVE_S
event = _sf_next_task.result()
+ approval_flush_pending = False
# Done; drop the reference so the finally-block drain no-ops.
_sf_next_task = None
if event is _sf_tool_sentinel:
@@ -14477,6 +14497,7 @@ async def openai_chat_completions(
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"
continue
diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.py
index cad997b4439..24d4a02cdc0 100644
--- a/studio/backend/tests/test_openai_tool_passthrough.py
+++ b/studio/backend/tests/test_openai_tool_passthrough.py
@@ -2715,6 +2715,89 @@ class TestGgufVisionToolRouting:
asyncio.run(_run())
+ def test_gguf_gated_tool_start_gets_a_separate_prompt_flush(self, monkeypatch):
+ async def _run():
+ import routes.inference as inf_mod
+
+ async def fake_select_tools(*_args, **_kwargs):
+ return [
+ {
+ "type": "function",
+ "function": {
+ "name": "python",
+ "parameters": {"type": "object", "properties": {}},
+ },
+ }
+ ]
+
+ stopped = threading.Event()
+
+ def _generate(**kwargs):
+ cancel_event = kwargs["cancel_event"]
+ yield {"type": "status", "text": "Waiting for approval: Python"}
+ yield {
+ "type": "tool_start",
+ "tool_name": "python",
+ "tool_call_id": "call_0",
+ "arguments": {"code": "print(1)"},
+ "awaiting_confirmation": True,
+ "approval_id": "approval_0",
+ }
+ while not cancel_event.is_set():
+ time.sleep(0.005)
+ stopped.set()
+
+ 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,
+ base_url = "http://llama.tool.test",
+ effective_parallel_slots = 1,
+ generate_chat_completion = lambda **_kwargs: "unused",
+ generate_chat_completion_with_tools = _generate,
+ )
+ monkeypatch.setattr(inf_mod, "api_monitor", ApiMonitor(max_entries = 3))
+ monkeypatch.setattr(inf_mod, "get_llama_cpp_backend", lambda: backend)
+ monkeypatch.setattr(inf_mod, "_select_request_tools", fake_select_tools)
+ monkeypatch.setattr(inf_mod, "TOOL_APPROVAL_FLUSH_DELAY_S", 0.01)
+
+ payload = ChatCompletionRequest(
+ model = "default",
+ messages = [{"role": "user", "content": "run python"}],
+ enable_tools = True,
+ stream = True,
+ )
+ response = await openai_chat_completions(
+ payload,
+ request = self._Request(),
+ current_subject = "test",
+ )
+ iterator = response.body_iterator
+ try:
+ for _ in range(8):
+ chunk = await asyncio.wait_for(iterator.__anext__(), timeout = 0.2)
+ if '"tool_start"' in chunk:
+ break
+ else:
+ pytest.fail("gated tool_start was not emitted")
+
+ next_turn = [False]
+ asyncio.get_running_loop().call_soon(next_turn.__setitem__, 0, True)
+ flush = await asyncio.wait_for(iterator.__anext__(), timeout = 0.2)
+ assert flush == ": keep-alive\n\n"
+ assert next_turn[0] is True
+ finally:
+ await iterator.aclose()
+
+ assert stopped.is_set()
+
+ asyncio.run(_run())
+
def test_gguf_tool_stream_task_cancel_after_first_chunk_finalizes_monitor(self, monkeypatch):
async def _run():
import routes.inference as inf_mod