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
Unsloth Studio / Desktop: expose prefill progress in API monitor (#11161)
Maheswar Kumar5651def4f30f
diff --git a/studio/backend/core/inference/api_monitor.py b/studio/backend/core/inference/api_monitor.pyindex 44ef860cff9..8d9f2cd6f8e 100644--- a/studio/backend/core/inference/api_monitor.py+++ b/studio/backend/core/inference/api_monitor.py@@ -205,6 +205,11 @@ class ApiMonitorEntry:shared: bool = False# 0-100 for a running download row; None when not applicable.progress: Optional[float] = None+ running_phase: Optional[str] = None+ prompt_progress_total: Optional[int] = None+ prompt_progress_processed: Optional[int] = None+ prompt_progress_cached: Optional[int] = None+ prompt_progress_time_ms: Optional[float] = None# Stamped on the first reply text; snapshot() prefers it over engine timings.first_token_monotonic: Optional[float] = None# The same instant, but only for output the model decoded. A tool card is client output that TTFT should count and@@ -263,6 +268,28 @@ class ApiMonitorEntry:gen_s = self.finished_monotonic - self.first_decode_monotonicif gen_s > 0.05:tok_per_sec = (self.completion_tokens - 1) / gen_s+ prompt_progress = None+ if self.prompt_progress_processed is not None:+ percent = None+ if self.prompt_progress_total is not None and self.prompt_progress_total > 0:+ percent = min(+ 100.0,+ max(+ 0.0,+ self.prompt_progress_processed / self.prompt_progress_total * 100.0,+ ),+ )+ prompt_progress = {+ "total": self.prompt_progress_total,+ "processed": self.prompt_progress_processed,+ "cached": self.prompt_progress_cached,+ "time_ms": (+ round(self.prompt_progress_time_ms, 2)+ if self.prompt_progress_time_ms is not None+ else None+ ),+ "percent": round(percent, 1) if percent is not None else None,+ }payload = {"id": self.id,"endpoint": self.endpoint,@@ -290,6 +317,8 @@ class ApiMonitorEntry:"event": self.event,"reason": self.reason,"progress": self.progress,+ "running_phase": self.running_phase,+ "prompt_progress": prompt_progress,"ttft_ms": ttft_ms,"tok_per_sec": round(tok_per_sec, 2) if tok_per_sec is not None else None,"prompt_tok_per_sec": (@@ -479,6 +508,58 @@ class ApiMonitor:entry.progress = min(100.0, max(0.0, float(progress)))_advance_updated_at(entry)+ def set_prompt_progress(+ self,+ entry_id: Optional[str],+ *,+ total: Any = None,+ processed: Any = None,+ cached: Any = None,+ time_ms: Any = None,+ ) -> None:+ if not entry_id:+ return+ total = _token_count_or_none(total)+ processed = _token_count_or_none(processed)+ cached = _token_count_or_none(cached)+ time_ms = _finite_float_or_none(time_ms)+ if processed is None:+ return+ if total is not None and total > 0:+ processed = min(processed, total)+ if cached is not None:+ cached = min(cached, processed)+ if time_ms is not None and time_ms < 0:+ time_ms = None+ with self._lock:+ entry = self._find_locked(entry_id)+ if entry is None or entry.status != "running" or entry.kind != "request":+ return+ if entry.running_phase != "prompt_processing":+ entry.prompt_progress_total = None+ entry.prompt_progress_processed = None+ entry.prompt_progress_cached = None+ entry.prompt_progress_time_ms = None+ entry.running_phase = "prompt_processing"+ if total is not None:+ entry.prompt_progress_total = total+ entry.prompt_progress_processed = processed+ if cached is not None:+ entry.prompt_progress_cached = cached+ if time_ms is not None:+ entry.prompt_progress_time_ms = time_ms+ _advance_updated_at(entry)++ def set_running_phase(self, entry_id: Optional[str], phase: Optional[str]) -> None:+ if not entry_id or phase not in ("prompt_processing", "token_generation"):+ return+ with self._lock:+ entry = self._find_locked(entry_id)+ if entry is None or entry.status != "running" or entry.kind != "request":+ return+ entry.running_phase = phase+ _advance_updated_at(entry)+def discard(self, entry_id: Optional[str]) -> None:"""Drop a row that turned out not to be an event (an already-satisfied load)."""if not entry_id:@@ -508,6 +589,7 @@ class ApiMonitor: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:+ entry.running_phase = "token_generation"now = time.monotonic()if entry.first_token_monotonic is None:entry.first_token_monotonic = now@@ -616,6 +698,7 @@ class ApiMonitor:budget,serialize_json = True,)+ entry.running_phase = "token_generation"now = time.monotonic()if entry.first_token_monotonic is None:entry.first_token_monotonic = now@@ -687,6 +770,7 @@ class ApiMonitor:entry.first_token_monotonic = nowif decoded and entry.first_decode_monotonic is None:entry.first_decode_monotonic = now+ entry.running_phase = "token_generation" if decoded else Nonedef set_reply(self, entry_id: Optional[str], text: str) -> None:if not entry_id:diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex c80060abb9a..14c8ccff98e 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -6785,6 +6785,25 @@ def _backfill_usage_from_timings(usage, timings):return out+def _llama_chunk_has_generated_output(data: dict) -> bool:+ if data.get("type") == "diffusion_frame":+ return True+ choices = data.get("choices")+ if not isinstance(choices, list):+ return False+ for choice in choices:+ if not isinstance(choice, dict):+ continue+ delta = choice.get("delta")+ if isinstance(delta, dict) and any(+ value not in (None, "", []) for key, value in delta.items() if key != "role"+ ):+ return True+ if choice.get("text") not in (None, ""):+ return True+ return False++def _report_live_llama_timings(callback, chunk) -> None:"""Report request-scoped llama.cpp progress without altering the public stream."""if callback is None or not isinstance(chunk, dict):@@ -6795,6 +6814,7 @@ def _report_live_llama_timings(callback, chunk) -> None:sample.pop("prompt_ms", None)progress = chunk.get("prompt_progress")if isinstance(progress, dict):+ sample["prompt_progress"] = dict(progress)try:processed = max(0.0, float(progress.get("processed", 0)))cached = max(0.0, float(progress.get("cache", 0)))@@ -6807,6 +6827,8 @@ def _report_live_llama_timings(callback, chunk) -> None:)except (TypeError, ValueError, OverflowError):pass+ if getattr(callback, "needs_phase", True) and _llama_chunk_has_generated_output(chunk):+ sample["running_phase"] = "token_generation"if not sample:returntry:@@ -34742,22 +34764,7 @@ class LlamaCppBackend:data = LlamaCppBackend._sse_event_payload(event)if data is None:return False- if data.get("type") == "diffusion_frame":- return True- choices = data.get("choices")- if not isinstance(choices, list):- return False- for choice in choices:- if not isinstance(choice, dict):- continue- delta = choice.get("delta")- if isinstance(delta, dict) and any(- value not in (None, "", []) for key, value in delta.items() if key != "role"- ):- return True- if choice.get("text") not in (None, ""):- return True- return False+ return _llama_chunk_has_generated_output(data)@staticmethoddef _iter_text_cancellable(diff --git a/studio/backend/main.py b/studio/backend/main.pyindex 549ca96c15a..83959cdf121 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -1634,6 +1634,7 @@ app.add_middleware("X-Unsloth-Conflict-Kind","X-Unsloth-Refusal","x-typesafe-request-id",+ "X-Unsloth-Monitor-ID",*_hub_endpoint_proxy.EXPOSED_HEADERS,],# is_allowed_origin closes the moment the tunnel URL clears, but a preflight already cached by the browserdiff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 7d2c6568109..060a80855d2 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -41,6 +41,7 @@ from typing import ()import functoolsimport json+import reimport httpxfrom hub.services.models import account_accessfrom hub.services.models.account_access import media_link_account, media_link_target@@ -138,7 +139,7 @@ from core.inference.llama_admission import (peek_llama_admission_snapshot,)from core.inference.tool_stream_exec import TOOL_APPROVAL_FLUSH_DELAY_S-from core.inference.llama_cpp import requested_video_fps+from core.inference.llama_cpp import _llama_chunk_has_generated_output, requested_video_fpsfrom core.inference.llama_video_input import shrink_video_for_llama@@ -778,7 +779,12 @@ def _raise_unsupported_n(path_label: str, monitor_id: Optional[str] = None) -> N_raise_unsupported_openai_parameter("n", message)-def _sse_streaming_response(content, *, unstarted_cleanup = None) -> StreamingResponse:+def _sse_streaming_response(+ content,+ *,+ unstarted_cleanup = None,+ monitor_id = None,+) -> StreamingResponse:"""A ``text/event-stream`` response with the standard SSE headers used byevery streaming path here: no client/proxy caching, no proxy buffering, anda one-shot connection. Two callers build their response inline instead: the@@ -795,15 +801,51 @@ def _sse_streaming_response(content, *, unstarted_cleanup = None) -> StreamingRereturn _SameTaskStreamingResponse(content,media_type = "text/event-stream",- headers = {- "Cache-Control": "no-cache",- "Connection": "close",- "X-Accel-Buffering": "no",- },+ headers = _monitor_response_headers(+ {+ "Cache-Control": "no-cache",+ "Connection": "close",+ "X-Accel-Buffering": "no",+ },+ monitor_id,+ ),unstarted_cleanup = unstarted_cleanup,)+def _monitor_response_headers(headers: Optional[dict], monitor_id: Optional[str]) -> dict:+ result = dict(headers or {})+ if monitor_id:+ result["X-Unsloth-Monitor-ID"] = monitor_id+ return result+++def _is_prefill_progress_only(data) -> bool:+ if not isinstance(data, dict) or not isinstance(data.get("prompt_progress"), dict):+ return False+ if data.get("usage") or _llama_chunk_has_generated_output(data):+ return False+ choices = data.get("choices")+ return not (+ isinstance(choices, list)+ and any(isinstance(c, dict) and c.get("finish_reason") for c in choices)+ )+++class _ProgressKeepalive:+ """Dropped progress still resets the relay's idle timer, so stand in for the keepalive it starved."""++ def __init__(self, interval_s: Optional[float]):+ self._interval_s = interval_s+ self._due = time.monotonic() + interval_s if interval_s else None++ def due(self) -> bool:+ if self._due is None or time.monotonic() < self._due:+ return False+ self._due = time.monotonic() + self._interval_s+ return True++def _openai_stream_error_chunk(exc) -> dict:"""Build an in-band OpenAI error chunk for a mid-stream failure. Once thestream's 200 headers are flushed the status can't change, so the error must@@ -3394,6 +3436,7 @@ async def _aiter_llama_stream_items(request: Optional[Request] = None,first_token_deadline: Optional[float] = None,response: Optional[httpx.Response] = None,+ track_prefill_progress: bool = False,post_first_item_read_timeout_s: Optional[Union[float, Callable[[], Optional[float]]]] = _DEFAULT_STREAM_STALL_TIMEOUT_S,@@ -3410,7 +3453,11 @@ async def _aiter_llama_stream_items(if first_token_deadline is None:first_token_deadline = time.monotonic() + _first_token_timeout_s()last_item_at: Optional[float] = None+ last_prefill_progress: Optional[float] = None+ prefill_buffer = b""item_task: Optional[asyncio.Future] = None+ if track_prefill_progress:+ from core.inference.llama_cpp import LlamaCppBackenddef _post_first_timeout_s() -> Optional[float]:if callable(post_first_item_read_timeout_s):@@ -3435,9 +3482,10 @@ async def _aiter_llama_stream_items(# and its range is unknowable here, so it latches nothing and# leaves the wall clock, authoritative anyway, to enforce.if waiting_first_item:+ # progress renews the prefill deadline beyond the initially latched socket ceiling.ceiling = (None- if callable(post_first_item_read_timeout_s)+ if track_prefill_progress or callable(post_first_item_read_timeout_s)else _ceiling_for_first_read(first_token_deadline, post_first_item_read_timeout_s)@@ -3495,6 +3543,38 @@ async def _aiter_llama_stream_items(raise httpx.ReadTimeout(timed_out_message) from excfinally:item_task = None+ if track_prefill_progress and last_item_at is None:+ if isinstance(item, bytes):+ prefill_buffer += item+ events = re.split(rb"\r\n\r\n|\n\n|\r\r", prefill_buffer)+ prefill_buffer = events.pop()+ events = [event.decode("utf-8", "replace") for event in events]+ else:+ events = [item]+ starts_output = False+ for event in events:+ data = LlamaCppBackend._sse_event_payload(event)+ if data is None:+ continue+ if _llama_chunk_has_generated_output(data) or any(+ choice.get("finish_reason")+ for choice in data.get("choices", [])+ if isinstance(choice, dict)+ ):+ starts_output = True+ break+ processed = LlamaCppBackend._sse_event_prefill_progress(event)+ if processed is not None and (+ last_prefill_progress is None or processed > last_prefill_progress+ ):+ last_prefill_progress = processed+ first_token_deadline = time.monotonic() + _first_token_timeout_s()+ if not starts_output:+ if time.monotonic() >= first_token_deadline:+ raise httpx.ReadTimeout("The model did not produce a first token in time.")+ yield item+ continue+ prefill_buffer = b""if last_item_at is None and response is not None:# Before yielding, not before the next read: the consumer may sit# on this item while the first-token deadline is still armed.@@ -6750,6 +6830,17 @@ def _monitor_usage(prompt_ms = timings.get("prompt_ms")# The span the tile rates on: total tokens over total time, not a mean of per-request rates.decode_ms = timings.get("predicted_ms")+ prompt_progress = timings.get("prompt_progress")+ if isinstance(prompt_progress, dict):+ api_monitor.set_prompt_progress(+ monitor_id,+ total = prompt_progress.get("total"),+ processed = prompt_progress.get("processed"),+ cached = prompt_progress.get("cache"),+ time_ms = prompt_progress.get("time_ms"),+ )+ if timings.get("running_phase") == "token_generation":+ api_monitor.set_running_phase(monitor_id, "token_generation")if (tok_per_sec is not Noneor prompt_tok_per_sec is not None@@ -6773,6 +6864,11 @@ def _monitor_perf_callback(monitor_id: Optional[str], context_length):return Nonedef _callback(timings: dict) -> None:+ # Report the decode phase once per prefill round, not on every token.+ if "prompt_progress" in timings:+ _callback.needs_phase = True+ elif timings.get("running_phase") == "token_generation":+ _callback.needs_phase = False_monitor_usage(monitor_id,None,@@ -6780,6 +6876,7 @@ def _monitor_perf_callback(monitor_id: Optional[str], context_length):timings = timings,)+ _callback.needs_phase = Truereturn _callback@@ -6906,6 +7003,10 @@ def _monitor_openai_chunk(if isinstance(choice, dict) and choice.get("finish_reason"):api_monitor.note_stop_reason(monitor_id, str(choice["finish_reason"]))timings = data.get("timings")+ prompt_progress = data.get("prompt_progress")+ if isinstance(prompt_progress, dict):+ timings = dict(timings) if isinstance(timings, dict) else {}+ timings["prompt_progress"] = prompt_progress_monitor_usage(monitor_id,data.get("usage"),@@ -26780,15 +26881,10 @@ async def produce_openai_chat_completions(await _stop_local_disconnect_cancel_watcher(disconnect_watcher)_tracker.__exit__(None, None, None)- return _SameTaskStreamingResponse(+ return _sse_streaming_response(audio_input_stream(),unstarted_cleanup = _tracked_cancel_unstarted_cleanup(_tracker),- media_type = "text/event-stream",- headers = {- "Cache-Control": "no-cache",- "Connection": "close",- "X-Accel-Buffering": "no",- },+ monitor_id = monitor_id,)else:# `stream` defaults to False, so this is the ordinary shape of an audio-input chat and it@@ -28021,15 +28117,10 @@ async def produce_openai_chat_completions(reservation.cancel()_tracker.__exit__(None, None, None)- return _SameTaskStreamingResponse(+ return _sse_streaming_response(admitted_gguf_tool_stream(),unstarted_cleanup = _gguf_tool_admission_unstarted_cleanup,- media_type = "text/event-stream",- headers = {- "Cache-Control": "no-cache",- "Connection": "close",- "X-Accel-Buffering": "no",- },+ monitor_id = monitor_id,)# Non-streaming JSON: drain the agentic generator into one@@ -28650,15 +28741,10 @@ async def produce_openai_chat_completions(reservation.cancel()_tracker.__exit__(None, None, None)- return _SameTaskStreamingResponse(+ return _sse_streaming_response(admitted_gguf_stream_chunks(),unstarted_cleanup = _gguf_admission_unstarted_cleanup,- media_type = "text/event-stream",- headers = {- "Cache-Control": "no-cache",- "Connection": "close",- "X-Accel-Buffering": "no",- },+ monitor_id = monitor_id,)else:try:@@ -29706,15 +29792,10 @@ async def produce_openai_chat_completions(_sf_tracker.__exit__(None, None, None)if payload.stream:- return _SameTaskStreamingResponse(+ return _sse_streaming_response(sf_tool_stream(),unstarted_cleanup = _tracked_cancel_unstarted_cleanup(_sf_tracker),- media_type = "text/event-stream",- headers = {- "Cache-Control": "no-cache",- "Connection": "close",- "X-Accel-Buffering": "no",- },+ monitor_id = monitor_id,)# Non-streaming JSON: drain the loop, build one ChatCompletion.@@ -30366,15 +30447,10 @@ async def produce_openai_chat_completions(pass_tracker.__exit__(None, None, None)- return _SameTaskStreamingResponse(+ return _sse_streaming_response(stream_chunks(),unstarted_cleanup = _tracked_cancel_unstarted_cleanup(_tracker),- media_type = "text/event-stream",- headers = {- "Cache-Control": "no-cache",- "Connection": "close",- "X-Accel-Buffering": "no",- },+ monitor_id = monitor_id,)# ── Non-streaming response ────────────────────────────────────@@ -32052,9 +32128,13 @@ async def openai_completions(request: Request, current_subject: str = Depends(ge# request it for internal accounting, then keep the caller's opt-in# contract by filtering that chunk through _cmpl_stream_event_out.upstream_body = dict(body)+ _client_wants_progress = bool(body.get("return_progress"))+ upstream_body["return_progress"] = Trueupstream_stream_options = dict(body.get("stream_options") or {})upstream_stream_options["include_usage"] = Trueupstream_body["stream_options"] = upstream_stream_options+ _keepalive_s = _openai_passthrough_stream_keepalive_interval()+ from core.inference.llama_cpp import LlamaCppBackendfrom core.inference.llama_keepwarm import mark_response_failedclient = httpx.AsyncClient(@@ -32106,8 +32186,10 @@ async def openai_completions(request: Request, current_subject: str = Depends(gerequest = request,first_token_deadline = first_token_deadline,response = resp,- keepalive_interval_s = _openai_passthrough_stream_keepalive_interval(),+ track_prefill_progress = True,+ keepalive_interval_s = _keepalive_s,)+ progress_keepalive = _ProgressKeepalive(_keepalive_s)async for chunk in items_iter:# Out of `buffer`: the split below would hand it to the monitor.if chunk is _LLAMA_STREAM_KEEPALIVE:@@ -32128,6 +32210,16 @@ async def openai_completions(request: Request, current_subject: str = Depends(ge# so don't let the middleware claim the slot and evict a# preview-owned model.mark_response_failed(getattr(request, "scope", None))+ if (+ not _client_wants_progress+ and b'"prompt_progress"' in event+ and _is_prefill_progress_only(+ LlamaCppBackend._sse_event_payload(event.decode("utf-8", "replace"))+ )+ ):+ if progress_keepalive.due():+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE.encode()+ continueout = _cmpl_stream_event_out(event, _include_usage)if out is not None:yield out + b"\n\n"@@ -32190,7 +32282,7 @@ async def openai_completions(request: Request, current_subject: str = Depends(ge_direct_llama_request_finished()_tracker.__exit__(None, None, None)- return _sse_streaming_response(_stream())+ return _sse_streaming_response(_stream(), monitor_id = monitor_id)else:# ``stream`` defaults to false, so this common shape registers with the swap gate like the# streaming branch: unregistered, a non-forced /unload counts zero generations and kills@@ -35041,15 +35133,10 @@ async def _responses_stream(api_monitor.finish(monitor_id, "cancelled")reservation.cancel()- return _SameTaskStreamingResponse(+ return _sse_streaming_response(admitted_event_generator(),- media_type = "text/event-stream",- headers = {- "Cache-Control": "no-cache",- "Connection": "close",- "X-Accel-Buffering": "no",- },unstarted_cleanup = _responses_admission_unstarted_cleanup,+ monitor_id = monitor_id,)@@ -39831,15 +39918,8 @@ async def _openai_passthrough_stream(reservation.cancel()_tracker.__exit__(None, None, None)- return _SameTaskStreamingResponse(- _queued_stream(),- media_type = "text/event-stream",- headers = {- "Cache-Control": "no-cache",- "Connection": "close",- "X-Accel-Buffering": "no",- },- unstarted_cleanup = _queued_unstarted_cleanup,+ return _sse_streaming_response(+ _queued_stream(), unstarted_cleanup = _queued_unstarted_cleanup, monitor_id = monitor_id)@@ -39907,6 +39987,9 @@ async def _openai_passthrough_stream_admitted(body = await _build_openai_passthrough_body_async(payload, backend_ctx = llama_backend.context_length, llama_backend = llama_backend)+ # The body builder is allowlisted, so the caller's opt-in lives in the extra fields.+ client_wants_progress = bool((payload.model_extra or {}).get("return_progress"))+ body["return_progress"] = Trueclient_wants_usage = _wants_stream_usage(payload)upstream_stream_options = dict(body.get("stream_options") or {})upstream_stream_options["include_usage"] = True@@ -40027,11 +40110,14 @@ async def _openai_passthrough_stream_admitted(return _SameTaskStreamingResponse(iter(()),media_type = "text/event-stream",- headers = {- "Cache-Control": "no-cache",- "Connection": "keep-alive",- "X-Accel-Buffering": "no",- },+ headers = _monitor_response_headers(+ {+ "Cache-Control": "no-cache",+ "Connection": "keep-alive",+ "X-Accel-Buffering": "no",+ },+ monitor_id,+ ),)if resp.status_code == 200:@@ -40406,15 +40492,18 @@ async def _openai_passthrough_stream_admitted(_await_disconnect_then_close(request, resp, cancel_event))lines_iter = resp.aiter_lines()+ _keepalive_s = _openai_passthrough_stream_keepalive_interval()items_iter = _aiter_llama_stream_items(lines_iter,cancel_event = cancel_event,request = request,first_token_deadline = first_token_deadline,response = resp,+ track_prefill_progress = True,post_first_item_read_timeout_s = _terminal_read_timeout_s,- keepalive_interval_s = _openai_passthrough_stream_keepalive_interval(),+ keepalive_interval_s = _keepalive_s,)+ progress_keepalive = _ProgressKeepalive(_keepalive_s)async for raw_line in items_iter:if raw_line is _LLAMA_STREAM_KEEPALIVE:yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE@@ -40487,6 +40576,11 @@ async def _openai_passthrough_stream_admitted(if _monitor_openai_error_message(chunk_data):saw_stream_error = Truemark_response_failed(getattr(request, "scope", None))+ if not client_wants_progress and _is_prefill_progress_only(chunk_data):+ _monitor_openai_sse_line(monitor_id, raw_line, llama_backend.context_length)+ if progress_keepalive.due():+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE+ continue# With healing active, a content-bearing line may be replaced by# held/promoted chunks; otherwise the single (already# normalized) line relays unchanged (monitored exactly as@@ -40688,15 +40782,8 @@ async def _openai_passthrough_stream_admitted(finally:_release_admission(admission_lease, _tracker)- return _SameTaskStreamingResponse(- _stream(),- media_type = "text/event-stream",- headers = {- "Cache-Control": "no-cache",- "Connection": "close",- "X-Accel-Buffering": "no",- },- unstarted_cleanup = _unstarted_cleanup,+ return _sse_streaming_response(+ _stream(), unstarted_cleanup = _unstarted_cleanup, monitor_id = monitor_id)except BaseException as exc:if isinstance(exc, asyncio.CancelledError):diff --git a/studio/backend/tests/test_api_monitor.py b/studio/backend/tests/test_api_monitor.pyindex 7bc6c34ac29..f33425f73e6 100644--- a/studio/backend/tests/test_api_monitor.py+++ b/studio/backend/tests/test_api_monitor.py@@ -1515,6 +1515,137 @@ def test_the_decode_span_comes_only_from_engine_timings(monkeypatch):assert row["prompt_tok_per_sec"] == 11.0+def test_prompt_progress_updates_for_followup_prefill_and_decode_phase(monkeypatch):+ monitor = ApiMonitor(max_entries = 3)+ monkeypatch.setattr(inference_route, "api_monitor", monitor)+ entry_id = _start(monitor)++ monitor.set_prompt_progress(+ entry_id,+ total = 1000,+ processed = 400,+ cached = 100,+ time_ms = 250.25,+ )+ row = monitor.get(entry_id)+ assert row["running_phase"] == "prompt_processing"+ assert row["prompt_progress"] == {+ "total": 1000,+ "processed": 400,+ "cached": 100,+ "time_ms": 250.25,+ "percent": 40.0,+ }++ monitor.set_running_phase(entry_id, "token_generation")+ monitor.set_prompt_progress(entry_id, total = 1000, processed = 500)+ row = monitor.get(entry_id)+ assert row["running_phase"] == "prompt_processing"+ assert row["prompt_progress"]["processed"] == 500++ inference_route._monitor_usage(+ entry_id,+ None,+ timings = {+ "prompt_progress": {"total": 1000, "processed": 600},+ "running_phase": "token_generation",+ },+ )+ row = monitor.get(entry_id)+ assert row["running_phase"] == "token_generation"+ assert row["prompt_progress"]["processed"] == 600+++def test_monitor_usage_relays_live_progress_and_decode_phase(monkeypatch):+ monitor = ApiMonitor(max_entries = 3)+ monkeypatch.setattr(inference_route, "api_monitor", monitor)+ entry_id = _start(monitor)++ inference_route._monitor_usage(+ entry_id,+ None,+ timings = {+ "prompt_progress": {+ "total": 800,+ "processed": 200,+ "cache": 0,+ "time_ms": 10,+ }+ },+ )+ inference_route._monitor_usage(+ entry_id,+ None,+ timings = {"running_phase": "token_generation"},+ )++ row = monitor.get(entry_id)+ assert row["running_phase"] == "token_generation"+ assert row["prompt_progress"]["percent"] == 25.0+++ "delta",+ [+ {+ "tool_calls": [+ {+ "index": 0,+ "id": "call_1",+ "type": "function",+ "function": {"name": "search", "arguments": '{"query":'},+ }+ ]+ },+ {"function_call": {"name": "search", "arguments": '{"query":'}},+ ],+)+def test_tool_only_stream_leaves_prefill_phase(monkeypatch, delta):+ monitor = ApiMonitor(max_entries = 3)+ monkeypatch.setattr(inference_route, "api_monitor", monitor)+ entry_id = _start(monitor)+ inference_route._monitor_openai_chunk(+ entry_id,+ {"prompt_progress": {"total": 1000, "processed": 1000}, "choices": []},+ streaming = True,+ )+ inference_route._monitor_openai_chunk(+ entry_id,+ {"choices": [{"index": 0, "delta": delta}]},+ streaming = True,+ )+ assert monitor.get(entry_id)["running_phase"] == "token_generation"+++def test_streaming_response_exposes_monitor_id():+ response = inference_route._sse_streaming_response(+ iter(()),+ monitor_id = "apireq_test",+ )+ assert response.headers["X-Unsloth-Monitor-ID"] == "apireq_test"+ assert "X-Unsloth-Monitor-ID" not in inference_route._sse_streaming_response(iter(())).headers+++def test_monitor_id_reads_the_matching_concurrent_request(monkeypatch):+ monitor = ApiMonitor(max_entries = 3)+ monkeypatch.setattr(inference_route, "api_monitor", monitor)+ first_id = _start(monitor, subject = "alice", model = "same-model", prompt = "same")+ second_id = _start(monitor, subject = "alice", model = "same-model", prompt = "same")+ monitor.set_prompt_progress(first_id, total = 1000, processed = 200)+ monitor.set_prompt_progress(second_id, total = 1000, processed = 800)++ app = FastAPI()+ app.include_router(inference_route.studio_router)+ app.dependency_overrides = {get_current_subject: lambda: "alice"}+ client = TestClient(app)++ first = client.get(f"/monitor/{first_id}").json()+ second = client.get(f"/monitor/{second_id}").json()+ assert first["id"] != second["id"]+ assert first["prompt_progress"]["processed"] == 200+ assert second["prompt_progress"]["processed"] == 800++def test_a_timings_only_final_chunk_still_sets_the_decode_span(monkeypatch):"""llama-server can end a stream with timings and no usage."""monitor = ApiMonitor(max_entries = 3)@@ -1563,3 +1694,41 @@ def test_a_bad_predicted_ms_is_dropped_rather_than_raising(monkeypatch, predictemonitor.finish(entry_id)assert monitor.snapshot()[0]["decode_ms"] is None+++def test_perf_callback_reports_decode_phase_once_per_prefill_round(monkeypatch):+ import routes.inference as inf_mod+ from core.inference.llama_cpp import _report_live_llama_timings++ seen = []+ monkeypatch.setattr(+ inf_mod,+ "_monitor_usage",+ lambda *_a, timings, **_k: seen.append(timings.get("running_phase")),+ )+ callback = inf_mod._monitor_perf_callback("apireq_x", 4096)+ progress = {+ "choices": [{"index": 0, "delta": {"role": "assistant", "content": None}}],+ "prompt_progress": {"total": 10, "processed": 10, "cache": 0, "time_ms": 1},+ }+ token = {"choices": [{"index": 0, "delta": {"content": "a"}}], "timings": {"predicted_n": 1}}+ for chunk in (progress, token, token, token, progress, token, token):+ _report_live_llama_timings(callback, chunk)++ assert seen == [None, "token_generation", None, None, None, "token_generation", None]+++def test_progress_updates_advance_updated_at_on_a_frozen_clock(monkeypatch):+ import core.inference.api_monitor as monitor_mod++ monitor = ApiMonitor(max_entries = 3)+ entry_id = monitor.start(endpoint = "/v1/chat/completions", method = "POST", model = "m", prompt = "p")+ monkeypatch.setattr(monitor_mod.time, "time", lambda: 1_000.0)+ seen = []+ for processed in (10, 20):+ monitor.set_prompt_progress(entry_id, total = 100, processed = processed)+ seen.append(monitor.snapshot()[0]["updated_at"])+ monitor.set_running_phase(entry_id, "token_generation")+ seen.append(monitor.snapshot()[0]["updated_at"])++ assert seen[0] < seen[1] < seen[2]diff --git a/studio/backend/tests/test_llama_cpp_tool_loop.py b/studio/backend/tests/test_llama_cpp_tool_loop.pyindex e38bf52d0df..bc8a208e12e 100644--- a/studio/backend/tests/test_llama_cpp_tool_loop.py+++ b/studio/backend/tests/test_llama_cpp_tool_loop.py@@ -278,6 +278,8 @@ def test_plain_stream_reports_request_scoped_live_prompt_and_generation_timings(assert payloads[0]["timings_per_token"] is Trueassert samples[0]["prompt_n"] == 900assert samples[0]["prompt_per_second"] == 9000+ assert samples[0]["prompt_progress"]["total"] == 1000+ assert samples[1]["running_phase"] == "token_generation"assert all("prompt_ms" not in sample for sample in samples)assert samples[-1]["predicted_per_second"] == 200diff --git a/studio/backend/tests/test_llama_route_timeouts.py b/studio/backend/tests/test_llama_route_timeouts.pyindex b71138ef613..7137accbc18 100644--- a/studio/backend/tests/test_llama_route_timeouts.py+++ b/studio/backend/tests/test_llama_route_timeouts.py@@ -2,6 +2,7 @@# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.import asyncio+import jsonimport mathimport osimport sys@@ -9,6 +10,8 @@ import timeimport threadingfrom types import SimpleNamespace+import pytest+_backend = os.path.join(os.path.dirname(__file__), "..")sys.path.insert(0, _backend)@@ -509,3 +512,107 @@ def test_stream_stall_timeout_disabled_clears_read_timeout():assert seen == [None, None], seenasyncio.run(_run())++[email protected]("wire_format", ["lines", "bytes"])+def test_prompt_progress_does_not_start_the_decode_timeout(wire_format):+ async def run():+ progress = "data: " + json.dumps(+ {+ "choices": [{"index": 0, "delta": {"role": "assistant", "content": None}}],+ "prompt_progress": {"processed": 512, "total": 2048},+ }+ )+ output = 'data: {"choices":[{"index":0,"delta":{"content":"ok"}}]}'+ response = SimpleNamespace(request = SimpleNamespace(extensions = {"timeout": {}}))++ async def items():+ if wire_format == "bytes":+ data = (progress + "\n\n").encode()+ yield data[:40]+ yield data[40:]+ else:+ yield progress+ yield ""+ await asyncio.sleep(0.08)+ yield (output + "\n\n").encode() if wire_format == "bytes" else output+ await asyncio.Future()++ received = []+ with pytest.raises(inf_mod.httpx.ReadTimeout, match = "mid-response"):+ async for item in inf_mod._aiter_llama_stream_items(+ items(),+ response = response,+ first_token_deadline = time.monotonic() + 1,+ post_first_item_read_timeout_s = 0.02,+ track_prefill_progress = True,+ ):+ received.append(item)+ if "ok" not in str(item):+ assert response.request.extensions["timeout"]["read"] is None+ assert any("ok" in str(item) for item in received)+ assert response.request.extensions["timeout"]["read"] == 0.02++ asyncio.run(run())++[email protected]("advancing", [True, False])+def test_only_advancing_prefill_progress_renews_the_deadline(monkeypatch, advancing):+ monkeypatch.setattr(inf_mod, "_first_token_timeout_s", lambda: 0.12)++ async def run():+ async def items():+ for index in range(6):+ yield "data: " + json.dumps(+ {+ "choices": [{"delta": {"role": "assistant", "content": None}}],+ "prompt_progress": {"processed": index if advancing else 0},+ }+ )+ await asyncio.sleep(0.04)+ yield 'data: {"choices":[{"delta":{"content":"ok"}}]}'++ received = []++ async def drain():+ async for item in inf_mod._aiter_llama_stream_items(+ items(),+ first_token_deadline = time.monotonic() + 0.12,+ post_first_item_read_timeout_s = 0.02,+ track_prefill_progress = True,+ ):+ received.append(item)++ if advancing:+ await drain()+ assert '"ok"' in received[-1]+ else:+ with pytest.raises(inf_mod.httpx.ReadTimeout, match = "first token"):+ await drain()+ assert len(received) < 6++ asyncio.run(run())+++def test_prefill_tracking_preserves_terminal_grace_without_output():+ async def run():+ response = SimpleNamespace(request = SimpleNamespace(extensions = {"timeout": {}}))+ armed = []++ async def items():+ armed.append(response.request.extensions["timeout"]["read"])+ yield 'data: {"choices":[{"delta":{},"finish_reason":"stop"}]}'+ await asyncio.Future()++ with pytest.raises(inf_mod.httpx.ReadTimeout, match = "mid-response"):+ async for _ in inf_mod._aiter_llama_stream_items(+ items(),+ response = response,+ first_token_deadline = time.monotonic() + 1,+ post_first_item_read_timeout_s = lambda: 0.02,+ track_prefill_progress = True,+ ):+ pass+ assert armed == [None]++ asyncio.run(run())diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.pyindex 38f324b1192..23330de3729 100644--- a/studio/backend/tests/test_openai_tool_passthrough.py+++ b/studio/backend/tests/test_openai_tool_passthrough.py@@ -6585,6 +6585,7 @@ class TestApiMonitorProviderAndCompletionStreams:monkeypatch,lines,stream_options = None,+ **payload_extra,):import routes.inference as inf_mod@@ -6609,6 +6610,7 @@ class TestApiMonitorProviderAndCompletionStreams:stream = True,stream_options = stream_options,tools = [_LOOKUP_TOOL],+ **payload_extra,)response = await _openai_passthrough_stream(@@ -6625,6 +6627,8 @@ class TestApiMonitorProviderAndCompletionStreams:chunks = chunks,body = "".join(chunks),monitor = monitor,+ monitor_id = monitor_id,+ response_headers = dict(response.headers),upstream_bodies = upstream_bodies,)@@ -7426,7 +7430,8 @@ class TestApiMonitorProviderAndCompletionStreams:asyncio.run(_run())- def test_completions_stream_requests_usage_only_for_monitor(self, monkeypatch):+ @pytest.mark.parametrize("client_progress", [False, True])+ def test_completions_stream_requests_usage_only_for_monitor(self, monkeypatch, client_progress):import routes.inference as inf_modasync def _run():class Request:@@ -7435,7 +7440,10 @@ class TestApiMonitorProviderAndCompletionStreams:method = "POST"async def json(self):- return {"prompt": "hi", "stream": True}+ body = {"prompt": "hi", "stream": True}+ if client_progress:+ body["return_progress"] = True+ return bodyasync def is_disconnected(self):return False@@ -7448,6 +7456,8 @@ class TestApiMonitorProviderAndCompletionStreams:async def fake_items(*_args, **_kwargs):yield (+ b'data: {"choices":[{"text":"","finish_reason":null}],'+ b'"prompt_progress":{"total":4,"processed":2,"cache":0,"time_ms":1}}\n\n'b'data: {"choices":[{"text":"ok","finish_reason":"stop"}]}\n\n'b'data: {"choices":[],"usage":{"prompt_tokens":3,'b'"completion_tokens":2,"total_tokens":5}}\n\n'@@ -7459,12 +7469,19 @@ class TestApiMonitorProviderAndCompletionStreams:_pin_loaded_backend(monkeypatch)monkeypatch.setattr(inf_mod, "_send_stream_with_preheader_cancel", fake_send)monkeypatch.setattr(inf_mod, "_aiter_llama_stream_items", fake_items)+ monkeypatch.setattr(+ inf_mod, "_openai_passthrough_stream_keepalive_interval", lambda: 1e-9+ )response = await openai_completions(Request(), current_subject = "test")body = b"".join([chunk async for chunk in response.body_iterator])+ assert upstream_bodies[0]["return_progress"] is True+ assert (b": keep-alive" in body) is not client_progressassert upstream_bodies[0]["stream_options"]["include_usage"] is Trueassert b'"usage"' not in body+ assert (b"prompt_progress" in body) is client_progress+ assert b'"ok"' in body[entry] = monitor.snapshot()assert entry["prompt_tokens"] == 3assert entry["completion_tokens"] == 2@@ -8833,6 +8850,35 @@ class TestApiMonitorProviderAndCompletionStreams:asyncio.run(_run())+ @pytest.mark.parametrize("client_progress", [False, True])+ def test_passthrough_prompt_progress_reaches_monitor_and_response_header(+ self, monkeypatch, client_progress+ ):+ async def _run():+ extra = {"return_progress": True} if client_progress else {}+ result = await self._run_passthrough_stream(+ monkeypatch,+ [+ 'data: {"prompt_progress":{"total":2000,"processed":1200,"cache":0,"time_ms":15000},"choices":[{"index":0,"delta":{"role":"assistant","content":null},"finish_reason":null}]}',+ 'data: {"choices":[{"index":0,"delta":{"content":"ok"},"finish_reason":null}]}',+ "data: [DONE]",+ ],+ **extra,+ )++ assert result.upstream_bodies[0]["return_progress"] is True+ assert (+ result.response_headers.get("x-unsloth-monitor-id") == result.monitor_id+ ), result.response_headers+ [entry] = result.monitor.snapshot()+ assert entry["running_phase"] == "token_generation"+ assert entry["prompt_progress"]["processed"] == 1200+ assert entry["prompt_progress"]["percent"] == 60.0+ assert ("prompt_progress" in result.body) is client_progress+ assert '"ok"' in result.body++ asyncio.run(_run())+def test_passthrough_stream_queued_request_sends_keepalive_before_upstream(self, monkeypatch):import routes.inference as inf_modasync def _run():@@ -8871,6 +8917,7 @@ class TestApiMonitorProviderAndCompletionStreams:"chatcmpl-test",monitor_id = monitor_id,)+ assert response.headers["x-unsloth-monitor-id"] == monitor_iditerator = response.body_iteratortry:chunk = await asyncio.wait_for(iterator.__anext__(), timeout = 0.2)diff --git a/studio/backend/tests/test_secure_tunnel_gate.py b/studio/backend/tests/test_secure_tunnel_gate.pyindex 2396eb91eb5..2d32ba244cf 100644--- a/studio/backend/tests/test_secure_tunnel_gate.py+++ b/studio/backend/tests/test_secure_tunnel_gate.py@@ -345,6 +345,7 @@ def test_run_server_exports_secure_env_for_cors():assert "set_studio_tunnel_runtime_callback(set_remote_connector_active)" in srcmain_src = (_BACKEND / "main.py").read_text(encoding = "utf-8")assert "RemoteAccessCORSMiddleware,\n remote_access_state = app.state" in main_src+ assert '"X-Unsloth-Monitor-ID"' in main_srcdef test_run_server_emit_tauri_port_defaults_on():diff --git a/studio/frontend/src/features/api-monitor/api-monitor-page.tsx b/studio/frontend/src/features/api-monitor/api-monitor-page.tsxindex 99414d4d952..f3ad8fbe415 100644--- a/studio/frontend/src/features/api-monitor/api-monitor-page.tsx+++ b/studio/frontend/src/features/api-monitor/api-monitor-page.tsx@@ -384,6 +384,20 @@ function PayloadBlock({);}+function requestStatusLabel(entry: ApiMonitorEntry): string {+ if (entry.status !== "running") return entry.status;+ if (entry.running_phase === "token_generation") return "Token generation";+ if (entry.running_phase !== "prompt_processing") return "Running";+ const progress = entry.prompt_progress;+ if (progress?.percent != null) {+ return `Prompt processing · ${Math.round(progress.percent)}%`;+ }+ if (progress?.processed != null) {+ return `Prompt processing · ${formatCount(progress.processed)} tokens`;+ }+ return "Prompt processing";+}+function RequestDetail({entry,detail,@@ -422,7 +436,7 @@ function RequestDetail({statusTextClass(entry.status),)}>- {entry.status}+ {requestStatusLabel(entry)}</span><span className="ml-auto shrink-0 font-mono text-ui-10 text-muted-foreground">{entry.id}diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.tsindex 12d60960417..73060e561b4 100644--- a/studio/frontend/src/features/chat/types/api.ts+++ b/studio/frontend/src/features/chat/types/api.ts@@ -505,6 +505,14 @@ export interface ApiMonitorEntry {reason?: "manual" | "idle" | "api" | null;// 0-100 while a download row is running.progress?: number | null;+ running_phase?: "prompt_processing" | "token_generation" | null;+ prompt_progress?: {+ total: number | null;+ processed: number | null;+ cached: number | null;+ time_ms: number | null;+ percent: number | null;+ } | null;// Server-side time to first token (measured, else engine prefill).ttft_ms?: number | null;tok_per_sec?: number | null;diff --git a/tests/studio/test_stream_cancel_registration_timing.py b/tests/studio/test_stream_cancel_registration_timing.pyindex 6862d963281..14cea4861c7 100644--- a/tests/studio/test_stream_cancel_registration_timing.py+++ b/tests/studio/test_stream_cancel_registration_timing.py@@ -148,6 +148,25 @@ def test_async_generators_cleanup_tracker_in_finally():)+# _sse_streaming_response is the shared SSE constructor; the test below pins that it stays same-task.+_SAME_TASK_BUILDERS = ("_SameTaskStreamingResponse", "_sse_streaming_response")+++def test_sse_streaming_response_builds_a_same_task_response():+ fn = next(+ n+ for n in ast.walk(_TREE)+ if isinstance(n, ast.FunctionDef) and n.name == "_sse_streaming_response"+ )+ names = {+ sub.func.id+ for sub in ast.walk(fn)+ if isinstance(sub, ast.Call) and isinstance(sub.func, ast.Name)+ }+ assert "_SameTaskStreamingResponse" in names+ assert "StreamingResponse" not in names++def test_chat_completions_streams_avoid_starlette_task_group():top = _async_function("produce_openai_chat_completions")legacy_calls = []@@ -157,7 +176,7 @@ def test_chat_completions_streams_avoid_starlette_task_group():continueif sub.func.id == "StreamingResponse":legacy_calls.append(sub.lineno)- if sub.func.id == "_SameTaskStreamingResponse":+ if sub.func.id in _SAME_TASK_BUILDERS:same_task_calls += 1assert not legacy_calls, ("Streaming /v1/chat/completions must use _SameTaskStreamingResponse, "@@ -180,7 +199,7 @@ def test_openai_passthrough_stream_avoids_starlette_task_group():continueif sub.func.id == "StreamingResponse":legacy_calls.append(sub.lineno)- if sub.func.id == "_SameTaskStreamingResponse":+ if sub.func.id in _SAME_TASK_BUILDERS:same_task_calls += 1assert not legacy_calls, ("OpenAI passthrough streams must use _SameTaskStreamingResponse, "