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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: refresh the context meter when a tool loop hands off to a tool (#13356)
Daniel Han1f1b9e78d894
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex ba110cf7d9f..8927dc38c5b 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -7461,6 +7461,33 @@ def _backfill_usage_from_timings(usage, timings):return out+def _context_usage_event(usage, timings):+ """UI frame pricing the context one finished tool-loop pass leaves behind, or None.++ ``timings.prompt_n`` excludes the KV-cache hit (``cache_n``) while ``usage.prompt_tokens``+ includes it, so a prompt read from timings adds the hit back.+ """+ usage = usage or {}+ timings = timings or {}+ cached = (usage.get("prompt_tokens_details") or {}).get("cached_tokens") or timings.get(+ "cache_n"+ )+ prompt = usage.get("prompt_tokens")+ if not prompt and timings.get("prompt_n") is not None:+ prompt = int(timings.get("prompt_n") or 0) + int(timings.get("cache_n") or 0)+ completion = usage.get("completion_tokens") or timings.get("predicted_n")+ if not prompt:+ return None+ prompt, completion = int(prompt), int(completion or 0)+ return {+ "type": "context_usage",+ "prompt_tokens": prompt,+ "completion_tokens": completion,+ "context_tokens": prompt + completion,+ "cached_tokens": int(cached or 0),+ }++def _llama_chunk_has_generated_output(data: dict) -> bool:if data.get("type") == "diffusion_frame":return True@@ -39991,6 +40018,9 @@ class LlamaCppBackend:_it = _iter_timings or {}_accumulated_predicted_ms += _it.get("predicted_ms", 0)_accumulated_predicted_n += _it.get("predicted_n", 0)+ # Refreshes the context meter from the usage llama-server already reported (no+ # recount). Sent once the first tool is running, so it never delays a tool.+ _pending_context_usage = _context_usage_event(_iter_usage, _iter_timings)# Collapse exact-duplicate calls and cap the count for the TEXTUAL# fallback (mirrors the safetensors loop; see _MAX_TOOL_CALLS_PER_TURN).@@ -40190,6 +40220,10 @@ class LlamaCppBackend:),}yield start_event+ if needs_confirm and _pending_context_usage is not None:+ # Nothing runs while a human decides, so the meter need not wait for it.+ yield _pending_context_usage+ _pending_context_usage = None_decision = (wait_tool_decision(@@ -40828,12 +40862,17 @@ class LlamaCppBackend:# Without this the handler below re-raises and a bad# argument kills the whole answer. A raising tool is the# tool's failure; the other two loops hand it back.+ _started_events = (+ (_pending_context_usage,) if _pending_context_usage is not None else ()+ )+ _pending_context_usage = Nonetry:result = yield from stream_tool_execution(_invoke_tool,tool_name = decision.tool_name,tool_call_id = decision.tool_call_id,cancel_event = cancel_event,+ started_events = _started_events,)except _LlamaStreamCancelled:# Subclasses Exception, so the arm below would eat@@ -41146,6 +41185,11 @@ class LlamaCppBackend:"provenance": provisional_tool_provenance(_pname),}+ # No call in the batch ran (denied, duplicate, capped), so nothing was waiting on it.+ if _pending_context_usage is not None:+ yield _pending_context_usage+ _pending_context_usage = None+# Clear tool status badge before next generation/final pass.yield {"type": "status", "text": ""}if tool_controller.force_final_answer or not tool_controller.active_tools():diff --git a/studio/backend/core/inference/sse_control_frames.py b/studio/backend/core/inference/sse_control_frames.pyindex da448604bb1..a6a5784930b 100644--- a/studio/backend/core/inference/sse_control_frames.py+++ b/studio/backend/core/inference/sse_control_frames.py@@ -41,6 +41,7 @@ _CONTROL_TYPES = frozenset("skill_load","diffusion_frame","reasoning_summary",+ "context_usage",})@@ -50,6 +51,7 @@ _CONTROL_KEYS = ("_toolStatus","_diffusionFrame","_reasoningDurationMs",+ "_contextUsage","_mcp_provenance","quote_cut",)diff --git a/studio/backend/core/inference/tool_stream_exec.py b/studio/backend/core/inference/tool_stream_exec.pyindex f7adfc47fa0..b40e2a18fe1 100644--- a/studio/backend/core/inference/tool_stream_exec.py+++ b/studio/backend/core/inference/tool_stream_exec.py@@ -26,7 +26,7 @@ import inspectimport queueimport threadingimport time-from typing import Any, Callable, Generator+from typing import Any, Callable, Generator, Sequencefrom loggers import get_logger@@ -172,6 +172,7 @@ def stream_tool_execution(cancel_event: Any = None,heartbeat_interval_s: float = TOOL_HEARTBEAT_INTERVAL_S,poll_interval_s: float = _POLL_INTERVAL_S,+ started_events: Sequence[dict] = (),) -> Generator[dict, None, str]:"""Run ``invoke(output_callback)`` in a thread; yield live events; return the result.@@ -186,6 +187,8 @@ def stream_tool_execution(timeout. Set ONLY on that abnormal-exit path, never on a clean finish, becausethe event is shared across a turn's tool calls and setting it early wouldabort the next tool.++ ``started_events`` are yielded once the worker is running, so a slow consumer never delays the tool."""output_queue: queue.Queue[Any] = queue.Queue()done_sentinel = object()@@ -277,6 +280,8 @@ def stream_tool_execution(abnormal_exit = Falsetry:+ for event in started_events:+ yield eventwhile not finished:try:item = output_queue.get(timeout = poll_interval_s)diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 09b087415a7..d92fd4a5362 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -32061,6 +32061,14 @@ async def produce_openai_chat_completions(_stream_finish = event.get("finish_reason")continue+ if event["type"] == "context_usage":+ # Must not reach the content branch below: its empty text resets prev_text.+ if _ui_events:+ yield f"data: {json.dumps(event)}\n\n"+ elif _drop_keepalive.due():+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE+ continue+if event["type"] == "quote_cut":# Bypass content handling to avoid resetting the text cursor.if _ui_events:diff --git a/studio/backend/tests/test_llama_cpp_tool_loop.py b/studio/backend/tests/test_llama_cpp_tool_loop.pyindex 56b196776a1..7417e7aebac 100644--- a/studio/backend/tests/test_llama_cpp_tool_loop.py+++ b/studio/backend/tests/test_llama_cpp_tool_loop.py@@ -4685,6 +4685,139 @@ def test_metadata_event_context_tokens_count_earlier_passes_once(monkeypatch):assert usage["context_tokens"] == 150+def test_context_usage_frame_precedes_each_tool_run(monkeypatch):+ """#12624: the meter refreshes when a pass hands off to a tool, from the usage+ llama-server already reported, before the tool runs; none on the final pass."""+ streams = [+ [+ _tool_call_sse("web_search", {"query": "cats"}, "call_1"),+ _usage_done(+ {+ "prompt_tokens": 100,+ "completion_tokens": 30,+ "prompt_tokens_details": {"cached_tokens": 64},+ },+ "tool_calls",+ ),+ _done(),+ ],+ [+ _tool_call_sse("web_search", {"query": "dogs"}, "call_2"),+ _usage_done({"prompt_tokens": 140, "completion_tokens": 20}, "tool_calls"),+ _done(),+ ],+ [+ _sse({"content": "Found both."}),+ _usage_done({"prompt_tokens": 170, "completion_tokens": 10}),+ _done(),+ ],+ ]+ backend, payloads = _backend_and_payloads(monkeypatch, streams)+ _record_tool_calls(monkeypatch, "result")++ events = _run_tool_loop(+ backend,+ [{"role": "user", "content": "search cats then dogs"}],+ [_web_search_tool()],+ max_tool_iterations = 3,+ )++ assert len(payloads) == 3+ frames = [e for e in events if e.get("type") == "context_usage"]+ assert frames == [+ {+ "type": "context_usage",+ "prompt_tokens": 100,+ "completion_tokens": 30,+ "context_tokens": 130,+ "cached_tokens": 64,+ },+ {+ "type": "context_usage",+ "prompt_tokens": 140,+ "completion_tokens": 20,+ "context_tokens": 160,+ "cached_tokens": 0,+ },+ ]+ # Each frame lands once its pass's tool has started and before it finishes.+ order = [+ e["type"] for e in events if e.get("type") in ("context_usage", "tool_start", "tool_end")+ ]+ assert order == ["tool_start", "context_usage", "tool_end"] * 2, order+ assert [e for e in events if e.get("type") == "metadata"][-1]["usage"]["context_tokens"] == 180+++def test_context_usage_frame_never_delays_the_tool(monkeypatch):+ """The frame goes out while the tool is already executing, so the tool never waits on the+ consumer: hold the generator at the frame and the tool still starts."""+ streams = [+ [+ _tool_call_sse("web_search", {"query": "cats"}, "call_1"),+ _usage_done({"prompt_tokens": 100, "completion_tokens": 30}, "tool_calls"),+ _done(),+ ],+ [+ _sse({"content": "Found cats."}),+ _usage_done({"prompt_tokens": 140, "completion_tokens": 10}),+ _done(),+ ],+ ]+ backend, _ = _backend_and_payloads(monkeypatch, streams)+ # No window: the result budget is priced through a template render the fake server lacks.+ backend._effective_context_length = None+ tool_started = threading.Event()+ release_tool = threading.Event()++ def fake_execute_tool(name, arguments, **_kwargs):+ tool_started.set()+ release_tool.wait(timeout = 10)+ return "result"++ monkeypatch.setattr("core.inference.tools.execute_tool", fake_execute_tool)+ gen = backend.generate_chat_completion_with_tools(+ messages = [{"role": "user", "content": "search cats"}],+ tools = [_web_search_tool()],+ max_tool_iterations = 2,+ )+ for event in gen:+ if event.get("type") == "context_usage":+ break+ # The consumer has not pulled again, yet the tool is already running.+ assert tool_started.wait(timeout = 5)+ release_tool.set()+ rest = list(gen)+ assert [e["type"] for e in rest if e.get("type") == "tool_end"] == ["tool_end"]+++def test_context_usage_frame_absent_on_a_single_pass(monkeypatch):+ stream = [+ _sse({"content": "hi"}),+ _usage_done({"prompt_tokens": 5, "completion_tokens": 2}),+ _done(),+ ]+ backend, _ = _backend_and_payloads(monkeypatch, [stream])++ events = _run_tool_loop(backend, [{"role": "user", "content": "hi"}], [_web_search_tool()])++ assert not [e for e in events if e.get("type") == "context_usage"]+++def test_context_usage_event_reads_timings_when_usage_is_missing():+ """timings.prompt_n leaves out the KV-cache hit that usage.prompt_tokens includes."""+ from core.inference.llama_cpp import _context_usage_event++ assert _context_usage_event(None, {"prompt_n": 12, "cache_n": 88, "predicted_n": 7}) == {+ "type": "context_usage",+ "prompt_tokens": 100,+ "completion_tokens": 7,+ "context_tokens": 107,+ "cached_tokens": 88,+ }+ assert _context_usage_event(None, None) is None+ assert _context_usage_event({"prompt_tokens": 0}, {}) is None++def test_gguf_rehearsal_name_split_before_args_is_not_leaked(monkeypatch):"""Finding 6: a rehearsal call whose name (``web_search``) and ``[ARGS]{...}``arrive in separate content deltas must hold the bare name in the buffer untildiff --git a/studio/backend/tests/test_provider_control_frame_spoofing.py b/studio/backend/tests/test_provider_control_frame_spoofing.pyindex 72dab08a86f..8698fe9c0ab 100644--- a/studio/backend/tests/test_provider_control_frame_spoofing.py+++ b/studio/backend/tests/test_provider_control_frame_spoofing.py@@ -39,6 +39,7 @@ from core.inference.sse_control_frames import sanitize_provider_sse_line"tool_status","diffusion_frame","reasoning_summary",+ "context_usage",],)def test_every_control_type_is_dropped(frame_type):@@ -54,6 +55,7 @@ def test_every_control_type_is_dropped(frame_type):"_toolStatus","_diffusionFrame","_reasoningDurationMs",+ "_contextUsage","_mcp_provenance","quote_cut",],diff --git a/studio/backend/tests/test_ui_stream_events_gate.py b/studio/backend/tests/test_ui_stream_events_gate.pyindex aaa5f92129b..614884583c6 100644--- a/studio/backend/tests/test_ui_stream_events_gate.py+++ b/studio/backend/tests/test_ui_stream_events_gate.py@@ -164,6 +164,7 @@ def test_control_frame_lines_are_recognised_by_type():"tool_status","diffusion_frame","reasoning_summary",+ "context_usage",):assert is_ui_control_sse_line('data: {"type": "%s"}' % frame) is True, framediff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex d661ad42fb7..0061b22d38b 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -6467,6 +6467,29 @@ export function createOpenAIStreamAdapter(usage?: ServerUsage;timings?: ServerTimings;} | null = null;+ // Gate on the captured checkpoint and thread so a late write from provider A cannot repaint+ // the bar after a switch to B. A first turn is adopted onto an id mid-run and autosave moves+ // activeThreadId with it, so read the adopted key, or the bar stays blank for life.+ const publishContextUsage = (+ usage: NonNullable<+ ReturnType<typeof useChatRuntimeStore.getState>["contextUsage"]+ >,+ ) => {+ const usageKey = liveThreadKey(serverCancel);+ const usageThreadKey = usageKey === "__default" ? null : usageKey;+ const store = useChatRuntimeStore.getState();+ // File it under this run's own thread even when the gate blocks the visible write, so+ // switching back re-applies it.+ if (usageThreadKey !== null) {+ store.setThreadContextUsage(usageThreadKey, usage);+ }+ if (+ store.activeThreadId === (usageThreadKey ?? activeThreadIdAtRunStart) &&+ store.params.checkpoint === params.checkpoint+ ) {+ store.setContextUsage(usage);+ }+ };// llama.cpp output count, including reasoning.let windowCount: number | null = null;@@ -7304,6 +7327,37 @@ export function createOpenAIStreamAdapter(continue;}+ // A tool loop handing off to a tool: show its context now rather than at turn end, which+ // still writes the final figure.+ const liveContext = (+ chunk as unknown as {+ _contextUsage?: {+ prompt_tokens?: unknown;+ completion_tokens?: unknown;+ context_tokens?: unknown;+ cached_tokens?: unknown;+ };+ }+ )._contextUsage;+ if (liveContext !== undefined) {+ const { prompt_tokens, completion_tokens, context_tokens, cached_tokens } =+ liveContext ?? {};+ if (+ typeof prompt_tokens === "number" &&+ typeof completion_tokens === "number" &&+ typeof context_tokens === "number"+ ) {+ publishContextUsage({+ promptTokens: prompt_tokens,+ completionTokens: completion_tokens,+ totalTokens: context_tokens,+ contextTokens: context_tokens,+ cachedTokens: typeof cached_tokens === "number" ? cached_tokens : 0,+ });+ }+ continue;+ }+// Diffusion frame: a transient canvas snapshot routed to the transient store and skipped; it// has no assistant text, so it never enters the transcript.const diffusionFrame = (@@ -8598,23 +8652,13 @@ export function createOpenAIStreamAdapter(0;const cacheWriteTokens = usageCacheWriteTokens(meta?.usage);- // Gate on the captured checkpoint and thread so a late completion from provider A cannot- // repaint the bar after a switch to B. A first turn is adopted onto an id mid-run, so read- // the adopted key or the bar stays blank for life.- // A first turn is adopted onto an id mid-run and autosave moves activeThreadId with it, so read the- // adopted key, or the run stays "unresolved" for life and the bar stays blank.- const usageKey = liveThreadKey(serverCancel);- const usageThreadKey = usageKey === "__default" ? null : usageKey;- const usageThreadIsVisible =- useChatRuntimeStore.getState().activeThreadId ===- (usageThreadKey ?? activeThreadIdAtRunStart);if (meta?.usage &&typeof meta.usage.prompt_tokens === "number" &&typeof meta.usage.completion_tokens === "number" &&typeof meta.usage.total_tokens === "number") {- const usage = {+ publishContextUsage({promptTokens: meta.usage.prompt_tokens,completionTokens: meta.usage.completion_tokens,totalTokens: meta.usage.total_tokens,@@ -8623,21 +8667,7 @@ export function createOpenAIStreamAdapter(: {}),cachedTokens,cacheWriteTokens,- };- // File it under this run's own thread even when the gate blocks the visible write, so- // switching back re-applies it.- if (usageThreadKey !== null) {- useChatRuntimeStore- .getState()- .setThreadContextUsage(usageThreadKey, usage);- }- if (- usageThreadIsVisible &&- useChatRuntimeStore.getState().params.checkpoint ===- params.checkpoint- ) {- useChatRuntimeStore.getState().setContextUsage(usage);- }+ });}if (diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex 5383d96c99b..b7224df1e93 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -1966,6 +1966,12 @@ export async function* streamChatCompletions(separatorIndex = buffer.search(/\r?\n\r?\n/);continue;}+ // A tool loop's context as it hands off to a tool, so the meter moves mid-turn.+ if ("type" in parsed && parsed.type === "context_usage") {+ yield { _contextUsage: parsed } as unknown as OpenAIChatChunk;+ separatorIndex = buffer.search(/\r?\n\r?\n/);+ continue;+ }const {usage: parsedUsage,timings: parsedTimings,diff --git a/studio/frontend/src/features/chat/api/chat-generation-api.ts b/studio/frontend/src/features/chat/api/chat-generation-api.tsindex a2b5d46c8df..21404969ab0 100644--- a/studio/frontend/src/features/chat/api/chat-generation-api.ts+++ b/studio/frontend/src/features/chat/api/chat-generation-api.ts@@ -95,6 +95,9 @@ export function normalizeChatGenerationChunkPayload(if (frameType === "diffusion_frame") {return { _diffusionFrame: payload } as unknown as OpenAIChatChunk;}+ if (frameType === "context_usage") {+ return { _contextUsage: payload } as unknown as OpenAIChatChunk;+ }}return payload;}diff --git a/studio/frontend/src/features/chat/utils/chat-generation-recovery.ts b/studio/frontend/src/features/chat/utils/chat-generation-recovery.tsindex a2dfe63f539..3a9a69ffd2d 100644--- a/studio/frontend/src/features/chat/utils/chat-generation-recovery.ts+++ b/studio/frontend/src/features/chat/utils/chat-generation-recovery.ts@@ -48,6 +48,7 @@ export function generationChunkCountsTowardTiming(payload: unknown): boolean {const chunk = payload as| {_reasoningDurationMs?: unknown;+ _contextUsage?: unknown;context_truncated?: unknown;quote_cut?: unknown;usage?: unknown;@@ -56,7 +57,12 @@ export function generationChunkCountsTowardTiming(payload: unknown): boolean {| null| undefined;if (!chunk || typeof chunk !== "object") return false;- if ("_reasoningDurationMs" in chunk || chunk.context_truncated || chunk.quote_cut) {+ if (+ "_reasoningDurationMs" in chunk ||+ "_contextUsage" in chunk ||+ chunk.context_truncated ||+ chunk.quote_cut+ ) {return false;}return !(chunk.usage && Array.isArray(chunk.choices) && chunk.choices.length === 0);diff --git a/studio/frontend/tests/context-usage-tool-handoff.test.ts b/studio/frontend/tests/context-usage-tool-handoff.test.tsnew file mode 100644index 00000000000..c747c911c24--- /dev/null+++ b/studio/frontend/tests/context-usage-tool-handoff.test.ts@@ -0,0 +1,58 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// #12624: a tool loop sends its context as it hands off to a tool, so the meter moves mid-turn.++import assert from "node:assert/strict";+import test from "node:test";++import { readSrc, registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();++const { normalizeChatGenerationChunkPayload } = await import(+ "../src/features/chat/api/chat-generation-api.ts"+);+const { generationChunkCountsTowardTiming } = await import(+ "../src/features/chat/utils/chat-generation-recovery.ts"+);++const frame = {+ type: "context_usage",+ prompt_tokens: 100,+ completion_tokens: 30,+ context_tokens: 130,+ cached_tokens: 64,+};++test("a persisted context_usage frame is re-tagged like the live stream", () => {+ assert.deepEqual(normalizeChatGenerationChunkPayload(frame), { _contextUsage: frame });+});++test("a context_usage frame is not a decoded chunk for recovered timing", () => {+ assert.equal(generationChunkCountsTowardTiming({ _contextUsage: frame }), false);+});++test("the live stream routes context_usage off the transcript", () => {+ const src = readSrc("features/chat/api/chat-api.ts");+ assert.match(+ src,+ /parsed\.type === "context_usage"\) \{\s*yield \{ _contextUsage: parsed \}/,+ );+});++test("the adapter prices the handoff through the same gated meter write as the turn end", () => {+ const src = readSrc("features/chat/api/chat-adapter.ts");+ const handler = src.slice(src.indexOf(")._contextUsage;"));+ assert.ok(handler.length > 0, "the _contextUsage handler disappeared");+ assert.match(+ handler.slice(0, 1500),+ /publishContextUsage\(\{[\s\S]*?totalTokens: context_tokens,\s*contextTokens: context_tokens,/,+ );+ // The turn-end write shares the helper, so both obey the thread and checkpoint gate.+ assert.equal(src.match(/publishContextUsage\(\{/g)?.length, 2);+ assert.match(+ src,+ /store\.activeThreadId === \(usageThreadKey \?\? activeThreadIdAtRunStart\) &&\s*store\.params\.checkpoint === params\.checkpoint/,+ );+});diff --git a/tests/studio/test_multi_chat_prompt_queue_contract.py b/tests/studio/test_multi_chat_prompt_queue_contract.pyindex c85151ae4f6..9146e388283 100644--- a/tests/studio/test_multi_chat_prompt_queue_contract.py+++ b/tests/studio/test_multi_chat_prompt_queue_contract.py@@ -854,19 +854,17 @@ def test_queued_settings_are_thread_scoped_without_cross_chat_fallback():< ensure_compare_model.index("const resp = await loadModel("))assert "force_cancel_active:" in SHARED_COMPOSER- assert (- "useChatRuntimeStore.getState().activeThreadId ===\n"- " (usageThreadKey ?? activeThreadIdAtRunStart)" in CHAT_ADAPTER- )assert ("findLatestUserAudioBase64(\n survivingMessages,\n !queuedRunSettings"in CHAT_ADAPTER)assert "if (audioBase64 && !queuedRunSettings)" in CHAT_ADAPTER+ # The live meter write (turn end and tool handoffs share it) files per thread and paints only+ # the run's own visible thread on the run's own model.assert ".setThreadContextUsage(usageThreadKey, usage)" in CHAT_ADAPTERassert re.search(- r"usageThreadIsVisible\s*&&\s*"- r"useChatRuntimeStore\.getState\(\)\.params\.checkpoint\s*===\s*params\.checkpoint",+ r"store\.activeThreadId\s*===\s*\(usageThreadKey \?\? activeThreadIdAtRunStart\)\s*&&\s*"+ r"store\.params\.checkpoint\s*===\s*params\.checkpoint",CHAT_ADAPTER,)