Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: say which part of the prompt does not fit the context window (#9413)
Daniel Han430a32f3021f
diff --git a/studio/backend/core/inference/checkpoint.py b/studio/backend/core/inference/checkpoint.pyindex 9613f915bff..514575db66b 100644--- a/studio/backend/core/inference/checkpoint.py+++ b/studio/backend/core/inference/checkpoint.py@@ -606,6 +606,9 @@ def fit_checkpoint_context(projected, block = _project(fitted)current_tokens = count_tokens(projected)+ # What `current_tokens` prices, tracked separately because `projected` is rebound+ # below on a path that does not re-count. The refusal reports the pair together.+ measured = projected# Phase two: the epoch is full, so start a new one. keep_ratio 0.0 takes every evictable# group in one pass; the primitive itself protects system, developer, final and newest@@ -620,6 +623,7 @@ def fit_checkpoint_context(is_new_epoch = Trueprojected, block = _project(fitted)current_tokens = count_tokens(projected)+ measured = projectedif dropped == 0 and current_tokens <= prompt_target:return messages, None@@ -636,18 +640,20 @@ def fit_checkpoint_context(projected = _without_block(fitted)block = ""current_tokens = count_tokens(projected)+ measured = projectedif current_tokens > prompt_target:# Let the rolling fit retry from the originals; any projection made here would# be discarded by `_fit_context`.- from core.inference.context_window import _latest_turn_tokens # noqa: PLC0415+ from core.inference.context_window import turn_diagnosis # noqa: PLC0415return messages, {"fits": False,"dropped_messages": 0,"prompt_tokens_before": initial_tokens,"prompt_tokens_after": initial_tokens,"irreducible_tokens": current_tokens,- "latest_turn_tokens": _latest_turn_tokens(messages, count_tokens),- "latest_turn_role": str(messages[-1].get("role") or "") if messages else "",+ **turn_diagnosis(+ messages, count_tokens, irreducible_tokens = current_tokens, fitted = measured+ ),"context_length": context_length,"prompt_target": prompt_target,}diff --git a/studio/backend/core/inference/context_refusal.py b/studio/backend/core/inference/context_refusal.pynew file mode 100644index 00000000000..676d8001ecf--- /dev/null+++ b/studio/backend/core/inference/context_refusal.py@@ -0,0 +1,260 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Why a prompt did not fit, carried from the context fit to the message the user reads.++The fit knows the SHAPE of a refusal (how much is the turn just sent vs the floor+eviction could not reduce); `_friendly_error` builds the message much later from+llama-server's text, which knows only a total, and so tells a two-message thread to+"shorten the conversation". Threading the diagnosis through `_friendly_error`'s+forty-odd call sites would be worse than the disease, so it rides the request in a+ContextVar: per-task, and asyncio copies the context per request, so one request's+refusal cannot describe another's.+"""++from contextvars import ContextVar+from typing import Optional++__all__ = [+ "record_fit",+ "clear",+ "latest_refusal",+ "describe_oversize",+ "open_slot",+]+++# A one-key box, not the refusal itself: `.set()` in a context copy is invisible to the+# original, where `_friendly_error` runs, but copies share VALUES. See `open_slot`.+_REFUSAL_SLOT: ContextVar[Optional[dict]] = ContextVar("unsloth_context_refusal", default = None)++# Share of the irreducible prompt the latest turn must reach before the turn, not the+# conversation, is blamed. Never all of it: the system prompt and template wrapper are in+# the floor too. Dominating is NOT the same as not fitting, so it only earns the softer+# "most of this prompt is ..." wording; the flat "does not fit" needs the turn alone to+# exceed the budget.+_TURN_DOMINATES = 0.66+++def open_slot() -> None:+ """Install a slot here that a worker thread or child task can record into.++ Call it in the request's own context, before spawning anything, on any path that+ diagnoses the fit somewhere other than where the error is formatted. The+ non-streaming GGUF drains are that case twice over: `asyncio.create_task` copies the+ context and so does `asyncio.to_thread`, and on the path that matters the drain+ records the refusal and then raises the oversize error it explains, so there is no+ return value to carry it back in either.+ """+ _REFUSAL_SLOT.set({"refusal": None})+++def _slot(*, create: bool = False) -> Optional[dict]:+ slot = _REFUSAL_SLOT.get()+ if slot is None and create:+ # No one opened one, so this context is where the message is built too.+ slot = {"refusal": None}+ _REFUSAL_SLOT.set(slot)+ return slot+++def record_fit(truncation) -> None:+ """Remember a fit that refused, and forget one that succeeded.++ Called on every `context_truncated` event, not just refusals, so a tool loop whose+ later iteration fits does not leave a stale refusal behind to explain another error.+ """+ if not isinstance(truncation, dict):+ return+ slot = _slot(create = True)+ slot["refusal"] = None if truncation.get("fits") else dict(truncation)+++def clear() -> None:+ slot = _slot()+ if slot is not None:+ # Empty it as well as dropping it, so a worker mid-flight holding a reference+ # cannot read a stale refusal back.+ slot["refusal"] = None+ _REFUSAL_SLOT.set(None)+++def latest_refusal() -> Optional[dict]:+ """The most recent fit on this request that could not fit, if there was one."""+ slot = _slot()+ return slot["refusal"] if slot else None+++def _int(value) -> int:+ try:+ return int(value or 0)+ except (TypeError, ValueError):+ return 0+++def _blame_latest_turn(context_tokens: int):+ """`(role, fits_alone)` for the turn worth naming, or None if the history is to blame.++ None also covers no diagnosis recorded, and a diagnosis describing a different+ window than the one just refused: both fall back to generic advice rather than guess.++ `fits_alone` is False only when the turn's own COUNTED rendered size is at or over+ the CONTEXT WINDOW, which is the only evidence that it cannot be sent at all.+ """+ refusal = latest_refusal()+ if not refusal:+ return None+ recorded_context = _int(refusal.get("context_length"))+ if context_tokens and recorded_context and recorded_context != context_tokens:+ # A different load or backend: it cannot describe this refusal.+ return None+ irreducible = _int(refusal.get("irreducible_tokens"))+ latest_turn = _int(refusal.get("latest_turn_tokens"))+ if irreducible <= 0 or latest_turn <= 0:+ return None+ # Only a COUNTED turn is comparable to `irreducible_tokens`. That is a tokenizer count+ # of the rendered prompt; the fallback `latest_turn_tokens` is the message's JSON at+ # four characters a token, so weighing them against each other compares a guess with a+ # truth rather than two sides of one. Measured on the bundled gemma-4 template with a+ # real Gemma tokenizer: 16,400 characters of newlines estimate 8,207 tokens against+ # 557 rendered, 14.8x, which alone clears this ratio against a 8,629-token prompt the+ # turn is 6.5% of -- next to a system prompt that is 93% of it. The user was then told+ # "Most of this prompt is a single tool result" and to fetch a smaller slice of a file+ # that was not the problem. Escaped JSON runs the other way at 0.86x, so the error is+ # not even one-directional and cannot be corrected for.+ #+ # The producer now prices such a turn by difference against the prompt it measured+ # (`turn_diagnosis`), so this flag is False only when nothing could be counted at all.+ # There, no turn is named: a lost diagnosis costs the user a specific lever, a false+ # one sends them after the wrong one. Absent flag means a producer that predates it,+ # which was always a count.+ exact = bool(refusal.get("latest_turn_exact", True))+ if not exact:+ return None+ # Both numbers price a whole rendered PROMPT, so both carry the same floor (template+ # wrapper plus any tool catalogue). Left in, it swamps the comparison: a 6,000-token+ # MCP catalogue makes a 20-token "hi" 97% of the irreducible prompt. Off BOTH sides,+ # so the turn's contribution is compared against the rest of the conversation's.+ shared = _int(refusal.get("shared_prompt_tokens"))+ shared = max(0, min(shared, latest_turn - 1, irreducible - 1))+ latest_turn -= shared+ irreducible -= shared+ if latest_turn < _TURN_DOMINATES * irreducible:+ return None+ # The WINDOW, not the fit's `prompt_target` (the window minus reserved reply room):+ # llama-server admits a prompt on its size alone ("n_tokens() >= n_ctx" in+ # tools/server/server-context.cpp, the check whose text this rewrites), so a turn+ # between the two really would have been served and only earns the soft wording.+ # `>=` to match that check. Compared without the shared floor, since the hard wording+ # is a claim about the turn's own size.+ window = recorded_context or context_tokens+ # Reached only on a counted turn, per the gate above, so this is a claim about a size+ # that was measured. A turn the template renders as nothing on its own is counted by+ # difference, which is why every Gemma tool result can earn this wording again rather+ # than being hedged down for being a guess.+ # Not defaulted to "user": `describe_oversize` gives an unnameable role generic advice.+ role = str(refusal.get("latest_turn_role") or "")+ return role, not (window and latest_turn >= window)+++def _history_cannot_help(context_tokens: int) -> bool:+ """True when the prompt is over the window with every evictable turn already gone.++ `irreducible_tokens` is not "the prompt": it is what the fit measured AFTER dropping+ every group `truncate_oldest_messages` is willing to drop, and a refusal is only ever+ recorded once that evictor returned zero (the fit's loop exits on `dropped == 0`, and+ any other exit means the prompt fits). So it prices the floor eviction cannot go+ below: the template wrapper, the tool catalogue, every system/developer turn, the+ latest user turn and the final group. Deleting ordinary history changes none of those,+ which is why this number is invariant under the one action the generic advice asks for.++ Against the WINDOW for the same reason `_blame_latest_turn` uses it: llama-server+ admits a prompt on size alone ("n_tokens() >= n_ctx"), so at or over it the request is+ refused no matter how short the conversation gets. Below it, shortening really can+ work -- the fit refuses at `prompt_target` but passes the untrimmed messages on, and+ llama-server serves anything under `n_ctx` -- so that case keeps the generic advice.+ """+ refusal = latest_refusal()+ if not refusal:+ return False+ recorded_context = _int(refusal.get("context_length"))+ if context_tokens and recorded_context and recorded_context != context_tokens:+ # A different load or backend: it cannot describe this refusal.+ return False+ irreducible = _int(refusal.get("irreducible_tokens"))+ window = recorded_context or context_tokens+ return irreducible > 0 and window > 0 and irreducible >= window+++# Per role: what to call the turn when it merely dominates, what to call it when it does+# not fit at all, and the lever worth offering. The lever is why this splits by role --+# "send it in smaller pieces" is useless for turns the user did not type.+_ROLE_ADVICE = {+ "user": (+ "Most of this prompt is the message just sent",+ "The message just sent does not fit on its own",+ "send it in smaller pieces",+ ),+ "tool": (+ "Most of this prompt is a single tool result",+ "A tool returned more than this context window can hold",+ "ask for a smaller slice of the file or page",+ ),+ # The reply resumed after it hit Max Tokens: the user cannot split or shorten it.+ "assistant": (+ "Most of this prompt is the reply being continued",+ "The reply being continued is already too long for this window",+ "start a new reply",+ ),+ # These survive eviction, so splitting one preserves the total and changes nothing.+ "system": (+ "Most of this prompt is the system instructions",+ "The system instructions do not fit on their own",+ "shorten the system prompt",+ ),+}+_ROLE_ADVICE["function"] = _ROLE_ADVICE["tool"]+_ROLE_ADVICE["developer"] = _ROLE_ADVICE["system"]+++def describe_oversize(request_tokens: int, context_tokens: int) -> str:+ """The user-facing message for a prompt that exceeds the loaded context window.++ The advice splits on the only two things that change what the user can do: whose+ turn is the bulk of the prompt, and whether that turn is merely most of the prompt+ or actually too big to send at all. An unrecognised role falls back to the generic+ wording rather than blaming a turn it cannot describe.+ """+ head = (+ f"Message too long: {request_tokens} tokens exceeds the "+ f"{context_tokens}-token context window. "+ )+ blamed = _blame_latest_turn(context_tokens)+ advice = _ROLE_ADVICE.get(blamed[0]) if blamed else None+ if advice is None:+ if _history_cannot_help(context_tokens):+ # No turn to name, and yet "shorten the conversation" is not merely vague+ # here, it is an action that provably cannot work: what survives eviction is+ # already at or over the window. Named levers rather than a role, because the+ # bulk is spread across the parts eviction never touches, and the recorded+ # fields cannot say which of them it is -- `shared_prompt_tokens` bundles the+ # template wrapper with the catalogue, so a large one does not prove there+ # are tools. Both levers are offered, and neither is claimed to be the cause.+ return (+ head + "Even with every earlier turn dropped, this prompt would still be "+ "too long, so shortening the conversation will not help. Increase the "+ "Context Length in Model settings, or reduce what every request carries: "+ "the system prompt and any tools that are enabled."+ )+ return (+ head + "Try increasing the Context Length in Model settings, or shorten the "+ "conversation."+ )+ dominant_cause, oversize_cause, lever = advice+ fits_alone = blamed[1]+ cause = dominant_cause if fits_alone else oversize_cause+ hedge = "will not help much" if fits_alone else "will not help"+ return (+ f"{head}{cause}, so shortening the conversation {hedge}. Increase the Context "+ f"Length in Model settings, or {lever}."+ )diff --git a/studio/backend/core/inference/context_window.py b/studio/backend/core/inference/context_window.pyindex ea7fe1d8805..ee6b37fba8b 100644--- a/studio/backend/core/inference/context_window.py+++ b/studio/backend/core/inference/context_window.py@@ -244,19 +244,143 @@ def retrieval_budget(return room-def _latest_turn_tokens(messages: list[dict], count_tokens: Callable[[list[dict]], int]) -> int:- """Tokens in the newest message, estimated if the template refuses to render it.+def _latest_turn_count(+ messages: list[dict], count_tokens: Callable[[list[dict]], int]+) -> tuple[int, bool]:+ """`(tokens, exact)` for the newest message, estimated if the template refuses it.A tool loop can reach the does-not-fit diagnosis with a tool result last, which stricttemplates reject on its own; letting that raise would abort the fit and tell the user- nothing. An approximate number beats a diagnosis that never arrives.+ nothing. An approximate number beats a diagnosis that never arrives -- but the caller+ has to know which it got, because only the counted one carries the prompt's floor."""if not messages:+ return 0, False+ try:+ return int(count_tokens(messages[-1:])), True+ except Exception:+ return int(estimate_messages_tokens(messages[-1:])), False+++def _shared_prompt_tokens(count_tokens: Callable[[list[dict]], int]) -> int:+ """What a rendered prompt costs before any message at all.++ The counter prices a whole PROMPT, not a bag of messages: the template's own wrapper+ and, on a request that advertises tools, the entire tool catalogue rendered into the+ system turn. So that constant sits inside every count the fit takes, including the+ one-message slice above -- on the GGUF tool loop the counters pass `safe_tools` to+ `count_chat_tokens`, which puts the schemas in the prompt it measures, and a couple+ of MCP servers is thousands of tokens of them.++ Measured on the empty prompt rather than estimated: this number is subtracted from+ the two counts that decide which part of the prompt gets named, and a subtraction+ that is only roughly right moves the blame instead of removing it. One extra count,+ taken only on the branch that has already decided to refuse the request.+ """+ try:+ return max(0, int(count_tokens([])))+ except Exception:+ # No measurable floor; zero leaves the diagnosis as it was before this existed.return 0+++def _marginal_turn_count(+ fitted: list[dict], count_tokens: Callable[[list[dict]], int], irreducible_tokens: int+) -> Optional[int]:+ """What the newest turn ADDED to the prompt that was actually measured.++ The one-message slice is unusable when the template renders the newest message as+ nothing on its own, but the difference against the same prompt WITHOUT it is a real+ tokenizer count of exactly the turn's contribution, with the floor cancelled on both+ sides of the subtraction. So the diagnosis keeps a counted turn where it used to fall+ back to a guess.++ `irreducible_tokens` must be the count of `fitted` itself, which is what both callers+ pass. One extra count, on a branch that has already decided to refuse the request,+ next to the one `_shared_prompt_tokens` takes there. None when the counter cannot+ price the prefix, which is the caller's cue to fall back to the estimate.+ """try:- return count_tokens(messages[-1:])+ return int(irreducible_tokens) - int(count_tokens(list(fitted)[:-1]))except Exception:- return estimate_messages_tokens(messages[-1:])+ return None+++def turn_diagnosis(+ messages: list[dict],+ count_tokens: Callable[[list[dict]], int],+ *,+ irreducible_tokens: int,+ fitted: Optional[list[dict]] = None,+) -> dict[str, Any]:+ """The fields that say WHICH part of a refused prompt is which.++ `shared_prompt_tokens` is the floor both `latest_turn_tokens` and+ `irreducible_tokens` carry, so a consumer comparing the two can take it off both+ sides and compare what the turn actually contributed against what the rest of the+ conversation did. Zero when the turn was estimated rather than counted: that estimate+ prices the message's own JSON and no catalogue, so it has no floor to remove.++ `latest_turn_exact` says which of the two `latest_turn_tokens` is. It is False only+ on the fallback below, where nothing could be counted at all, and a consumer must+ then not compare it against `irreducible_tokens`: that number is a tokenizer count of+ the rendered prompt while the estimate is four characters to a token over the+ message's JSON, and the two do not share units. Measured on the bundled gemma-4+ template with a real Gemma tokenizer, 16,400 characters of newlines estimate 8,207+ tokens against 557 rendered, 14.8x, which is enough for the estimate alone to clear+ the dominance ratio against a prompt the turn is 6% of.++ `fitted` is the message list `irreducible_tokens` was counted over. Given it, a turn+ the template refuses to render alone is still priced by difference rather than+ guessed.+ """+ if not messages:+ # Vacuously exact: nothing was estimated, and a zero count is ignored anyway.+ return {+ "latest_turn_tokens": 0,+ "latest_turn_role": "",+ "shared_prompt_tokens": 0,+ "latest_turn_exact": True,+ }+ latest, exact = _latest_turn_count(messages, count_tokens)+ shared = _shared_prompt_tokens(count_tokens) if exact else 0+ if exact and latest <= shared:+ # Counted, and yet no bigger than the empty prompt: the template rendered the turn+ # as nothing. Both bundled Gemma-4 templates do exactly that to a `role: tool`+ # message on its own -- `{%- if message['role'] != 'tool' -%}` skips it, and the+ # result is emitted only while scanning forward from the assistant tool call that+ # asked for it, which a one-message slice does not contain. So the number is the+ # floor and nothing else, and subtracting the floor from it would leave the turn+ # contributing ~0 and blame the conversation.+ #+ # Price it by DIFFERENCE against the prompt that was measured instead: the slice+ # is unrenderable, the contribution is not. Reported floor-inclusive, so the+ # consumer's existing subtraction of `shared` leaves exactly the marginal and the+ # ratio still compares two tokenizer counts.+ marginal = _marginal_turn_count(+ fitted if fitted is not None else messages, count_tokens, irreducible_tokens+ )+ if marginal is not None and marginal > 0:+ latest = marginal + shared+ else:+ # Nothing countable left: same remedy as a template that refuses the slice+ # outright -- price the message's own JSON, and record no floor, because that+ # estimate does not carry one.+ latest = int(estimate_messages_tokens(messages[-1:]))+ shared = 0+ # What is REPORTED is now the estimate, and that is what the flag describes.+ # Leaving it True would be the worse half of the bug.+ exact = False+ # Never all of either side: a floor at or above them would leave no ratio to compare.+ shared = max(0, min(shared, latest - 1, int(irreducible_tokens) - 1))+ return {+ "latest_turn_tokens": latest,+ # Whose message it is: often a tool result the user cannot shorten.+ "latest_turn_role": str(messages[-1].get("role") or ""),+ "shared_prompt_tokens": shared,+ # Whether the number above is a token count or a four-characters-a-token guess.+ "latest_turn_exact": bool(exact),+ }def fit_rolling_context(@@ -366,10 +490,11 @@ def fit_rolling_context(# Floor for the conversation, and how much of it is the message just sent:# together they say whether the chat or the single message is the problem."irreducible_tokens": current_tokens,- "latest_turn_tokens": _latest_turn_tokens(messages, count_tokens),- # ...and whose message that is. In a tool loop the last message is often a- # tool result, which the user did not write and cannot shorten.- "latest_turn_role": str(messages[-1].get("role") or "") if messages else "",+ # `fitted` is what `current_tokens` prices, so the turn can be counted by+ # difference against it rather than estimated.+ **turn_diagnosis(+ messages, count_tokens, irreducible_tokens = current_tokens, fitted = fitted+ ),"context_length": context_length,"prompt_target": prompt_target,}diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex ffcffaa0302..c05e63240bd 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -24267,6 +24267,16 @@ class LlamaCppBackend:tools_withheld = _memory_tool_withheld(thread_id, tools),),)+ # Recorded here, not left to the forwarding below. That list is+ # drained from INSIDE the reopened stream, so a replacement server+ # that came back with a smaller window and then refused this prompt+ # raises at the door and the refusal reaches `_friendly_error` as+ # nothing at all -- which then advises shortening a conversation+ # eviction has already emptied. Idempotent, and safe on a fit:+ # `record_fit` clears whatever the last one left.+ from core.inference import context_refusal # noqa: PLC0415++ context_refusal.record_fit(truncation)if truncation:# Archive only. The replacement fit reserves no recall room, and a# rescued refusal may still have evicted messages.@@ -25797,6 +25807,11 @@ class LlamaCppBackend:branch_messages = _extend_live_branch(conversation),)["counts"])+ # Recorded rather than only forwarded, for the same reason as the+ # iteration refit above.+ from core.inference import context_refusal # noqa: PLC0415++ context_refusal.record_fit(truncation)stream_payload["messages"] = neutralize_control_markup_in_messages(conversation, None, self.markup_profile)diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex fa72ff3b142..ea710f624db 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -59,6 +59,7 @@ from core.inference.audio_errors import (AudioBackendUnsupportedError,AudioGenerationCancelledError,)+from core.inference import context_refusalfrom core.inference.context_window import (estimate_message_tokens as _estimate_message_tokens,estimate_messages_tokens as _estimate_messages_tokens,@@ -263,11 +264,9 @@ def _friendly_error(exc: Exception) -> str:msg,)if m:- return (- f"Message too long: {m.group(1)} tokens exceeds the {m.group(2)}-token "- f"context window. Try increasing the Context Length in Model settings, "- f"or shorten the conversation."- )+ # llama-server knows only the prompt total, so its "shorten the conversation" is+ # wrong for a single oversized turn: let the fit's diagnosis pick the wording.+ return context_refusal.describe_oversize(int(m.group(1)), int(m.group(2)))if "Lost connection to llama-server" in msg:return _LOST_CONNECTION_MSGtemplate_msg = _template_raise_message(msg, _loaded_chat_template())@@ -686,6 +685,9 @@ def _overflow_truncation_requested(payload) -> bool:def _context_truncated_sse_chunk(completion_id: str, model_name: str, truncation: dict) -> str:+ # Every streaming route passes through here, so record the refusal `_friendly_error`+ # will read. See `context_refusal`.+ context_refusal.record_fit(truncation)data = {"id": completion_id,"object": "chat.completion.chunk",@@ -699,6 +701,9 @@ def _context_truncated_sse_chunk(completion_id: str, model_name: str, truncationdef _accumulate_context_truncation(current: Optional[dict], event: dict) -> dict:incoming = {key: value for key, value in event.items() if key != "type"}+ # The drains accumulate rather than forwarding each event, so record here. The per-fit+ # event, not `combined`, which sums counters across a tool loop.+ context_refusal.record_fit(incoming)if current is None:return incomingcombined = {**current, **incoming}@@ -15865,6 +15870,14 @@ async def openai_chat_completions(try:yield _chat_role_chunk(completion_id, created, model_name)+ # In this generator's own context, before the per-event task and+ # thread below each get a COPY of it. The forwarded events record+ # into the parent already, but only when there are any: a prompt+ # that fit leaves no slot, and then the respawn refit -- which runs+ # inside the worker, not out here -- records into a copy that dies+ # with it, so the except-clause below builds its message from+ # nothing. See `context_refusal`, and the two non-streaming drains.+ context_refusal.open_slot()# Iterate the sync generator in a thread so the event loop# stays free for disconnect detection.gen = gguf_generate_with_tools()@@ -16342,6 +16355,9 @@ async def openai_chat_completions(request = request,cancel_event = cancel_event,)+ # In the request's own context: the task and thread below each get a+ # context COPY, so only a slot opened first reaches `_friendly_error`.+ context_refusal.open_slot()drain_task = asyncio.create_task(asyncio.to_thread(_drain_gguf_tool_loop))(full_text,@@ -17041,6 +17057,8 @@ async def openai_chat_completions(_context_truncation,)+ # See the tool-loop drain: the slot has to exist before the copies.+ context_refusal.open_slot()drain_task = asyncio.create_task(asyncio.to_thread(_drain_gguf_choices))(_n,@@ -22453,6 +22471,10 @@ async def _anthropic_tool_stream(# stall window still gets one though its events are dropped._last_drop_keepalive = time.monotonic()+ # See the GGUF tool stream: this loop drives the same tool generator, and its+ # respawn refit records the refusal from inside the worker thread, so the slot+ # has to exist out here before the per-event copies are taken.+ context_refusal.open_slot()gen = run_gen()_next_task = None# Watcher to cancel on disconnect: the in-loop poll fires only between events,diff --git a/studio/backend/tests/test_context_refusal_message.py b/studio/backend/tests/test_context_refusal_message.pynew file mode 100644index 00000000000..c607d6b3b80--- /dev/null+++ b/studio/backend/tests/test_context_refusal_message.py@@ -0,0 +1,965 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Tests for the context-overflow message picking advice the user can act on.++llama-server reports one number for the whole prompt and advises shortening the+conversation. On a two-message thread whose single turn is oversized that advice is+useless, and on a tool result it is worse than useless: the user did not write it. These+tests pin each wording and the conditions under which it is chosen, including the two+thresholds: whose turn is the bulk of the prompt, and whether that turn could have been+sent at all.+"""++from __future__ import annotations++import asyncio+import json+import sys+from pathlib import Path++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++from core.inference import context_refusal # noqa: E402+from core.inference.context_window import ( # noqa: E402+ estimate_messages_tokens,+ fit_rolling_context,+)+from routes.inference import ( # noqa: E402+ _accumulate_context_truncation,+ _context_truncated_sse_chunk,+ _friendly_error,+)++_SERVER_ERROR = "the request (7153 tokens) exceeds the available context size (5120 tokens)"++[email protected](autouse = True)+def _no_carried_refusal():+ """Each test starts with no diagnosis, and leaves none behind."""+ context_refusal.clear()+ yield+ context_refusal.clear()+++def _refusal(+ *,+ irreducible: int,+ latest_turn: int,+ role: str = "user",+ context_length: int = 5120,+ prompt_target: int = 4096,+) -> dict:+ return {+ "fits": False,+ "dropped_messages": 0,+ "irreducible_tokens": irreducible,+ "latest_turn_tokens": latest_turn,+ "latest_turn_role": role,+ "context_length": context_length,+ "prompt_target": prompt_target,+ }+++# ---------------------------------------------------------------- wording+++def test_no_diagnosis_keeps_the_generic_advice():+ message = _friendly_error(ValueError(_SERVER_ERROR))+ assert "Message too long: 7153 tokens exceeds the 5120-token context window." in message+ assert "shorten the conversation" in message+++def test_long_history_keeps_the_generic_advice():+ # A long thread: the newest turn is a small part of what could not be evicted.+ context_refusal.record_fit(_refusal(irreducible = 5000, latest_turn = 300))+ message = _friendly_error(ValueError(_SERVER_ERROR))+ assert "shorten the conversation" in message+ assert "does not fit on its own" not in message+++def test_single_oversized_turn_says_shortening_will_not_help():+ context_refusal.record_fit(_refusal(irreducible = 5600, latest_turn = 5400))+ message = _friendly_error(ValueError(_SERVER_ERROR))+ assert "The message just sent does not fit on its own" in message+ assert "shortening the conversation will not help" in message+ assert "Increase the Context Length in Model settings" in message+++def test_oversized_tool_result_names_the_tool():+ context_refusal.record_fit(_refusal(irreducible = 5600, latest_turn = 5400, role = "tool"))+ message = _friendly_error(ValueError(_SERVER_ERROR))+ assert "A tool returned more than this context window can hold" in message+ assert "smaller slice" in message+ # The user cannot shorten what a tool wrote.+ assert "send it in smaller pieces" not in message+++def test_function_role_is_treated_as_a_tool_result():+ context_refusal.record_fit(_refusal(irreducible = 5600, latest_turn = 5400, role = "function"))+ assert "A tool returned" in _friendly_error(ValueError(_SERVER_ERROR))+++def test_an_oversized_assistant_prefill_does_not_ask_the_user_to_split_it():+ # Auto-continue resends the truncated reply, which the user did not write.+ context_refusal.record_fit(_refusal(irreducible = 5600, latest_turn = 5400, role = "assistant"))+ message = _friendly_error(ValueError(_SERVER_ERROR))+ assert "The reply being continued is already too long for this window" in message+ assert "start a new reply" in message+ assert "send it in smaller pieces" not in message++[email protected]("role", ["system", "developer"])+def test_oversized_instructions_point_at_the_system_prompt(role):+ # These survive eviction, so splitting one preserves the total and resolves nothing.+ context_refusal.record_fit(_refusal(irreducible = 5600, latest_turn = 5400, role = role))+ message = _friendly_error(ValueError(_SERVER_ERROR))+ assert "The system instructions do not fit on their own" in message+ assert "shorten the system prompt" in message+ assert "send it in smaller pieces" not in message+++def test_a_dominating_assistant_prefill_hedges_the_same_way():+ context_refusal.record_fit(_refusal(irreducible = 5120, latest_turn = 3500, role = "assistant"))+ message = _friendly_error(ValueError(_SERVER_ERROR))+ assert "Most of this prompt is the reply being continued" in message+ assert "shortening the conversation will not help much" in message++[email protected]("role", ["", "moderator"])+def test_an_unnameable_role_is_never_blamed(role):+ # Unspecific advice beats advice aimed at the wrong turn.+ context_refusal.record_fit(_refusal(irreducible = 5600, latest_turn = 5400, role = role))+ message = _friendly_error(ValueError(_SERVER_ERROR))+ for named in (+ "the message just sent",+ "a single tool result",+ "the reply being continued",+ "the system instructions",+ ):+ assert named not in message+ # Still says what IS known: this floor is over the window, so no shorter conversation+ # reaches the server either.+ assert "Even with every earlier turn dropped" in message+++def test_every_wording_keeps_the_counts_and_the_client_markers():+ # `isContextLimitError` in chat-adapter.ts matches these substrings, and the numbers+ # are all the user has to size the window by.+ for refusal in (+ None,+ _refusal(irreducible = 5000, latest_turn = 300),+ _refusal(irreducible = 5000, latest_turn = 4800),+ _refusal(irreducible = 5000, latest_turn = 4800, role = "tool"),+ _refusal(irreducible = 5600, latest_turn = 5400, role = "tool"),+ ):+ context_refusal.clear()+ if refusal is not None:+ context_refusal.record_fit(refusal)+ message = _friendly_error(ValueError(_SERVER_ERROR))+ assert "Message too long" in message+ assert "context window" in message+ assert "Context Length" in message+ assert "7153" in message and "5120" in message+++# ---------------------------------------------------------------- selection+++ "latest_turn,expected",+ [+ # Below two thirds, the rest of the prompt is a real share of the problem, so no+ # turn is named. This floor stands at the window, hence the fixed-overhead+ # wording rather than the generic one.+ (3379, "Even with every earlier turn dropped"),+ # Over that share but inside the window: the bulk of the prompt, yet servable by+ # itself. Note 4097, over the 4096 PROMPT BUDGET the fit (not the server) refuses.+ (3380, "Most of this prompt is the message just sent"),+ (4097, "Most of this prompt is the message just sent"),+ (5119, "Most of this prompt is the message just sent"),+ # At the window: llama-server refuses on prompt size alone, so it cannot be sent.+ (5120, "does not fit on its own"),+ ],+)+def test_dominating_the_floor_is_not_the_same_as_not_fitting(latest_turn, expected):+ context_refusal.record_fit(_refusal(irreducible = 5120, latest_turn = latest_turn))+ assert expected in _friendly_error(ValueError(_SERVER_ERROR))+++def test_a_turn_that_merely_dominates_hedges_its_advice():+ # Trimming the rest buys little, but "will not help" would overstate the numbers.+ context_refusal.record_fit(_refusal(irreducible = 5120, latest_turn = 3500))+ message = _friendly_error(ValueError(_SERVER_ERROR))+ assert "shortening the conversation will not help much" in message+ assert "send it in smaller pieces" in message+++def test_a_dominating_tool_result_hedges_the_same_way():+ context_refusal.record_fit(_refusal(irreducible = 5120, latest_turn = 3500, role = "tool"))+ message = _friendly_error(ValueError(_SERVER_ERROR))+ assert "Most of this prompt is a single tool result" in message+ assert "shortening the conversation will not help much" in message+ assert "smaller slice" in message++[email protected]("role", ["user", "tool", "assistant", "system"])+def test_a_turn_the_window_could_have_held_is_never_called_too_big(role):+ """The reply reservation is not part of what the window "can hold".++ `prompt_budget` hands the prompt the window minus room for the reply (up to a+ quarter of it), so a 5120-token window with Max Tokens 1024 refuses the prompt at+ 4096. But llama-server admits a prompt on its size alone -- `n_tokens >= n_ctx`,+ nothing reserved -- so a 4800-token turn in that window IS servable by itself, and+ every hard wording here would be a false claim about it.+ """+ context_refusal.record_fit(+ _refusal(irreducible = 5000, latest_turn = 4800, role = role, prompt_target = 4096)+ )+ message = _friendly_error(ValueError(_SERVER_ERROR))+ assert "Most of this prompt is" in message+ for false_claim in (+ "does not fit on its own",+ "do not fit on their own",+ "more than this context window can hold",+ "already too long for this window",+ ):+ assert false_claim not in message+++def test_a_recorded_prompt_budget_does_not_move_the_hard_boundary():+ # Same turn and window, differing only in what Max Tokens reserved. "Can hold" means+ # the window, so both read the same.+ with_budget = _refusal(irreducible = 5000, latest_turn = 4800, prompt_target = 4096)+ without_budget = dict(with_budget)+ without_budget.pop("prompt_target")+ context_refusal.record_fit(with_budget)+ first = _friendly_error(ValueError(_SERVER_ERROR))+ context_refusal.record_fit(without_budget)+ assert _friendly_error(ValueError(_SERVER_ERROR)) == first+++def test_a_diagnosis_for_a_different_window_is_ignored():+ # A model reload between the fit and the error: that shape describes another window.+ context_refusal.record_fit(_refusal(irreducible = 5000, latest_turn = 4800, context_length = 8192))+ assert "shorten the conversation" in _friendly_error(ValueError(_SERVER_ERROR))+++# ------------------------------------------------- the floor both counts stand on+++def _tool_catalogue_counter(catalogue_tokens: int):+ """`count_chat_tokens(fitted, None, safe_tools)` in miniature.++ The real counter renders a PROMPT: llama-server's /apply-template writes the tool+ catalogue into the system turn of whatever messages it is handed, so the catalogue is+ a constant on top of any slice -- including the one-message slice the fit prices to+ find the newest turn.+ """++ def count(messages):+ body = sum(+ max(1, len(json.dumps(message, ensure_ascii = False)) // 4) for message in messages+ )+ return body + catalogue_tokens++ return count+++def _thread(+ *,+ system_tokens: int,+ turn_tokens: int,+ role: str = "user",+ history_turns: int = 6,+):+ messages = [{"role": "system", "content": "s" * (system_tokens * 4)}]+ for index in range(history_turns):+ messages.append({"role": "user", "content": f"q{index} " + "x" * 1200})+ messages.append({"role": "assistant", "content": f"a{index} " + "y" * 1200})+ messages.append({"role": role, "content": "z" * (turn_tokens * 4)})+ return messages+++def _refuse_and_explain(+ *,+ window: int,+ catalogue: int,+ system_tokens: int,+ turn_tokens: int,+ role: str = "user",+ history_turns: int = 6,+):+ """Drive the real path: fit -> recorded diagnosis -> the message the user reads."""+ _, truncation = fit_rolling_context(+ _thread(+ system_tokens = system_tokens,+ turn_tokens = turn_tokens,+ role = role,+ history_turns = history_turns,+ ),+ context_length = window,+ max_tokens = None,+ count_tokens = _tool_catalogue_counter(catalogue),+ )+ assert truncation is not None and not truncation["fits"]+ _context_truncated_sse_chunk("cmpl-1", "model", truncation)+ return truncation, _friendly_error(+ ValueError(+ f"the request (9000 tokens) exceeds the available context size ({window} tokens)"+ )+ )+++def test_a_tool_catalogue_is_not_the_message_just_sent():+ """A 20-token "hi" beside a large MCP catalogue is not what the user should shorten.++ Both counts in the diagnosis price a whole prompt, so both carry the catalogue: the+ turn reads as 97% of the irreducible prompt while contributing 20 tokens of it. The+ remedy is fewer tools or a bigger window, and neither is "send it in smaller pieces".+ """+ truncation, message = _refuse_and_explain(+ window = 8192, catalogue = 6000, system_tokens = 200, turn_tokens = 20+ )+ # The raw counts really are that lopsided; the floor is why.+ assert truncation["latest_turn_tokens"] > 0.9 * truncation["irreducible_tokens"]+ assert truncation["shared_prompt_tokens"] == 6000+ assert "shorten the conversation" in message+ assert "message just sent" not in message+++def test_a_catalogue_bigger_than_the_window_never_makes_a_tiny_turn_unsendable():+ # The false claim, not just the unhelpful one: a catalogue over the window pushes the+ # one-message count past it, reporting a twenty-token turn as unsendable.+ truncation, message = _refuse_and_explain(+ window = 4096, catalogue = 4200, system_tokens = 200, turn_tokens = 20+ )+ assert truncation["latest_turn_tokens"] > truncation["context_length"]+ assert "does not fit on its own" not in message+ assert "message just sent" not in message+ # And a catalogue over the window puts the FLOOR over it too, so the honest advice is+ # the fixed-overhead one, not a shorter conversation.+ assert truncation["irreducible_tokens"] >= truncation["context_length"]+ assert "shortening the conversation will not help" in message+++def _servable_without_history(*, window: int, catalogue: int, system_tokens: int) -> bool:+ """Would the same request go through with the conversation shortened to nothing?++ The one claim the generic advice makes. A refused fit hands the ORIGINAL messages on+ (dropping turns off a doomed request loses them for nothing), and llama-server admits+ a prompt on size alone, so "served" is the untrimmed prompt landing under `n_ctx`.+ """+ messages = _thread(system_tokens = system_tokens, turn_tokens = 20, history_turns = 0)+ count = _tool_catalogue_counter(catalogue)+ sent, _ = fit_rolling_context(+ messages, context_length = window, max_tokens = None, count_tokens = count+ )+ return count(sent) < window+++def test_a_two_message_thread_is_never_told_to_shorten_the_conversation():+ """The case this module exists for, on the branch that names no turn.++ A system prompt over the window with a twenty-token "hi" after it: eviction has+ nothing to take (the primitive protects system turns and the newest user turn), so+ the floor IS the prompt. "Shorten the conversation" names an action that cannot+ work, and measurably does not: with the history at zero the request is still refused.+ """+ truncation, message = _refuse_and_explain(+ window = 4096, catalogue = 0, system_tokens = 5000, turn_tokens = 20, history_turns = 0+ )+ assert truncation["irreducible_tokens"] >= truncation["context_length"]+ assert not _servable_without_history(window = 4096, catalogue = 0, system_tokens = 5000)+ assert "Even with every earlier turn dropped" in message+ assert "shortening the conversation will not help" in message+ assert "the system prompt and any tools that are enabled" in message+ # Never the advice llama-server itself gives, which is the whole point of the rewrite.+ assert "or shorten the conversation" not in message+++def test_a_floor_under_the_window_keeps_the_advice_that_still_works():+ """The other side of the same line, and why it is drawn at the window.++ A catalogue that fits leaves room the conversation is standing in: the fit refuses at+ `prompt_target`, but the untrimmed prompt is served whenever it lands under `n_ctx`,+ so trimming history really does clear this one. Advising against it would be the new+ false claim.+ """+ truncation, message = _refuse_and_explain(+ window = 8192, catalogue = 6000, system_tokens = 200, turn_tokens = 20+ )+ assert truncation["irreducible_tokens"] < truncation["context_length"]+ assert _servable_without_history(window = 8192, catalogue = 6000, system_tokens = 200)+ assert "shorten the conversation" in message+ assert "will not help" not in message+++def test_a_diagnosis_for_a_different_window_claims_nothing_about_the_floor():+ # A reload between the fit and the error: that floor was measured elsewhere, so the+ # "cannot be shortened" claim has no evidence behind it either.+ context_refusal.record_fit(_refusal(irreducible = 9000, latest_turn = 300, context_length = 8192))+ message = _friendly_error(ValueError(_SERVER_ERROR))+ assert "shorten the conversation" in message+ assert "Even with every earlier turn dropped" not in message+++ "turn_tokens,expected",+ [+ # Still the bulk of what is left once the catalogue is off both sides.+ (5000, "Most of this prompt is the message just sent"),+ # And still bigger than the window on its own.+ (8300, "does not fit on its own"),+ ],+)+def test_a_catalogue_does_not_cost_a_turn_that_really_is_the_problem(turn_tokens, expected):+ _, message = _refuse_and_explain(+ window = 8192, catalogue = 1500, system_tokens = 200, turn_tokens = turn_tokens+ )+ assert expected in message+++def test_a_tool_result_beside_a_catalogue_is_judged_on_its_own_size():+ # The same trap on a role the user cannot edit.+ _, small = _refuse_and_explain(+ window = 8192, catalogue = 6000, system_tokens = 200, turn_tokens = 20, role = "tool"+ )+ assert "tool result" not in small and "shorten the conversation" in small+ _, large = _refuse_and_explain(+ window = 8192, catalogue = 1500, system_tokens = 200, turn_tokens = 5000, role = "tool"+ )+ assert "Most of this prompt is a single tool result" in large+++def test_the_floor_is_never_all_of_either_count():+ # A nonsense floor must not drive either side to zero and invent a ratio.+ context_refusal.record_fit(+ _refusal(irreducible = 5120, latest_turn = 5000) | {"shared_prompt_tokens": 99999}+ )+ assert "Most of this prompt is" not in _friendly_error(ValueError(_SERVER_ERROR))+ for bad in (None, "", -5, "junk"):+ context_refusal.record_fit(+ _refusal(irreducible = 5120, latest_turn = 3500) | {"shared_prompt_tokens": bad}+ )+ assert "Most of this prompt is the message just sent" in _friendly_error(+ ValueError(_SERVER_ERROR)+ )+++def test_an_unrenderable_turn_records_no_floor_to_subtract():+ """The estimate fallback prices the message's own JSON and no catalogue.++ Strict templates reject a lone tool result, which is exactly the shape a tool loop+ refuses on, so the fit falls back to the estimator for that turn. There is no shared+ floor inside that number, so none is recorded, and the count stays comparable to+ nothing -- which lands on the generic advice rather than a wrong blame.+ """++ def _rejects_a_lone_tool_result(messages):+ if len(messages) == 1 and messages[0].get("role") == "tool":+ raise RuntimeError("template rejected the message")+ return sum(max(1, len(json.dumps(m, ensure_ascii = False)) // 4) for m in messages) + 6000++ _, truncation = fit_rolling_context(+ _thread(system_tokens = 200, turn_tokens = 20, role = "tool"),+ context_length = 8192,+ max_tokens = None,+ count_tokens = _rejects_a_lone_tool_result,+ )+ assert truncation is not None and not truncation["fits"]+ assert truncation["shared_prompt_tokens"] == 0+ _context_truncated_sse_chunk("cmpl-1", "model", truncation)+ assert "shorten the conversation" in _friendly_error(+ ValueError("the request (9000 tokens) exceeds the available context size (8192 tokens)")+ )+++def _gemma_style_counter(catalogue_tokens: int):+ """A counter that renders a lone tool result as nothing, as Gemma 4 does.++ Both bundled Gemma-4 templates skip `role: tool` in the message loop and emit the+ result only while scanning forward from the assistant tool call that asked for it, so+ a one-message slice renders byte-for-byte the same prompt as an empty one.+ """++ def count(messages):+ total = catalogue_tokens+ for index, message in enumerate(messages):+ if message.get("role") == "tool":+ previous = messages[index - 1] if index else None+ anchored = bool(previous) and (+ previous.get("role") == "tool"+ or (previous.get("role") == "assistant" and previous.get("tool_calls"))+ )+ if not anchored:+ continue+ total += max(1, len(json.dumps(message, ensure_ascii = False)) // 4)+ return total++ return count+++def _tool_loop_thread(+ turn_tokens: int,+ system_tokens: int = 200,+ history_turns: int = 6,+):+ """A tool loop caught mid-flight: the result of the call just made is last."""+ messages = [{"role": "system", "content": "s" * (system_tokens * 4)}]+ for index in range(history_turns):+ messages.append({"role": "user", "content": f"q{index} " + "x" * 1200})+ messages.append({"role": "assistant", "content": f"a{index} " + "y" * 1200})+ messages.append({"role": "user", "content": "read the file"})+ messages.append(+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {+ "id": "c1",+ "type": "function",+ "function": {"name": "read_file", "arguments": {"path": "big.txt"}},+ }+ ],+ }+ )+ messages.append(+ {+ "role": "tool",+ "tool_call_id": "c1",+ "name": "read_file",+ "content": "z" * (turn_tokens * 4),+ }+ )+ return messages+++ "turn_tokens,system_tokens,expected",+ [+ # Big enough to be the problem: the tool-specific advice must survive.+ (5000, 200, "Most of this prompt is a single tool result"),+ # And a small result beside instructions that do not fit is still not the result's+ # fault: the estimate must not invent a blame the count never earned.+ (20, 5000, "shorten the conversation"),+ ],+)+def test_a_turn_the_template_renders_as_nothing_is_not_counted_as_the_floor(+ turn_tokens, system_tokens, expected+):+ """A count no bigger than the empty prompt measured framing, not the turn.++ Gemma 4 renders a lone tool result as nothing, so the one-message slice succeeds and+ returns the floor exactly. Recording that as an exact turn size makes the turn worth+ ~0 once the floor comes off both sides, and a 5,000-token tool result reads as the+ conversation's fault. The remedy is to price the turn by DIFFERENCE against the prompt+ that was measured, which is still a tokenizer count of exactly its contribution.+ """+ _, truncation = fit_rolling_context(+ _tool_loop_thread(turn_tokens, system_tokens = system_tokens),+ context_length = 8192,+ max_tokens = None,+ count_tokens = _gemma_style_counter(1500),+ )+ assert truncation is not None and not truncation["fits"]+ # Not the floor reported as the turn: a number that moves with the result's size+ # instead of pinning to the 1,500-token catalogue.+ assert truncation["latest_turn_tokens"] != 1500+ # Counted by difference, so the floor IS recorded and comes off both sides, and what+ # is left is the turn's own contribution rather than a four-chars-a-token guess.+ assert truncation["shared_prompt_tokens"] == 1500+ assert truncation["latest_turn_exact"] is True+ # The payload plus its envelope (`tool_call_id`, `name`), and nothing else: 5,018 for+ # the big result and 38 for the small one, against a 1,500-token catalogue that used+ # to be the whole number.+ contribution = truncation["latest_turn_tokens"] - truncation["shared_prompt_tokens"]+ assert turn_tokens <= contribution <= turn_tokens + 100+ _context_truncated_sse_chunk("cmpl-1", "model", truncation)+ assert expected in _friendly_error(+ ValueError("the request (9000 tokens) exceeds the available context size (8192 tokens)")+ )+++# ------------------------------------------------- an estimate is not a measurement+++ "role,hard,soft",+ [+ ("user", "The message just sent does not fit on its own", "the message just sent"),+ ("tool", "A tool returned more than this context window can hold", "a single tool result"),+ (+ "assistant",+ "The reply being continued is already too long for this window",+ "the reply being continued",+ ),+ ("system", "The system instructions do not fit on their own", "the system instructions"),+ ],+)+def test_an_estimated_turn_names_no_turn_at_all(role, hard, soft):+ """Neither wording, because an estimate cannot be weighed against a count.++ The fallback `latest_turn_tokens` is `len(json.dumps(message)) // 4` while+ `irreducible_tokens` is a tokenizer count of the rendered prompt, so the dominance+ ratio compares a guess with a truth. Text that tokenises sparsely blows through the+ guess: on the bundled gemma-4 template with a real Gemma tokenizer, 16,400 characters+ of newlines estimate 8,207 tokens against 557 rendered, 14.8x. That alone clears the+ ratio against an 8,629-token prompt the turn is 6.5% of, beside a system prompt that+ is 93% of it -- and the softer wording is then a false attribution, not a hedge. It is+ not correctable either: escaped JSON runs the other way, 0.86x.++ The producer prices such a turn by difference now, so this flag is only ever False+ when nothing could be counted, and there the generic advice is the honest answer.+ """+ estimated = _refusal(irreducible = 5120, latest_turn = 5400, role = role) | {+ "latest_turn_exact": False+ }+ context_refusal.record_fit(estimated)+ message = _friendly_error(ValueError(_SERVER_ERROR))+ assert hard not in message+ assert f"Most of this prompt is {soft}" not in message+ # No turn named, so the advice is whichever generic branch fits. This refusal is+ # irreducible at its window, so it is the one that says shortening cannot work and+ # names the levers instead of a role.+ assert "Even with every earlier turn dropped" in message+ assert "the system prompt and any tools that are enabled" in message+++def test_a_measured_turn_still_gets_the_hard_wording():+ # The gate is provenance, not size: a counted turn over the window is unchanged.+ context_refusal.record_fit(+ _refusal(irreducible = 5120, latest_turn = 5400, role = "tool") | {"latest_turn_exact": True}+ )+ assert "A tool returned more than this context window can hold" in _friendly_error(+ ValueError(_SERVER_ERROR)+ )+++def test_a_payload_without_the_flag_is_read_as_a_count():+ # Absent means a producer that predates the flag, and every one of those counted.+ refusal = _refusal(irreducible = 5120, latest_turn = 5400, role = "tool")+ refusal.pop("latest_turn_exact", None)+ context_refusal.record_fit(refusal)+ assert "A tool returned more than this context window can hold" in _friendly_error(+ ValueError(_SERVER_ERROR)+ )+++def test_a_sparse_tool_result_is_blamed_for_no_more_than_it_rendered():+ """End to end on the Gemma shape, with a counter that tokenises whitespace runs.++ A real tokenizer merges long runs of whitespace into single tokens, so the JSON-length+ estimate the fit used to be forced onto for a lone `role: tool` message can clear the+ window while the rendered turn costs a fraction of it. Measured on the bundled+ gemma-4 template with a real Gemma tokenizer: 16,400 characters of newlines estimate+ 8,207 tokens and render 557, 14.8x, and a lone tool message renders to exactly the+ empty prompt.++ The band this pins is the one no estimate can survive. Here the turn is 29% of the+ prompt -- too small to blame, too large for the estimate's error to cancel out of a+ ratio -- so the refusal is real, an oversized system prompt is what the request died+ of, and the tool result is neither what could not be sent nor the bulk of the prompt.+ """++ def count(messages):+ total = 0+ for index, message in enumerate(messages):+ text = json.dumps(message, ensure_ascii = False)+ if message.get("role") == "tool":+ previous = messages[index - 1] if index else None+ if not (+ previous and previous.get("role") == "assistant" and previous.get("tool_calls")+ ):+ continue+ # Calibrated to the measurement above: 32,876 characters of escaped+ # JSON for this payload against 838 real tokens, so ~39 chars a token.+ total += max(1, len(text) // 39)+ else:+ total += max(1, len(text) // 4)+ return total++ thread = _tool_loop_thread(20, system_tokens = 2000, history_turns = 0)+ thread[-1]["content"] = ("\n" * 40 + "\t" * 40) * 205+ _, truncation = fit_rolling_context(+ thread, context_length = 2048, max_tokens = 512, count_tokens = count+ )+ assert truncation is not None and not truncation["fits"]+ # The estimate this replaced really would have blamed the turn: 8,218 against a+ # 2,899-token prompt clears the 0.66 share several times over.+ assert estimate_messages_tokens(thread[-1:]) >= 0.66 * truncation["irreducible_tokens"]+ # What it really contributed is 842 of 2,899, 29%, and it is a count, not a guess.+ assert truncation["latest_turn_exact"] is True+ contribution = truncation["latest_turn_tokens"] - truncation["shared_prompt_tokens"]+ assert contribution == count(thread) - count(thread[:-1])+ assert contribution < 0.4 * truncation["irreducible_tokens"]+ _context_truncated_sse_chunk("cmpl-1", "model", truncation)+ message = _friendly_error(+ ValueError("the request (2899 tokens) exceeds the available context size (2048 tokens)")+ )+ # Neither wording blames the tool result, and the advice names the parts eviction+ # never touches, which is where the 2,000-token system prompt actually is.+ assert "A tool returned more than this context window can hold" not in message+ assert "Most of this prompt is a single tool result" not in message+ assert "Even with every earlier turn dropped" in message+ assert "the system prompt and any tools that are enabled" in message+++def test_a_diagnosis_with_no_window_recorded_is_still_usable():+ # The server's own number stands in for the window it did not record.+ refusal = _refusal(irreducible = 5600, latest_turn = 5400)+ refusal.pop("context_length")+ context_refusal.record_fit(refusal)+ assert "does not fit on its own" in _friendly_error(ValueError(_SERVER_ERROR))++[email protected]("field", ["irreducible_tokens", "latest_turn_tokens"])+def test_a_diagnosis_missing_its_counts_falls_back(field):+ refusal = _refusal(irreducible = 5000, latest_turn = 4800)+ refusal[field] = 0+ context_refusal.record_fit(refusal)+ assert "shorten the conversation" in _friendly_error(ValueError(_SERVER_ERROR))+++def test_unparsable_counts_do_not_raise():+ refusal = _refusal(irreducible = 5000, latest_turn = 4800)+ refusal["irreducible_tokens"] = "lots"+ context_refusal.record_fit(refusal)+ assert "shorten the conversation" in _friendly_error(ValueError(_SERVER_ERROR))+++# ---------------------------------------------------------------- recording+++def test_a_fit_that_succeeded_clears_an_earlier_refusal():+ # A tool loop refuses on one iteration and fits on the next: no stale refusal.+ context_refusal.record_fit(_refusal(irreducible = 5000, latest_turn = 4800))+ context_refusal.record_fit({"fits": True, "dropped_messages": 4})+ assert context_refusal.latest_refusal() is None+ assert "shorten the conversation" in _friendly_error(ValueError(_SERVER_ERROR))+++def test_non_dict_events_are_ignored():+ context_refusal.record_fit(_refusal(irreducible = 5000, latest_turn = 4800))+ for value in (None, "fits", 7, ["fits"]):+ context_refusal.record_fit(value)+ assert context_refusal.latest_refusal() is not None+++def test_the_sse_chunk_records_the_refusal_it_forwards():+ refusal = _refusal(irreducible = 5000, latest_turn = 4800)+ line = _context_truncated_sse_chunk("cmpl-1", "model", refusal)+ assert "context_truncated" in line+ assert context_refusal.latest_refusal() == refusal+++def test_the_sse_chunk_clears_on_a_fit_that_succeeded():+ context_refusal.record_fit(_refusal(irreducible = 5000, latest_turn = 4800))+ _context_truncated_sse_chunk("cmpl-1", "model", {"fits": True, "dropped_messages": 2})+ assert context_refusal.latest_refusal() is None+++def test_the_drain_records_each_fit_not_the_running_total():+ # `_accumulate_context_truncation` sums `dropped_messages` across a tool loop, so the+ # refusal must be the per-fit event or it reports counts no fit produced.+ first = {"type": "context_truncated", "fits": True, "dropped_messages": 4}+ second = {"type": "context_truncated", **_refusal(irreducible = 5000, latest_turn = 4800)}+ combined = _accumulate_context_truncation(None, first)+ combined = _accumulate_context_truncation(combined, second)+ assert combined["dropped_messages"] == 4+ recorded = context_refusal.latest_refusal()+ assert recorded is not None+ assert recorded["dropped_messages"] == 0+ assert recorded["latest_turn_tokens"] == 4800+++def test_the_recorded_diagnosis_is_a_copy():+ refusal = _refusal(irreducible = 5000, latest_turn = 4800)+ context_refusal.record_fit(refusal)+ refusal["latest_turn_tokens"] = 1+ assert context_refusal.latest_refusal()["latest_turn_tokens"] == 4800+++# ---------------------------------------------------------------- worker threads+++def _record_in_worker():+ context_refusal.record_fit(_refusal(irreducible = 5600, latest_turn = 5400))+ return "drained"+++def _record_then_fail():+ _record_in_worker()+ raise ValueError(_SERVER_ERROR)+++async def _drain_like_the_route(func):+ """The exact shape both non-streaming GGUF drains use: a task around a thread.++ Two context copies between the record and the read, which is what makes the slot+ necessary. Anything less than this shape does not test the thing that broke.+ """+ task = asyncio.create_task(asyncio.to_thread(func))+ return await asyncio.shield(task)+++def test_without_a_slot_the_drain_loses_the_refusal():+ # The behaviour worked around: both copy the context, and a `.set()` in a copy never+ # reaches the request.+ async def _run():+ await _drain_like_the_route(_record_in_worker)+ return context_refusal.latest_refusal()++ assert asyncio.run(_run()) is None+++def test_a_slot_carries_the_refusal_back_through_task_and_thread():+ async def _run():+ context_refusal.open_slot()+ assert await _drain_like_the_route(_record_in_worker) == "drained"+ return context_refusal.latest_refusal()++ # Read inside the coroutine: `asyncio.run` gives it its own context copy, as a request+ # task does, and that is where `_friendly_error` reads from.+ assert asyncio.run(_run())["latest_turn_tokens"] == 5400+++def test_a_slot_carries_the_refusal_back_when_the_drain_raises():+ # The path that matters: the drain diagnoses, then raises the error that refusal+ # explains, so there is no return value to carry it back.+ async def _run():+ context_refusal.open_slot()+ with pytest.raises(ValueError):+ await _drain_like_the_route(_record_then_fail)+ return _friendly_error(ValueError(_SERVER_ERROR))++ assert "does not fit on its own" in asyncio.run(_run())+++def test_a_drain_that_records_nothing_leaves_the_slot_empty():+ def _quiet():+ return 1++ async def _run():+ context_refusal.open_slot()+ await _drain_like_the_route(_quiet)+ return context_refusal.latest_refusal()++ assert asyncio.run(_run()) is None+++def test_a_drain_that_fits_clears_an_earlier_refusal_through_the_slot():+ def _fits():+ context_refusal.record_fit({"fits": True, "dropped_messages": 3})++ async def _run():+ context_refusal.open_slot()+ context_refusal.record_fit(_refusal(irreducible = 5000, latest_turn = 4800))+ await _drain_like_the_route(_fits)+ return context_refusal.latest_refusal()++ assert asyncio.run(_run()) is None+++def test_opening_a_slot_starts_empty():+ # Two requests on one connection: the second must not inherit the first's refusal.+ context_refusal.record_fit(_refusal(irreducible = 5000, latest_turn = 4800))+ context_refusal.open_slot()+ assert context_refusal.latest_refusal() is None+++def test_both_non_streaming_gguf_drains_open_a_slot_first():+ # Dropping either `open_slot` would silently restore the generic advice.+ source = (Path(_BACKEND_DIR) / "routes" / "inference.py").read_text(encoding = "utf-8")+ for drain in ("_drain_gguf_tool_loop", "_drain_gguf_choices"):+ spawn = f"asyncio.create_task(asyncio.to_thread({drain}))"+ assert spawn in source+ preceding = source.split(spawn)[0].splitlines()[-4:]+ assert any("context_refusal.open_slot()" in line for line in preceding)+++# ---------------------------------------------------------- streaming tool loops+++def _respawn_refit_then_refused():+ """A tool generator that fits, respawns, refits into a refusal, then is refused.++ The refit runs inside the generator, i.e. inside the worker thread the stream loop+ drives it from, and the prompt that FIT emitted no `context_truncated` event, so+ nothing recorded out in the stream's own context first.+ """+ yield "the first tokens, before llama-server died"+ context_refusal.record_fit(_refusal(irreducible = 5600, latest_turn = 5400, role = "tool"))+ raise ValueError(_SERVER_ERROR)+++async def _stream_like_the_tool_route(*, with_slot: bool):+ """The shape both streaming tool loops use: a task around a thread, per event.++ The message is built in this generator's own `except`, which is where the slot has+ to be visible; anything less than this shape does not test the thing that broke.+ """+ sentinel = object()+ if with_slot:+ context_refusal.open_slot()+ gen = _respawn_refit_then_refused()+ try:+ while True:+ next_task = asyncio.create_task(asyncio.to_thread(next, gen, sentinel))+ event = await asyncio.shield(next_task)+ if event is sentinel:+ break+ yield event+ except ValueError as exc:+ yield _friendly_error(exc)+++def _drive(*, with_slot: bool) -> str:+ async def _run():+ async def _consume():+ return [chunk async for chunk in _stream_like_the_tool_route(with_slot = with_slot)]++ # Iterated from a task of its own, as a streaming response body is.+ return await asyncio.create_task(_consume())++ return asyncio.run(_run())[-1]+++def test_a_streaming_tool_loop_without_a_slot_loses_the_respawn_refusal():+ # The regression: two context copies between the refit and the message, and no slot+ # in the stream's own context because the prompt that fit recorded nothing there.+ message = _drive(with_slot = False)+ assert "shorten the conversation" in message, message+ assert "tool" not in message, message+++def test_a_streaming_tool_loop_with_a_slot_keeps_the_respawn_refusal():+ message = _drive(with_slot = True)+ assert "A tool returned more than this context window can hold" in message, message+ assert "ask for a smaller slice of the file or page" in message, message+++def test_both_streaming_tool_loops_open_a_slot_first():+ """Only the loops that drive the tool generator: it owns the respawn refit.++ The no-tool streams reach `generate_chat_completion`, which has no refit callback,+ and their own fit is recorded out in the stream where the message is built.+ """+ source = (Path(_BACKEND_DIR) / "routes" / "inference.py").read_text(encoding = "utf-8")+ loops = (+ ("async def gguf_tool_stream():", "gen = gguf_generate_with_tools()"),+ ("async def _anthropic_tool_stream(", "gen = run_gen()"),+ )+ for header, spawn in loops:+ body = source.split(header, 1)[1]+ assert spawn in body, header+ assert "context_refusal.open_slot()" in body.split(spawn, 1)[0], header+++def test_other_friendly_errors_are_untouched():+ assert _friendly_error(RuntimeError("unrelated")) == "An internal error occurred"+ assert "Lost connection" in _friendly_error(RuntimeError("Lost connection to llama-server"))diff --git a/studio/backend/tests/test_context_refusal_units.py b/studio/backend/tests/test_context_refusal_units.pynew file mode 100644index 00000000000..045915b7d3a--- /dev/null+++ b/studio/backend/tests/test_context_refusal_units.py@@ -0,0 +1,206 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Two regressions the refusal diagnosis still carries.++`test_an_estimated_turn_never_claims_to_be_most_of_the_prompt` is item A: the dominance+ratio weighs a four-characters-a-token GUESS against a real tokenizer COUNT.+`test_a_respawn_refit_that_refuses_is_not_lost_when_the_retry_is_refused` is item B: a+refit that refuses after a respawn is never recorded, so the retry's own context error+falls back to the generic advice.+"""++import contextlib++import httpx+import pytest++from core.inference import context_refusal+from core.inference.context_window import fit_rolling_context+++# Measured on the real `studio/backend/assets/chat_templates/gemma-4.jinja` with the real+# unsloth/gemma-3-270m-it tokenizer, so the fake counter below reproduces numbers that+# actually occur rather than numbers chosen to fail:+# empty prompt 16 tokens+# the system prompt alone 8009 tokens+# a 16,400-character newline tool result 557 tokens rendered, 8207 ESTIMATED (14.8x)+# the whole conversation 8629 tokens+_FLOOR = 16+_SYSTEM = 8009+_USER = 30+_CALL = 17+_TOOL = 557+++def _gemma_like_counter(messages: list[dict]) -> int:+ """A counter that renders like gemma-4: a LONE tool message renders as nothing."""+ if len(messages) == 1 and messages[0].get("role") == "tool":+ return _FLOOR+ total = _FLOOR+ for message in messages:+ total += {+ "system": _SYSTEM,+ "user": _USER,+ "assistant": _CALL,+ "tool": _TOOL,+ }[message["role"]]+ return total+++def _sparse_tool_conversation() -> list[dict]:+ return [+ {"role": "system", "content": "s" * 32000},+ {"role": "user", "content": "Read the log and tell me what broke."},+ {"role": "assistant", "content": "", "tool_calls": [{"id": "1"}]},+ # 16,400 newlines: 32,829 characters of JSON, so 8,207 estimated tokens.+ {"role": "tool", "content": "\n" * 16400},+ ]+++def test_an_estimated_turn_never_claims_to_be_most_of_the_prompt():+ """The tool result is 6.5% of this prompt and the system prompt is 93% of it.++ `latest_turn_tokens` is an estimate over the message's JSON while+ `irreducible_tokens` is a tokenizer count of the rendered prompt, so the dominance+ ratio compares a guess against a truth and blames the turn that is nearly absent.+ """+ messages = _sparse_tool_conversation()+ context_length = 8192++ _fitted, truncation = fit_rolling_context(+ messages,+ context_length = context_length,+ max_tokens = 512,+ count_tokens = _gemma_like_counter,+ )+ assert truncation is not None and truncation["fits"] is False+ assert truncation["irreducible_tokens"] == 8629, "a real count of the rendered prompt"+ # The four-characters-a-token estimate of this message is 8207, 14.8x the 557 it+ # really renders to, and weighing that against a real count is what blames it.+ assert truncation["latest_turn_exact"] is True+ assert truncation["latest_turn_tokens"] - truncation["shared_prompt_tokens"] == 557++ context_refusal.open_slot()+ try:+ context_refusal.record_fit(truncation)+ message = context_refusal.describe_oversize(8629, context_length)+ finally:+ context_refusal.clear()++ assert "Most of this prompt is a single tool result" not in message, message+ assert "ask for a smaller slice" not in message, message+ # The truth here is the branch that names the parts eviction never touches.+ assert "shortening the conversation will not help" in message, message+++def test_a_dominant_tool_result_still_gets_the_tool_advice():+ """The counterweight: an estimated turn that really IS the prompt keeps its advice.++ Same conversation with no system prompt, so the 557-token tool result is 93% of what+ is left. Gating the dominance test on `latest_turn_exact` would send this back to the+ generic wording, which is the loss the estimate branch exists to prevent.+ """+ messages = [message for message in _sparse_tool_conversation() if message["role"] != "system"]+ context_length = 512++ _fitted, truncation = fit_rolling_context(+ messages,+ context_length = context_length,+ max_tokens = 64,+ count_tokens = _gemma_like_counter,+ )+ assert truncation is not None and truncation["fits"] is False++ context_refusal.open_slot()+ try:+ context_refusal.record_fit(truncation)+ message = context_refusal.describe_oversize(+ truncation["irreducible_tokens"], context_length+ )+ finally:+ context_refusal.clear()++ # 557 rendered tokens against a 512-token window, so it earns the flat wording; what+ # matters is that the tool-specific advice survives an unrenderable lone slice.+ assert "A tool returned more than this context window can hold" in message, message+ assert "ask for a smaller slice of the file or page" in message, message+++def test_a_respawn_refit_that_refuses_is_not_lost_when_the_retry_is_refused():+ """A refused refit is only forwarded from INSIDE the reopened stream.++ `_refit_*_after_respawn` appends its refusal to `_respawn_truncations`, but the+ consumer drains that list INSIDE the `with` block, so a retry refused at the door+ raises before any `context_truncated` event exists. `_friendly_error` then has no+ diagnosis and tells the user to shorten a conversation that is already irreducible.+ """+ from core.inference.llama_cpp import LlamaCppBackend++ backend = object.__new__(LlamaCppBackend)+ backend._port = 1+ backend._maybe_recover_from_mtp_crash = lambda _exc: False+ backend._respawn_if_dead = lambda: True++ attempts = {"n": 0}++ @contextlib.contextmanager+ def _open_stream(_url, _payload, _cancel_event):+ attempts["n"] += 1+ if attempts["n"] == 1:+ raise httpx.ReadError("llama-server died mid-request")+ # The replacement server came back with a smaller n_ctx and refused the prompt+ # the refit could not shrink.+ raise RuntimeError(+ 'llama-server returned 400: {"error":{"code":400,"message":"the request '+ 'exceeds the available context size...","type":"exceed_context_size_error",'+ '"n_prompt_tokens":6000,"n_ctx":4096}}'+ )++ backend._open_stream = _open_stream++ refit_ran = {"value": False}+ forwarded = {"value": False}++ def _on_respawn() -> None:+ # Stands in for the real callback, which refits against the smaller replacement+ # window and is refused. The companion test below pins that the real callbacks+ # record it; this one pins that recording is the ONLY thing that can carry it,+ # because the forwarding loop lives inside a stream that is never opened.+ refit_ran["value"] = True+ context_refusal.record_fit({"fits": False, "context_length": 4096})++ context_refusal.open_slot()+ try:+ with pytest.raises(RuntimeError, match = "exceed_context_size_error"):+ with backend._open_chat_stream_with_respawn_retry({}, None, on_respawn = _on_respawn):+ forwarded["value"] = True++ assert attempts["n"] == 2+ assert refit_ran["value"] is True+ assert forwarded["value"] is False, "the forwarding loop never runs on this path"++ refusal = context_refusal.latest_refusal()+ assert refusal is not None, "the respawn refit's refusal has to survive the retry"+ assert refusal.get("fits") is False+ finally:+ context_refusal.clear()+++def test_the_respawn_refits_record_the_refusal_rather_than_only_forwarding_it():+ """Structural pin for the two callsites the behavioural test cannot reach.++ Both refit callbacks live inside `generate_chat_completion_with_tools`, so the only+ way to hold them to recording a refusal is to read them.+ """+ import inspect++ from core.inference.llama_cpp import LlamaCppBackend++ body = inspect.getsource(LlamaCppBackend.generate_chat_completion_with_tools)+ for callback in ("_refit_iteration_after_respawn", "_refit_final_after_respawn"):+ start = body.index(f"def {callback}(")+ chunk = body[start : start + 4000]+ assert (+ "context_refusal.record_fit(truncation)" in chunk+ ), f"{callback} must record the fit itself; forwarding is gated on `fits`"diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex e4f74eff384..33c49cb54e3 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -582,8 +582,8 @@ export function useThreadAutosaveHandle(): ThreadAutosaveHandle {* "the request exceeds the available context size (N tokens)".* 2. The friendly rewrite from* ``backend/routes/inference.py::_friendly_error``: "Message too long:- * ... context window. Try increasing the Context Length ..." (the one- * most users see on the streaming GGUF path).+ * ... context window. ..." (the one most users see on the streaming GGUF+ * path). Its advice branches, so only the lead-in is stable to match on.** Match substrings, not full regexes: both layers have drifted across* versions (llama.cpp phrasing and _friendly_error copy edits).@@ -7112,8 +7112,17 @@ export function createOpenAIStreamAdapter(// send the user to a new chat that fails identically.const budget =irreducible?.prompt_target ?? irreducible?.context_length ?? 0;+ // `latest_turn_exact: false` means nothing could price the turn at all, so+ // the count is the message's own JSON at four characters a token. Whitespace+ // runs and escaped JSON tokenise several times denser than that, so printing+ // it as "N tokens on its own" states a number the turn never cost. A turn the+ // template renders as NOTHING on its own is not this case: the server prices+ // that by difference against the prompt it measured and reports it exact.+ // Absent means a server that predates the flag, which only ever sent a count.const oneTurnIsTheProblem =- irreducible != null && (irreducible.latest_turn_tokens ?? 0) > budget;+ irreducible != null &&+ (irreducible.latest_turn_tokens ?? 0) > budget &&+ (irreducible.latest_turn_exact ?? true);// Whose turn it is decides the advice: in a tool loop the offending turn is// often output the user never wrote and cannot edit, so "shorten this// message" names the wrong thing and offers no remedy.diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.tsindex 5417384b771..be1c199dbb4 100644--- a/studio/frontend/src/features/chat/types/api.ts+++ b/studio/frontend/src/features/chat/types/api.ts@@ -752,6 +752,11 @@ export interface OpenAIChatChunk {// that one message is the problem, i.e. whether "shorten the conversation" helps.irreducible_tokens?: number;latest_turn_tokens?: number;+ // Whether `latest_turn_tokens` is a real token count or the four-characters-a-token+ // estimate the fit falls back to when nothing could price the turn at all. A turn the+ // template renders as nothing on its own is priced by difference and stays exact.+ // Only the counted one may be quoted as the turn's size.+ latest_turn_exact?: boolean;// Where the compaction boundary sits in the messages THIS request was sent with.// Absolute, unlike dropped_messages, so re-sending it after a turn that refit several// times cannot advance the boundary past the turns actually evicted.diff --git a/studio/frontend/src/features/chat/utils/context-truncation.ts b/studio/frontend/src/features/chat/utils/context-truncation.tsindex b0a7cc48f92..9fa92a5f04a 100644--- a/studio/frontend/src/features/chat/utils/context-truncation.ts+++ b/studio/frontend/src/features/chat/utils/context-truncation.ts@@ -77,6 +77,9 @@ export function mergeContextTruncation(if (incoming.fits) {delete merged.irreducible_tokens;delete merged.latest_turn_tokens;+ // Rides with the count it describes: alone it says nothing, and left behind it would+ // describe a number that is no longer there.+ delete merged.latest_turn_exact;}return merged;}