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.

fix(studio): refresh token count after model load (#7450) (#7453)

Souravrajvi077ed5e9c0784
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 5cbb5398e44..17ff9dac291 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -2812,6 +2812,10 @@ def _coerce_reasoning_effort(architecture, kwargs: dict) -> dict:
return kwargs
+class CountAborted(Exception):
+ """A token count stood down mid-flight because its answer stopped mattering."""
+
+
class LlamaCppBackend:
"""Manages a llama-server subprocess for GGUF model inference.
@@ -14624,40 +14628,27 @@ class LlamaCppBackend:
system = None,
tools = None,
strict: bool = False,
+ chat_template_kwargs = None,
+ should_abort = None,
) -> int:
"""Count prompt tokens for a chat request via llama-server.
- Non-strict callers keep the historical best-effort behavior and receive
- 0 when a count cannot be determined. Strict callers (public count_tokens
- endpoints) get an exception instead of a successful-looking zero when
- tokenizer/template calls fail or a multimodal prompt would fall back to a
- text-only approximation.
+ Non-strict callers keep the historical best-effort behavior and get 0 when a
+ count cannot be determined. Strict callers (public count_tokens endpoints)
+ raise instead: the text-only fallback is an approximation, not a count.
+
+ ``chat_template_kwargs`` reaches /apply-template unchanged, so a caller can
+ price a request rendered in a non-default reasoning mode.
+
+ ``should_abort`` is polled between the two llama-server calls. Admission is the
+ caller's job; this only stops a count that was admitted while idle from spending its
+ second round trip once the answer stopped mattering. Raises when it fires.
"""
if not self.is_loaded:
if strict:
raise RuntimeError("llama-server is not loaded")
return 0
- def _has_non_text_content(content) -> bool:
- if isinstance(content, list):
- for block in content:
- if isinstance(block, str):
- continue
- if not isinstance(block, dict):
- return True
- if isinstance(block.get("text"), str):
- continue
- return True
- return False
-
- def _has_non_text_prompt_parts() -> bool:
- if _has_non_text_content(system):
- return True
- for msg in messages or []:
- if isinstance(msg, dict) and _has_non_text_content(msg.get("content", "")):
- return True
- return False
-
def _block_text(content) -> str:
if isinstance(content, str):
return content
@@ -14704,6 +14695,9 @@ class LlamaCppBackend:
template_messages = [
{"role": "system", "content": system_text}
] + template_messages
+ # An empty list is passed through as-is: llama-server renders through minja, not
+ # jinja2, so messages[0] yields undefined rather than raising and the template
+ # returns its bare preamble. A placeholder turn would add a system block instead.
apply_template_failed = False
try:
# llama-server's /apply-template renders tool declarations
@@ -14712,6 +14706,9 @@ class LlamaCppBackend:
template_body = {"messages": template_messages}
if tools:
template_body["tools"] = tools
+ # Layered over the load-time --chat-template-kwargs: only keys sent here move.
+ if chat_template_kwargs:
+ template_body["chat_template_kwargs"] = chat_template_kwargs
resp = client.post(
f"{self.base_url}/apply-template",
json = template_body,
@@ -14719,15 +14716,21 @@ class LlamaCppBackend:
if resp.status_code == 200:
prompt = resp.json().get("prompt", "")
if isinstance(prompt, str):
+ if should_abort is not None and should_abort():
+ raise CountAborted()
return _tokenize(prompt)
apply_template_failed = True
+ except CountAborted:
+ # Not a template failure: swallowed, the text fallback tokenizes anyway,
+ # which is the work being declined. Must precede the generic except.
+ raise
except Exception:
apply_template_failed = True
- if strict and apply_template_failed and _has_non_text_prompt_parts():
- raise RuntimeError(
- "cannot fall back to text-only token counting for multimodal messages"
- )
+ # The fallback drops role markers, special tokens and tool schemas (~30% of a
+ # six-turn two-tool prompt), so strict callers error rather than undercount.
+ if strict and apply_template_failed:
+ raise RuntimeError("llama-server could not render the chat template")
# 2. Fallback: concatenate plain text and tokenize. Append a
# serialized form of the tools so they still contribute to the
diff --git a/studio/backend/core/inference/llama_keepwarm.py b/studio/backend/core/inference/llama_keepwarm.py
index 05b1271b270..a6b84686b12 100644
--- a/studio/backend/core/inference/llama_keepwarm.py
+++ b/studio/backend/core/inference/llama_keepwarm.py
@@ -60,6 +60,7 @@ _INFERENCE_SUFFIXES = (
"/completions",
"/messages",
"/messages/count_tokens", # counts via the loaded tokenizer; protect like /messages
+ "/chat/count_tokens",
"/embeddings",
"/responses",
"/generate/stream", # Unsloth's own streaming route on the same llama-server
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 8d0fff46419..78716c99876 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -7153,6 +7153,35 @@ def _mcp_specs_for_server(server: dict, mcp_tools: list[dict]) -> list[dict]:
return specs
+def cached_mcp_tools() -> tuple[list[dict], bool]:
+ """The MCP schemas already in cache, and whether that is the whole set.
+
+ get_enabled_mcp_tools() renders the same servers, but reaches the network to do it: it
+ spawns stdio servers, blocks for a probe timeout on one that is down, and writes cache and
+ cool-off state. A background token count must not do any of that, so this reads only what
+ those probes have already filled in.
+
+ ``complete`` is False when an enabled server has nothing cached and is not in its
+ post-failure cool-off, meaning a completion would probe it and render schemas this cannot
+ price. A cool-off server renders nothing on the completion path either, so skipping that one
+ is exact rather than short. Callers that must not undercount should decline on False.
+ """
+ servers = [s for s in mcp_servers_db.list_servers() if s.get("is_enabled")]
+ if not stdio_mcp_enabled():
+ servers = [s for s in servers if not is_stdio(s["url"])]
+
+ specs: list[dict] = []
+ complete = True
+ for server in servers:
+ payload = get_cached_tools(server["id"])
+ if payload is None:
+ if not in_failure_cooloff(server["id"]):
+ complete = False
+ continue
+ specs.extend(_mcp_specs_for_server(server, payload))
+ return specs, complete
+
+
async def get_enabled_mcp_tools() -> list[dict]:
servers = [s for s in mcp_servers_db.list_servers() if s.get("is_enabled")]
# Never spawn stdio servers when stdio is disabled on this host.
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 36296074ca2..5480a4181f1 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -1415,6 +1415,57 @@ class ChatCompletionRequest(BaseModel):
return self
+class ChatCountTokensRequest(BaseModel):
+ """Count prompt tokens for a local GGUF chat without generating."""
+
+ model_config = {"extra": "allow"}
+
+ model: str = Field(
+ "default",
+ description = "Model identifier (informational; the active model is used)",
+ )
+ messages: list[ChatMessage] = Field(
+ ...,
+ description = "Conversation messages in OpenAI chat form",
+ )
+ tools: Optional[list[dict]] = Field(
+ None,
+ description = "Optional OpenAI tool definitions included in the prompt",
+ )
+ enable_thinking: Optional[bool] = Field(
+ None,
+ description = "[x-unsloth] Render the template in thinking mode, as a completion would",
+ )
+ reasoning_effort: Optional[str] = Field(
+ None,
+ description = "[x-unsloth] Reasoning effort level the completion would request",
+ )
+ preserve_thinking: Optional[bool] = Field(
+ None,
+ description = "[x-unsloth] Keep historical <think> blocks in the rendered prompt",
+ )
+ enable_tools: Optional[bool] = Field(
+ None,
+ description = "[x-unsloth] Enable tool calling for supported models",
+ )
+ enabled_tools: Optional[list[str]] = Field(
+ None,
+ description = "[x-unsloth] List of enabled built-in tool names",
+ )
+ mcp_enabled: Optional[bool] = Field(
+ None,
+ description = "[x-unsloth] Append tools from every enabled MCP server",
+ )
+ rag_scope: Optional[dict] = Field(
+ None,
+ description = "[x-unsloth] Hidden RAG retrieval scope for search_knowledge_base",
+ )
+ auto_heal_tool_calls: Optional[bool] = Field(
+ None,
+ description = "[x-unsloth] Strip leaked tool-call markup from replayed history",
+ )
+
+
class ToolConfirmRequest(BaseModel):
session_id: Optional[str] = None
approval_id: Optional[str] = None
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 97d6e302cad..946b62c7d0d 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -1836,6 +1836,7 @@ from models.inference import (
UnloadResponse,
InferenceStatusResponse,
ChatCompletionRequest,
+ ChatCountTokensRequest,
ChatCompletionChunk,
ChatCompletion,
ToolConfirmRequest,
@@ -2291,6 +2292,39 @@ def _explicit_studio_tool_loop_requested(payload) -> bool:
return policy is not False and (payload.enable_tools is True or bool(payload.mcp_enabled))
+def _takes_tool_passthrough(payload, llama_backend) -> bool:
+ """True when a GGUF request is forwarded to llama-server verbatim.
+
+ The passthrough sends the caller's own tools, no built-in schema and no nudge, so the counter
+ must decide this BEFORE applying the process tool policy: `unsloth run --enable-tools` sets
+ that policy without asking for the tool loop, so its catalog would price a prompt never sent.
+ """
+ supports_tools = getattr(llama_backend, "supports_tools", False)
+ if supports_tools and _explicit_studio_tool_loop_requested(payload):
+ return False
+ # Read defensively: a count request carries no tool_choice, and absent withdraws nothing.
+ has_client_contract = (
+ bool(payload.tools) and getattr(payload, "tool_choice", None) != "none"
+ ) or _has_openai_tool_history(payload.messages)
+ supports_passthrough = getattr(llama_backend, "supports_tool_passthrough", supports_tools)
+ if supports_passthrough and has_client_contract:
+ return True
+ return _extract_response_format(payload) is not None
+
+
+def _passthrough_client_tools(payload):
+ """The caller's own tool catalog exactly as the passthrough puts it on the wire.
+
+ ``tool_choice: "none"`` withdraws it, unless tool history needs those schemas to replay.
+ /apply-template renders any ``tools`` regardless of tool_choice, so the counter shares the rule.
+ """
+ if getattr(payload, "tool_choice", None) == "none" and not _has_openai_tool_history(
+ payload.messages
+ ):
+ return None
+ return payload.tools or None
+
+
def _permission_mode_confirm(payload) -> bool:
"""Effective confirm-gate intent for Unsloth's own local tool loop.
@@ -3817,6 +3851,36 @@ def _llama_public_model_id(llama_backend, fallback: Optional[str] = None) -> Opt
)
+def _llama_status_model_ids(llama_backend) -> "tuple[Optional[str], Optional[str]]":
+ """The ``(active_model, model_identifier)`` pair ``/api/inference/status`` publishes
+ for a loaded GGUF. A native-lease load reports only the display label, never the
+ leased on-disk path."""
+ model_id = getattr(llama_backend, "model_identifier", None)
+ native_grant_backed = getattr(llama_backend, "_native_grant_backed", False)
+ display_model_id = getattr(
+ llama_backend, "_native_display_label", None
+ ) or display_label_for_native_path(model_id)
+ if (
+ native_grant_backed
+ and model_id
+ and display_model_id == model_id
+ and os.path.isabs(model_id)
+ ):
+ display_model_id = os.path.basename(model_id)
+ elif not native_grant_backed and display_model_id == model_id:
+ # No label registered, so report the clean public id, not the snapshot's sha.
+ display_model_id = _llama_public_model_id(llama_backend) or display_model_id
+ return display_model_id, (None if native_grant_backed else model_id)
+
+
+def _llama_status_checkpoint_id(llama_backend) -> Optional[str]:
+ """The exact string a Studio client holds as ``params.checkpoint`` for the loaded
+ GGUF: ``status.model_identifier ?? status.active_model``. Built from the same pair the
+ status handler returns so the two cannot drift."""
+ display_model_id, model_identifier = _llama_status_model_ids(llama_backend)
+ return display_model_id if model_identifier is None else model_identifier
+
+
_DISABLE_OPENAI_AUTO_SWITCH_SCOPE_KEY = "_unsloth_disable_openai_auto_switch"
# Sentinel a raw-body endpoint passes when the request omits ``model``: it must
# only restore an idle-freed model, never run the resolver (so a downloaded GGUF
@@ -7588,20 +7652,10 @@ async def get_status(current_subject: str = Depends(get_current_subject)):
# If a GGUF model is loaded via llama-server, report that
if llama_backend.is_loaded:
_model_id = llama_backend.model_identifier
+ # is_local_model below needs the flag; the helper reports identities, not provenance.
_native_grant_backed = getattr(llama_backend, "_native_grant_backed", False)
- _display_model_id = getattr(
- llama_backend, "_native_display_label", None
- ) or display_label_for_native_path(_model_id)
- if (
- _native_grant_backed
- and _model_id
- and _display_model_id == _model_id
- and os.path.isabs(_model_id)
- ):
- _display_model_id = os.path.basename(_model_id)
- elif not _native_grant_backed and _display_model_id == _model_id:
- # No label registered, so report the clean public id, not the snapshot's sha.
- _display_model_id = _llama_public_model_id(llama_backend) or _display_model_id
+ # Shared with /chat/count_tokens, so a client can tell whose tokenizer counted.
+ _display_model_id, _reported_model_identifier = _llama_status_model_ids(llama_backend)
_inference_cfg = load_inference_config(_model_id) if _model_id else None
# Don't surface Unsloth's auto-applied bundled family template (e.g. the
# gemma-4 override) as a user-authored override: the frontend adopts
@@ -7620,7 +7674,7 @@ async def get_status(current_subject: str = Depends(get_current_subject)):
_reported_chat_template_override = None
return InferenceStatusResponse(
active_model = _display_model_id,
- model_identifier = None if _native_grant_backed else _model_id,
+ model_identifier = _reported_model_identifier,
is_gguf = True,
is_local_model = _loaded_is_local_model(
llama_backend, _native_grant_backed, _model_id
@@ -9731,14 +9785,6 @@ async def openai_chat_completions(
normalized_stop = _normalize_stop_sequences(payload.stop)
_has_tool_messages = _has_openai_tool_history(payload.messages)
- # Route guided-decoding requests through the verbatim passthrough so
- # ``response_format`` (JSON schema) reaches llama-server and the model's
- # GBNF-constrained output comes back unmodified. The non-passthrough GGUF
- # path below calls ``generate_chat_completion`` which has no response_format
- # kwarg, so the schema gets silently dropped and data_designer falls back to
- # free-form sampling. Guided decoding does not require ``supports_tools`` --
- # the grammar machinery is independent of tool-call parsing.
- _has_response_format = _extract_response_format(payload) is not None
_has_tool_catalog = bool(payload.tools and len(payload.tools) > 0)
_has_active_tool_catalog = _has_tool_catalog and payload.tool_choice != "none"
_has_client_tool_contract = _has_active_tool_catalog or _has_tool_messages
@@ -9752,7 +9798,6 @@ async def openai_chat_completions(
_supports_tool_passthrough = getattr(
llama_backend, "supports_tool_passthrough", llama_backend.supports_tools
)
- _tools_passthrough = _supports_tool_passthrough and _has_client_tool_contract
if (
using_gguf
and not _studio_tool_loop_requested
@@ -9771,11 +9816,11 @@ async def openai_chat_completions(
param = "tools" if payload.tools else "messages",
),
)
- if (
- using_gguf
- and not _studio_tool_loop_requested
- and (_tools_passthrough or _has_response_format)
- ):
+ # Shared with the token counter, so a count can never describe a route the completion does
+ # not take. Guided decoding routes here too: the non-passthrough path calls
+ # generate_chat_completion, which has no response_format kwarg and would silently drop the
+ # schema. No ``supports_tools`` needed -- grammars are independent of it.
+ if using_gguf and _takes_tool_passthrough(payload, llama_backend):
if _wants_multiple_choices(payload):
raise _reject_unsupported_n("GGUF tool or response_format passthrough")
if payload.audio_base64:
@@ -14916,6 +14961,209 @@ def _validate_anthropic_client_tools(tools) -> None:
)
+def _append_to_system_message(messages: list[dict], addition: str) -> list[dict]:
+ """Append text to the leading system/developer message, or prepend one."""
+ if not addition:
+ return messages
+ copied = [dict(msg) for msg in messages]
+ for msg in copied:
+ if msg.get("role") not in ("system", "developer"):
+ continue
+ content = msg.get("content", "")
+ if isinstance(content, str):
+ msg["content"] = content.rstrip() + "\n\n" + addition
+ return copied
+ return [{"role": "system", "content": addition}, *copied]
+
+
[email protected]("/chat/count_tokens")
+async def chat_count_tokens(
+ payload: ChatCountTokensRequest, current_subject: str = Depends(get_current_subject)
+):
+ """Count prompt tokens for OpenAI-form chat messages using the loaded tokenizer.
+
+ Unlike the /v1 count endpoints this never auto-switches: ``model`` is informational. The
+ caller is a background recount with no abort signal, so switching could drag the backend back
+ to the model loaded when the count started, a reload the client's guards cannot undo."""
+ # Admitted only while nothing generates, and stood down at the next checkpoint if that changes:
+ # admission is not atomic with the work, and true mutual exclusion would put a lock in front of
+ # generation startup, which is the cost this avoids. Refusing here also covers the second tab or
+ # the script against /api that the client-side gate cannot. Deliberately coarse: _TrackedCancel
+ # registers external-provider runs too, so those decline a count they could have served;
+ # narrowing it means trusting a kind/model field to decide whether to work next to a decode, and
+ # being wrong there costs inference time while over-refusing only costs a redraw.
+ if active_generations.count() > 0:
+ raise HTTPException(
+ status_code = 503,
+ detail = "Cannot count tokens while a generation is in progress.",
+ )
+
+ # /apply-template swaps each image for a short media marker, so refuse rather than undercount.
+ if _request_has_image(payload):
+ raise HTTPException(
+ status_code = 503,
+ detail = "Cannot count tokens for messages containing images.",
+ )
+ # Same for audio: the completion injects the recording, this cannot.
+ if getattr(payload, "audio_base64", None):
+ raise HTTPException(
+ status_code = 503,
+ detail = "Cannot count tokens for messages containing audio.",
+ )
+
+ llama_backend = get_llama_cpp_backend()
+ if not llama_backend.is_loaded:
+ raise HTTPException(
+ status_code = 503,
+ detail = _no_model_loaded_detail("No GGUF model loaded. Load a GGUF model first."),
+ )
+
+ # Same sanitization the GGUF chat path runs before generation. Route FIRST: the passthrough
+ # does not merge adjacent user turns, so coalescing here would price a prompt it never sends
+ # (two user turns split by an empty assistant sentinel, after a stopped response).
+ _takes_passthrough = _takes_tool_passthrough(payload, llama_backend)
+ openai_messages = _strip_provider_synthetic_tool_history(
+ _drop_empty_assistant_sentinels([m.model_dump(exclude_none = True) for m in payload.messages])
+ )
+ if not _takes_passthrough:
+ openai_messages = _coalesce_consecutive_user_turns(openai_messages)
+ _system_prompt, _, _ = _extract_content_parts(payload.messages)
+ openai_messages = _set_or_prepend_system_message(openai_messages, _system_prompt)
+
+ # A PENDING turn (unanswered user message or tool result) is the one shape the tool loop
+ # answers from exactly these messages, splicing in whatever build_rag_autoinject retrieves --
+ # thousands of tokens this never sees, so the bar would claim room the generation lacks. Any
+ # other shape ends on an assistant turn, where retrieval has no user message to run against.
+ if (
+ payload.rag_scope
+ and openai_messages
+ and openai_messages[-1].get("role") in ("user", "tool")
+ ):
+ raise HTTPException(
+ status_code = 503,
+ detail = "Cannot count tokens for a pending turn that would retrieve documents.",
+ )
+
+ # The passthrough is the only route that puts the caller's own catalog on the wire; every other
+ # renders from the selection below, so a catalog surviving here would price schemas never sent.
+ openai_tools = _passthrough_client_tools(payload) if _takes_passthrough else None
+ # The CLI hard-override still applies: _effective_enable_tools resolves it into _tools_on.
+ _client_disabled_tool_calls = getattr(payload, "tool_choice", None) == "none" and not (
+ _explicit_studio_tool_loop_requested(payload) and llama_backend.supports_tools
+ )
+ # Schemas and the nudge are a large share of the prompt: price the completion's own selection.
+ _tools_on = False if _client_disabled_tool_calls else _effective_enable_tools(payload)
+ # Same rule the completion path resolves, so the two agree on whether MCP schemas are in the
+ # prompt at all. MCP alone turns tools on there, hence the widened branch below.
+ from state.tool_policy import get_tool_policy as _get_tool_policy_ct
+
+ _mcp_on = (
+ not _client_disabled_tool_calls
+ and bool(getattr(payload, "mcp_enabled", False))
+ and _get_tool_policy_ct() is not False
+ )
+ # Never discovery on a count: get_enabled_mcp_tools spawns stdio servers, writes cache and
+ # cool-off state, and blocks a probe timeout on a server that is down. _mcp_allowed stays
+ # False because it is the flag that reaches the network; schemas come from the cache that
+ # path fills instead, and an incomplete view is declined rather than undercounted.
+ _mcp_allowed = False
+ _mcp_tools: list[dict] = []
+ if _mcp_on and not _takes_passthrough and llama_backend.supports_tools:
+ from core.inference.tools import cached_mcp_tools
+ _mcp_tools, _mcp_complete = cached_mcp_tools()
+ if not _mcp_complete:
+ raise HTTPException(
+ status_code = 503,
+ detail = "Cannot count tokens until enabled MCP tools have been discovered.",
+ )
+ if not _takes_passthrough and (_tools_on or _mcp_on) and llama_backend.supports_tools:
+ tools_to_use = await _select_request_tools(
+ payload, tools_on = _tools_on, mcp_allowed = _mcp_allowed
+ )
+ # Appended in the position _select_request_tools would have used, so the order matches.
+ tools_to_use = tools_to_use + _mcp_tools
+ if tools_to_use:
+ openai_tools = tools_to_use
+ openai_messages = _append_to_system_message(
+ openai_messages,
+ _apply_rag_nudge(
+ _build_tool_action_nudge(
+ tools = tools_to_use,
+ model_name = _llama_public_model_id(llama_backend, payload.model),
+ ),
+ tools_to_use,
+ rag_scope = payload.rag_scope,
+ ),
+ )
+
+ # The GGUF tool path strips leaked markup from replayed history before rendering,
+ # so without the same strip the count prices text it removes.
+ _count_auto_heal = (
+ payload.auto_heal_tool_calls if payload.auto_heal_tool_calls is not None else True
+ )
+ _count_history_gate = _display_tool_name_gate(tools_to_use)
+ openai_messages = [dict(msg) for msg in openai_messages]
+ for _msg in openai_messages:
+ if _msg.get("role") == "assistant" and isinstance(_msg.get("content"), str):
+ _msg["content"] = _strip_tool_xml_for_display(
+ _msg["content"],
+ auto_heal_tool_calls = _count_auto_heal,
+ enabled_tool_names = _count_history_gate,
+ ).strip()
+
+ # llama-server falls back to the load-time --chat-template-kwargs per key a request omits,
+ # so omitting these prices the template in whatever mode the model was LOADED in.
+ _template_kwargs = llama_backend._request_reasoning_kwargs(
+ payload.enable_thinking,
+ payload.reasoning_effort,
+ payload.preserve_thinking,
+ )
+
+ # Whose tokenizer this is, in the shape /api/inference/status publishes: another tab's load
+ # moves it while the caller's own checkpoint guard sees no change, so report and let it drop.
+ _tokenizer_model = _llama_status_checkpoint_id(llama_backend)
+
+ # Re-checked immediately before the only work that reaches llama-server, because everything
+ # between here and the entry check awaits, so a run can have started in the gap.
+ if active_generations.count() > 0:
+ raise HTTPException(
+ status_code = 503,
+ detail = "Cannot count tokens while a generation is in progress.",
+ )
+
+ from core.inference.llama_cpp import CountAborted
+
+ try:
+ count = await asyncio.to_thread(
+ llama_backend.count_chat_tokens,
+ openai_messages,
+ None,
+ openai_tools,
+ strict = True,
+ chat_template_kwargs = _template_kwargs,
+ # Polled between /apply-template and /tokenize: admission and the work are separate
+ # steps, so a run starting in between is caught here and the second round trip is not.
+ should_abort = lambda: active_generations.count() > 0,
+ )
+ except CountAborted:
+ raise HTTPException(
+ status_code = 503,
+ detail = "Cannot count tokens while a generation is in progress.",
+ )
+ except Exception:
+ raise HTTPException(
+ status_code = 503,
+ detail = "Unable to count tokens with the loaded model tokenizer.",
+ )
+ # A load landing mid-count leaves the total attributable to neither model.
+ if _llama_status_checkpoint_id(llama_backend) != _tokenizer_model:
+ raise HTTPException(
+ status_code = 503,
+ detail = "The loaded model changed while counting tokens.",
+ )
+ return JSONResponse(content = {"input_tokens": int(count), "model": _tokenizer_model})
+
+
@router.post("/messages/count_tokens")
async def anthropic_count_tokens(
payload: AnthropicMessagesRequest,
@@ -17072,9 +17320,7 @@ def _build_openai_passthrough_body(
system_prompt, _, _ = _extract_content_parts(payload.messages)
messages = _set_or_prepend_system_message(messages, system_prompt)
tool_choice = payload.tool_choice if payload.tool_choice is not None else "auto"
- tools = payload.tools
- if payload.tool_choice == "none" and not _has_openai_tool_history(payload.messages):
- tools = None
+ tools = _passthrough_client_tools(payload)
# Forward per-request reasoning fields (enable_thinking / reasoning_effort /
# preserve_thinking) via chat_template_kwargs so the Jinja template renders
# in the caller's mode, gated on the active template's capabilities exactly
diff --git a/studio/backend/tests/test_inference_status_loaded_gguf.py b/studio/backend/tests/test_inference_status_loaded_gguf.py
new file mode 100644
index 00000000000..8ddd5f3492b
--- /dev/null
+++ b/studio/backend/tests/test_inference_status_loaded_gguf.py
@@ -0,0 +1,118 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""``GET /api/inference/status`` must answer with a GGUF loaded.
+
+The loaded-GGUF branch sits inside a ``try`` whose ``except`` reports 500, so an undefined
+name there is invisible until it runs -- which is how ``_native_grant_backed`` once lost its
+binding to a refactor while ``is_local_model`` kept reading it. The backend is a stub.
+"""
+
+import asyncio
+import os
+
+import pytest
+
+import routes.inference as inference_route
+from models.inference import _InferenceRuntimeFields
+
+
+class _StatusBackend:
+ """A loaded GGUF with the shape ``get_status`` reads, not a full backend.
+
+ Unknown attributes answer None so a later Optional field needs no edit here; typed ones
+ are set explicitly so the response model validates for real, not against a mock.
+
+ Runtime fields are seeded from the response model's defaults: ``_llama_runtime_fields``
+ resolves them by ``hasattr``, which the None catch-all always satisfies, so without real
+ values every bool arrives as None and fails validation. New upstream fields land typed.
+ """
+
+ def __init__(
+ self,
+ model_identifier,
+ *,
+ native_grant_backed = None,
+ display_label = None,
+ ):
+ for name, value in _InferenceRuntimeFields().model_dump().items():
+ setattr(self, name, value)
+ self.model_identifier = model_identifier
+ self.is_loaded = True
+ if native_grant_backed is not None:
+ self._native_grant_backed = native_grant_backed
+ if display_label is not None:
+ self._native_display_label = display_label
+ self.is_vision = False
+ self.is_diffusion = False
+ self.supports_reasoning = False
+ self.reasoning_always_on = False
+ self.supports_preserve_thinking = False
+ self.supports_tools = False
+ self.reasoning_style = "enable_thinking"
+ self.reasoning_effort_levels = []
+ self.requested_parallel_slots = 1
+ self.effective_parallel_slots = 1
+ self._is_audio = False
+ self._has_audio_input = False
+ self.tensor_parallel = False
+ self.gpu_memory_mode = "auto"
+ self.gpu_layers = 0
+ self.n_cpu_moe = 0
+ self.n_moe_layers = 0
+
+ def __getattr__(self, name):
+ # Not a MagicMock on purpose: a bool or int field must fail validation, not pass.
+ if name.startswith("__"):
+ raise AttributeError(name)
+ return None
+
+
+def status_route(monkeypatch):
+ """The handler with its filesystem and config lookups stubbed out."""
+ monkeypatch.setattr(inference_route, "load_inference_config", lambda *a, **k: None)
+ monkeypatch.setattr(
+ inference_route, "resolve_effective_chat_template_override", lambda **k: None
+ )
+
+ def _run(backend):
+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: backend)
+ return asyncio.run(inference_route.get_status("tester"))
+
+ return _run
+
+
+def test_a_loaded_repo_gguf_reports_its_public_id(status_route):
+ status = status_route(_StatusBackend("org/A-GGUF", native_grant_backed = False))
+ assert status.is_gguf is True
+ assert status.active_model == "org/A-GGUF"
+ assert status.model_identifier == "org/A-GGUF"
+ # Not a path, so provenance falls through to the filesystem check and stays False.
+ assert status.is_local_model is False
+
+
+def test_a_backend_without_the_flag_still_reports(status_route):
+ # A server started before the flag existed: read through a default, do not assume it.
+ backend = _StatusBackend("org/A-GGUF")
+ assert not hasattr(backend, "__dict__") or "_native_grant_backed" not in backend.__dict__
+ status = status_route(backend)
+ assert status.is_gguf is True
+ assert status.is_local_model is False
+
+
+def test_a_native_lease_load_reports_the_label_not_the_leased_path(status_route):
+ # The leased on-disk path is exactly what /status must not hand back.
+ leased = os.path.join(os.sep, "models", "private", "A-Q4_K_M.gguf")
+ status = status_route(_StatusBackend(leased, native_grant_backed = True))
+ assert status.model_identifier is None, "the leased path must not be published"
+ assert status.active_model == "A-Q4_K_M.gguf"
+ assert status.is_local_model is True
+
+
+def test_a_local_path_load_without_a_lease_is_still_local(status_route):
+ # is_local_model is provenance, not lease bookkeeping: a plain local path counts.
+ local = os.path.join(os.sep, "models", "local", "A-Q4_K_M.gguf")
+ status = status_route(_StatusBackend(local, native_grant_backed = False))
+ assert status.is_gguf is True
+ assert status.is_local_model is True
diff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.py
index a030959c280..3c48da7ac05 100644
--- a/studio/backend/tests/test_openai_auto_switch.py
+++ b/studio/backend/tests/test_openai_auto_switch.py
@@ -8,7 +8,9 @@ tests/test_gguf_completion_usage.py.
"""
import asyncio
+import json
import os
+import threading
import pytest
from fastapi import HTTPException
@@ -958,6 +960,7 @@ def test_count_tokens_is_tracked_as_inference_path():
assert _is_inference_path("/v1/messages/count_tokens") is True
assert _is_inference_path("/api/inference/messages/count_tokens") is True
+ assert _is_inference_path("/api/inference/chat/count_tokens") is True
assert _is_inference_path("/v1/messages") is True
@@ -3182,6 +3185,1035 @@ def test_count_tokens_forwards_vision_guard_to_switch(monkeypatch):
assert captured["require_vision"] is True
+# ── /chat/count_tokens: what the recount prices ───────────────────
+
+
+def _count_tokens_backend(
+ monkeypatch,
+ loaded_id = "org/A-GGUF",
+ count = 10,
+ *,
+ supports_tools = False,
+ reasoning_style = "enable_thinking",
+):
+ """A loaded GGUF backend wired into the count endpoint, as ``(switched, counted)``: auto-switch
+ attempts, and the messages/system/tools/template kwargs the route hands to the tokenizer."""
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ backend = _FakeBackend(loaded_id)
+ backend.supports_tools = supports_tools
+ # The real kwargs builder, so this pins the route against the completion path's mapping.
+ backend._supports_reasoning = True
+ backend._reasoning_always_on = False
+ backend._reasoning_style = reasoning_style
+ backend._reasoning_effort_levels = ["high", "max"]
+ backend._supports_preserve_thinking = True
+ backend._architecture = None
+ backend._request_reasoning_kwargs = LlamaCppBackend._request_reasoning_kwargs.__get__(
+ backend, type(backend)
+ )
+ switched: list = []
+ counted: dict = {}
+
+ def _count(
+ messages,
+ system,
+ tools,
+ strict = False,
+ chat_template_kwargs = None,
+ should_abort = None,
+ ):
+ counted.update(
+ messages = messages,
+ system = system,
+ tools = tools,
+ strict = strict,
+ chat_template_kwargs = chat_template_kwargs,
+ )
+ return count
+
+ async def _switch(*args, **kwargs):
+ switched.append(True)
+ return None
+
+ backend.count_chat_tokens = _count
+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: backend)
+ monkeypatch.setattr(inference_route, "_maybe_auto_switch_model", _switch)
+ return switched, counted
+
+
+def _count_request(
+ messages,
+ model = "org/A-GGUF",
+ **fields,
+):
+ """A /chat/count_tokens payload built from plain message dicts."""
+ from models.inference import ChatCountTokensRequest, ChatMessage
+ return ChatCountTokensRequest(
+ model = model,
+ messages = [ChatMessage(**message) for message in messages],
+ **fields,
+ )
+
+
+def _counted_body(payload):
+ """Run the count endpoint and return its decoded JSON body."""
+ response = asyncio.run(inference_route.chat_count_tokens(payload, "tester"))
+ return json.loads(response.body)
+
+
+ "content",
+ [
+ pytest.param("hello", id = "plain_string"),
+ # Control for the image guard below: a text-only parts array is unaffected.
+ pytest.param([{"type": "text", "text": "hello"}], id = "text_parts"),
+ ],
+)
+def test_chat_count_tokens_prices_the_loaded_model_without_switching(monkeypatch, content):
+ # The recount has no abort signal, so a stale payload naming A must not drag the backend back.
+ switched, _counted = _count_tokens_backend(monkeypatch, "org/B-GGUF", count = 42)
+ payload = _count_request([{"role": "user", "content": content}])
+ # The reply names B, the tokenizer that produced the total, not the A asked for.
+ assert _counted_body(payload) == {"input_tokens": 42, "model": "org/B-GGUF"}
+ assert switched == []
+
+
+def test_chat_count_tokens_forwards_enabled_tools(monkeypatch):
+ # Schemas and the nudge are a large share of the prompt: price the completion's own selection.
+ _switched, counted = _count_tokens_backend(monkeypatch, count = 99, supports_tools = True)
+ gate = {}
+
+ async def _select(payload, *, tools_on, mcp_allowed):
+ gate.update(tools_on = tools_on, mcp_allowed = mcp_allowed)
+ return [{"type": "function", "function": {"name": "web_search"}}]
+
+ monkeypatch.setattr(inference_route, "_select_request_tools", _select)
+ payload = _count_request(
+ [{"role": "user", "content": "hello"}],
+ enable_tools = True,
+ enabled_tools = ["web_search"],
+ )
+ assert _counted_body(payload) == {"input_tokens": 99, "model": "org/A-GGUF"}
+ assert gate.get("tools_on") is True
+ assert [t.get("function", {}).get("name") for t in counted.get("tools") or []] == ["web_search"]
+ assert any(
+ message.get("role") == "system" and "web_search" in str(message.get("content", ""))
+ for message in counted.get("messages") or []
+ )
+
+
+# A leaked tool call in a replayed turn, plus an example naming a NOT-enabled tool the gate keeps.
+_LEAKED_TOOL_HISTORY = [
+ {"role": "user", "content": "weather?"},
+ {
+ "role": "assistant",
+ "content": 'sunny <tool_call>{"name": "web_search", "arguments": {"q": "weather"}}'
+ "</tool_call> and call it as offline_tool[ARGS]{}",
+ },
+ {"role": "user", "content": "and tomorrow?"},
+]
+
+
+ ("fields", "expect_markup"),
+ [
+ # Auto-Heal on (default): the tool path strips before rendering, so raw markup reads high.
+ pytest.param({}, False, id = "auto_heal_default_on"),
+ pytest.param({"auto_heal_tool_calls": True}, False, id = "auto_heal_on"),
+ # Off leaves the markup in the real prompt, so the count has to keep it as well.
+ pytest.param({"auto_heal_tool_calls": False}, True, id = "auto_heal_off"),
+ ],
+)
+def test_chat_count_tokens_strips_replayed_tool_markup(monkeypatch, fields, expect_markup):
+ """The GGUF tool path strips stale tool-call XML out of replayed assistant turns before
+ rendering, so a count that keeps it prices text the completion removes."""
+ _switched, counted = _count_tokens_backend(monkeypatch, count = 99, supports_tools = True)
+
+ async def _select(_payload, *, tools_on, mcp_allowed):
+ return [{"type": "function", "function": {"name": "web_search"}}]
+
+ monkeypatch.setattr(inference_route, "_select_request_tools", _select)
+ payload = _count_request(
+ _LEAKED_TOOL_HISTORY,
+ enable_tools = True,
+ enabled_tools = ["web_search"],
+ **fields,
+ )
+ assert _counted_body(payload)["input_tokens"] == 99
+ assistant = [m for m in counted["messages"] if m.get("role") == "assistant"]
+ assert len(assistant) == 1
+ content = str(assistant[0].get("content", ""))
+ assert (
+ "<tool_call>" in content
+ ) is expect_markup, "the count must render the same replayed history the completion does"
+ assert (
+ "offline_tool[ARGS]" in content
+ ), "an inactive tool name is prose in the real prompt, so the count keeps it too"
+
+
+_PASSTHROUGH_CATALOG = [
+ {"type": "function", "function": {"name": "get_weather", "parameters": {"type": "object"}}}
+]
+_PASSTHROUGH_TOOL_HISTORY = [
+ {"role": "user", "content": "weather?"},
+ {
+ "role": "assistant",
+ "tool_calls": [
+ {"id": "c1", "type": "function", "function": {"name": "get_weather", "arguments": "{}"}}
+ ],
+ },
+ {"role": "tool", "tool_call_id": "c1", "content": "sunny"},
+]
+_PASSTHROUGH_PLAIN = [{"role": "user", "content": "hi"}]
+
+
+ ("cli_policy", "messages", "fields", "priced_tools"),
+ [
+ # The reported shape: `unsloth run --enable-tools` sets the process policy without asking
+ # for the tool loop, so tool history still goes to llama-server verbatim, bare.
+ pytest.param(
+ True,
+ _PASSTHROUGH_TOOL_HISTORY,
+ {},
+ None,
+ id = "cli_policy_does_not_price_a_passthrough_prompt",
+ ),
+ # Negative control: with no tool history the same policy takes the ordinary GGUF loop.
+ pytest.param(
+ True,
+ _PASSTHROUGH_PLAIN,
+ {},
+ ["web_search"],
+ id = "cli_policy_prices_an_ordinary_chat",
+ ),
+ # The passthrough is the one route that forwards the caller's own catalog.
+ pytest.param(
+ None,
+ _PASSTHROUGH_PLAIN,
+ {"tools": _PASSTHROUGH_CATALOG},
+ ["get_weather"],
+ id = "client_catalog_is_priced_verbatim",
+ ),
+ # tool_choice "none" withdraws the catalog, leaving the request on the ordinary path.
+ pytest.param(
+ None,
+ _PASSTHROUGH_PLAIN,
+ {"tools": _PASSTHROUGH_CATALOG, "tool_choice": "none"},
+ None,
+ id = "withdrawn_catalog_is_not_priced",
+ ),
+ # ... unless tool history needs those schemas to replay, keeping it on the passthrough.
+ pytest.param(
+ None,
+ _PASSTHROUGH_TOOL_HISTORY,
+ {"tools": _PASSTHROUGH_CATALOG, "tool_choice": "none"},
+ ["get_weather"],
+ id = "withdrawn_catalog_with_tool_history_is_priced",
+ ),
+ # It withdraws the process policy's own catalog too, as _client_disabled_tool_calls does.
+ pytest.param(
+ True,
+ _PASSTHROUGH_PLAIN,
+ {"tool_choice": "none"},
+ None,
+ id = "withdrawn_catalog_beats_the_cli_policy",
+ ),
+ ],
+)
+def test_chat_count_tokens_prices_the_route_the_completion_takes(
+ monkeypatch, cli_policy, messages, fields, priced_tools
+):
+ """The count must describe the request the completion actually sends (#7453).
+
+ Applying the process tool policy without first asking which route the request takes prices a
+ built-in catalog plus the action nudge, while the completion forwards verbatim and sends neither.
+ """
+ import state.tool_policy as _tp
+
+ _switched, counted = _count_tokens_backend(monkeypatch, count = 99, supports_tools = True)
+
+ async def _select(payload, *, tools_on, mcp_allowed):
+ return [{"type": "function", "function": {"name": "web_search"}}]
+
+ monkeypatch.setattr(inference_route, "_select_request_tools", _select)
+ monkeypatch.setattr(_tp, "get_tool_policy", lambda: cli_policy)
+
+ assert _counted_body(_count_request(messages, **fields))["input_tokens"] == 99
+ assert [(tool.get("function") or {}).get("name") for tool in counted.get("tools") or []] == (
+ priced_tools or []
+ )
+ # The nudge rides with the built-in selection, so it must follow the same verdict.
+ nudged = any(
+ message.get("role") == "system" and "web_search" in str(message.get("content", ""))
+ for message in counted.get("messages") or []
+ )
+ assert nudged is (priced_tools == ["web_search"])
+
+
+def test_chat_count_tokens_keeps_adjacent_user_turns_on_the_passthrough(monkeypatch):
+ """Coalescing is an ordinary-GGUF-path step, so it has to follow the routing.
+
+ ``_openai_messages_for_passthrough`` drops the empty assistant sentinel but keeps the two user
+ turns around it (a stopped response's shape), so merging prices a prompt that route never sends.
+ """
+ _switched, counted = _count_tokens_backend(monkeypatch, count = 99, supports_tools = True)
+ sentinel_thread = [
+ {"role": "user", "content": "first"},
+ {"role": "assistant", "content": ""},
+ {"role": "user", "content": "second"},
+ ]
+
+ _counted_body(_count_request(sentinel_thread, tools = _PASSTHROUGH_CATALOG))
+ assert [message.get("content") for message in counted.get("messages") or []] == [
+ "first",
+ "second",
+ ]
+
+ # Negative control: off the passthrough the same thread merges, so no two user turns in a row.
+ _counted_body(_count_request(sentinel_thread))
+ assert [message.get("content") for message in counted.get("messages") or []] == [
+ "first\n\nsecond"
+ ]
+
+
+def _in_flight_generation():
+ """One registered generation, as the completion path registers it."""
+ from state import active_generations
+ return active_generations.ActiveGeneration(threading.Event(), thread_id = "t1")
+
+
+def test_chat_count_tokens_refuses_while_a_generation_is_in_flight(monkeypatch):
+ # The whole point of the endpoint's cost budget: a count must never share llama-server with a
+ # decode. The frontend gate only covers our own tab, so the refusal has to live here too.
+ switched, counted = _count_tokens_backend(monkeypatch, count = 1234)
+ # Reached only after the tool selection and message rewriting, so it doubles as proof that the
+ # refusal happens on entry rather than after the handler has already done that work.
+ reached: list = []
+ real = inference_route._llama_status_checkpoint_id
+ monkeypatch.setattr(
+ inference_route,
+ "_llama_status_checkpoint_id",
+ lambda backend: (reached.append(1), real(backend))[1],
+ )
+ payload = _count_request([{"role": "user", "content": "hello"}])
+ with _in_flight_generation():
+ with pytest.raises(HTTPException) as excinfo:
+ asyncio.run(inference_route.chat_count_tokens(payload, "tester"))
+ assert excinfo.value.status_code == 503
+ assert "generation" in str(excinfo.value.detail).lower()
+ assert reached == [], "the handler must decline before doing any of the count's work"
+ assert counted == {}, "the tokenizer must not be reached"
+ assert switched == [], "and neither must the auto-switch hook"
+
+
+def test_chat_count_tokens_counts_again_once_the_generation_ends(monkeypatch):
+ # Control: the refusal keys on a live generation, not on the request, and it does not latch.
+ _switched, counted = _count_tokens_backend(monkeypatch, count = 1234)
+ payload = _count_request([{"role": "user", "content": "hello"}])
+ with _in_flight_generation():
+ with pytest.raises(HTTPException):
+ asyncio.run(inference_route.chat_count_tokens(payload, "tester"))
+ body = _counted_body(payload)
+ assert body["input_tokens"] == 1234
+ assert counted != {}, "the tokenizer must be reached once nothing is decoding"
+
+
+def test_chat_count_tokens_refuses_a_generation_that_starts_mid_count(monkeypatch):
+ # Everything between the entry guard and the tokenizer awaits, so a run can begin in the gap.
+ # _llama_status_checkpoint_id is the last call before the second guard: start a generation
+ # from inside it and the count must abandon rather than proceed with what it already built.
+ _switched, counted = _count_tokens_backend(monkeypatch, count = 1234)
+ started: list = []
+ real = inference_route._llama_status_checkpoint_id
+
+ def _start_a_run(backend):
+ if not started:
+ handle = _in_flight_generation()
+ handle.__enter__()
+ started.append(handle)
+ return real(backend)
+
+ monkeypatch.setattr(inference_route, "_llama_status_checkpoint_id", _start_a_run)
+ payload = _count_request([{"role": "user", "content": "hello"}])
+ try:
+ with pytest.raises(HTTPException) as excinfo:
+ asyncio.run(inference_route.chat_count_tokens(payload, "tester"))
+ finally:
+ for handle in started:
+ handle.__exit__(None, None, None)
+ assert started, "the hook must have fired, or the test proves nothing"
+ assert excinfo.value.status_code == 503
+ assert "generation" in str(excinfo.value.detail).lower()
+ assert counted == {}, "the tokenizer must not be reached"
+
+
+def _enabled_mcp_server(
+ tmp_path,
+ monkeypatch,
+ *,
+ cached = None,
+ cooloff = False,
+):
+ """One enabled MCP server, with its discovery cache in a known state.
+
+ Both cache dicts are module globals shared across the whole test session, so they are
+ replaced rather than mutated: a leftover entry would make an "undiscovered" case look
+ discovered and quietly pass.
+ """
+ from core.inference import mcp_client
+ from core.inference import tools as tools_mod
+ from storage import mcp_servers_db
+
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
+ monkeypatch.setattr(mcp_servers_db, "_schema_ready", False)
+ monkeypatch.setattr(tools_mod, "stdio_mcp_enabled", lambda: True)
+ monkeypatch.setattr(mcp_client, "_tool_cache", {})
+ monkeypatch.setattr(mcp_client, "_probe_cooloff_until", {})
+ mcp_servers_db.create_server(
+ id = "s1", display_name = "S", url = "http://mcp.test/sse", is_enabled = True
+ )
+ if cached is not None:
+ mcp_client.cache_tools("s1", cached)
+ if cooloff:
+ mcp_client.record_probe_failure("s1")
+
+ # Any probe at all is a failure of the whole design: a count must not reach the network.
+ async def _no_probes(**_kwargs):
+ raise AssertionError("a count must never probe an MCP server")
+
+ monkeypatch.setattr(tools_mod, "list_tools_async", _no_probes)
+
+
+MCP_TOOL_PAYLOAD = [{"name": "lookup", "description": "d", "inputSchema": {"type": "object"}}]
+
+
+def test_cached_mcp_tools_reads_the_cache_without_probing(tmp_path, monkeypatch):
+ from core.inference.tools import cached_mcp_tools
+
+ _enabled_mcp_server(tmp_path, monkeypatch, cached = MCP_TOOL_PAYLOAD)
+ specs, complete = cached_mcp_tools()
+ assert complete is True
+ assert [spec["function"]["name"] for spec in specs] == ["mcp__s1__lookup"]
+
+
+def test_cached_mcp_tools_reports_an_undiscovered_server_as_incomplete(tmp_path, monkeypatch):
+ from core.inference.tools import cached_mcp_tools
+
+ _enabled_mcp_server(tmp_path, monkeypatch)
+ specs, complete = cached_mcp_tools()
+ assert specs == []
+ assert complete is False, (
+ "a completion would probe this server and render its schemas, so a count that skips "
+ "them is short, not exact"
+ )
+
+
+def test_cached_mcp_tools_counts_a_cooloff_server_as_complete(tmp_path, monkeypatch):
+ # The completion renders nothing for a cool-off server either, so skipping it is exact rather
+ # than short. Declining here would blank the bar over an agreement.
+ from core.inference.tools import cached_mcp_tools
+
+ _enabled_mcp_server(tmp_path, monkeypatch, cooloff = True)
+ specs, complete = cached_mcp_tools()
+ assert specs == []
+ assert complete is True
+
+
+def test_chat_count_tokens_declines_an_undiscovered_mcp_server(tmp_path, monkeypatch):
+ # Undercounting is the dangerous direction: it tells the user room exists that the next
+ # request will not find. Discovery is not an option on this path, so decline instead.
+ _switched, counted = _count_tokens_backend(monkeypatch, count = 1234, supports_tools = True)
+ _enabled_mcp_server(tmp_path, monkeypatch)
+ payload = _count_request([{"role": "user", "content": "hello"}], mcp_enabled = True)
+ with pytest.raises(HTTPException) as excinfo:
+ asyncio.run(inference_route.chat_count_tokens(payload, "tester"))
+ assert excinfo.value.status_code == 503
+ assert "mcp" in str(excinfo.value.detail).lower()
+ assert counted == {}, "the tokenizer must not be reached with a short tool list"
+
+
+def test_chat_count_tokens_prices_cached_mcp_schemas(tmp_path, monkeypatch):
+ # MCP alone turns tools on for the completion, so the count has to render them even with the
+ # built-in tools off, or the bar is short by a whole catalog.
+ _switched, counted = _count_tokens_backend(monkeypatch, count = 1234, supports_tools = True)
+ _enabled_mcp_server(tmp_path, monkeypatch, cached = MCP_TOOL_PAYLOAD)
+ payload = _count_request(
+ [{"role": "user", "content": "hello"}], mcp_enabled = True, enabled_tools = []
+ )
+ body = _counted_body(payload)
+ assert body["input_tokens"] == 1234
+ names = [tool["function"]["name"] for tool in (counted.get("tools") or [])]
+ assert (
+ "mcp__s1__lookup" in names
+ ), "a cached MCP schema is in the completion's prompt, so it must be in the count"
+
+
+def test_chat_count_tokens_ignores_an_mcp_server_the_request_did_not_enable(tmp_path, monkeypatch):
+ # Control: the decline keys on the request asking for MCP, not on a server merely existing.
+ # tool_choice "none" would NOT be a control here: _explicit_studio_tool_loop_requested treats
+ # mcp_enabled as an explicit ask, so the completion still renders the catalog.
+ _switched, counted = _count_tokens_backend(monkeypatch, count = 1234, supports_tools = True)
+ _enabled_mcp_server(tmp_path, monkeypatch)
+ body = _counted_body(_count_request([{"role": "user", "content": "hello"}]))
+ assert body["input_tokens"] == 1234
+ assert counted != {}, "the tokenizer must still be reached"
+
+
+def test_a_count_admitted_while_idle_stands_down_if_a_run_starts(monkeypatch):
+ """Admission and the work are separate steps. A run that registers in between cannot be
+ prevented without a lock in front of generation startup, so the count abandons at the
+ checkpoint between /apply-template and /tokenize instead of spending the second trip."""
+ _switched, counted = _count_tokens_backend(monkeypatch, count = 1234)
+ payload = _count_request([{"role": "user", "content": "hello"}])
+ started: list = []
+
+ def _count(
+ messages,
+ system,
+ tools,
+ strict = False,
+ chat_template_kwargs = None,
+ should_abort = None,
+ ):
+ # Stand in for /apply-template returning: the run lands, then the checkpoint is polled.
+ handle = _in_flight_generation()
+ handle.__enter__()
+ started.append(handle)
+ assert should_abort is not None, "the route must give the tokenizer a way to stand down"
+ if should_abort():
+ from core.inference.llama_cpp import CountAborted
+ raise CountAborted()
+ counted.update(messages = messages)
+ return 1234
+
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ backend = inference_route.get_llama_cpp_backend()
+ monkeypatch.setattr(backend, "count_chat_tokens", _count)
+ assert LlamaCppBackend is not None
+ try:
+ with pytest.raises(HTTPException) as excinfo:
+ asyncio.run(inference_route.chat_count_tokens(payload, "tester"))
+ finally:
+ for handle in started:
+ handle.__exit__(None, None, None)
+ assert started, "the hook must have fired, or the test proves nothing"
+ assert excinfo.value.status_code == 503
+ assert "generation" in str(excinfo.value.detail).lower()
+ assert counted == {}, "the second round trip must not happen"
+
+
+def test_a_count_that_stays_idle_is_not_aborted(monkeypatch):
+ # Control: the checkpoint fires on a live run, not on every count.
+ _switched, counted = _count_tokens_backend(monkeypatch, count = 1234)
+ seen: list = []
+
+ def _count(
+ messages,
+ system,
+ tools,
+ strict = False,
+ chat_template_kwargs = None,
+ should_abort = None,
+ ):
+ seen.append(should_abort() if should_abort else None)
+ counted.update(messages = messages)
+ return 1234
+
+ backend = inference_route.get_llama_cpp_backend()
+ monkeypatch.setattr(backend, "count_chat_tokens", _count)
+ body = _counted_body(_count_request([{"role": "user", "content": "hello"}]))
+ assert body["input_tokens"] == 1234
+ assert seen == [False], "an idle server must report nothing to stand down for"
+
+
+ ("abort", "expect_tokenize"),
+ [(True, False), (False, True)],
+ ids = ["run_started", "still_idle"],
+)
+def test_count_chat_tokens_stands_down_before_tokenizing(monkeypatch, abort, expect_tokenize):
+ """The abort has to escape the template except-block. Swallowed, it would set
+ apply_template_failed and the text fallback would tokenize anyway, which is the work
+ being declined. The control shows the poll alone does not stop an idle count."""
+ from core.inference import llama_cpp as llama_cpp_mod
+ from core.inference.llama_cpp import CountAborted, LlamaCppBackend
+
+ posted: list = []
+
+ class _FakeResponse:
+ status_code = 200
+
+ def __init__(self, payload):
+ self._payload = payload
+
+ def json(self):
+ return self._payload
+
+ class _FakeClient:
+ def __init__(self, **_kwargs):
+ pass
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_exc):
+ return False
+
+ def post(
+ self,
+ url,
+ json = None,
+ ):
+ posted.append(url)
+ if url.endswith("/apply-template"):
+ return _FakeResponse({"prompt": "user hi"})
+ return _FakeResponse({"tokens": [1, 2]})
+
+ class _CountBackend(LlamaCppBackend):
+ is_loaded = True
+ base_url = "http://127.0.0.1:1"
+ _auth_headers = None
+
+ def __init__(self):
+ pass
+
+ monkeypatch.setattr(llama_cpp_mod.httpx, "Client", _FakeClient)
+ call = lambda: _CountBackend().count_chat_tokens(
+ [{"role": "user", "content": "hi"}],
+ strict = True,
+ should_abort = lambda: abort,
+ )
+ if abort:
+ with pytest.raises(CountAborted):
+ call()
+ else:
+ assert call() == 2
+ assert any(u.endswith("/tokenize") for u in posted) is expect_tokenize
+
+
+def test_chat_count_tokens_refuses_image_messages(monkeypatch):
+ # Images become a short /apply-template marker: refuse rather than undercount, before the switch.
+ switched, counted = _count_tokens_backend(monkeypatch, count = 1234)
+ payload = _count_request(
+ [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "what is this"},
+ {
+ "type": "image_url",
+ "image_url": {"url": "data:image/png;base64,iVBORw0KGgo="},
+ },
+ ],
+ }
+ ]
+ )
+ with pytest.raises(HTTPException) as excinfo:
+ asyncio.run(inference_route.chat_count_tokens(payload, "tester"))
+ assert excinfo.value.status_code == 503
+ assert counted == {}, "the tokenizer must not be reached"
+ assert switched == [], "and neither must the auto-switch hook"
+
+
+def test_chat_count_tokens_refuses_audio_messages(monkeypatch):
+ # extra = "allow", so without this guard audio_base64 is accepted, dropped and undercounted.
+ switched, counted = _count_tokens_backend(monkeypatch, count = 1234)
+ payload = _count_request(
+ [{"role": "user", "content": "what did I just say"}],
+ audio_base64 = "UklGRiQAAABXQVZF",
+ )
+ with pytest.raises(HTTPException) as excinfo:
+ asyncio.run(inference_route.chat_count_tokens(payload, "tester"))
+ assert excinfo.value.status_code == 503
+ assert "audio" in str(excinfo.value.detail).lower()
+ assert counted == {}, "the tokenizer must not be reached"
+ assert switched == [], "and neither must the auto-switch hook"
+
+
+def test_chat_count_tokens_still_counts_without_audio(monkeypatch):
+ # Control: the refusal keys on the audio, not on the shape of the request.
+ _switched, counted = _count_tokens_backend(monkeypatch, count = 1234)
+ body = _counted_body(_count_request([{"role": "user", "content": "what did I just say"}]))
+ assert body["input_tokens"] == 1234
+ assert counted != {}, "the tokenizer must be reached"
+
+
+# Shapes the recount sends for a thread with documents in scope. Only a PENDING turn is answered
+# from these exact messages, and the tool loop opens it by splicing in what RAG retrieves.
+_PENDING_USER_TURN = [{"role": "user", "content": "what does the contract say"}]
+_PENDING_TOOL_TURN = [
+ {"role": "user", "content": "what does the contract say"},
+ {"role": "assistant", "content": "checking"},
+ {"role": "tool", "content": "{}", "tool_call_id": "call_1"},
+]
+_SETTLED_TURN = [
+ {"role": "user", "content": "what does the contract say"},
+ {"role": "assistant", "content": "it renews yearly"},
+]
+
+
+ ("messages", "rag_scope", "expected_total"),
+ [
+ # Retrieval splices passages in front of this turn, so counting alone says it fits.
+ pytest.param(_PENDING_USER_TURN, {"thread_id": "t1"}, None, id = "pending_user_turn"),
+ # An interrupted loop's unanswered tool result is the same pending shape.
+ pytest.param(_PENDING_TOOL_TURN, {"project_id": "p1"}, None, id = "pending_tool_turn"),
+ # Ends on an assistant turn: retrieval has no user message yet, so nothing is omitted.
+ pytest.param(_SETTLED_TURN, {"thread_id": "t1"}, 4242, id = "settled_turn_still_counts"),
+ # No documents in scope means no injection to miss, pending turn or not.
+ pytest.param(_PENDING_USER_TURN, None, 4242, id = "no_rag_scope_still_counts"),
+ ],
+)
+def test_chat_count_tokens_declines_a_pending_turn_that_would_retrieve(
+ monkeypatch, messages, rag_scope, expected_total
+):
+ """A recount that omits RAG injection under-reports, the one direction the context bar must
+ never be wrong in. Decline as the image case does and leave the usage the bar already had."""
+ _switched, counted = _count_tokens_backend(monkeypatch, count = 4242)
+ payload = _count_request(
+ messages,
+ **({"rag_scope": rag_scope} if rag_scope else {}),
+ )
+ try:
+ total = _counted_body(payload).get("input_tokens")
+ except HTTPException as exc:
+ if exc.status_code != 503:
+ raise
+ total = None
+
+ assert total == expected_total, (
+ "a pending turn whose generation would retrieve documents must be declined, "
+ "not priced without them"
+ )
+ if expected_total is None:
+ assert counted == {}, "the tokenizer must not be reached for a declined count"
+
+
+def test_chat_count_tokens_declines_when_the_model_changes_mid_count(monkeypatch):
+ """A load landing while the tokenizer runs leaves a total attributable to neither model, and
+ the caller's checkpoint guard never moved, so either identity would have it trust the number."""
+ _switched, counted = _count_tokens_backend(monkeypatch, "org/A-GGUF", count = 555)
+ backend = inference_route.get_llama_cpp_backend()
+ inner = backend.count_chat_tokens
+
+ def _count_then_swap(*args, **kwargs):
+ result = inner(*args, **kwargs)
+ # Another tab finishes loading B while this count is in the worker thread.
+ backend.model_identifier = "org/B-GGUF"
+ return result
+
+ backend.count_chat_tokens = _count_then_swap
+ payload = _count_request([{"role": "user", "content": "hello"}])
+ try:
+ total = _counted_body(payload).get("input_tokens")
+ except HTTPException as exc:
+ if exc.status_code != 503:
+ raise
+ total = None
+
+ assert (
+ total is None
+ ), "a total counted across a model change must not be published as either model's"
+ assert counted.get("messages"), "the tokenizer still ran; only its result is dropped"
+
+
+def test_chat_count_tokens_collapses_system_turns(monkeypatch):
+ # The completion path joins every system/developer turn into one; the count renders that.
+ _switched, counted = _count_tokens_backend(monkeypatch, count = 13)
+ payload = _count_request(
+ [
+ {"role": "system", "content": "Runtime rules."},
+ {"role": "system", "content": "Studio prompt."},
+ {"role": "user", "content": "hello"},
+ ]
+ )
+ asyncio.run(inference_route.chat_count_tokens(payload, "tester"))
+ messages = counted.get("messages") or []
+ systems = [m for m in messages if m.get("role") in ("system", "developer")]
+ assert len(systems) == 1, messages
+ assert "Runtime rules." in systems[0].get("content", "")
+ assert "Studio prompt." in systems[0].get("content", "")
+
+
+ ("reasoning_style", "fields", "expected"),
+ [
+ # Qwen3-style gate: with Thinking off the completion sends enable_thinking=false and the
+ # template prefills an empty <think> block; without it, the LOADED mode renders.
+ pytest.param(
+ "enable_thinking",
+ {"enable_thinking": False},
+ {"enable_thinking": False},
+ id = "thinking_turned_off",
+ ),
+ # gpt-oss-style: the effort level is rendered into the system turn.
+ pytest.param(
+ "reasoning_effort",
+ {"reasoning_effort": "low"},
+ {"reasoning_effort": "low"},
+ id = "effort_level",
+ ),
+ # preserve_thinking decides whether past <think> blocks stay: a short count or the history.
+ pytest.param(
+ "enable_thinking",
+ {"enable_thinking": True, "preserve_thinking": True},
+ {"enable_thinking": True, "preserve_thinking": True},
+ id = "preserve_thinking",
+ ),
+ # Nothing selected: send nothing, so llama-server keeps its load-time defaults.
+ pytest.param("enable_thinking", {}, None, id = "template_default"),
+ ],
+)
+def test_chat_count_tokens_renders_the_requested_reasoning_mode(
+ monkeypatch, reasoning_style, fields, expected
+):
+ # llama-server layers request kwargs over the load-time ones: omitting them prices LOAD mode.
+ _switched, counted = _count_tokens_backend(
+ monkeypatch, count = 7, reasoning_style = reasoning_style
+ )
+ payload = _count_request([{"role": "user", "content": "hello"}], **fields)
+ assert _counted_body(payload) == {"input_tokens": 7, "model": "org/A-GGUF"}
+ assert counted.get("chat_template_kwargs") == expected
+
+
+ ("template_kwargs", "expected_tokens"),
+ [
+ # Thinking off: the template prefills an empty <think></think> pair the completion pays for.
+ pytest.param({"enable_thinking": False}, 5, id = "thinking_off"),
+ pytest.param(None, 3, id = "template_default"),
+ ],
+)
+def test_count_chat_tokens_renders_with_the_requested_template_kwargs(
+ monkeypatch, template_kwargs, expected_tokens
+):
+ """The kwargs have to reach llama-server itself: /apply-template runs the same parser
+ as /v1/chat/completions, so the rendered prompt only moves when they are in the body."""
+ from core.inference import llama_cpp as llama_cpp_mod
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ class _FakeResponse:
+ status_code = 200
+
+ def __init__(self, payload):
+ self._payload = payload
+
+ def json(self):
+ return self._payload
+
+ class _FakeClient:
+ def __init__(self, **_kwargs):
+ pass
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_exc):
+ return False
+
+ def post(
+ self,
+ url,
+ json = None,
+ ):
+ body = json or {}
+ if not url.endswith("/apply-template"):
+ return _FakeResponse({"tokens": str(body.get("content", "")).split()})
+ # A Qwen3-style template: thinking off prefills an empty reasoning block.
+ kwargs = body.get("chat_template_kwargs") or {}
+ prefill = "" if kwargs.get("enable_thinking", True) else " <think> </think>"
+ return _FakeResponse({"prompt": "user hi assistant" + prefill})
+
+ class _CountBackend(LlamaCppBackend):
+ is_loaded = True
+ base_url = "http://127.0.0.1:1"
+ _auth_headers = None
+
+ def __init__(self):
+ pass
+
+ monkeypatch.setattr(llama_cpp_mod.httpx, "Client", _FakeClient)
+ assert (
+ _CountBackend().count_chat_tokens(
+ [{"role": "user", "content": "hi"}],
+ strict = True,
+ chat_template_kwargs = template_kwargs,
+ )
+ == expected_tokens
+ )
+
+
+ "failure",
+ [
+ # A minja template that cannot render this history, or a build without the endpoint.
+ pytest.param("status", id = "apply_template_rejects"),
+ # The template call times out while the tokenizer answers.
+ pytest.param("raise", id = "apply_template_unreachable"),
+ ],
+)
+def test_strict_count_refuses_a_text_only_template_fallback(monkeypatch, failure):
+ """/apply-template failing on a TEXT-ONLY prompt used to fall through to concatenating message
+ text, dropping every role marker, special token and tool schema (~30% of a six-turn two-tool
+ prompt). Strict callers publish what they get, so it must be an error, not an estimate."""
+ from core.inference import llama_cpp as llama_cpp_mod
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ class _FakeResponse:
+ def __init__(
+ self,
+ payload,
+ status_code = 200,
+ ):
+ self._payload = payload
+ self.status_code = status_code
+
+ def json(self):
+ return self._payload
+
+ class _FakeClient:
+ def __init__(self, **_kwargs):
+ pass
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_exc):
+ return False
+
+ def post(
+ self,
+ url,
+ json = None,
+ ):
+ body = json or {}
+ if url.endswith("/apply-template"):
+ if failure == "raise":
+ raise RuntimeError("timed out")
+ return _FakeResponse({"error": "template error"}, status_code = 500)
+ return _FakeResponse({"tokens": str(body.get("content", "")).split()})
+
+ class _CountBackend(LlamaCppBackend):
+ is_loaded = True
+ base_url = "http://127.0.0.1:1"
+ _auth_headers = None
+
+ def __init__(self):
+ pass
+
+ monkeypatch.setattr(llama_cpp_mod.httpx, "Client", _FakeClient)
+ messages = [{"role": "user", "content": "hi there"}]
+ tools = [{"type": "function", "function": {"name": "web_search"}}]
+ with pytest.raises(RuntimeError):
+ _CountBackend().count_chat_tokens(messages, None, tools, strict = True)
+ # Non-strict callers keep the best-effort approximation they have always had.
+ assert _CountBackend().count_chat_tokens(messages, None, tools) > 0
+
+
+def test_an_empty_chat_sends_the_empty_list_unchanged(monkeypatch):
+ """A fresh New Chat has no messages and, by default, no system prompt. The count must
+ forward that empty list as-is rather than inventing a turn to make the template happy.
+
+ Templates that index ``messages[0]`` look like they must reject an empty list, and under
+ python jinja2 they do. llama-server renders through minja, where that yields undefined
+ instead of raising, so the real engine returns the bare preamble. Checked against the
+ shipped templates for Llama-3.2-1B-Instruct, Qwen3-8B, Phi-4, gemma-3-270m-it and
+ mistral-7b-instruct-v0.3 driven through llama-server with --jinja: all five render.
+ Injecting a placeholder system turn would add a system block to the count for Qwen3
+ (+30 chars) and Phi-4 (+38), overcounting the empty chat the bar exists to show."""
+ from core.inference import llama_cpp as llama_cpp_mod
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ seen = {}
+
+ class _FakeResponse:
+ def __init__(
+ self,
+ payload,
+ status_code = 200,
+ ):
+ self._payload = payload
+ self.status_code = status_code
+
+ def json(self):
+ return self._payload
+
+ class _FakeClient:
+ def __init__(self, **_kwargs):
+ pass
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_exc):
+ return False
+
+ def post(
+ self,
+ url,
+ json = None,
+ ):
+ body = json or {}
+ if url.endswith("/apply-template"):
+ seen["messages"] = body.get("messages")
+ # What minja does: no messages renders the preamble, it does not raise.
+ return _FakeResponse({"prompt": "<start_of_turn>model\n"})
+ return _FakeResponse({"tokens": str(body.get("content", "")).split()})
+
+ class _CountBackend(LlamaCppBackend):
+ is_loaded = True
+ base_url = "http://127.0.0.1:1"
+ _auth_headers = None
+
+ def __init__(self):
+ pass
+
+ monkeypatch.setattr(llama_cpp_mod.httpx, "Client", _FakeClient)
+ count = _CountBackend().count_chat_tokens([], None, None, strict = True)
+ assert seen["messages"] == [], "the count must not invent a turn the caller never sent"
+ assert count > 0, "a fresh chat still prices the template preamble"
+
+
+def test_a_count_never_spawns_mcp_servers():
+ """get_enabled_mcp_tools starts stdio MCP server processes, writes cache and cooloff state,
+ and blocks for a whole probe timeout against a server that is down. A background recount
+ must not do host work the user's completion never asked for, so the count path pins
+ mcp_allowed False rather than deriving it from payload.mcp_enabled."""
+ import ast
+ import pathlib
+
+ src = pathlib.Path(__file__).resolve().parents[1] / "routes" / "inference.py"
+ tree = ast.parse(src.read_text(encoding = "utf-8"))
+ handler = next(
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.AsyncFunctionDef) and node.name == "chat_count_tokens"
+ )
+
+ # The only assignment to _mcp_allowed in the handler must be the constant False.
+ assigned = [
+ node.value
+ for node in ast.walk(handler)
+ if isinstance(node, ast.Assign)
+ and any(isinstance(t, ast.Name) and t.id == "_mcp_allowed" for t in node.targets)
+ ]
+ assert assigned, "the count handler no longer pins _mcp_allowed; this test is stale"
+ assert all(
+ isinstance(v, ast.Constant) and v.value is False for v in assigned
+ ), "a count must never enable MCP discovery"
+
+ called = {
+ node.func.id
+ for node in ast.walk(handler)
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
+ }
+ assert "get_enabled_mcp_tools" not in called
+
+
def test_audio_generate_is_reload_only(monkeypatch):
# Codex P2: /audio/generate must not switch to a client-named GGUF. A local
# GGUF's audio-input capability is not a cheap pre-load probe (the mmproj signal
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 1b09176032b..e1d6ece5f12 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -1231,6 +1231,28 @@ function extractAudioPartBase64(
}
// Exported for tests.
+// Whether any message carries an image, by the rule collectImageParts pushes one. A predicate,
+// not that helper: building the parts would copy the base64 this exists to avoid touching.
+export function messagesContainImage(messages: RunMessages): boolean {
+ const isImage = (part: { type: string }) =>
+ part.type === "image" &&
+ "image" in part &&
+ Boolean((part as { image: string }).image);
+ for (const message of messages) {
+ for (const part of message.content ?? []) {
+ if (isImage(part)) return true;
+ }
+ if ("attachments" in message) {
+ for (const attachment of message.attachments ?? []) {
+ for (const part of attachment.content ?? []) {
+ if (isImage(part)) return true;
+ }
+ }
+ }
+ }
+ return false;
+}
+
export function findLatestUserAudioBase64(
messages: RunMessages,
): string | undefined {
@@ -1267,6 +1289,197 @@ export function findLatestUserAudioBase64(
return pendingAudio ?? undefined;
}
+// The Canvas instructions createOpenAIStreamAdapter appends, named so the recount prices the same
+// text the request carries.
+export const CANVAS_TOOL_INSTRUCTION =
+ "When the user asks for an HTML, CSS, or JavaScript canvas, call render_html once with one complete self-contained HTML document in the code argument. Embed CSS and JavaScript inside the document. After render_html succeeds, do not call it again in the same response unless the user asks for changes. Future user requests for new canvases may call render_html once.";
+export const CANVAS_FALLBACK_INSTRUCTION =
+ "When the user asks for an HTML, CSS, or JavaScript canvas, return one complete self-contained fenced html code block. Embed CSS and JavaScript inside the document. Do not emit tool-call syntax.";
+
+/**
+ * The OpenAI-form messages a completion would send. Mirrors the prune + system-prompt half of
+ * createOpenAIStreamAdapter; the tool catalog is priced server-side instead, since --enable-tools
+ * can inject schemas the client cannot see.
+ */
+export async function buildOutboundMessagesForTokenCount(
+ messages: RunMessages,
+ threadId: string | undefined,
+): Promise<OpenAIChatMessage[]> {
+ const survivingMessages: RunMessage[] = [];
+ for (const message of messages) {
+ if (isAnthropicRefusalMessage(message)) {
+ const last = survivingMessages.at(-1);
+ if (last && last.role === "user") survivingMessages.pop();
+ continue;
+ }
+ survivingMessages.push(message);
+ }
+
+ const outboundMessages = survivingMessages
+ .flatMap(toOpenAIMessages)
+ .filter((message): message is NonNullable<typeof message> =>
+ Boolean(message),
+ );
+
+ const { params, artifactsEnabled, supportsTools } =
+ useChatRuntimeStore.getState();
+ const safeSystemPrompt =
+ typeof params.systemPrompt === "string"
+ ? resolveSystemPromptVariables(
+ params.systemPrompt,
+ typeof params.systemVariables === "string"
+ ? params.systemVariables
+ : "",
+ )
+ : "";
+ const projectInstructions = await resolveProjectInstructions(threadId);
+ const combinedSystemPrompt = [
+ projectInstructions
+ ? `<project_instructions>\n${projectInstructions}\n</project_instructions>`
+ : "",
+ safeSystemPrompt.trim(),
+ ]
+ .filter(Boolean)
+ .join("\n\n");
+ if (combinedSystemPrompt) {
+ outboundMessages.unshift({
+ role: "system",
+ content: combinedSystemPrompt,
+ });
+ }
+
+ // Canvas appends one of these on every request, schema or not, so a count without it reads low.
+ // The adapter's image gate is never why render_html is off here: the count route refuses images.
+ const canvasInstruction = artifactsEnabled
+ ? supportsTools
+ ? CANVAS_TOOL_INSTRUCTION
+ : CANVAS_FALLBACK_INSTRUCTION
+ : "";
+ if (canvasInstruction) {
+ const first = outboundMessages[0];
+ if (first && first.role === "system" && typeof first.content === "string") {
+ outboundMessages[0] = {
+ ...first,
+ content: `${first.content}\n\n${canvasInstruction}`,
+ };
+ } else {
+ outboundMessages.unshift({ role: "system", content: canvasInstruction });
+ }
+ }
+
+ return outboundMessages as OpenAIChatMessage[];
+}
+
+/**
+ * The reasoning fields a completion would send. llama-server falls back to the load-time
+ * `--chat-template-kwargs` only for keys a request omits, so a count sending none renders the
+ * template in whatever mode the model was LOADED in and misreports any prefilled thinking block.
+ */
+export function buildLocalTokenCountReasoning(): Record<string, unknown> {
+ const {
+ supportsReasoning,
+ reasoningStyle,
+ reasoningEnabled,
+ reasoningEffort,
+ reasoningEffortLevels,
+ supportsPreserveThinking,
+ preserveThinking,
+ } = useChatRuntimeStore.getState();
+ // Same clamp the request build applies: a level the loaded template does not offer would be
+ // dropped by the backend and counted against the template default.
+ const localReasoningEffort = clampReasoningEffortToLevels(
+ reasoningEffort,
+ reasoningEffortLevels,
+ );
+ return {
+ // enable_thinking, not the Anthropic-style `thinking` block: the backend normalizes it anyway.
+ ...(supportsReasoning
+ ? reasoningStyle === "enable_thinking_effort"
+ ? reasoningEnabled
+ ? { enable_thinking: true, reasoning_effort: localReasoningEffort }
+ : { enable_thinking: false }
+ : reasoningStyle === "reasoning_effort"
+ ? reasoningEnabled
+ ? { reasoning_effort: localReasoningEffort }
+ : {}
+ : { enable_thinking: reasoningEnabled }
+ : {}),
+ ...(supportsPreserveThinking
+ ? { preserve_thinking: preserveThinking }
+ : {}),
+ };
+}
+
+/**
+ * The tool flags a completion would send, so the count includes the schemas and the action nudge.
+ * Same gates the adapter applies; the render_html image gate is left to the server.
+ */
+export async function buildLocalTokenCountExtras(
+ threadId: string | undefined,
+): Promise<Record<string, unknown>> {
+ const {
+ supportsTools,
+ toolsEnabled,
+ codeToolsEnabled,
+ artifactsEnabled,
+ mcpEnabledForChat,
+ ragEnabled,
+ ragSource,
+ ragMode,
+ ragTopK,
+ autoHealToolCalls,
+ } = useChatRuntimeStore.getState();
+ if (!supportsTools) return {};
+
+ const ragProjectId = await resolveProjectId(threadId);
+ const projectRagEnabled = ragProjectId
+ ? await projectHasSources(ragProjectId)
+ : false;
+ const ragOn = ragEnabled || projectRagEnabled;
+ if (
+ !toolsEnabled &&
+ !codeToolsEnabled &&
+ !artifactsEnabled &&
+ !mcpEnabledForChat &&
+ !ragOn
+ ) {
+ return {};
+ }
+
+ return {
+ enable_tools: true,
+ // Auto-Heal off leaves leaked tool markup in the real prompt, so the count keeps it.
+ auto_heal_tool_calls: autoHealToolCalls,
+ enabled_tools: [
+ ...(ragOn ? ["search_knowledge_base"] : []),
+ ...(toolsEnabled ? ["web_search"] : []),
+ ...(codeToolsEnabled ? ["python", "terminal"] : []),
+ ...(artifactsEnabled ? ["render_html"] : []),
+ ],
+ mcp_enabled: mcpEnabledForChat,
+ // Only truthiness is read server-side, to keep search_knowledge_base and its grounding nudge
+ // in the prompt; no retrieval runs for a count.
+ ...(ragOn
+ ? {
+ rag_scope: {
+ ...(ragEnabled && ragSource.type === "kb"
+ ? { kb_id: ragSource.kbId }
+ : {
+ ...(ragEnabled && threadId ? { thread_id: threadId } : {}),
+ ...(projectRagEnabled && ragProjectId
+ ? { project_id: ragProjectId }
+ : {}),
+ }),
+ // Carried as the completion carries them: an unpersisted New Chat has neither id,
+ // and {} is falsy in Python, so the count alone would drop the tool and its nudge.
+ default_top_k: ragTopK,
+ mode: ragMode,
+ },
+ }
+ : {}),
+ };
+}
+
async function resolveUseAdapter(
threadId: string | undefined,
options: OpenAIStreamAdapterOptions = {},
@@ -2863,8 +3076,8 @@ export function createOpenAIStreamAdapter(
);
const artifactInstruction = artifactsEnabled
? renderHtmlToolEnabledForThisTurn
- ? "When the user asks for an HTML, CSS, or JavaScript canvas, call render_html once with one complete self-contained HTML document in the code argument. Embed CSS and JavaScript inside the document. After render_html succeeds, do not call it again in the same response unless the user asks for changes. Future user requests for new canvases may call render_html once."
- : "When the user asks for an HTML, CSS, or JavaScript canvas, return one complete self-contained fenced html code block. Embed CSS and JavaScript inside the document. Do not emit tool-call syntax."
+ ? CANVAS_TOOL_INSTRUCTION
+ : CANVAS_FALLBACK_INSTRUCTION
: null;
const effectiveDisabledToolGuard =
disabledToolGuard && artifactsEnabled
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 2bb0a58fead..5d15ab80eab 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -211,6 +211,27 @@ export async function loadModel(
return parseJsonOrThrow<LoadModelResponse>(response, "Model load");
}
+export async function countChatInputTokens(payload: {
+ model: string;
+ messages: OpenAIChatCompletionsRequest["messages"];
+ enable_thinking?: boolean;
+ reasoning_effort?: OpenAIChatCompletionsRequest["reasoning_effort"];
+ preserve_thinking?: boolean;
+ enable_tools?: boolean;
+ enabled_tools?: string[];
+ mcp_enabled?: boolean;
+ rag_scope?: Record<string, unknown>;
+ auto_heal_tool_calls?: boolean;
+ // `model` is informational: the endpoint counts with whatever is resident and reports which.
+}): Promise<{ input_tokens: number; model?: string }> {
+ const response = await authFetch("/api/inference/chat/count_tokens", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(payload),
+ });
+ return parseJsonOrThrow<{ input_tokens: number; model?: string }>(response);
+}
+
export async function validateModel(
payload: LoadModelRequest,
): Promise<ValidateModelResponse> {
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
index 0e912bc3db9..2039e69ad06 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
@@ -58,6 +58,7 @@ import {
resolveManualAutoCtxPin,
} from "../presets/preset-policy";
import { recordLastLocalModelLoad } from "../utils/last-local-model-load";
+import { refreshContextUsage } from "../utils/refresh-context-usage";
import { ensureGpuDeviceCache } from "@/hooks/use-gpu-info";
import {
isMultimodalResponse,
@@ -326,6 +327,20 @@ async function syncInferenceStatusToStore(options?: {
// setModels(listRes...) above used catalog data, which omits audio
// capability. Re-apply live status so attach gates survive a refresh.
syncModelCapabilities(checkpointId, statusRes);
+
+ // Studio starting against an already-resident GGUF: history can load before this first
+ // status refresh has a checkpoint or window, so its own recount never runs. A null thread
+ // would publish an empty count, hence the mounted-thread guard.
+ const hydrated = useChatRuntimeStore.getState();
+ if (
+ !selectedCheckpoint &&
+ hydrated.contextUsage == null &&
+ hydrated.activeThreadId != null &&
+ hydrated.ggufContextLength != null &&
+ !isExternalModelId(checkpointId)
+ ) {
+ void refreshContextUsage({ threadId: hydrated.activeThreadId });
+ }
}
} else if (!statusRes.active_model && !isExternalSelectionActive) {
// specFallbackReason survives here, so clearing activeModelIsLocal
@@ -600,6 +615,9 @@ export function useChatModelRuntime() {
readoptingSameModel: true,
});
syncModelCapabilities(modelId, residentStatus);
+ // setCheckpoint above blanked the bar, this path returns before the post-load recount,
+ // and a mounted thread does not rerun its history loader, so the bar would stay empty.
+ void refreshContextUsage({ afterModelLoad: true });
return;
}
}
@@ -694,6 +712,7 @@ export function useChatModelRuntime() {
loadingModelRef.current = loadInfo;
const abortCtrl = new AbortController();
loadAbortRef.current = abortCtrl;
+ const postLoadRefresh = { needed: false };
try {
async function performLoad(): Promise<void> {
if (abortCtrl.signal.aborted) throw new Error("Cancelled");
@@ -1289,6 +1308,10 @@ export function useChatModelRuntime() {
}
}
await refresh({ signal: abortCtrl.signal });
+ postLoadRefresh.needed = Boolean(
+ (loadResponse.is_gguf || isGguf || ggufVariant) &&
+ !isExternalModelId(modelId),
+ );
if (
!isLora &&
!(loadResponse.is_lora ?? false) &&
@@ -1721,6 +1744,9 @@ export function useChatModelRuntime() {
} finally {
if (progressInterval) clearInterval(progressInterval);
resetLoadingUi();
+ if (postLoadRefresh.needed && !abortCtrl.signal.aborted) {
+ void refreshContextUsage({ afterModelLoad: true });
+ }
}
} catch (error) {
restorePreviousConfig();
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsx
index c22c753545f..823bd2dda69 100644
--- a/studio/frontend/src/features/chat/runtime-provider.tsx
+++ b/studio/frontend/src/features/chat/runtime-provider.tsx
@@ -66,6 +66,10 @@ import {
chatContentPartAttachmentSignature,
onChatAttachmentDeleted,
} from "./utils/chat-attachment-events";
+import {
+ refreshContextUsage,
+ setActiveBranchReader,
+} from "./utils/refresh-context-usage";
import {
deleteStoredChatThreads,
ensureStoredChatThread,
@@ -1169,15 +1173,27 @@ function useStudioRuntimeAdapters(
? savedUsage.modelId === store.params.checkpoint
: typeof store.ggufContextLength === "number" &&
store.ggufContextLength > 0;
- if (savedUsage && withinLocalLimit && modelMatches) {
+ // The value, not a boolean: the writes below need the narrowing.
+ const restoredUsage =
+ savedUsage && withinLocalLimit && modelMatches ? savedUsage : null;
+ if (restoredUsage) {
// Key by the thread this loader read, not whichever is active when the await resolves:
// a switch inside it would file this thread's usage under the incoming one. Same rule
// the adapter's end-of-run write follows.
- store.setThreadContextUsage(remoteId, savedUsage);
+ store.setThreadContextUsage(remoteId, restoredUsage);
if (store.activeThreadId === remoteId) {
- store.setContextUsage(savedUsage);
+ store.setContextUsage(restoredUsage);
}
}
+ // Only when nothing was restored: saved usage is the last completion's exact totals, and
+ // refreshContextUsage does NOT stand down for usage already there, so it would overwrite
+ // them with an estimate whose completionTokens is 0. A thread opened after a model switch
+ // fails modelMatches and still gets priced (#7450).
+ // Primary pane only: a compare pane never owns the global bar, so its count would be
+ // rebuilt from storage, sent, then dropped at publish for not being activeThreadId.
+ if (!restoredUsage && modelType === "base" && !pairId) {
+ void refreshContextUsage({ threadId: remoteId });
+ }
// If any message has a stored parentId, reconstruct the tree so
// retries/regenerations load as branches rather than a flat list. For
@@ -1381,6 +1397,13 @@ function ThreadNewChatSwitch({
}: { nonce: string }): ReactElement | null {
const aui = useAui();
const isLoading = useAuiState(({ threads }) => threads.isLoading);
+ const checkpoint = useChatRuntimeStore((s) => s.params.checkpoint);
+ const ggufContextLength = useChatRuntimeStore((s) => s.ggufContextLength);
+ const modelLoading = useChatRuntimeStore((s) => s.modelLoading);
+ // Read only by the recount below: New Chat itself must not care whether a run is still going.
+ const runActive = useChatRuntimeStore((s) =>
+ Object.values(s.runningByThreadId).some(Boolean),
+ );
// The outgoing thread is not read here: New Chat leaves it running.
useEffect(() => {
if (isLoading) {
@@ -1395,6 +1418,28 @@ function ThreadNewChatSwitch({
useChatRuntimeStore.getState().setActiveThreadId(null);
}, [aui, isLoading, nonce]);
+ // The effect above blanks the bar, and this view reaches no other recount trigger: no persisted
+ // thread for the history loader, and ActiveThreadSync is off while a nonce is present. Keyed on
+ // the model too: on a RELOAD of /chat?new=<uuid> nothing is known until status answers.
+ useEffect(() => {
+ if (
+ isLoading ||
+ modelLoading ||
+ runActive ||
+ !checkpoint ||
+ ggufContextLength == null
+ ) {
+ return;
+ }
+ const store = useChatRuntimeStore.getState();
+ if (store.activeThreadId != null || store.contextUsage != null) return;
+ void refreshContextUsage();
+ // nonce: a fresh New Chat click re-runs the effect above, which blanks the bar again.
+ // runActive is a DEPENDENCY, not just a guard: refreshContextUsage declines while anything
+ // generates, and nothing else re-fires this when the run ends. ThreadContextUsageRecount
+ // cannot cover for it -- an unpersisted New Chat has no activeThreadId.
+ }, [checkpoint, ggufContextLength, isLoading, modelLoading, nonce, runActive]);
+
return null;
}
@@ -1416,6 +1461,75 @@ function ActiveThreadSync({
return null;
}
+// Lets the recount read the on-screen branch, not the stored records: an incognito thread stores
+// none, and a retried thread's newest stored leaf is not what the runtime would send.
+function ActiveBranchRegistrar({
+ enabled,
+}: { enabled: boolean }): ReactElement | null {
+ const aui = useAui();
+
+ useEffect(() => {
+ if (!enabled) {
+ return;
+ }
+ setActiveBranchReader(() => {
+ try {
+ return aui.thread().getState().messages;
+ } catch {
+ // No thread mounted yet; the recount falls back to the stored records.
+ return null;
+ }
+ });
+ return () => setActiveBranchReader(null);
+ }, [aui, enabled]);
+
+ return null;
+}
+
+// Price whichever thread the bar points at whenever it has nothing to show. Only two paths reach
+// it: (1) a model change empties contextUsageByThreadId and a mounted thread does not rerun its
+// history loader; (2) on a deep link to /chat/:id the history loader and status can each land
+// before the other, so neither independently timed callback counts.
+function ThreadContextUsageRecount({
+ enabled,
+}: { enabled: boolean }): ReactElement | null {
+ const activeThreadId = useChatRuntimeStore((s) => s.activeThreadId);
+ const checkpoint = useChatRuntimeStore((s) => s.params.checkpoint);
+ const ggufContextLength = useChatRuntimeStore((s) => s.ggufContextLength);
+ const modelLoading = useChatRuntimeStore((s) => s.modelLoading);
+ // A DEPENDENCY, not just a guard: nothing else here changes when a run ends, so a count skipped
+ // for being busy would never be retried. Every run, not just local ones, since that is what the
+ // endpoint refuses on.
+ const runActive = useChatRuntimeStore((s) =>
+ Object.values(s.runningByThreadId).some(Boolean),
+ );
+
+ useEffect(() => {
+ if (
+ !enabled ||
+ !activeThreadId ||
+ modelLoading ||
+ runActive ||
+ !checkpoint ||
+ ggufContextLength == null
+ ) {
+ return;
+ }
+ // Only into a blank bar: restored or completion-written usage is exact, this is an estimate.
+ if (useChatRuntimeStore.getState().contextUsage != null) return;
+ void refreshContextUsage({ threadId: activeThreadId });
+ }, [
+ activeThreadId,
+ checkpoint,
+ enabled,
+ ggufContextLength,
+ runActive,
+ modelLoading,
+ ]);
+
+ return null;
+}
+
// Exposes the current thread's cancelRun() via the shared store so external
// surfaces (e.g. the sidebar trash button) can stop an in-flight stream before
// deleting the thread, mirroring the Stop -> Trash sequence.
@@ -1598,6 +1712,8 @@ export function ChatRuntimeProvider({
!initialThreadId
}
/>
+ <ActiveBranchRegistrar enabled={modelType === "base" && !pairId} />
+ <ThreadContextUsageRecount enabled={modelType === "base" && !pairId} />
<ThreadBackendAutosave modelType={modelType} pairId={pairId} />
<CancelRegistrar />
{initialThreadId && (
diff --git a/studio/frontend/src/features/chat/utils/refresh-context-usage.ts b/studio/frontend/src/features/chat/utils/refresh-context-usage.ts
new file mode 100644
index 00000000000..0ad05d74a69
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/refresh-context-usage.ts
@@ -0,0 +1,367 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import type { ThreadMessage } from "@assistant-ui/react";
+import {
+ buildLocalTokenCountExtras,
+ buildLocalTokenCountReasoning,
+ buildOutboundMessagesForTokenCount,
+ findLatestUserAudioBase64,
+ messagesContainImage,
+} from "../api/chat-adapter";
+import { countChatInputTokens } from "../api/chat-api";
+import { isExternalModelId } from "../external-providers";
+import { useChatRuntimeStore } from "../stores/chat-runtime-store";
+import type { MessageRecord } from "../types";
+import { listStoredChatMessages } from "./chat-history-storage";
+
+// Per thread, not per module: in compare mode a hidden pane's history load would otherwise
+// invalidate the visible thread's count, blanking the bar.
+const refreshGenerations = new Map<string | null, number>();
+
+function nextGeneration(threadKey: string | null): number {
+ const generation = (refreshGenerations.get(threadKey) ?? 0) + 1;
+ refreshGenerations.set(threadKey, generation);
+ return generation;
+}
+
+function superseded(threadKey: string | null, generation: number): boolean {
+ return refreshGenerations.get(threadKey) !== generation;
+}
+
+// Threads with a count on the wire. A model load fires two triggers (the post-load call and the
+// modelLoading effect), and both would otherwise render the template and tokenize.
+const countsInFlight = new Set<string | null>();
+
+// A trigger deferred behind an in-flight count, replayed once that count settles WITHOUT
+// publishing. Dropping it loses the bar: a run stopped before it emits usage fires the retry this
+// depends on, and the in-flight count then rejects its now-stale branch. Replaying it
+// unconditionally would restore the doubled model-load count, where the first trigger publishes.
+const retryAfterInFlight = new Map<string | null, RefreshOptions>();
+
+function storedMessageToRunMessage(record: MessageRecord): ThreadMessage {
+ const content =
+ Array.isArray(record.content) && record.content.length > 0
+ ? structuredClone(record.content)
+ : [{ type: "text" as const, text: "" }];
+
+ if (record.role === "user") {
+ return {
+ id: record.id,
+ createdAt: new Date(record.createdAt),
+ role: "user",
+ content: content as Extract<ThreadMessage, { role: "user" }>["content"],
+ attachments: record.attachments
+ ? structuredClone(record.attachments)
+ : [],
+ metadata: { custom: {} },
+ };
+ }
+
+ const custom = (record.metadata as Record<string, unknown>) ?? {};
+ const savedTiming = custom.timing as
+ | import("@assistant-ui/react").MessageTiming
+ | undefined;
+ return {
+ id: record.id,
+ createdAt: new Date(record.createdAt),
+ role: "assistant",
+ content: content as Extract<ThreadMessage, { role: "assistant" }>["content"],
+ status: { type: "complete", reason: "unknown" },
+ metadata: {
+ custom,
+ ...(savedTiming ? { timing: savedTiming } : {}),
+ steps: [],
+ unstable_annotations: [],
+ unstable_data: [],
+ unstable_state: null,
+ },
+ };
+}
+
+// Same order the history adapter sorts stored records in before importing them.
+const ROLE_ORDER: Record<string, number> = { system: 0, user: 1, assistant: 2 };
+
+/**
+ * The displayed branch, rebuilt as the history adapter does: sort by (createdAt, role, id), parent
+ * legacy records to the previous one, then walk the last record's ancestor chain. Greedy
+ * newest-child descent would pick another branch and drop pre-parentId history.
+ */
+function orderBySelectedBranch<T extends MessageRecord>(messages: T[]): T[] {
+ const sorted = messages.slice().sort((a, b) => {
+ if (a.createdAt !== b.createdAt) return a.createdAt - b.createdAt;
+ const aOrder = ROLE_ORDER[a.role] ?? 99;
+ const bOrder = ROLE_ORDER[b.role] ?? 99;
+ if (aOrder !== bOrder) return aOrder - bOrder;
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
+ });
+
+ const byId = new Map<string, T>();
+ const parentOf = new Map<string, string | null>();
+ let previousId: string | null = null;
+ for (const m of sorted) {
+ byId.set(m.id, m);
+ parentOf.set(m.id, m.parentId ?? previousId);
+ previousId = m.id;
+ }
+
+ const chain: T[] = [];
+ const seen = new Set<string>();
+ let cur: string | null = sorted.at(-1)?.id ?? null;
+ while (cur != null && !seen.has(cur)) {
+ seen.add(cur);
+ const record = byId.get(cur);
+ if (!record) break;
+ chain.push(record);
+ cur = parentOf.get(cur) ?? null;
+ }
+ return chain.reverse();
+}
+
+/** Rolling 32-bit hash. Only has to change when the input does, not resist an adversary. */
+function foldHash(text: string, seed: number): number {
+ let hash = seed;
+ for (let i = 0; i < text.length; i += 1) {
+ hash = (Math.imul(hash, 31) + text.charCodeAt(i)) | 0;
+ }
+ return hash;
+}
+
+function foldPart(part: unknown, seed: number): number {
+ let serialized: string;
+ try {
+ serialized = JSON.stringify(part) ?? "";
+ } catch {
+ // Unserializable payload: fall back to the part kind, which both sides derive the same way.
+ serialized = String((part as { type?: unknown })?.type);
+ }
+ return foldHash(serialized, seed);
+}
+
+/**
+ * Identity of the branch a count priced. Content is hashed, not measured: a run mutates a turn in
+ * place (streaming grows its text; a tool result lands on a part with no `text`), so neither a
+ * length nor a part tally sees it. Attachments are folded in because the counter prices them too.
+ */
+function branchSignature(messages: readonly ThreadMessage[]): string {
+ let hash = 0;
+ let parts = 0;
+ for (const message of messages) {
+ for (const part of message.content as readonly unknown[]) {
+ parts += 1;
+ hash = foldPart(part, hash);
+ }
+ const attachments = (message as { attachments?: readonly unknown[] })
+ .attachments;
+ for (const attachment of attachments ?? []) {
+ parts += 1;
+ hash = foldPart(attachment, hash);
+ }
+ }
+ return `${messages.length}:${parts}:${messages.at(-1)?.id ?? ""}:${hash}`;
+}
+
+/** The branch the mounted runtime is showing for the thread the store calls active. */
+type ActiveBranchReader = () => readonly ThreadMessage[] | null;
+
+let readActiveBranch: ActiveBranchReader | null = null;
+
+/**
+ * Publish the mounted runtime's visible branch so the recount prices it instead of the persisted
+ * records. Only the single-chat pane registers one; compare panes never own the bar.
+ */
+export function setActiveBranchReader(reader: ActiveBranchReader | null): void {
+ readActiveBranch = reader;
+}
+
+type RefreshOptions =
+ | {
+ threadId?: string;
+ /** When true, skip the modelLoading guard (post-load recount). */
+ afterModelLoad?: boolean;
+ }
+ | undefined;
+
+/** Re-count prompt tokens for the active local GGUF chat and fill the usage bar. */
+export async function refreshContextUsage(
+ options?: RefreshOptions,
+): Promise<void> {
+ const store = useChatRuntimeStore.getState();
+ const threadId = options?.threadId ?? store.activeThreadId;
+ const checkpoint = store.params.checkpoint;
+
+ if (
+ !checkpoint ||
+ isExternalModelId(checkpoint) ||
+ (!options?.afterModelLoad && store.modelLoading) ||
+ store.ggufContextLength == null
+ ) {
+ return;
+ }
+
+ // An output-only audio GGUF never sends a chat completion: the adapter routes the turn to
+ // /audio/generate, which returns no usage, so a chat-template total is never corrected.
+ const activeModel = store.models?.find(
+ (model: { id: string }) => model.id === checkpoint,
+ );
+ if (activeModel?.isAudio && !activeModel?.hasAudioInput) return;
+
+ // Deep Research routes the turn to a server-side research run whose reply carries no usage, so
+ // a total counted here would describe a request that is never made and nothing would correct it.
+ if (store.deepResearchEnabled) return;
+
+ // Never count while anything is generating: the endpoint refuses, and the recount effect depends
+ // on this, so the last run finishing re-fires it. runningByThreadId, not the narrower
+ // localRunByThreadId: the endpoint refuses during an external-provider run too, so gating on less
+ // than the server refuses on would spend a request to be told 503 and lose the retry -- nothing
+ // re-fires this effect when an external run ends unless it is in the dependency array.
+ if (Object.values(store.runningByThreadId ?? {}).some(Boolean)) return;
+
+ const capturedThreadId = threadId ?? null;
+ const capturedCheckpoint = checkpoint;
+
+ if (countsInFlight.has(capturedThreadId)) {
+ retryAfterInFlight.set(capturedThreadId, options);
+ return;
+ }
+
+ // Bump only once this call will do work, so a bail-out cannot cancel an in-flight recount.
+ const generation = nextGeneration(capturedThreadId);
+
+ // The checkpoint can move under any await below, and a later recount for the same thread
+ // supersedes this one; publishing after either puts another model's number on the bar.
+ const stale = (): boolean =>
+ superseded(capturedThreadId, generation) ||
+ useChatRuntimeStore.getState().params.checkpoint !== capturedCheckpoint;
+
+ countsInFlight.add(capturedThreadId);
+ let published = false;
+ try {
+ // Prefer the mounted runtime: it is what the next request reads from (an incognito thread
+ // persists nothing, and after a retry the newest stored leaf is a branch the user left). A
+ // captured null is EXCLUDED, not matched: New Chat leaves the outgoing conversation mounted
+ // until switchToNewThread() settles, so null === null would price it into the empty chat.
+ const readOwnBranch = (): readonly ThreadMessage[] | null =>
+ capturedThreadId != null &&
+ useChatRuntimeStore.getState().activeThreadId === capturedThreadId
+ ? (readActiveBranch?.() ?? null)
+ : null;
+
+ const liveBranch = readOwnBranch();
+
+ let runMessages: readonly ThreadMessage[];
+ // Re-read before publishing, so a turn sent while this count was in flight drops it.
+ let countedBranch: string | null = null;
+ // The stored fallback's witness: storage records and ThreadMessages hash differently, so only
+ // ids survive both, and the last one moves as soon as a turn is sent or an edit mints one.
+ let countedLastId: string | null = null;
+ const fromLiveBranch = Boolean(liveBranch && liveBranch.length > 0);
+ if (fromLiveBranch) {
+ runMessages = liveBranch as readonly ThreadMessage[];
+ } else {
+ const records = threadId ? await listStoredChatMessages(threadId) : [];
+ if (stale()) return;
+ runMessages = orderBySelectedBranch(records).map(
+ storedMessageToRunMessage,
+ );
+ }
+
+ // /chat/count_tokens always 503s on images: /apply-template swaps each for a marker. Declining
+ // before the hash below keeps the base64 out of it and out of a request body that can reach
+ // megabytes, both synchronous on the UI thread.
+ if (messagesContainImage(runMessages)) return;
+
+ // The real request replays the newest user audio as audio_base64 but toOpenAIMessages has
+ // no audio branch, so counting would price a text-only prompt. Decline as images do.
+ if (findLatestUserAudioBase64(runMessages)) return;
+
+ if (fromLiveBranch) {
+ countedBranch = branchSignature(runMessages);
+ } else {
+ countedLastId = runMessages.at(-1)?.id ?? "";
+ }
+
+ // A completion finishing mid-count writes exact usage for a turn this count predates, so drop
+ // the recount rather than roll the bar backwards. Sampled once runMessages is fixed.
+ const usageBeforeCount = useChatRuntimeStore.getState().contextUsage;
+
+ // undefined, not null: a chat with no persisted thread has no project to resolve from.
+ const payloadThreadId = threadId ?? undefined;
+ const outbound = await buildOutboundMessagesForTokenCount(
+ runMessages,
+ payloadThreadId,
+ );
+ if (stale()) return;
+ const countExtras = await buildLocalTokenCountExtras(payloadThreadId);
+ if (stale()) return;
+
+ // Always ask the server: the template itself has tokens, and `unsloth run --enable-tools`
+ // injects schemas the client cannot see.
+ const { input_tokens: inputTokens, model: countedModel } =
+ await countChatInputTokens({
+ model: capturedCheckpoint,
+ messages: outbound,
+ ...buildLocalTokenCountReasoning(),
+ ...countExtras,
+ });
+
+ if (stale()) return;
+ // The response type is a compile-time assertion only: anything else answering 200 here would
+ // put undefined on the bar and throw from toLocaleString.
+ if (typeof inputTokens !== "number" || !Number.isFinite(inputTokens)) return;
+ // The endpoint counts with whatever is resident, never the model asked for: a load from
+ // another tab returns another tokenizer's total, which the checkpoint guards cannot see.
+ if (countedModel != null && countedModel !== capturedCheckpoint) {
+ return;
+ }
+ // Compared even when null: a count started with no thread must not land on one since opened.
+ if (useChatRuntimeStore.getState().activeThreadId !== capturedThreadId) {
+ return;
+ }
+ if (useChatRuntimeStore.getState().contextUsage !== usageBeforeCount) {
+ return;
+ }
+ // A run writes its own usage when it lands, so declining while one is live never loses a
+ // number. A first turn has no thread id yet and files under "__default".
+ if (useChatRuntimeStore.getState().runningByThreadId[capturedThreadId ?? "__default"]) {
+ return;
+ }
+ // The usage snapshot above only sees a completion that WROTE usage, so a run stopped before
+ // emitting any leaves it equal and the branch is the only witness. An empty current branch is
+ // a mismatch: deleting the sole exchange mid-count would leave the old total on the thread.
+ if (countedBranch != null) {
+ const current = readActiveBranch?.();
+ if (current != null && branchSignature(current) !== countedBranch) {
+ return;
+ }
+ } else if (countedLastId != null) {
+ // The count priced storage because the runtime had not mounted this thread yet; if it has
+ // since, the last id is the one witness the two shapes share. readOwnBranch, not
+ // readActiveBranch: an empty New Chat still sees the conversation it is leaving.
+ const current = readOwnBranch();
+ if (
+ current != null &&
+ current.length > 0 &&
+ (current.at(-1)?.id ?? "") !== countedLastId
+ ) {
+ return;
+ }
+ }
+
+ useChatRuntimeStore.getState().setContextUsage({
+ promptTokens: inputTokens,
+ completionTokens: 0,
+ totalTokens: inputTokens,
+ cachedTokens: 0,
+ cacheWriteTokens: 0,
+ });
+ published = true;
+ } catch {
+ // Background recount should not interrupt chat; saved usage stays visible.
+ } finally {
+ countsInFlight.delete(capturedThreadId);
+ const queued = retryAfterInFlight.get(capturedThreadId);
+ const hadQueued = retryAfterInFlight.delete(capturedThreadId);
+ if (hadQueued && !published) void refreshContextUsage(queued);
+ }
+}
diff --git a/tests/studio/_node_harness.py b/tests/studio/_node_harness.py
new file mode 100644
index 00000000000..aa0a2842809
--- /dev/null
+++ b/tests/studio/_node_harness.py
@@ -0,0 +1,79 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Shared plumbing for the ``node --experimental-strip-types`` source harnesses.
+
+``studio/frontend`` carries no JS test runner, so frontend behaviours are pinned by slicing
+the real source VERBATIM into a harness module and running it under node; only the fixtures
+the sliced code reads through are hand-written. Harness and runner go into a per-invocation
+``mkdtemp(prefix = "run")``, so concurrent tests share no file.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import subprocess
+import tempfile
+from collections.abc import Iterable
+from pathlib import Path
+
+import pytest
+
+WORKDIR = Path(__file__).resolve().parents[2]
+
+
+def source_path(relative_path: str) -> Path:
+ """Locate a studio source both in this repo and in a vendored checkout."""
+ direct = WORKDIR / relative_path
+ if direct.exists():
+ return direct
+ return WORKDIR / "unsloth_repo" / relative_path
+
+
+def read(path: Path) -> str:
+ return path.read_text(encoding = "utf-8")
+
+
+def slice_between(text: str, start_marker: str, end_marker: str) -> str:
+ """The source from ``start_marker`` up to (not including) ``end_marker``."""
+ start = text.index(start_marker)
+ end = text.index(end_marker, start + len(start_marker))
+ return text[start:end]
+
+
+def require_node(sources: Iterable[Path]) -> None:
+ """Skip unless node can strip types and every sliced source is present."""
+ if shutil.which("node") is None:
+ pytest.skip("node not available")
+ for path in sources:
+ if not Path(path).exists():
+ pytest.skip("studio chat sources not present")
+ probe = subprocess.run(
+ ["node", "--experimental-strip-types", "--version"],
+ capture_output = True,
+ text = True,
+ timeout = 30,
+ )
+ if probe.returncode != 0:
+ pytest.skip("node --experimental-strip-types not available")
+
+
+def run_harness(temp_root: Path, harness_source: str, script: str) -> dict:
+ """Run ``script`` against ``harness_source`` and parse its last stdout line."""
+ temp_root.mkdir(parents = True, exist_ok = True)
+ workdir = Path(tempfile.mkdtemp(prefix = "run", dir = str(temp_root)))
+ (workdir / "harness.ts").write_text(harness_source, encoding = "utf-8")
+ (workdir / "run.mts").write_text(script, encoding = "utf-8")
+ result = subprocess.run(
+ ["node", "--experimental-strip-types", "--no-warnings", "run.mts"],
+ cwd = str(workdir),
+ capture_output = True,
+ text = True,
+ timeout = 60,
+ env = dict(os.environ, NODE_NO_WARNINGS = "1"),
+ )
+ assert result.returncode == 0, f"stderr: {result.stderr}\nstdout: {result.stdout}"
+ lines = [line for line in result.stdout.strip().splitlines() if line.strip()]
+ return json.loads(lines[-1])
diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.py
index 140c0bb747d..7d5faca3e35 100644
--- a/tests/studio/test_model_picker_contracts.py
+++ b/tests/studio/test_model_picker_contracts.py
@@ -1386,8 +1386,9 @@ def test_a_native_leased_gguf_is_not_mirrored_to_the_server():
assert "const NATIVE_FILE_LABEL_RE = /^[^/\\\\]+\\.gguf$/i;" in identity
inference = _read_backend("routes/inference.py")
+ # /api/inference/status and the checkpoint helper share _llama_status_model_ids.
assert (
- "model_identifier = None if _native_grant_backed else _model_id" in inference
+ "return display_model_id, (None if native_grant_backed else model_id)" in inference
), "why the checkpoint is only a display name"
models = _read_backend("routes/models.py")
assert "display_name = gguf_file.stem," in models, "why the name is never an index key"
diff --git a/tests/studio/test_new_chat_context_recount.py b/tests/studio/test_new_chat_context_recount.py
new file mode 100644
index 00000000000..23e0fa4805a
--- /dev/null
+++ b/tests/studio/test_new_chat_context_recount.py
@@ -0,0 +1,1640 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Opening a New Chat against a resident GGUF must recount the empty prompt (#7450).
+
+A ``/chat?new=<uuid>`` view reaches none of the other recount triggers: it has no persisted
+thread for the history loader, and ``ThreadNewChatSwitch`` writes ``setActiveThreadId(null)``,
+which blanks ``contextUsage``. A page RELOAD adds a second gap -- that effect runs before
+``/api/inference/status`` answers, so the store still holds ``checkpoint: ""`` and the recount
+returns without counting; the component's dependency array is what retries it.
+
+The effects, the real ``refreshContextUsage`` and the real store reducers are sliced verbatim out
+of the studio sources (see ``_node_harness``) and replayed through a React-effect emulator:
+per-effect dependency arrays, re-run only when a dependency changed.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import textwrap
+
+import pytest
+
+from _node_harness import (
+ WORKDIR,
+ read,
+ require_node,
+ run_harness,
+ slice_between,
+ source_path,
+)
+
+REFRESH = source_path("studio/frontend/src/features/chat/utils/refresh-context-usage.ts")
+PROVIDER = source_path("studio/frontend/src/features/chat/runtime-provider.tsx")
+STORE = source_path("studio/frontend/src/features/chat/stores/chat-runtime-store.ts")
+RUNTIME = source_path("studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts")
+
+TEMP = WORKDIR / "temp" / "new_chat_context_recount"
+
+SOURCES = (REFRESH, PROVIDER, STORE, RUNTIME)
+
+# Every name the emulator can supply to a sliced dependency array.
+BOUND_NAMES = {
+ "activeThreadId",
+ "aui",
+ "checkpoint",
+ "enabled",
+ "ggufContextLength",
+ "isLoading",
+ "runActive",
+ "modelLoading",
+ "nonce",
+}
+
+
+def _refresh_module_body() -> str:
+ """Everything in refresh-context-usage.ts after its import block, verbatim."""
+ text = read(REFRESH)
+ marker = 'from "./chat-history-storage";'
+ return text[text.index(marker) + len(marker) :]
+
+
+def _component_effects(start: str, end: str) -> list[tuple[list[str], str]]:
+ """Every ``useEffect`` in one component as (dependency names, verbatim body)."""
+ component = slice_between(read(PROVIDER), start, end)
+ matches = re.findall(r"useEffect\(\(\) => \{\n(.*?)\n \}, \[([^\]]*)\]\);", component, re.S)
+ assert matches, f"{start} effects not found"
+ effects = [
+ ([name.strip() for name in deps.split(",") if name.strip()], body) for body, deps in matches
+ ]
+ for deps, _body in effects:
+ unknown = set(deps) - BOUND_NAMES
+ assert not unknown, f"emulator does not bind {sorted(unknown)}"
+ return effects
+
+
+def _new_chat_effects() -> list[tuple[list[str], str]]:
+ return _component_effects("function ThreadNewChatSwitch(", "\nfunction ActiveThreadSync(")
+
+
+def _thread_recount_effects() -> list[tuple[list[str], str]]:
+ return _component_effects(
+ "function ThreadContextUsageRecount(",
+ "\n// Exposes the current thread's cancelRun()",
+ )
+
+
+def _store_reducers() -> str:
+ """The four reducers the recount goes through, verbatim."""
+ text = read(STORE)
+ checkpoint = slice_between(
+ text,
+ "setCheckpoint: (modelId, ggufVariant) =>",
+ " // Re-apply the incoming thread's own usage",
+ )
+ active = slice_between(text, "setActiveThreadId: (activeThreadId) =>", "setActiveProjectId:")
+ usage = slice_between(text, "setContextUsage: (contextUsage) =>", "setThreadContextUsage:")
+ thread_usage = slice_between(text, "setThreadContextUsage: (threadId, usage) =>", "}));")
+ return (
+ " "
+ + checkpoint.strip()
+ + "\n "
+ + active.strip()
+ + "\n "
+ + usage.strip()
+ + "\n "
+ + thread_usage.strip()
+ )
+
+
+def _resident_fast_path() -> str:
+ """loadModel's already-resident branch, verbatim."""
+ return slice_between(
+ read(RUNTIME),
+ " // Picking an external provider leaves the local model resident",
+ " // Every chat decodes on the llama-server this load replaces",
+ )
+
+
+def _history_usage_restore() -> str:
+ """The history loader's saved-usage restore and its recount call, verbatim."""
+ return slice_between(
+ read(PROVIDER),
+ " // Window check applies only when a local GGUF window is known; external",
+ " // If any message has a stored parentId, reconstruct the tree so",
+ )
+
+
+HARNESS_PRELUDE = """
+// @ts-nocheck
+// Fixtures the sliced source reads through. Everything below the PRELUDE marker
+// is copied verbatim out of the studio sources.
+export const world: any = {
+ storedMessages: {} as Record<string, any[]>,
+ countedMessages: [] as any[][],
+ countedModel: undefined as string | undefined,
+ switchedToNewThread: 0,
+ promptQueueStops: 0,
+ // Set to { value: x } to stand in for a non-conforming 200 on the count path. Wrapped
+ // so that { value: undefined } means "the reply omits input_tokens" rather than "no
+ // override", which a bare undefined cannot express.
+ countedTokensOverride: undefined as { value: any } | undefined,
+ // Holds the count in flight, so a test can move the world while it is awaiting.
+ countGate: null as Promise<void> | null,
+};
+
+const state: any = {
+ activeThreadId: null,
+ contextUsage: null,
+ contextUsageByThreadId: {},
+ params: { checkpoint: "", systemPrompt: "", systemVariables: "", maxTokens: 4096 },
+ activeGgufVariant: null,
+ ggufContextLength: null,
+ modelLoading: false,
+ runningByThreadId: {},
+ // The subset decoding on the local llama-server: the recount must not share it with a decode.
+ localRunByThreadId: {},
+ // What the recount reads to tell an output-only audio GGUF from a chat one.
+ models: [],
+ // Deep Research sends a research run instead of this history, so the count would price
+ // a request that is never made.
+ deepResearchEnabled: false,
+};
+
+function set(updater: any): void {
+ const patch = typeof updater === "function" ? updater(state) : updater;
+ Object.assign(state, patch);
+}
+
+// What the sliced setCheckpoint reducer reads through: nothing is persisted here, and
+// no external provider is configured, so its output-cap clamp is a no-op.
+const CHAT_DEEP_RESEARCH_ENABLED_KEY = "unsloth_deep_research_enabled";
+function saveLastExternalCheckpoint(_id: string | null): void {}
+function saveBool(_key: string, _value: boolean): void {}
+function parseExternalModelId(id: string): any {
+ const [providerId, ...rest] = id.split(":");
+ return rest.length > 0 ? { providerId, modelId: rest.join(":") } : null;
+}
+const useExternalProvidersStore: any = { getState: () => ({ providers: [] }) };
+function getExternalMaxOutputTokens(_providerType: any, _modelId: any): number {
+ return 8192;
+}
+
+const actions: any = {
+__STORE_REDUCERS__
+};
+
+export const useChatRuntimeStore: any = {
+ getState: () => ({ ...state, ...actions }),
+ // The sliced load paths write straight to the store as zustand allows, so the fake needs the
+ // same door. Merge, like the real setState: a replacing one would drop the seeded fixture.
+ setState: (patch: any) =>
+ Object.assign(state, typeof patch === "function" ? patch(state) : patch),
+};
+
+export function seed(patch: any): void {
+ Object.assign(state, patch);
+}
+
+export function snapshot(): any {
+ return {
+ activeThreadId: state.activeThreadId,
+ contextUsage: state.contextUsage,
+ contextUsageByThreadId: state.contextUsageByThreadId,
+ };
+}
+
+async function listStoredChatMessages(id: string): Promise<any[]> {
+ return world.storedMessages[id] ?? [];
+}
+
+function isExternalModelId(id: string): boolean {
+ return typeof id === "string" && id.includes(":");
+}
+
+function findLatestUserAudioBase64(_messages: any): string | null {
+ return null;
+}
+
+// The real predicate's rule, so a test can put an image on a branch and see it declined.
+function messagesContainImage(messages: any): boolean {
+ const isImage = (p: any) => p?.type === "image" && Boolean(p?.image);
+ for (const message of messages) {
+ for (const part of message.content ?? []) if (isImage(part)) return true;
+ for (const attachment of message.attachments ?? []) {
+ for (const part of attachment.content ?? []) if (isImage(part)) return true;
+ }
+ }
+ return false;
+}
+
+// The adapter's own prompt build is exercised by the request tests; here it only has
+// to turn the reconstructed branch into something countable.
+async function buildOutboundMessagesForTokenCount(messages: any): Promise<any[]> {
+ return messages.map((m: any) => ({ role: m.role, content: "x" }));
+}
+
+async function buildLocalTokenCountExtras(): Promise<Record<string, unknown>> {
+ return {};
+}
+
+// The reasoning kwargs are pinned by test_token_count_prompt_parity.py; here the count
+// only has to reach the server with the right branch of messages.
+function buildLocalTokenCountReasoning(): Record<string, unknown> {
+ return {};
+}
+
+// 12 tokens for the bare template, 25 more per message actually sent. The endpoint also
+// names the tokenizer that produced the total; world.countedModel unset means the reply
+// omits it, as an older backend would.
+async function countChatInputTokens(payload: any): Promise<any> {
+ world.countedMessages.push(payload.messages);
+ if (world.countGate) await world.countGate;
+ return {
+ input_tokens:
+ world.countedTokensOverride === undefined
+ ? 12 + payload.messages.length * 25
+ : world.countedTokensOverride.value,
+ ...(world.countedModel === undefined ? {} : { model: world.countedModel }),
+ };
+}
+
+const requestPromptQueueStop = (_opts: any): void => {
+ world.promptQueueStops += 1;
+};
+
+const auiFixture: any = {
+ threads: () => ({
+ switchToNewThread: async () => {
+ world.switchedToNewThread += 1;
+ },
+ }),
+};
+
+// ---- PRELUDE ENDS: verbatim studio source follows ----
+"""
+
+HARNESS_RENDER = """
+
+// Replays sliced effects with React's dependency rule: an effect re-runs only when one
+// of its own dependencies changed since the last render.
+function replayEffects(effects: any[], scope: any, memo: any[]): void {
+ effects.forEach((effect: any, index: number) => {
+ const next = effect.deps.map((name: string) => scope[name]);
+ const previous = memo[index];
+ if (
+ previous != null &&
+ previous.length === next.length &&
+ previous.every((value: any, i: number) => Object.is(value, next[i]))
+ ) {
+ return;
+ }
+ memo[index] = next;
+ effect.run();
+ });
+}
+
+const recountDeps: any[] = [];
+
+export function renderThreadContextUsageRecount(props: any = {}): void {
+ const enabled = props.enabled ?? true;
+ // Read through the store the way the component's selectors do.
+ const activeThreadId = state.activeThreadId;
+ const checkpoint = state.params.checkpoint;
+ const ggufContextLength = state.ggufContextLength;
+ const modelLoading = state.modelLoading;
+ const runActive = Object.values(state.runningByThreadId ?? {}).some(Boolean);
+ const scope: any = {
+ activeThreadId,
+ checkpoint,
+ enabled,
+ ggufContextLength,
+ modelLoading,
+ runActive,
+ };
+ const effects: any[] = [
+__RECOUNT_EFFECTS__
+ ];
+ replayEffects(effects, scope, recountDeps);
+}
+
+const renderedDeps: any[] = [];
+
+export function renderNewChatSwitch(props: any): void {
+ const aui = auiFixture;
+ const isLoading = props.isLoading;
+ const nonce = props.nonce;
+ // The component reads these through useChatRuntimeStore selectors, so a
+ // re-render sees whatever the store holds right now.
+ const checkpoint = state.params.checkpoint;
+ const ggufContextLength = state.ggufContextLength;
+ const modelLoading = state.modelLoading;
+ const runActive = Object.values(state.runningByThreadId ?? {}).some(Boolean);
+ const scope: any = {
+ aui,
+ isLoading,
+ nonce,
+ checkpoint,
+ ggufContextLength,
+ modelLoading,
+ runActive,
+ };
+ const effects: any[] = [
+__EFFECTS__
+ ];
+ replayEffects(effects, scope, renderedDeps);
+}
+"""
+
+
+HARNESS_RESIDENT = """
+
+// Picking the model that never left memory takes loadModel's already-resident branch,
+// sliced verbatim below. It returns early, so it is replayed inside its own function
+// with the surrounding load machinery stubbed.
+export async function adoptResidentModel(props: any): Promise<void> {
+ const forceReload = false;
+ const selection = "pick";
+ const modelId: string = props.modelId;
+ const ggufVariant = props.ggufVariant ?? null;
+ const bailIfLoadInFlight = (): boolean => false;
+ const applyPerModelConfigToRuntime = (_config: any): void => {};
+ const getInferenceStatus = async (): Promise<any> => props.residentStatus;
+ const resolveInferenceCheckpointId = (status: any): string | null =>
+ status?.active_model ?? null;
+ // The real hydration writes the whole status; the recount only reads the window.
+ const applyActiveModelStatusToStore = (status: any, _options: any): void => {
+ set({
+ ggufContextLength: status.is_gguf ? (status.context_length ?? null) : null,
+ });
+ };
+ const syncModelCapabilities = (_id: string, _status: any): void => {};
+__FAST_PATH__
+}
+"""
+
+
+def _rendered_effects(effects: list[tuple[list[str], str]]) -> str:
+ blocks = []
+ for deps, body in effects:
+ blocks.append(
+ " {\n"
+ f" deps: {json.dumps(deps)},\n"
+ " run: () => {\n"
+ f"{body}\n"
+ " },\n"
+ " },"
+ )
+ return "\n".join(blocks)
+
+
+HARNESS_HISTORY = """
+
+// Opening a stored thread runs this inside the history adapter, before assistant-ui is handed
+// the repository, so the live branch is empty and only the stored path can answer.
+export async function hydrateThreadUsage(props: any): Promise<void> {
+ const remoteId: string = props.remoteId;
+ const savedUsage = props.savedUsage;
+ // The loader is created per pane; a compare pane carries a pairId and never owns the bar.
+ const modelType: string = props.modelType ?? "base";
+ const pairId = props.pairId ?? undefined;
+ // Read once, as the loader does, just above the sliced block.
+ const store = useChatRuntimeStore.getState();
+__RESTORE__
+}
+"""
+
+
+def _harness_source() -> str:
+ prelude = HARNESS_PRELUDE.replace("__STORE_REDUCERS__", _store_reducers())
+ render = HARNESS_RENDER.replace("__EFFECTS__", _rendered_effects(_new_chat_effects())).replace(
+ "__RECOUNT_EFFECTS__", _rendered_effects(_thread_recount_effects())
+ )
+ resident = HARNESS_RESIDENT.replace("__FAST_PATH__", _resident_fast_path())
+ history = HARNESS_HISTORY.replace("__RESTORE__", _history_usage_restore())
+ return prelude + _refresh_module_body() + render + resident + history
+
+
+def _run(script: str) -> dict:
+ require_node(SOURCES)
+ return run_harness(TEMP, _harness_source(), script)
+
+
+# The status response that hydrates a resident GGUF; neither field survives a reload.
+LOADED_MODEL = """
+ seed({
+ params: { checkpoint: "unsloth/gguf-model", systemPrompt: "", systemVariables: "" },
+ ggufContextLength: 8192,
+ modelLoading: false,
+ });
+"""
+
+
+ ("before_status", "expected_early_counts"),
+ [
+ # Arriving on New Chat with the GGUF already resident. The second render repeats identical
+ # store values (a deferred inventory refresh rewrites the checkpoint) and must not re-price.
+ pytest.param(
+ LOADED_MODEL
+ + """
+ seed({
+ activeThreadId: "thread-a",
+ contextUsage: { promptTokens: 900, completionTokens: 30, totalTokens: 930, cachedTokens: 0 },
+ });
+ """,
+ 1,
+ id = "model_already_resident",
+ ),
+ # A page RELOAD of /chat?new=<uuid>: nothing is priceable until /api/inference/status answers.
+ pytest.param("", 0, id = "reload_before_status_hydrates"),
+ # New Chat opened FROM a populated conversation left running: its runtime stays mounted and
+ # the live branch reader keeps returning its messages until switchToNewThread() settles.
+ # The empty chat must still be priced as a bare template.
+ pytest.param(
+ LOADED_MODEL
+ + """
+ seed({
+ activeThreadId: "thread-a",
+ contextUsage: { promptTokens: 900, completionTokens: 30, totalTokens: 930, cachedTokens: 0 },
+ });
+ setActiveBranchReader(() => [
+ { id: "m1", role: "user", createdAt: new Date(1), content: [{ type: "text", text: "hi" }] },
+ { id: "m2", role: "assistant", createdAt: new Date(2), content: [{ type: "text", text: "yo" }] },
+ ]);
+ """,
+ 1,
+ id = "outgoing_conversation_still_mounted",
+ ),
+ ],
+)
+def test_a_new_chat_prices_its_empty_prompt_against_a_resident_gguf(
+ before_status, expected_early_counts
+):
+ """#7450: the empty New Chat request already carries a template, but this view reaches no other
+ recount trigger. It has to land on a count in either order, and open exactly one thread."""
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{
+ renderNewChatSwitch,
+ seed,
+ setActiveBranchReader,
+ snapshot,
+ world,
+ }} from "./harness.ts";
+ {before_status}
+ renderNewChatSwitch({{ isLoading: false, nonce: "n1" }});
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ const early = {{
+ counts: world.countedMessages.length,
+ contextUsage: snapshot().contextUsage,
+ }};
+
+ // /api/inference/status answers; a no-op when the model was already known.
+ {LOADED_MODEL}
+ renderNewChatSwitch({{ isLoading: false, nonce: "n1" }});
+ await new Promise((resolve) => setTimeout(resolve, 30));
+
+ const after = snapshot();
+ console.log(JSON.stringify({{
+ early,
+ switched: world.switchedToNewThread,
+ promptQueueStops: world.promptQueueStops,
+ activeThreadId: after.activeThreadId,
+ contextUsage: after.contextUsage,
+ counts: world.countedMessages.length,
+ }}));
+ """
+ )
+ )
+ assert out["early"].get("counts") == expected_early_counts
+ if expected_early_counts == 0:
+ assert out["early"].get("contextUsage") is None
+ assert out["activeThreadId"] is None
+ assert out["counts"] == 1, "the empty New Chat view must be priced exactly once"
+ assert out["contextUsage"] is not None, (
+ "without the recount the bar stays hidden on a New Chat opened against an "
+ "already-resident GGUF, until the first completion"
+ )
+ assert out["contextUsage"].get("totalTokens") == 12
+ assert out["contextUsage"].get("completionTokens") == 0
+ assert out["switched"] == 1, "hydration must not open a second thread"
+ assert out["promptQueueStops"] == 1, "hydration must not re-stop the prompt queue"
+
+
+ "reply",
+ ["undefined", "null", '"1670"', "NaN", "Infinity", "{}"],
+ ids = ["missing", "null", "string", "nan", "infinity", "object"],
+)
+def test_a_count_that_is_not_a_finite_number_never_reaches_the_bar(reply):
+ """The response type is a compile-time assertion, so a 200 from anything but a matched backend
+ can put a non-number on the bar. ContextUsageBar's "nothing to show" guard is `used <= 0`,
+ which undefined does not satisfy, and its tooltip calls toLocaleString on it."""
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{ renderNewChatSwitch, seed, snapshot, world }} from "./harness.ts";
+ {LOADED_MODEL}
+ world.countedTokensOverride = {{ value: {reply} }};
+ renderNewChatSwitch({{ isLoading: false, nonce: "n1" }});
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ console.log(JSON.stringify({{
+ counts: world.countedMessages.length,
+ contextUsage: snapshot().contextUsage,
+ }}));
+ """
+ )
+ )
+ assert out["counts"] == 1, "the count must still be attempted"
+ assert out["contextUsage"] is None, (
+ f"a reply of {reply} was published to the bar; it renders as "
+ '"undefined / 8.2k" and throws from toLocaleString on hover'
+ )
+
+
+NO_LOCAL_MODEL = """
+ seed({
+ params: { checkpoint: "", systemPrompt: "", systemVariables: "" },
+ ggufContextLength: null,
+ });
+"""
+
+
+ ("seed_script", "is_loading", "expected_switched"),
+ [
+ # No GGUF window means nothing to price; the seeded placeholder must not stick.
+ pytest.param(NO_LOCAL_MODEL, "false", 1, id = "no_local_model"),
+ # assistant-ui is still hydrating: both effects bail before touching anything.
+ pytest.param(LOADED_MODEL, "true", 0, id = "assistant_ui_still_loading"),
+ ],
+)
+def test_the_bar_stays_hidden_when_there_is_nothing_to_price(
+ seed_script, is_loading, expected_switched, request
+):
+ case = request.node.callspec.id
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{ renderNewChatSwitch, seed, snapshot, world }} from "./harness.ts";
+ {seed_script}
+ renderNewChatSwitch({{ isLoading: {is_loading}, nonce: "n1" }});
+ await new Promise((resolve) => setTimeout(resolve, 30));
+
+ console.log(JSON.stringify({{
+ switched: world.switchedToNewThread,
+ counts: world.countedMessages.length,
+ contextUsage: snapshot().contextUsage,
+ }}));
+ """
+ )
+ )
+ assert out["counts"] == 0, case
+ assert out["contextUsage"] is None, case
+ assert out["switched"] == expected_switched, case
+
+
+def test_the_hydration_retry_stays_off_a_started_chat():
+ """The user sent a message before the status response landed, so a real completion owns the
+ bar. The retry effect re-runs on any model field change, so it needs its own guard."""
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{ renderNewChatSwitch, seed, snapshot, world }} from "./harness.ts";
+ renderNewChatSwitch({{ isLoading: false, nonce: "n1" }});
+ await new Promise((resolve) => setTimeout(resolve, 30));
+
+ // First turn completed against the resident model, on a persisted thread.
+ {LOADED_MODEL}
+ seed({{
+ activeThreadId: "thread-a",
+ contextUsage: {{ promptTokens: 640, completionTokens: 40, totalTokens: 680, cachedTokens: 0 }},
+ }});
+ renderNewChatSwitch({{ isLoading: false, nonce: "n1" }});
+ await new Promise((resolve) => setTimeout(resolve, 30));
+
+ console.log(JSON.stringify({{
+ counts: world.countedMessages.length,
+ contextUsage: snapshot().contextUsage,
+ }}));
+ """
+ )
+ )
+ assert out["counts"] == 0, "a real completion's usage must not be recounted away"
+ assert out["contextUsage"].get("totalTokens") == 680
+
+
+TWO_STORED_TURNS = """
+ world.storedMessages["thread-a"] = [
+ { id: "m1", role: "user", createdAt: 1, content: [{ type: "text", text: "hi" }], metadata: {} },
+ { id: "m2", role: "assistant", createdAt: 2, content: [{ type: "text", text: "yo" }], metadata: {} },
+ ];
+"""
+
+# A regenerated last answer: the newest stored leaf is not the branch the runtime is showing.
+RETRY_BRANCH_STORED = """
+ world.storedMessages["thread-a"] = [
+ { id: "m1", role: "user", createdAt: 1, content: [{ type: "text", text: "hi" }], metadata: {} },
+ { id: "m2", role: "assistant", createdAt: 2, parentId: "m1", content: [{ type: "text", text: "yo" }], metadata: {} },
+ { id: "m3", role: "user", createdAt: 3, parentId: "m2", content: [{ type: "text", text: "again" }], metadata: {} },
+ { id: "m4", role: "assistant", createdAt: 4, parentId: "m3", content: [{ type: "text", text: "sure" }], metadata: {} },
+ ];
+"""
+
+LIVE_BRANCH = """
+ setActiveBranchReader(() => [
+ { id: "m1", role: "user", createdAt: new Date(1), content: [{ type: "text", text: "hi" }] },
+ { id: "m2", role: "assistant", createdAt: new Date(2), content: [{ type: "text", text: "yo" }] },
+ ]);
+"""
+
+LIVE_INCOGNITO_BRANCH = """
+ setActiveBranchReader(() => [
+ { id: "m1", role: "user", createdAt: new Date(1), content: [{ type: "text", text: "hi" }] },
+ { id: "m2", role: "assistant", createdAt: new Date(2), content: [{ type: "text", text: "yo" }] },
+ { id: "m3", role: "user", createdAt: new Date(3), content: [{ type: "text", text: "more" }] },
+ ]);
+"""
+
+
+ ("world_setup", "expected_sent", "counted_model"),
+ [
+ # No runtime branch yet: the stored records are the only source, and both turns count.
+ pytest.param(TWO_STORED_TURNS, 2, None, id = "stored_branch"),
+ # An incognito chat persists nothing, so the records would price a bare template.
+ pytest.param(LIVE_INCOGNITO_BRANCH, 3, None, id = "incognito_thread_stores_nothing"),
+ # Regenerated, then switched back: the stored leaf is the retry, four turns not sent.
+ pytest.param(
+ RETRY_BRANCH_STORED + LIVE_BRANCH, 2, None, id = "runtime_shows_an_older_branch"
+ ),
+ # The endpoint counts with whatever is resident, never the model asked for: another tab
+ # loaded a different GGUF, and since this client's checkpoint never moved, the reported
+ # id is the only witness that the total came from the wrong tokenizer.
+ pytest.param(
+ TWO_STORED_TURNS, 2, "unsloth/other-gguf", id = "another_client_swapped_the_model"
+ ),
+ ],
+)
+def test_a_loaded_model_reprices_the_open_thread(world_setup, expected_sent, counted_model):
+ """The post-load recount on a real chat: a model change clears the per-thread cache, so the bar
+ has to be refilled by pricing the conversation. It must price the branch the next request would
+ send -- the mounted runtime's when it has one, the stored records otherwise -- and reach the
+ per-thread cache setActiveThreadId restores from, or the bar blanks on the way back. A total
+ counted by another tokenizer is dropped instead, leaving the previous usage in place."""
+ # None means the reply names the model this client already holds, so it is published.
+ expected_total = 12 + 25 * expected_sent if counted_model is None else None
+ counted_model_setup = (
+ "" if counted_model is None else f"world.countedModel = {json.dumps(counted_model)};"
+ )
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{
+ refreshContextUsage,
+ seed,
+ setActiveBranchReader,
+ snapshot,
+ world,
+ }} from "./harness.ts";
+ {LOADED_MODEL}
+ {counted_model_setup}
+ {world_setup}
+ seed({{ activeThreadId: "thread-a", contextUsage: null, contextUsageByThreadId: {{}} }});
+ await refreshContextUsage({{ threadId: "thread-a", afterModelLoad: true }});
+
+ const after = snapshot();
+ console.log(JSON.stringify({{
+ counts: world.countedMessages.length,
+ sent: world.countedMessages.at(-1) ?? [],
+ contextUsage: after.contextUsage,
+ cached: after.contextUsageByThreadId["thread-a"] ?? null,
+ }}));
+ """
+ )
+ )
+ assert out["counts"] == 1
+ assert len(out["sent"]) == expected_sent, "the branch the request would send must be priced"
+ assert (out["contextUsage"] or {}).get(
+ "totalTokens"
+ ) == expected_total, "a total from another model's tokenizer must not reach the bar"
+ assert (out["cached"] or {}).get(
+ "totalTokens"
+ ) == expected_total, "nor the per-thread cache setActiveThreadId restores from"
+ if expected_total is not None:
+ assert out["cached"] is not None, "the recount must reach the per-thread cache"
+
+
+ ("send_a_turn", "expected_total"),
+ [
+ # Sent mid-count then stopped before any usage, so the snapshot guard cannot see the turn.
+ pytest.param(True, None, id = "a_turn_arrives_mid_count"),
+ # Control: the branch the count priced is still the one on screen.
+ pytest.param(False, 62, id = "branch_unchanged"),
+ ],
+)
+def test_a_turn_sent_while_counting_drops_the_count(send_a_turn, expected_total):
+ """The recount publishes for the branch it priced. A run that starts after the branch is fixed
+ and is stopped before writing usage leaves contextUsage reference-equal to the snapshot, so the
+ total lands anyway -- short by the turn just sent, until the next completion."""
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{
+ refreshContextUsage,
+ seed,
+ setActiveBranchReader,
+ snapshot,
+ world,
+ }} from "./harness.ts";
+ {LOADED_MODEL}
+ const live = [
+ {{ id: "m1", role: "user", createdAt: new Date(1), content: [{{ type: "text", text: "hi" }}] }},
+ {{ id: "m2", role: "assistant", createdAt: new Date(2), content: [{{ type: "text", text: "yo" }}] }},
+ ];
+ setActiveBranchReader(() => live.slice());
+ seed({{ activeThreadId: "thread-a", contextUsage: null, contextUsageByThreadId: {{}} }});
+
+ let release;
+ world.countGate = new Promise((resolve) => {{ release = resolve; }});
+ const pending = refreshContextUsage({{ threadId: "thread-a", afterModelLoad: true }});
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ if ({str(send_a_turn).lower()}) {{
+ // Sent, then stopped before the first token: no usage is ever written.
+ live.push({{
+ id: "m3",
+ role: "user",
+ createdAt: new Date(3),
+ content: [{{ type: "text", text: "a very long pasted document" }}],
+ }});
+ }}
+ release();
+ await pending;
+
+ const after = snapshot();
+ console.log(JSON.stringify({{
+ counts: world.countedMessages.length,
+ sent: world.countedMessages.at(-1) ?? [],
+ contextUsage: after.contextUsage,
+ cached: after.contextUsageByThreadId["thread-a"] ?? null,
+ }}));
+ """
+ )
+ )
+ assert out["counts"] == 1
+ assert len(out["sent"]) == 2, "the count priced the branch as it stood"
+ assert (out["contextUsage"] or {}).get(
+ "totalTokens"
+ ) == expected_total, "a total for a branch that has since gained a turn must not reach the bar"
+ assert (out["cached"] or {}).get("totalTokens") == expected_total
+
+
+ ("running", "grew", "expected_total"),
+ [
+ # A run that BEGINS after the count was issued. The entry gate cannot catch this one: it
+ # ran when the thread was idle, so only the publish guard is left to drop the total.
+ (True, True, None),
+ # Stopped before the count returned, so runningByThreadId is already false and the
+ # usage snapshot is still equal: only the content makes the branch look different.
+ (False, True, None),
+ (False, False, 62),
+ ],
+ ids = ["run_starts_mid_count", "stopped_before_publish", "idle_and_unchanged"],
+)
+def test_a_count_taken_while_the_thread_is_running_is_dropped(running, grew, expected_total):
+ """A run streaming into an existing turn grows its content without moving the branch length or
+ its last id, so the partial is what got priced. The run writes its own usage when it lands.
+
+ Seeded idle and flipped mid-count on purpose: seeding it running would now be refused before
+ the request went out, which would exercise the entry gate instead of this guard."""
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{
+ refreshContextUsage,
+ seed,
+ setActiveBranchReader,
+ snapshot,
+ world,
+ }} from "./harness.ts";
+ {LOADED_MODEL}
+ const live = [
+ {{ id: "m1", role: "user", createdAt: new Date(1), content: [{{ type: "text", text: "hi" }}] }},
+ {{ id: "m2", role: "assistant", createdAt: new Date(2), content: [{{ type: "text", text: "yo" }}] }},
+ ];
+ setActiveBranchReader(() => live.slice());
+ seed({{
+ activeThreadId: "thread-a",
+ contextUsage: null,
+ contextUsageByThreadId: {{}},
+ runningByThreadId: {{}},
+ }});
+
+ let release;
+ world.countGate = new Promise((resolve) => {{ release = resolve; }});
+ const pending = refreshContextUsage({{ threadId: "thread-a", afterModelLoad: true }});
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ if ({str(running).lower()}) {{
+ seed({{ runningByThreadId: {{ "thread-a": true }} }});
+ }}
+ if ({str(grew).lower()}) {{
+ // Same id, same part count: only the streamed content grew.
+ live[1].content = [{{ type: "text", text: "yo" + " and a great deal more" }}];
+ }}
+ release();
+ await pending;
+
+ console.log(JSON.stringify({{
+ counts: world.countedMessages.length,
+ contextUsage: snapshot().contextUsage,
+ }}));
+ """
+ )
+ )
+ assert out["counts"] == 1, "the count is still attempted"
+ assert (out["contextUsage"] or {}).get("totalTokens") == expected_total, (
+ "a partial mid-stream total must not reach the bar"
+ if expected_total is None
+ else "an idle, unchanged thread must still publish"
+ )
+
+
+ ("mutation", "expected_total"),
+ [
+ # A tool result landing on an existing tool-call part: no `text`, and no part added.
+ ("live[1].content[0] = { ...live[1].content[0], result: { rows: 4000 } };", None),
+ # An edit to different text of the same length, which a size-based signature cannot see.
+ ('live[0].content = [{ type: "text", text: "ih" }];', None),
+ # Deleting an attachment: priced, but the handler rewrites `attachments` alone.
+ ("live[0].attachments = [];", None),
+ ("", 62),
+ ],
+ ids = [
+ "tool_result_filled_in",
+ "text_swapped_same_length",
+ "attachment_deleted",
+ "unchanged",
+ ],
+)
+def test_a_count_for_a_branch_mutated_without_growing_is_dropped(mutation, expected_total):
+ """The branch a count priced has to be identified by content, not size: a tool loop mutates
+ parts in place, so a size-based signature would publish a total for a stale prompt."""
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{
+ refreshContextUsage,
+ seed,
+ setActiveBranchReader,
+ snapshot,
+ world,
+ }} from "./harness.ts";
+ {LOADED_MODEL}
+ const live = [
+ {{
+ id: "m1",
+ role: "user",
+ createdAt: new Date(1),
+ content: [{{ type: "text", text: "hi" }}],
+ attachments: [{{
+ id: "a1",
+ name: "notes.txt",
+ content: [{{ type: "text", text: "a stored note the count priced" }}],
+ }}],
+ }},
+ {{
+ id: "m2",
+ role: "assistant",
+ createdAt: new Date(2),
+ content: [{{
+ type: "tool-call",
+ toolCallId: "c1",
+ toolName: "query_docs",
+ argsText: '{{"q":"hi"}}',
+ args: {{ q: "hi" }},
+ }}],
+ }},
+ ];
+ setActiveBranchReader(() => live.slice());
+ seed({{ activeThreadId: "thread-a", contextUsage: null, contextUsageByThreadId: {{}} }});
+
+ let release;
+ world.countGate = new Promise((resolve) => {{ release = resolve; }});
+ const pending = refreshContextUsage({{ threadId: "thread-a", afterModelLoad: true }});
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ {mutation}
+ release();
+ await pending;
+
+ console.log(JSON.stringify({{
+ counts: world.countedMessages.length,
+ contextUsage: snapshot().contextUsage,
+ }}));
+ """
+ )
+ )
+ assert out["counts"] == 1, "the count is still attempted"
+ assert (out["contextUsage"] or {}).get("totalTokens") == expected_total, (
+ "a total for content that has since changed must not reach the bar"
+ if expected_total is None
+ else "an unchanged branch must still publish"
+ )
+
+
+ ("empties", "expected_total"),
+ [(True, None), (False, 62)],
+ ids = ["sole_exchange_deleted", "branch_kept"],
+)
+def test_a_count_for_a_branch_that_was_emptied_is_dropped(empties, expected_total):
+ """Deleting the only exchange while a count is in flight does not touch contextUsage, so
+ the old conversation's total would land on the now-empty thread."""
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{
+ refreshContextUsage,
+ seed,
+ setActiveBranchReader,
+ snapshot,
+ world,
+ }} from "./harness.ts";
+ {LOADED_MODEL}
+ let live = [
+ {{ id: "m1", role: "user", createdAt: new Date(1), content: [{{ type: "text", text: "hi" }}] }},
+ {{ id: "m2", role: "assistant", createdAt: new Date(2), content: [{{ type: "text", text: "yo" }}] }},
+ ];
+ setActiveBranchReader(() => live.slice());
+ seed({{ activeThreadId: "thread-a", contextUsage: null, contextUsageByThreadId: {{}} }});
+
+ let release;
+ world.countGate = new Promise((resolve) => {{ release = resolve; }});
+ const pending = refreshContextUsage({{ threadId: "thread-a", afterModelLoad: true }});
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ if ({str(empties).lower()}) live = [];
+ release();
+ await pending;
+
+ console.log(JSON.stringify({{
+ counts: world.countedMessages.length,
+ contextUsage: snapshot().contextUsage,
+ }}));
+ """
+ )
+ )
+ assert out["counts"] == 1
+ assert (out["contextUsage"] or {}).get(
+ "totalTokens"
+ ) == expected_total, "a total for a branch that has since been emptied must not reach the bar"
+
+
+ ("saved", "expect_counts", "expect_total", "expect_completion"),
+ [
+ # Exact totals for this very model: recounting would trade them for an estimate.
+ (
+ "{ totalTokens: 900, promptTokens: 700, completionTokens: 200, "
+ 'modelId: "unsloth/gguf-model" }',
+ 0,
+ 900,
+ 200,
+ ),
+ # Another model's tokenizer priced these, so they say nothing about this one (#7450).
+ (
+ '{ totalTokens: 900, promptTokens: 700, completionTokens: 200, modelId: "other" }',
+ 1,
+ 12,
+ 0,
+ ),
+ # Nothing stored, which is the case the recount was added for.
+ ("null", 1, 12, 0),
+ ],
+ ids = ["saved_matches_the_model", "saved_is_another_model", "nothing_saved"],
+)
+def test_history_hydration_keeps_saved_usage_it_restored(
+ saved, expect_counts, expect_total, expect_completion
+):
+ """The loader restores the last completion's own usage, exact and split into prompt and
+ completion. refreshContextUsage does not stand down for a value that was already there,
+ so recounting on top would publish an estimate with completionTokens 0 over it."""
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{ hydrateThreadUsage, seed, snapshot, world }} from "./harness.ts";
+ {LOADED_MODEL}
+ seed({{
+ activeThreadId: "thread-a",
+ contextUsage: null,
+ contextUsageByThreadId: {{}},
+ }});
+ await hydrateThreadUsage({{ remoteId: "thread-a", savedUsage: {saved} }});
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ console.log(JSON.stringify({{
+ counts: world.countedMessages.length,
+ contextUsage: snapshot().contextUsage,
+ }}));
+ """
+ )
+ )
+ assert out["counts"] == expect_counts, (
+ "usable saved usage must not be recounted over"
+ if expect_counts == 0
+ else "without usable saved usage the branch still has to be priced"
+ )
+ usage = out["contextUsage"] or {}
+ assert usage.get("totalTokens") == expect_total
+ assert (
+ usage.get("completionTokens") == expect_completion
+ ), "the completion half of an exact total must survive hydration"
+
+
+def test_deep_research_declines_the_recount():
+ """With Deep Research on, the next send creates a server-side research run instead of posting
+ this history, and the research reply carries no usage to correct a guess with. Counting would
+ put a total on the bar describing a request that is never made, and leave it there."""
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{ refreshContextUsage, seed, snapshot, world }} from "./harness.ts";
+ {LOADED_MODEL}
+ seed({{ activeThreadId: "thread-a", contextUsage: null, deepResearchEnabled: true }});
+ await refreshContextUsage({{ threadId: "thread-a", afterModelLoad: true }});
+ console.log(JSON.stringify({{
+ counts: world.countedMessages.length,
+ contextUsage: snapshot().contextUsage,
+ }}));
+ """
+ )
+ )
+ assert out["counts"] == 0, "a research turn must not be priced as a chat completion"
+ assert out["contextUsage"] is None
+
+
+def test_an_image_branch_is_declined_before_it_is_sent():
+ """The endpoint always 503s on images: /apply-template swaps each one for a short marker.
+ Declining client-side keeps the base64 out of the branch hash and out of a request body that
+ can run to megabytes, both of which are synchronous work on the UI thread."""
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{
+ refreshContextUsage, seed, setActiveBranchReader, snapshot, world,
+ }} from "./harness.ts";
+ {LOADED_MODEL}
+ const live = [
+ {{ id: "m1", role: "user", createdAt: new Date(1), content: [
+ {{ type: "text", text: "what is this" }},
+ {{ type: "image", image: "data:image/png;base64,AAAA" }},
+ ] }},
+ ];
+ setActiveBranchReader(() => live.slice());
+ seed({{ activeThreadId: "thread-a", contextUsage: null }});
+ await refreshContextUsage({{ threadId: "thread-a", afterModelLoad: true }});
+ console.log(JSON.stringify({{
+ counts: world.countedMessages.length,
+ contextUsage: snapshot().contextUsage,
+ }}));
+ """
+ )
+ )
+ assert out["counts"] == 0, "an image branch must never reach the endpoint"
+ assert out["contextUsage"] is None
+
+
+def test_a_second_trigger_does_not_duplicate_an_in_flight_count():
+ """A model load fires two triggers milliseconds apart: the explicit post-load call and the
+ effect watching modelLoading. Both would render the template and tokenize. The generation map
+ discards one RESULT but neither request, which is the work the recount is trying to keep off
+ the machine."""
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{ refreshContextUsage, seed, snapshot, world }} from "./harness.ts";
+ {LOADED_MODEL}
+ seed({{ activeThreadId: "thread-a", contextUsage: null }});
+
+ let release;
+ world.countGate = new Promise((resolve) => {{ release = resolve; }});
+ const first = refreshContextUsage({{ threadId: "thread-a", afterModelLoad: true }});
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ // The second trigger, while the first is still on the wire.
+ const second = refreshContextUsage({{ threadId: "thread-a", afterModelLoad: true }});
+ release();
+ await Promise.all([first, second]);
+ // Settle: the deferred trigger is replayed off the first count's finally, so a stray
+ // replay would land after the awaits above and this is what would see it.
+ await new Promise((resolve) => setTimeout(resolve, 40));
+
+ console.log(JSON.stringify({{
+ counts: world.countedMessages.length,
+ contextUsage: snapshot().contextUsage,
+ }}));
+ """
+ )
+ )
+ assert out["counts"] == 1, "the second trigger must not put a second count on the wire"
+ assert (out["contextUsage"] or {}).get("totalTokens") == 12, "and the first must still publish"
+
+
+ ("pane", "expect_counts"),
+ [
+ ('{ modelType: "base" }', 1),
+ # Compare panes never own the global bar, so this count could only be discarded.
+ ('{ modelType: "base", pairId: "pair-1" }', 0),
+ ('{ modelType: "finetuned", pairId: "pair-1" }', 0),
+ ],
+ ids = ["primary_pane", "compare_pane", "compare_finetuned_pane"],
+)
+def test_only_the_primary_pane_recounts_on_history_load(pane, expect_counts):
+ """refreshContextUsage drops a total whose thread is not activeThreadId, and a compare pane
+ deliberately never writes that. Counting there rebuilds the branch from storage and pays for
+ /apply-template and /tokenize to produce a number that cannot be shown."""
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{ hydrateThreadUsage, seed, snapshot, world }} from "./harness.ts";
+ {LOADED_MODEL}
+ seed({{ activeThreadId: "thread-a", contextUsage: null, contextUsageByThreadId: {{}} }});
+ await hydrateThreadUsage({{ remoteId: "thread-a", savedUsage: null, ...{pane} }});
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ console.log(JSON.stringify({{ counts: world.countedMessages.length }}));
+ """
+ )
+ )
+ assert out["counts"] == expect_counts, (
+ "the primary pane still prices its branch"
+ if expect_counts
+ else "a compare pane must not spend a count it can never display"
+ )
+
+
+def test_a_trigger_skipped_behind_an_in_flight_count_is_replayed():
+ """The dedupe must defer a trigger, not drop it. A run that starts and is stopped before it
+ emits usage flips runActive back and fires the retry this effect depends on; if that retry is
+ discarded while the first count is still going, the first then rejects its stale branch and
+ nothing fires again, so the bar stays blank for good."""
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{
+ refreshContextUsage, seed, setActiveBranchReader, snapshot, world,
+ }} from "./harness.ts";
+ {LOADED_MODEL}
+ const live = [
+ {{ id: "m1", role: "user", createdAt: new Date(1), content: [{{ type: "text", text: "hi" }}] }},
+ ];
+ setActiveBranchReader(() => live.slice());
+ seed({{ activeThreadId: "thread-a", contextUsage: null, contextUsageByThreadId: {{}} }});
+
+ let release;
+ world.countGate = new Promise((resolve) => {{ release = resolve; }});
+ const first = refreshContextUsage({{ threadId: "thread-a", afterModelLoad: true }});
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ // A turn lands, so the first count is now pricing a branch that moved: it will be
+ // dropped at publish. The stopped run's retry arrives while it is still in flight.
+ live.push({{
+ id: "m2", role: "assistant", createdAt: new Date(2),
+ content: [{{ type: "text", text: "yo" }}],
+ }});
+ const second = refreshContextUsage({{ threadId: "thread-a", afterModelLoad: true }});
+
+ release();
+ await Promise.all([first, second]);
+ await new Promise((resolve) => setTimeout(resolve, 40));
+
+ console.log(JSON.stringify({{
+ counts: world.countedMessages.length,
+ contextUsage: snapshot().contextUsage,
+ }}));
+ """
+ )
+ )
+ assert out["counts"] == 2, (
+ "the skipped trigger must be replayed once the stale count settles, or it is not "
+ "deferred but lost"
+ )
+ # 62, not 12: the replay prices the branch as it moved, which is the point of deferring it.
+ assert (
+ (out["contextUsage"] or {}).get("totalTokens") == 62
+ ), "and the replay must publish the current branch, which is why it is deferred not dropped"
+
+
+def test_a_new_chat_recount_is_retried_after_a_background_run_ends():
+ """New Chat during a background generation is a supported flow: the outgoing conversation
+ keeps streaming and only its own Stop button ends it. refreshContextUsage declines while
+ anything is running, and ThreadContextUsageRecount cannot pick the count up afterwards
+ because an unpersisted New Chat has no activeThreadId to key on. So this effect has to
+ observe the run itself, or the empty chat's bar stays blank for good once the run lands."""
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{ renderNewChatSwitch, seed, snapshot, world }} from "./harness.ts";
+ {LOADED_MODEL}
+ seed({{ runningByThreadId: {{ "thread-a": true }} }});
+ renderNewChatSwitch({{ isLoading: false, nonce: "n1" }});
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ const during = {{
+ counts: world.countedMessages.length,
+ contextUsage: snapshot().contextUsage,
+ }};
+
+ // The background run lands. In the app that store write re-renders the component.
+ seed({{ runningByThreadId: {{}} }});
+ renderNewChatSwitch({{ isLoading: false, nonce: "n1" }});
+ await new Promise((resolve) => setTimeout(resolve, 30));
+
+ console.log(JSON.stringify({{
+ during,
+ counts: world.countedMessages.length,
+ contextUsage: snapshot().contextUsage,
+ }}));
+ """
+ )
+ )
+ assert (
+ out["during"]["counts"] == 0
+ ), "a New Chat must not count while the outgoing conversation is still generating"
+ assert out["during"]["contextUsage"] is None
+ assert out["counts"] == 1, (
+ "the run ending must re-fire this effect: nothing else can, so without it the count is "
+ "not deferred but lost"
+ )
+ assert (out["contextUsage"] or {}).get("totalTokens") == 12
+
+
+ ("first_run_starts", "expected_total"),
+ [(True, None), (False, 12)],
+ ids = ["first_turn_sent_mid_count", "still_empty"],
+)
+def test_a_new_chat_count_is_dropped_once_its_first_run_starts(first_run_starts, expected_total):
+ """A New Chat count captures a null thread id, so it has no branch to compare. A first turn
+ files its run under "__default", the only witness that the bare-template total is now stale."""
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{ refreshContextUsage, seed, snapshot, world }} from "./harness.ts";
+ {LOADED_MODEL}
+ seed({{ activeThreadId: null, contextUsage: null, contextUsageByThreadId: {{}} }});
+
+ let release;
+ world.countGate = new Promise((resolve) => {{ release = resolve; }});
+ const pending = refreshContextUsage({{ afterModelLoad: true }});
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ if ({str(first_run_starts).lower()}) {{
+ seed({{ runningByThreadId: {{ __default: true }} }});
+ }}
+ release();
+ await pending;
+
+ console.log(JSON.stringify({{
+ counts: world.countedMessages.length,
+ contextUsage: snapshot().contextUsage,
+ }}));
+ """
+ )
+ )
+ assert out["counts"] == 1
+ assert (out["contextUsage"] or {}).get(
+ "totalTokens"
+ ) == expected_total, "a bare-template total must not land on a New Chat that already has a turn"
+
+
+def test_adopting_the_resident_gguf_reprices_the_open_thread():
+ """Switching back to a local model that never left memory takes loadModel's already-resident
+ branch, which returns before the post-load recount. setCheckpoint blanks the bar and a mounted
+ thread does not rerun its history loader, so this branch must recount or the bar stays empty."""
+ out = _run(
+ textwrap.dedent(
+ """
+ // @ts-nocheck
+ import { adoptResidentModel, seed, snapshot, world } from "./harness.ts";
+ world.storedMessages["thread-a"] = [
+ { id: "m1", role: "user", createdAt: 1, content: [{ type: "text", text: "hi" }], metadata: {} },
+ { id: "m2", role: "assistant", createdAt: 2, content: [{ type: "text", text: "yo" }], metadata: {} },
+ ];
+ // On an external provider, showing the usage that provider's last turn wrote.
+ seed({
+ params: { checkpoint: "openai:gpt-4o", systemPrompt: "", systemVariables: "" },
+ ggufContextLength: null,
+ activeThreadId: "thread-a",
+ contextUsage: { promptTokens: 900, completionTokens: 30, totalTokens: 930, cachedTokens: 0 },
+ });
+
+ await adoptResidentModel({
+ modelId: "unsloth/gguf-model",
+ residentStatus: {
+ active_model: "unsloth/gguf-model",
+ gguf_variant: null,
+ is_gguf: true,
+ context_length: 8192,
+ },
+ });
+ await new Promise((resolve) => setTimeout(resolve, 30));
+
+ const after = snapshot();
+ console.log(JSON.stringify({
+ counts: world.countedMessages.length,
+ contextUsage: after.contextUsage,
+ cached: after.contextUsageByThreadId["thread-a"] ?? null,
+ }));
+ """
+ )
+ )
+ assert out["counts"] == 1
+ assert (out["contextUsage"] or {}).get("totalTokens") == 62, (
+ "adopting the resident GGUF must reprice the open thread: setCheckpoint has "
+ "already blanked the external provider's usage"
+ )
+ assert (out["cached"] or {}).get("totalTokens") == 62
+
+
+# Revisiting a thread that was NOT open when the model changed: setCheckpoint emptied
+# contextUsageByThreadId, and the thread is already mounted so its history loader never reruns.
+REVISIT_AFTER_A_MODEL_SWITCH = """
+ seed({
+ activeThreadId: "thread-b",
+ contextUsage: { promptTokens: 700, completionTokens: 20, totalTokens: 720, cachedTokens: 0 },
+ contextUsageByThreadId: {
+ "thread-a": { promptTokens: 500, completionTokens: 10, totalTokens: 510, cachedTokens: 0 },
+ "thread-b": { promptTokens: 700, completionTokens: 20, totalTokens: 720, cachedTokens: 0 },
+ },
+ });
+ renderThreadContextUsageRecount();
+ const beforeSwitch = world.countedMessages.length;
+
+ // The user loads a different GGUF, then clicks back into thread-a in the sidebar.
+ useChatRuntimeStore.getState().setCheckpoint("unsloth/other-gguf");
+ useChatRuntimeStore.getState().setActiveThreadId("thread-a");
+ renderThreadContextUsageRecount();
+"""
+
+# A deep link to /chat/:id against a resident GGUF: the history loader's own recount runs before
+# /api/inference/status answers, and status lands before ThreadAutoSwitch writes activeThreadId.
+DEEP_LINK_HYDRATING_AFTER_THE_LOADER = """
+ renderThreadContextUsageRecount();
+ await refreshContextUsage({ threadId: "thread-a" });
+ const beforeSwitch = world.countedMessages.length;
+
+ // /api/inference/status answers while the thread is still not active.
+ seed({
+ params: { checkpoint: "unsloth/gguf-model", systemPrompt: "", systemVariables: "" },
+ ggufContextLength: 8192,
+ modelLoading: false,
+ });
+ renderThreadContextUsageRecount();
+
+ // ThreadAutoSwitch finally writes the active thread.
+ useChatRuntimeStore.getState().setActiveThreadId("thread-a");
+ renderThreadContextUsageRecount();
+"""
+
+
+ ("seed_script", "scenario"),
+ [
+ pytest.param(LOADED_MODEL, REVISIT_AFTER_A_MODEL_SWITCH, id = "revisit_a_cached_thread"),
+ pytest.param("", DEEP_LINK_HYDRATING_AFTER_THE_LOADER, id = "deep_link_hydrates_late"),
+ ],
+)
+def test_a_thread_becoming_active_with_a_blank_bar_is_repriced(seed_script, scenario):
+ """#7450 again, from the two orderings the load-time and history-load recounts miss. Both end
+ with a thread the bar points at, a known model and window, and no usage, so the recount has to
+ run off the thread becoming active rather than off either independently timed callback."""
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{
+ refreshContextUsage,
+ renderThreadContextUsageRecount,
+ seed,
+ snapshot,
+ useChatRuntimeStore,
+ world,
+ }} from "./harness.ts";
+ {seed_script}
+ {TWO_STORED_TURNS}
+ {scenario}
+ await new Promise((resolve) => setTimeout(resolve, 30));
+
+ const after = snapshot();
+ console.log(JSON.stringify({{
+ beforeSwitch,
+ counts: world.countedMessages.length,
+ sent: world.countedMessages.at(-1) ?? [],
+ contextUsage: after.contextUsage,
+ cached: after.contextUsageByThreadId["thread-a"] ?? null,
+ }}));
+ """
+ )
+ )
+ # thread-b still holds a completion's usage: exact, so becoming active must leave it alone.
+ assert out["beforeSwitch"] == 0, "nothing to reprice until the thread is the active one"
+ assert (out["contextUsage"] or {}).get("totalTokens") == 62, (
+ "a thread the bar points at with no cached usage stays blank until the next "
+ "completion unless becoming active reprices it"
+ )
+ assert (out["cached"] or {}).get("totalTokens") == 62
+ assert out["counts"] == 1
+ assert len(out["sent"]) == 2, "the thread's stored branch must be priced"
+
+
+ ("mount", "expected_total"),
+ [
+ # The runtime mounted mid-count after a turn was sent, so the priced branch is a prefix.
+ (
+ 'live = [...stored, { id: "m3", role: "user", createdAt: new Date(3),'
+ ' content: [{ type: "text", text: "and another" }] }];',
+ None,
+ ),
+ # Mounted with the same branch: nothing moved, so the stored count still describes it.
+ ("live = stored.slice();", 62),
+ # Never mounted: there is nothing to compare against and nothing to invalidate.
+ ("", 62),
+ ],
+ ids = ["mounted_with_a_new_turn", "mounted_unchanged", "still_unmounted"],
+)
+def test_a_stored_history_count_is_dropped_once_the_runtime_contradicts_it(mount, expected_total):
+ """A recount that falls back to storage runs before the thread is mounted, so it has no live
+ branch to sign. Ids survive both shapes: a different mounted tail means the total is stale."""
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{
+ refreshContextUsage,
+ seed,
+ setActiveBranchReader,
+ snapshot,
+ world,
+ }} from "./harness.ts";
+ {LOADED_MODEL}
+ {TWO_STORED_TURNS}
+ const stored = [
+ {{ id: "m1", role: "user", createdAt: new Date(1), content: [{{ type: "text", text: "hi" }}] }},
+ {{ id: "m2", role: "assistant", createdAt: new Date(2), content: [{{ type: "text", text: "yo" }}] }},
+ ];
+ let live = null;
+ setActiveBranchReader(() => live);
+ seed({{ activeThreadId: "thread-a", contextUsage: null, contextUsageByThreadId: {{}} }});
+
+ let release;
+ world.countGate = new Promise((resolve) => {{ release = resolve; }});
+ const pending = refreshContextUsage({{ threadId: "thread-a", afterModelLoad: true }});
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ {mount}
+ release();
+ await pending;
+
+ console.log(JSON.stringify({{
+ counts: world.countedMessages.length,
+ countedLength: world.countedMessages[0]?.length ?? 0,
+ contextUsage: snapshot().contextUsage,
+ }}));
+ """
+ )
+ )
+ assert out["counts"] == 1, "the count is still attempted"
+ assert out["countedLength"] == 2, "it priced the two stored turns"
+ assert (out["contextUsage"] or {}).get("totalTokens") == expected_total, (
+ "a stored total the runtime has since contradicted must not reach the bar"
+ if expected_total is None
+ else "a stored count with nothing contradicting it must still publish"
+ )
+
+
+ ("model_flags", "expected_counts"),
+ [
+ # Output only: every send goes to /audio/generate instead of a chat completion.
+ ("{ isAudio: true, hasAudioInput: false }", 0),
+ # Audio IN, chat out: a normal completion, so the chat-template total is the right one.
+ ("{ isAudio: true, hasAudioInput: true }", 1),
+ ("{ isAudio: false, hasAudioInput: false }", 1),
+ ],
+ ids = ["output_only_audio", "audio_input_model", "plain_gguf"],
+)
+def test_an_output_only_audio_gguf_is_never_recounted(model_flags, expected_counts):
+ """A TTS GGUF sends through /audio/generate, which answers with no usage. A chat-template total
+ over the thread would park a number on the bar that describes nothing and nothing corrects."""
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{ refreshContextUsage, seed, snapshot, world }} from "./harness.ts";
+ {LOADED_MODEL}
+ seed({{
+ activeThreadId: "thread-a",
+ contextUsage: null,
+ contextUsageByThreadId: {{}},
+ models: [{{ id: "unsloth/gguf-model", ...{model_flags} }}],
+ }});
+ await refreshContextUsage({{ threadId: "thread-a", afterModelLoad: true }});
+ console.log(JSON.stringify({{
+ counts: world.countedMessages.length,
+ contextUsage: snapshot().contextUsage,
+ }}));
+ """
+ )
+ )
+ assert out["counts"] == expected_counts, (
+ "an output-only audio model must not be counted at all"
+ if expected_counts == 0
+ else "a model that answers with a chat completion must still be counted"
+ )
+ if expected_counts == 0:
+ assert out["contextUsage"] is None, "the bar stays blank, as it did before the recount"
+
+
+ ("local_runs", "expected_counts"),
+ [
+ # Decoding on the local llama-server: the count would share the process with generation.
+ ('{ "thread-a": true }', 0),
+ # A different thread, still the same llama-server.
+ ('{ "thread-b": true }', 0),
+ # Control: an idle server is what the count is for.
+ ("{}", 1),
+ ],
+ ids = ["this_thread_running", "another_thread_running", "nothing_running"],
+)
+def test_no_count_is_issued_while_anything_is_generating(local_runs, expected_counts):
+ """/apply-template and /tokenize take no inference slot, so the measured cost of counting
+ during a decode is inside the noise, but the budget for this endpoint is zero rather than
+ small. The request is not issued at all while a run is live.
+
+ Every run, not only the local ones. An external-provider run cannot contend for llama-server,
+ but chat_count_tokens refuses during one regardless, because state's active_generations does
+ not distinguish them. Gating on less than the server refuses on would spend a request to be
+ told 503 and then never retry, since only what this effect depends on can re-fire it."""
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{ refreshContextUsage, seed, snapshot, world }} from "./harness.ts";
+ {LOADED_MODEL}
+ seed({{
+ activeThreadId: "thread-a",
+ contextUsage: null,
+ contextUsageByThreadId: {{}},
+ runningByThreadId: {local_runs},
+ }});
+ await refreshContextUsage({{ threadId: "thread-a", afterModelLoad: true }});
+ console.log(JSON.stringify({{
+ counts: world.countedMessages.length,
+ contextUsage: snapshot().contextUsage,
+ }}));
+ """
+ )
+ )
+ assert out["counts"] == expected_counts, (
+ "a count must never be issued while anything is generating"
+ if expected_counts == 0
+ else "an idle server must still be counted"
+ )
+
+
+def test_the_count_is_retried_once_the_run_finishes():
+ """Skipping is only safe because the run finishing re-fires the effect. The recount
+ component lists runActive in its dependency array for exactly this reason, so a count
+ skipped for being busy is not a count lost."""
+ src = read(PROVIDER)
+ recount = slice_between(
+ src,
+ "function ThreadContextUsageRecount(",
+ "\n// Exposes the current thread's cancelRun()",
+ )
+ assert "runningByThreadId" in recount, "the effect must observe decoding"
+ deps = re.search(r"\}, \[([^\]]*)\]\);", recount, re.S)
+ assert deps and "runActive" in deps.group(1), (
+ "runActive must be a DEPENDENCY, not just a guard: nothing else in this array "
+ "changes when a run ends, so without it a skipped count would never be retried"
+ )
diff --git a/tests/studio/test_token_count_prompt_parity.py b/tests/studio/test_token_count_prompt_parity.py
new file mode 100644
index 00000000000..4d75ed70752
--- /dev/null
+++ b/tests/studio/test_token_count_prompt_parity.py
@@ -0,0 +1,338 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The token recount must price the same system prompt the completion would send.
+
+``createOpenAIStreamAdapter`` appends a Canvas instruction to the outbound system prompt whenever
+the Canvas pill is on -- render_html wording when the model can call the tool, the fenced-HTML
+fallback otherwise. Neither is a tool schema, so the server cannot add it back from the flags
+``buildLocalTokenCountExtras`` sends. Same for reasoning: llama-server layers a request's
+``chat_template_kwargs`` over the load-time ``--chat-template-kwargs``, so a count sending none
+renders the template in whatever mode the model was LOADED in. Either way the count reads low.
+
+The builders, both instruction constants and the shared effort clamp are sliced verbatim out of
+the studio sources and run under ``node`` (see ``_node_harness``).
+"""
+
+from __future__ import annotations
+
+import math
+import textwrap
+
+import pytest
+
+from _node_harness import (
+ WORKDIR,
+ read,
+ require_node,
+ run_harness,
+ slice_between,
+ source_path,
+)
+
+ADAPTER = source_path("studio/frontend/src/features/chat/api/chat-adapter.ts")
+CAPABILITIES = source_path("studio/frontend/src/features/chat/provider-capabilities.ts")
+
+TEMP = WORKDIR / "temp" / "token_count_prompt_parity"
+
+SOURCES = (ADAPTER, CAPABILITIES)
+
+
+def _canvas_constants() -> str:
+ return slice_between(
+ read(ADAPTER),
+ "export const CANVAS_TOOL_INSTRUCTION =",
+ "/**\n * The OpenAI-form messages",
+ )
+
+
+def _outbound_builder() -> str:
+ return slice_between(
+ read(ADAPTER),
+ "export async function buildOutboundMessagesForTokenCount(",
+ "/**\n * The reasoning fields a completion would send",
+ )
+
+
+def _extras_builder() -> str:
+ """buildLocalTokenCountExtras, the tool flags the count sends."""
+ return slice_between(
+ read(ADAPTER),
+ "export async function buildLocalTokenCountExtras(",
+ "\n\nasync function resolveUseAdapter(",
+ )
+
+
+def _reasoning_builder() -> str:
+ """buildLocalTokenCountReasoning plus the clamp it shares with the request build."""
+ clamp = slice_between(
+ read(CAPABILITIES),
+ "export function clampReasoningEffortToLevels(",
+ "\n/**",
+ )
+ builder = slice_between(
+ read(ADAPTER),
+ "export function buildLocalTokenCountReasoning(",
+ "/**\n * The tool flags a completion would send",
+ )
+ return clamp + "\n" + builder
+
+
+def _instruction(name: str) -> str:
+ """The JS string literal assigned to ``name``, as Python text."""
+ text = read(ADAPTER)
+ start = text.index(f"export const {name} =")
+ opening = text.index('"', start)
+ closing = text.index('";', opening + 1)
+ return text[opening + 1 : closing]
+
+
+HARNESS = """
+// @ts-nocheck
+// Fixtures the sliced builder reads through. Everything below the PRELUDE marker is
+// copied verbatim out of studio/frontend/src/features/chat/api/chat-adapter.ts.
+const state: any = {
+ params: { systemPrompt: "", systemVariables: "" },
+ artifactsEnabled: false,
+ supportsTools: false,
+ supportsReasoning: false,
+ reasoningStyle: "enable_thinking",
+ reasoningEnabled: true,
+ reasoningEffort: "high",
+ reasoningEffortLevels: ["low", "medium", "high"],
+ supportsPreserveThinking: false,
+ preserveThinking: false,
+};
+
+const useChatRuntimeStore: any = { getState: () => state };
+
+export function seed(patch: any): void {
+ Object.assign(state, patch);
+}
+
+function isAnthropicRefusalMessage(_message: any): boolean {
+ return false;
+}
+
+function toOpenAIMessages(message: any): any[] {
+ return [{ role: message.role, content: message.text }];
+}
+
+function resolveSystemPromptVariables(prompt: string, _variables: string): string {
+ return prompt;
+}
+
+async function resolveProjectInstructions(_threadId: any): Promise<string> {
+ return "";
+}
+
+// The extras builder resolves a project from the thread; no project is configured here, so
+// the RAG scope depends on the Docs pill and the thread id alone.
+async function resolveProjectId(_threadId: any): Promise<string | null> {
+ return null;
+}
+
+async function projectHasSources(_projectId: any): Promise<boolean> {
+ return false;
+}
+
+// A stand-in for the server-side tokenizer: proportional to the rendered prompt, so a
+// dropped instruction shows up as a smaller total rather than a missing symbol.
+export function estimateTokens(messages: any[]): number {
+ return messages.reduce(
+ (total: number, m: any) => total + Math.ceil(String(m.content ?? "").length / 4) + 4,
+ 0,
+ );
+}
+
+// ---- PRELUDE ENDS: verbatim studio source follows ----
+"""
+
+
+def _estimate(contents: list[str]) -> int:
+ return sum(math.ceil(len(content) / 4) + 4 for content in contents)
+
+
+def _harness_source() -> str:
+ return (
+ HARNESS
+ + _canvas_constants()
+ + _outbound_builder()
+ + _reasoning_builder()
+ + _extras_builder()
+ )
+
+
+def _run(script: str) -> dict:
+ require_node(SOURCES)
+ return run_harness(TEMP, _harness_source(), script)
+
+
+def _count_script(seed_patch: str) -> str:
+ return textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{
+ buildOutboundMessagesForTokenCount,
+ estimateTokens,
+ seed,
+ }} from "./harness.ts";
+ seed({seed_patch});
+ const outbound = await buildOutboundMessagesForTokenCount(
+ [{{ role: "user", text: "draw me a bar chart" }}],
+ "thread-a",
+ );
+ console.log(JSON.stringify({{
+ system: outbound[0]?.role === "system" ? outbound[0].content : null,
+ inputTokens: estimateTokens(outbound),
+ }}));
+ """
+ )
+
+
+USER_TURN = "draw me a bar chart"
+SYSTEM_PROMPT = "You are a helpful assistant."
+WITH_PROMPT = (
+ '{ artifactsEnabled: true, supportsTools: true, params: { systemPrompt: "'
+ + SYSTEM_PROMPT
+ + '", systemVariables: "" } }'
+)
+
+
+ ("seed_patch", "constant", "prompt"),
+ [
+ # Canvas on, tool-capable: the request appends the render_html wording to the prompt.
+ pytest.param(WITH_PROMPT, "CANVAS_TOOL_INSTRUCTION", SYSTEM_PROMPT, id = "render_html"),
+ # No tool support: the fenced-HTML fallback, and with no prompt to append to it leads.
+ pytest.param(
+ "{ artifactsEnabled: true, supportsTools: false }",
+ "CANVAS_FALLBACK_INSTRUCTION",
+ "",
+ id = "fenced_html_fallback",
+ ),
+ # The pill is off by default; the count must not invent a prompt.
+ pytest.param("{ artifactsEnabled: false, supportsTools: true }", None, "", id = "canvas_off"),
+ ],
+)
+def test_the_recount_prices_the_canvas_instruction(seed_patch, constant, prompt):
+ """#7450's bar answers "does this chat still fit", so it must price every part of the next
+ prompt -- including the Canvas instruction, which no tool flag can add back server-side."""
+ instruction = _instruction(constant) if constant else ""
+ expected_system = "\n\n".join(part for part in (prompt, instruction) if part)
+ out = _run(_count_script(seed_patch))
+ assert out.get("system") == (expected_system or None)
+ assert out.get("inputTokens") == _estimate(
+ ([expected_system] if expected_system else []) + [USER_TURN]
+ ), "the recount must price the Canvas instruction the completion sends"
+
+
+def test_the_request_path_sends_the_same_constants():
+ """The adapter and the recount must read one source of truth, or the count drifts on edit."""
+ src = read(ADAPTER)
+ assert "? CANVAS_TOOL_INSTRUCTION\n : CANVAS_FALLBACK_INSTRUCTION" in src, (
+ "createOpenAIStreamAdapter must build artifactInstruction from the shared "
+ "constants the token recount prices"
+ )
+ for name in ("CANVAS_TOOL_INSTRUCTION", "CANVAS_FALLBACK_INSTRUCTION"):
+ assert src.count(f"export const {name} =") == 1
+ assert src.count(name) == 3, f"{name} must have exactly one declaration and two uses"
+
+
+ ("seed_patch", "expected"),
+ [
+ # No reasoning support: send nothing, and llama-server keeps its own defaults.
+ pytest.param("{ supportsReasoning: false }", {}, id = "no_reasoning_support"),
+ # Qwen3-style gate off: the template prefills an empty thinking block for this flag.
+ pytest.param(
+ '{ supportsReasoning: true, reasoningStyle: "enable_thinking", reasoningEnabled: false }',
+ {"enable_thinking": False},
+ id = "thinking_turned_off",
+ ),
+ # gpt-oss-style: the effort level is rendered into the prompt.
+ pytest.param(
+ '{ supportsReasoning: true, reasoningStyle: "reasoning_effort", reasoningEnabled: true,'
+ ' reasoningEffort: "low" }',
+ {"reasoning_effort": "low"},
+ id = "effort_level",
+ ),
+ # GLM-style: gate plus a level, clamped to this template's levels as the request build is.
+ pytest.param(
+ '{ supportsReasoning: true, reasoningStyle: "enable_thinking_effort",'
+ ' reasoningEnabled: true, reasoningEffort: "high", reasoningEffortLevels: ["max"] }',
+ {"enable_thinking": True, "reasoning_effort": "max"},
+ id = "effort_clamped_to_the_template_levels",
+ ),
+ # Independent of the gate: decides whether past <think> blocks stay in the prompt.
+ pytest.param(
+ "{ supportsPreserveThinking: true, preserveThinking: true }",
+ {"preserve_thinking": True},
+ id = "preserve_thinking",
+ ),
+ ],
+)
+def test_the_recount_sends_the_reasoning_mode_the_completion_would(seed_patch, expected):
+ """llama-server layers a request's chat_template_kwargs over the load-time
+ --chat-template-kwargs, so a count omitting them prices the mode the model was LOADED in."""
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{ buildLocalTokenCountReasoning, seed }} from "./harness.ts";
+ seed({seed_patch});
+ console.log(JSON.stringify({{ reasoning: buildLocalTokenCountReasoning() }}));
+ """
+ )
+ )
+ assert out.get("reasoning") == expected
+
+
+def test_the_request_path_clamps_the_effort_the_same_way():
+ """Both payloads have to clamp against the loaded template's levels, or the count
+ sends a level the backend drops and prices the template default instead."""
+ src = " ".join(read(ADAPTER).split())
+ assert (
+ src.count("clampReasoningEffortToLevels( reasoningEffort, reasoningEffortLevels, )") == 2
+ ), "the request build and the token recount must clamp from the same store fields"
+
+
+RAG_ON = (
+ "{ supportsTools: true, toolsEnabled: false, codeToolsEnabled: false, "
+ "artifactsEnabled: false, mcpEnabledForChat: false, ragEnabled: true, "
+ 'ragSource: { type: "thread" }, ragMode: "hybrid", ragTopK: 5, '
+ "autoHealToolCalls: true }"
+)
+
+
+ ("thread_id", "expected_thread_id"),
+ [("undefined", None), ('"thread-a"', "thread-a")],
+ ids = ["unpersisted_new_chat", "persisted_thread"],
+)
+def test_the_rag_scope_a_count_sends_is_never_empty(thread_id, expected_thread_id):
+ """The backend keeps search_knowledge_base and its grounding nudge only while rag_scope
+ is truthy, and ``{}`` is falsy in Python. A New Chat has no thread and no project, so an
+ id-only scope would drop from the count a tool schema and a nudge the send still pays."""
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{ buildLocalTokenCountExtras, seed }} from "./harness.ts";
+ seed({RAG_ON});
+ const extras = await buildLocalTokenCountExtras({thread_id});
+ console.log(JSON.stringify({{
+ scope: extras.rag_scope,
+ keys: Object.keys(extras.rag_scope ?? {{}}),
+ enabledTools: extras.enabled_tools,
+ }}));
+ """
+ )
+ )
+ assert "search_knowledge_base" in (
+ out.get("enabledTools") or []
+ ), "the Docs pill must still ask for the tool"
+ assert out.get(
+ "keys"
+ ), "an empty rag_scope is falsy server-side and drops the tool and the nudge"
+ assert (out.get("scope") or {}).get("thread_id") == expected_thread_id