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.

Studio: add rolling context windows for local GGUF chat (#8961)

alkinun645ca5c7bdb9
diff --git a/studio/backend/core/inference/context_window.py b/studio/backend/core/inference/context_window.py
new file mode 100644
index 00000000000..e25a5e21bd8
--- /dev/null
+++ b/studio/backend/core/inference/context_window.py
@@ -0,0 +1,198 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Message-aware rolling context helpers for local chat inference."""
+
+from __future__ import annotations
+
+import json
+from collections.abc import Callable
+from typing import Any, Optional
+
+_OMITTED_TOOL_EXCHANGE = "[Earlier tool exchange omitted from the rolling context window.]"
+
+
+def estimate_message_tokens(message: dict) -> int:
+ try:
+ return max(1, len(json.dumps(message, ensure_ascii = False)) // 4)
+ except Exception:
+ return 1
+
+
+def estimate_messages_tokens(messages: list[dict]) -> int:
+ return sum(estimate_message_tokens(message) for message in messages)
+
+
+def truncate_oldest_messages(
+ messages: list[dict],
+ keep_ratio: float,
+ *,
+ protected_message_ids: Optional[set[int]] = None,
+) -> tuple[list[dict], int]:
+ """Drop complete oldest turns while preserving system messages and the latest turn.
+
+ Normal user/assistant turns stay together. Each assistant tool call starts a
+ separate group containing its tool results, so long agent runs can evict old
+ exchanges without orphaning results or losing the task that initiated them.
+ """
+ if not messages or keep_ratio >= 1.0:
+ return messages, 0
+
+ groups: list[list[dict]] = []
+ for message in messages:
+ starts_tool_exchange = message.get("role") == "assistant" and bool(
+ message.get("tool_calls")
+ )
+ follows_instruction = bool(groups and groups[-1][0].get("role") in ("system", "developer"))
+ if (
+ message.get("role") in ("system", "developer", "user")
+ or starts_tool_exchange
+ or follows_instruction
+ ):
+ groups.append([message])
+ elif not groups:
+ groups.append([message])
+ else:
+ groups[-1].append(message)
+
+ if len(groups) <= 1:
+ return messages, 0
+
+ estimates = {id(message): estimate_message_tokens(message) for message in messages}
+ current_estimate = sum(estimates.values())
+ target_estimate = int(current_estimate * max(0.0, keep_ratio))
+ dropped = 0
+ protected_ids = protected_message_ids or set()
+ latest_user_group = next(
+ (
+ index
+ for index in range(len(groups) - 1, -1, -1)
+ if any(message.get("role") == "user" for message in groups[index])
+ ),
+ None,
+ )
+ protected_groups = {
+ index
+ for index, group in enumerate(groups)
+ if index == len(groups) - 1
+ or index == latest_user_group
+ or any(message.get("role") in ("system", "developer") for message in group)
+ or any(id(message) in protected_ids for message in group)
+ }
+ eviction_units: list[list[int]] = []
+ index = 0
+ while index < len(groups):
+ if index in protected_groups:
+ index += 1
+ continue
+ unit = [index]
+ starts_user_turn = groups[index][0].get("role") == "user"
+ next_index = index + 1
+ if starts_user_turn:
+ while next_index < len(groups) and groups[next_index][0].get("role") not in (
+ "system",
+ "developer",
+ "user",
+ ):
+ unit.append(next_index)
+ next_index += 1
+ if not any(group_index in protected_groups for group_index in unit):
+ eviction_units.append(unit)
+ index = next_index if starts_user_turn else index + 1
+
+ dropped_groups: set[int] = set()
+ for unit in eviction_units:
+ if current_estimate <= target_estimate:
+ break
+ dropped_groups.update(unit)
+ for group_index in unit:
+ group = groups[group_index]
+ dropped += len(group)
+ current_estimate -= sum(estimates[id(message)] for message in group)
+
+ if dropped == 0:
+ return messages, 0
+
+ kept: list[dict] = []
+ for index, group in enumerate(groups):
+ if index not in dropped_groups:
+ if kept and kept[-1].get("role") == "user" and group and group[0].get("role") == "user":
+ # Strict chat templates reject adjacent user turns. This occurs when
+ # an internal tool re-prompt follows an evicted exchange.
+ kept.append({"role": "assistant", "content": _OMITTED_TOOL_EXCHANGE})
+ kept.extend(group)
+ return kept, dropped
+
+
+def messages_have_media(messages: list[dict]) -> bool:
+ for message in messages:
+ content = message.get("content")
+ if not isinstance(content, list):
+ continue
+ for part in content:
+ if not isinstance(part, dict):
+ continue
+ # `input_video` is llama.cpp's own part type, written by `_inject_video_part`
+ # into the same message list this fit then sees. Missing from the list, a video
+ # prompt ran the rolling preflight even though `/apply-template` does not count
+ # the sampled video tokens, so it could be certified as fitting when it does
+ # not, or lose history it did not need to lose.
+ if part.get("type") in (
+ "image_url",
+ "input_audio",
+ "audio",
+ "input_image",
+ "input_video",
+ ):
+ return True
+ return False
+
+
+def fit_rolling_context(
+ messages: list[dict],
+ *,
+ context_length: int,
+ max_tokens: Optional[int],
+ count_tokens: Callable[[list[dict]], int],
+ protected_message_ids: Optional[set[int]] = None,
+) -> tuple[list[dict], Optional[dict[str, Any]]]:
+ """Fit a chat into its real context by dropping oldest complete turns.
+
+ The exact tokenizer/template count decides whether trimming is needed. The
+ inexpensive estimator only chooses candidate turns; exact recounts verify the
+ result. The current turn is never clipped, so an irreducibly large request still
+ reaches llama-server's normal context-length error.
+ """
+ if context_length <= 1:
+ return messages, None
+
+ requested_headroom = max_tokens if max_tokens is not None and max_tokens > 0 else context_length
+ output_headroom = min(requested_headroom, max(1, context_length // 4))
+ prompt_target = context_length - output_headroom
+ fitted = list(messages)
+ initial_tokens = count_tokens(fitted)
+ current_tokens = initial_tokens
+ dropped_total = 0
+
+ while current_tokens > prompt_target:
+ keep_ratio = min(0.95, prompt_target / max(1, current_tokens))
+ candidate, dropped = truncate_oldest_messages(
+ fitted,
+ keep_ratio,
+ protected_message_ids = protected_message_ids,
+ )
+ if dropped == 0:
+ break
+ fitted = candidate
+ dropped_total += dropped
+ current_tokens = count_tokens(fitted)
+
+ if dropped_total == 0 or current_tokens > prompt_target:
+ return messages, None
+ return fitted, {
+ "dropped_messages": dropped_total,
+ "prompt_tokens_before": initial_tokens,
+ "prompt_tokens_after": current_tokens,
+ "context_length": context_length,
+ "fits": True,
+ }
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 2cc8fb0f211..38ed378b10e 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -49,6 +49,7 @@ from typing import (
import httpx
+from core.inference.context_window import fit_rolling_context, messages_have_media
from core.inference.llama_server_args import (
_GPU_LAYER_FLAGS,
_LAYER_OFFLOAD_FLAGS,
@@ -21332,7 +21333,12 @@ class LlamaCppBackend:
return started
@contextlib.contextmanager
- def _open_chat_stream_with_respawn_retry(self, payload: dict, cancel_event):
+ def _open_chat_stream_with_respawn_retry(
+ self,
+ payload: dict,
+ cancel_event,
+ on_respawn: Optional[Callable[[], None]] = None,
+ ):
"""Open a chat stream, respawning a dead llama-server once before streaming.
Retry only when opening the response fails: once it is open a consumer may
@@ -21366,6 +21372,8 @@ class LlamaCppBackend:
logger.warning(
"llama-server was unreachable; respawned it and retrying the generation"
)
+ if on_respawn is not None:
+ on_respawn()
continue
raise
@@ -21389,6 +21397,7 @@ class LlamaCppBackend:
seed: Optional[int] = None,
promote_reasoning_only: bool = True,
perf_callback: Optional[Callable[[dict], None]] = None,
+ context_overflow: Optional[str] = None,
_allow_respawn_retry: bool = True,
) -> Generator[Union[str, dict], None, None]:
"""
@@ -21425,6 +21434,11 @@ class LlamaCppBackend:
"repeat_penalty": repetition_penalty,
"presence_penalty": presence_penalty,
}
+ retry_messages = messages
+ retry_image_b64 = image_b64
+ retry_max_tokens = max_tokens
+ retry_context_overflow = context_overflow
+ retry_preflight_context_length = None
if perf_callback is not None:
payload["return_progress"] = True
payload["timings_per_token"] = True
@@ -21444,6 +21458,40 @@ class LlamaCppBackend:
if max_tokens is not None
else (self._effective_context_length or _DEFAULT_MAX_TOKENS_FLOOR)
)
+ if (
+ context_overflow == "truncate_oldest"
+ and self._effective_context_length
+ and not messages_have_media(openai_messages)
+ ):
+ try:
+ openai_messages, truncation = fit_rolling_context(
+ openai_messages,
+ context_length = self._effective_context_length,
+ max_tokens = payload["max_tokens"],
+ count_tokens = lambda fitted: self.count_chat_tokens(
+ neutralize_control_markup_in_messages(fitted, None, self.markup_profile),
+ None,
+ None,
+ strict = True,
+ chat_template_kwargs = _reasoning_kw,
+ continue_final_message = continue_final_message,
+ should_abort = lambda: bool(cancel_event and cancel_event.is_set()),
+ ),
+ )
+ payload["messages"] = neutralize_control_markup_in_messages(
+ openai_messages, None, self.markup_profile
+ )
+ # Reuse the exact fitted request after a respawn. Re-running this
+ # preflight would emit the same truncation event a second time.
+ retry_messages = openai_messages
+ retry_image_b64 = None
+ retry_max_tokens = payload["max_tokens"]
+ retry_context_overflow = None
+ retry_preflight_context_length = self._effective_context_length
+ if truncation and truncation["fits"]:
+ yield {"type": "context_truncated", **truncation}
+ except Exception as exc:
+ logger.warning("Could not preflight the rolling context window: %s", exc)
if stop:
payload["stop"] = stop
if seed is not None:
@@ -21576,14 +21624,23 @@ class LlamaCppBackend:
logger.warning(
"llama-server was unreachable; respawned it and retrying the generation"
)
+ if (
+ retry_preflight_context_length is not None
+ and retry_preflight_context_length != self._effective_context_length
+ ):
+ # Refit the already-compacted prompt against a replacement server's
+ # actual window. Any event now reports only additional evictions.
+ retry_context_overflow = context_overflow
+ if max_tokens is None:
+ retry_max_tokens = None
yield from self.generate_chat_completion(
- messages,
- image_b64 = image_b64,
+ retry_messages,
+ image_b64 = retry_image_b64,
temperature = temperature,
top_p = top_p,
top_k = top_k,
min_p = min_p,
- max_tokens = max_tokens,
+ max_tokens = retry_max_tokens,
repetition_penalty = repetition_penalty,
presence_penalty = presence_penalty,
stop = stop,
@@ -21595,6 +21652,7 @@ class LlamaCppBackend:
seed = seed,
promote_reasoning_only = promote_reasoning_only,
perf_callback = perf_callback,
+ context_overflow = retry_context_overflow,
_allow_respawn_retry = False,
)
return
@@ -21639,6 +21697,7 @@ class LlamaCppBackend:
permission_mode: Optional[str] = None,
promote_reasoning_only: bool = True,
perf_callback: Optional[Callable[[dict], None]] = None,
+ context_overflow: Optional[str] = None,
) -> Generator[dict, None, None]:
"""
Agentic loop: let the model call tools, execute them, and continue.
@@ -21680,6 +21739,11 @@ class LlamaCppBackend:
raise RuntimeError("llama-server is not loaded")
conversation = list(messages)
+ _rolling_anchor_ids: set[int] = set()
+ for message in reversed(conversation):
+ if message.get("role") == "user":
+ _rolling_anchor_ids.add(id(message))
+ break
def _attach_internal_feedback_to_tool_result(feedback: str) -> bool:
"""Keep controller instructions inside the current tool exchange."""
@@ -21918,6 +21982,43 @@ class LlamaCppBackend:
neutralize_control_markup_in_messages,
)
+ _reasoning_kw = self._request_reasoning_kwargs(
+ enable_thinking, reasoning_effort, preserve_thinking
+ )
+ _preflight_context_length = None
+ _preflight_succeeded = False
+ if (
+ context_overflow == "truncate_oldest"
+ and self._effective_context_length
+ and not messages_have_media(conversation)
+ ):
+ _preflight_context_length = self._effective_context_length
+ try:
+ conversation, truncation = fit_rolling_context(
+ conversation,
+ context_length = self._effective_context_length,
+ max_tokens = max_tokens,
+ count_tokens = lambda fitted: self.count_chat_tokens(
+ neutralize_control_markup_in_messages(
+ fitted, _markup_cache, self.markup_profile
+ ),
+ None,
+ safe_tools,
+ strict = True,
+ chat_template_kwargs = _reasoning_kw,
+ continue_final_message = bool(
+ continue_final_message and trailing_assistant_text(fitted)
+ ),
+ should_abort = lambda: bool(cancel_event and cancel_event.is_set()),
+ ),
+ protected_message_ids = _rolling_anchor_ids,
+ )
+ if truncation and truncation["fits"]:
+ yield {"type": "context_truncated", **truncation}
+ _preflight_succeeded = True
+ except Exception as exc:
+ logger.warning("Could not preflight the rolling context window: %s", exc)
+
payload = {
# Re-run every iteration: tool results land in ``conversation`` as the
# loop goes, and a forged turn in one would render for real (#7066).
@@ -21942,9 +22043,6 @@ class LlamaCppBackend:
if safe_tools:
payload["tools"] = safe_tools
payload["tool_choice"] = "auto"
- _reasoning_kw = self._request_reasoning_kwargs(
- enable_thinking, reasoning_effort, preserve_thinking
- )
if _reasoning_kw is not None:
payload["chat_template_kwargs"] = _reasoning_kw
# Re-checked per iteration: once a tool result is appended the partial is
@@ -21962,6 +22060,50 @@ class LlamaCppBackend:
if seed is not None:
payload["seed"] = seed
+ _respawn_truncations: list[dict] = []
+
+ def _refit_iteration_after_respawn() -> None:
+ nonlocal conversation
+ if (
+ _preflight_context_length is None
+ or not self._effective_context_length
+ or (
+ _preflight_succeeded
+ and _preflight_context_length == self._effective_context_length
+ )
+ ):
+ return
+ if max_tokens is None:
+ payload["max_tokens"] = self._effective_context_length
+ try:
+ conversation, truncation = fit_rolling_context(
+ conversation,
+ context_length = self._effective_context_length,
+ max_tokens = max_tokens,
+ count_tokens = lambda fitted: self.count_chat_tokens(
+ neutralize_control_markup_in_messages(
+ fitted, _markup_cache, self.markup_profile
+ ),
+ None,
+ safe_tools,
+ strict = True,
+ chat_template_kwargs = _reasoning_kw,
+ continue_final_message = bool(
+ continue_final_message and trailing_assistant_text(fitted)
+ ),
+ should_abort = lambda: bool(cancel_event and cancel_event.is_set()),
+ ),
+ protected_message_ids = _rolling_anchor_ids,
+ )
+ payload["messages"] = neutralize_control_markup_in_messages(
+ conversation, _markup_cache, self.markup_profile
+ )
+ if truncation and truncation["fits"]:
+ _respawn_truncations.append(truncation)
+ except Exception as exc:
+ logger.warning("Could not refit rolling context after respawn: %s", exc)
+ raise
+
try:
# ── Speculative buffer state machine ──────────────────
# BUFFERING: accumulate content, check for tool signals
@@ -22010,10 +22152,16 @@ class LlamaCppBackend:
_text_args_name = ""
_confirm_gated_iteration = bool(confirm_tool_calls) and not bypass_permissions
- with self._open_chat_stream_with_respawn_retry(payload, cancel_event) as (
+ with self._open_chat_stream_with_respawn_retry(
+ payload,
+ cancel_event,
+ on_respawn = _refit_iteration_after_respawn,
+ ) as (
response,
first_token_deadline,
):
+ for truncation in _respawn_truncations:
+ yield {"type": "context_truncated", **truncation}
raw_buf = ""
for raw_chunk in self._iter_text_cancellable(
response,
@@ -23142,6 +23290,43 @@ class LlamaCppBackend:
# Final streaming pass with the full conversation context.
from core.inference.chat_template_helpers import neutralize_control_markup_in_messages
+ _reasoning_kw = self._request_reasoning_kwargs(
+ enable_thinking, reasoning_effort, preserve_thinking
+ )
+ _final_max_tokens = (
+ max_tokens
+ if max_tokens is not None
+ else (self._effective_context_length or _DEFAULT_MAX_TOKENS_FLOOR)
+ )
+ _final_preflight_context_length = None
+ _final_preflight_succeeded = False
+ if (
+ context_overflow == "truncate_oldest"
+ and self._effective_context_length
+ and not messages_have_media(conversation)
+ ):
+ _final_preflight_context_length = self._effective_context_length
+ try:
+ conversation, truncation = fit_rolling_context(
+ conversation,
+ context_length = self._effective_context_length,
+ max_tokens = _final_max_tokens,
+ count_tokens = lambda fitted: self.count_chat_tokens(
+ neutralize_control_markup_in_messages(fitted, None, self.markup_profile),
+ None,
+ None,
+ strict = True,
+ chat_template_kwargs = _reasoning_kw,
+ should_abort = lambda: bool(cancel_event and cancel_event.is_set()),
+ ),
+ protected_message_ids = _rolling_anchor_ids,
+ )
+ if truncation and truncation["fits"]:
+ yield {"type": "context_truncated", **truncation}
+ _final_preflight_succeeded = True
+ except Exception as exc:
+ logger.warning("Could not preflight the rolling context window: %s", exc)
+
stream_payload = {
"messages": neutralize_control_markup_in_messages(
conversation, None, self.markup_profile
@@ -23154,16 +23339,9 @@ class LlamaCppBackend:
"repeat_penalty": repetition_penalty,
"presence_penalty": presence_penalty,
}
- _reasoning_kw = self._request_reasoning_kwargs(
- enable_thinking, reasoning_effort, preserve_thinking
- )
if _reasoning_kw is not None:
stream_payload["chat_template_kwargs"] = _reasoning_kw
- stream_payload["max_tokens"] = (
- max_tokens
- if max_tokens is not None
- else (self._effective_context_length or _DEFAULT_MAX_TOKENS_FLOOR)
- )
+ stream_payload["max_tokens"] = _final_max_tokens
if stop:
stream_payload["stop"] = stop
if seed is not None:
@@ -23174,6 +23352,45 @@ class LlamaCppBackend:
stream_payload["return_progress"] = True
stream_payload["timings_per_token"] = True
+ _final_respawn_truncations: list[dict] = []
+
+ def _refit_final_after_respawn() -> None:
+ nonlocal conversation
+ if (
+ _final_preflight_context_length is None
+ or not self._effective_context_length
+ or (
+ _final_preflight_succeeded
+ and _final_preflight_context_length == self._effective_context_length
+ )
+ ):
+ return
+ if max_tokens is None:
+ stream_payload["max_tokens"] = self._effective_context_length
+ try:
+ conversation, truncation = fit_rolling_context(
+ conversation,
+ context_length = self._effective_context_length,
+ max_tokens = max_tokens,
+ count_tokens = lambda fitted: self.count_chat_tokens(
+ neutralize_control_markup_in_messages(fitted, None, self.markup_profile),
+ None,
+ None,
+ strict = True,
+ chat_template_kwargs = _reasoning_kw,
+ should_abort = lambda: bool(cancel_event and cancel_event.is_set()),
+ ),
+ protected_message_ids = _rolling_anchor_ids,
+ )
+ stream_payload["messages"] = neutralize_control_markup_in_messages(
+ conversation, None, self.markup_profile
+ )
+ if truncation and truncation["fits"]:
+ _final_respawn_truncations.append(truncation)
+ except Exception as exc:
+ logger.warning("Could not refit rolling context after respawn: %s", exc)
+ raise
+
cumulative = ""
_last_emitted = ""
in_thinking = False
@@ -23187,10 +23404,16 @@ class LlamaCppBackend:
_stream_done = False
try:
- with self._open_chat_stream_with_respawn_retry(stream_payload, cancel_event) as (
+ with self._open_chat_stream_with_respawn_retry(
+ stream_payload,
+ cancel_event,
+ on_respawn = _refit_final_after_respawn,
+ ) as (
response,
first_token_deadline,
):
+ for truncation in _final_respawn_truncations:
+ yield {"type": "context_truncated", **truncation}
buffer = ""
for raw_chunk in self._iter_text_cancellable(
response,
@@ -23310,6 +23533,7 @@ class LlamaCppBackend:
tools = None,
strict: bool = False,
chat_template_kwargs = None,
+ continue_final_message: bool = False,
should_abort = None,
) -> int:
"""Count prompt tokens for a chat request via llama-server.
@@ -23410,6 +23634,9 @@ class LlamaCppBackend:
# 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
+ if continue_final_message:
+ template_body["continue_final_message"] = True
+ template_body["add_generation_prompt"] = False
resp = client.post(
f"{self.base_url}/apply-template",
json = template_body,
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 3bfcdc3392e..9de58d853fb 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -1599,14 +1599,15 @@ class ChatCompletionRequest(BaseModel):
"the process default."
),
)
- context_overflow: Optional[Literal["error", "truncate_middle"]] = Field(
+ context_overflow: Optional[Literal["error", "truncate_middle", "truncate_oldest"]] = Field(
None,
description = (
- "[x-unsloth] Passthrough behavior when the prompt exceeds the real "
- "context window. 'error' (default) returns a 400 with "
- "code=context_length_exceeded. 'truncate_middle' drops middle "
- "turn-groups (system prompt, first turn, and recent turns kept; "
- "tool calls stay paired with their results) and retries."
+ "[x-unsloth] Local GGUF context-overflow behavior. 'error' (default) "
+ "returns a 400 with code=context_length_exceeded. 'truncate_middle' is "
+ "limited to client-tool or response_format passthrough and retries after "
+ "keeping the first and recent turns. 'truncate_oldest' provides a rolling "
+ "window for plain and Studio-tool chats by dropping complete oldest turns. "
+ "Both truncation policies preserve system messages and tool-call groups."
),
)
max_tool_calls_per_message: Optional[int] = Field(
@@ -2148,6 +2149,7 @@ class ChatCompletionChunk(BaseModel):
choices: list[ChunkChoice]
usage: Optional[CompletionUsage] = None
timings: Optional[dict] = None
+ context_truncated: Optional[dict] = None
# ── Non-streaming response ───────────────────────────────────────
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 39dc0916085..64bb96151a0 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -54,6 +54,11 @@ from core.inference.audio_errors import (
AudioBackendUnsupportedError,
AudioGenerationCancelledError,
)
+from core.inference.context_window import (
+ estimate_message_tokens as _estimate_message_tokens,
+ estimate_messages_tokens as _estimate_messages_tokens,
+ truncate_oldest_messages as _truncate_oldest_messages,
+)
from core.inference.orchestrator import (
AUDIO_GENERATION_MAX_TOKENS,
GenStreamError,
@@ -641,13 +646,48 @@ _OVERFLOW_TRUNCATE_MAX_RETRIES = 3
_OVERFLOW_PROMPT_TARGET_FRACTION = 0.75
+def _overflow_truncation_policy(payload) -> Optional[str]:
+ requested = getattr(payload, "context_overflow", None)
+ if requested is not None:
+ return requested if requested in ("truncate_middle", "truncate_oldest") else None
+ server_default = os.environ.get("UNSLOTH_CONTEXT_OVERFLOW", "").strip().lower()
+ return server_default if server_default in ("truncate_middle", "truncate_oldest") else None
+
+
+def _rolling_context_policy(payload) -> Optional[str]:
+ policy = _overflow_truncation_policy(payload)
+ return policy if policy == "truncate_oldest" else None
+
+
def _overflow_truncation_requested(payload) -> bool:
"""True when the request (or the UNSLOTH_CONTEXT_OVERFLOW server default,
for clients that cannot send custom fields) opted into truncation."""
- requested = getattr(payload, "context_overflow", None)
- if requested is not None:
- return requested == "truncate_middle"
- return os.environ.get("UNSLOTH_CONTEXT_OVERFLOW", "").strip().lower() == "truncate_middle"
+ return _overflow_truncation_policy(payload) is not None
+
+
+def _context_truncated_sse_chunk(completion_id: str, model_name: str, truncation: dict) -> str:
+ data = {
+ "id": completion_id,
+ "object": "chat.completion.chunk",
+ "created": int(time.time()),
+ "model": model_name,
+ "choices": [],
+ "context_truncated": truncation,
+ }
+ return f"data: {json.dumps(data)}\n\n"
+
+
+def _accumulate_context_truncation(current: Optional[dict], event: dict) -> dict:
+ incoming = {key: value for key, value in event.items() if key != "type"}
+ if current is None:
+ return incoming
+ combined = {**current, **incoming}
+ combined["dropped_messages"] = int(current.get("dropped_messages") or 0) + int(
+ incoming.get("dropped_messages") or 0
+ )
+ if current.get("prompt_tokens_before") is not None:
+ combined["prompt_tokens_before"] = current["prompt_tokens_before"]
+ return combined
def _parse_overflow_counts(err_text: str):
@@ -660,24 +700,6 @@ def _parse_overflow_counts(err_text: str):
return None
-def _estimate_message_tokens(msg: dict) -> int:
- try:
- return max(1, len(json.dumps(msg, ensure_ascii = False)) // 4)
- except Exception:
- return 1
-
-
-def _estimate_messages_tokens(messages: list) -> int:
- """Conservatively estimate a complete message list.
-
- Templates disagree about when historical ``reasoning_content`` renders,
- and arbitrary GGUFs can carry custom templates. Counting the serialized
- field avoids a retry that still exceeds context. The overflow recovery path
- clips large reasoning traces before it evicts conversation turns.
- """
- return sum(_estimate_message_tokens(msg) for msg in messages)
-
-
def _truncate_middle_messages(messages: list, keep_ratio: float):
"""Drop whole turn-groups from the middle of an OpenAI message list.
@@ -793,14 +815,18 @@ def _clip_long_contents(messages: list, target_est: int) -> int:
return clipped
-def _apply_overflow_truncation(body: dict, err_text: str) -> bool:
+def _apply_overflow_truncation(
+ body: dict,
+ err_text: str,
+ policy: str = "truncate_middle",
+) -> bool:
"""Shrink a passthrough body after an upstream context overflow: drop
middle turn-groups, clip still-oversized contents, clamp ``max_tokens``
to the generation headroom. Returns False when nothing could shrink."""
counts = _parse_overflow_counts(err_text)
messages = body.get("messages") or []
pre_clip_est = _estimate_messages_tokens(messages)
- clipped = _clip_reasoning_contents(messages)
+ clipped = 0 if policy == "truncate_oldest" else _clip_reasoning_contents(messages)
total_est = _estimate_messages_tokens(messages)
if counts:
n_prompt, n_ctx = counts
@@ -820,10 +846,16 @@ def _apply_overflow_truncation(body: dict, err_text: str) -> bool:
# Scale the server-token target into char-estimate units.
target_est = int(total_est * keep_ratio)
- new_messages, dropped = _truncate_middle_messages(messages, keep_ratio)
+ truncate = (
+ _truncate_oldest_messages if policy == "truncate_oldest" else _truncate_middle_messages
+ )
+ new_messages, dropped = truncate(messages, keep_ratio)
if dropped:
body["messages"] = new_messages
- if _estimate_messages_tokens(body.get("messages") or []) > target_est:
+ if (
+ policy != "truncate_oldest"
+ and _estimate_messages_tokens(body.get("messages") or []) > target_est
+ ):
clipped += _clip_long_contents(body.get("messages") or [], target_est)
if not dropped and not clipped:
return False
@@ -832,8 +864,9 @@ def _apply_overflow_truncation(body: dict, err_text: str) -> bool:
cur_max = body.get("max_tokens")
body["max_tokens"] = min(cur_max, headroom) if cur_max else headroom
logger.warning(
- "context_overflow=truncate_middle: dropped %d middle messages, clipped "
+ "context_overflow=%s: dropped %d messages, clipped "
"%d contents (keep_ratio %.2f); retrying within the real window",
+ policy,
dropped,
clipped,
keep_ratio,
@@ -841,6 +874,13 @@ def _apply_overflow_truncation(body: dict, err_text: str) -> bool:
return True
+def _apply_measured_overflow_truncation(body: dict, err_text: str, policy: str) -> Optional[int]:
+ before = len(body.get("messages") or [])
+ if not _apply_overflow_truncation(body, err_text, policy):
+ return None
+ return max(0, before - len(body.get("messages") or []))
+
+
def _anthropic_stream_error_event(exc, *, force: bool = False):
"""Return an Anthropic in-band stream error event when one is useful."""
_cls = _classify_llama_generation_error(exc)
@@ -7732,6 +7772,16 @@ def _model_json_response(model, status_code: int = 200) -> Response:
)
+def _model_json_response_with_context_truncation(
+ model, context_truncation: Optional[dict]
+) -> Response:
+ if context_truncation is None:
+ return _model_json_response(model)
+ content = model.model_dump()
+ content["context_truncated"] = context_truncation
+ return JSONResponse(content = content)
+
+
_NOT_SUPPORTED_HINTS = (
"No config file found",
"not yet supported",
@@ -14240,6 +14290,7 @@ async def openai_chat_completions(
bypass_permissions = bool(payload.bypass_permissions),
permission_mode = payload.permission_mode,
perf_callback = _gguf_perf_callback,
+ context_overflow = _rolling_context_policy(payload),
)
_tool_admission_mode = "chat_tool_stream" if payload.stream else "chat_tool_nonstream"
@@ -14436,6 +14487,14 @@ async def openai_chat_completions(
yield f"data: {json.dumps(event)}\n\n"
continue
+ if event["type"] == "context_truncated":
+ yield _context_truncated_sse_chunk(
+ completion_id,
+ model_name,
+ {key: value for key, value in event.items() if key != "type"},
+ )
+ continue
+
# "content" type -- cumulative text. Sanitize the full
# cumulative then diff against the last sanitized
# snapshot so cross-chunk XML tags are handled correctly.
@@ -14688,6 +14747,7 @@ async def openai_chat_completions(
usage = None
finish = None
timings = None
+ context_truncation = None
gen = gguf_generate_with_tools()
try:
for event in gen:
@@ -14697,6 +14757,10 @@ async def openai_chat_completions(
usage = event.get("usage")
finish = event.get("finish_reason")
timings = event.get("timings")
+ elif event.get("type") == "context_truncated":
+ context_truncation = _accumulate_context_truncation(
+ context_truncation, event
+ )
elif event.get("type") == "content":
# Content is cumulative within a turn and resets
# between turns, so the last event holds the final
@@ -14708,7 +14772,7 @@ async def openai_chat_completions(
auto_heal_tool_calls = _gguf_auto_heal_tool_calls,
enabled_tool_names = _gguf_display_tool_names,
)
- return full_text, usage, finish, timings
+ return full_text, usage, finish, timings, context_truncation
finally:
# Close the generator on early break/cancel so the underlying
# llama-server stream socket is released, like the SSE path.
@@ -14776,6 +14840,7 @@ async def openai_chat_completions(
completion_usage,
completion_finish,
completion_timings,
+ completion_context_truncation,
) = await asyncio.shield(drain_task)
reasoning_text, visible_text = _extract_responses_reasoning(
full_text,
@@ -14823,7 +14888,9 @@ async def openai_chat_completions(
api_monitor.finish(
monitor_id, "cancelled" if cancel_event.is_set() else "completed"
)
- return _model_json_response(response)
+ return _model_json_response_with_context_truncation(
+ response, completion_context_truncation
+ )
except asyncio.CancelledError:
cancel_event.set()
await _drain_cancelled_gguf_tool_task()
@@ -14914,6 +14981,7 @@ async def openai_chat_completions(
continue_final_message = _continue_final_message(payload),
seed = _seed,
perf_callback = _gguf_perf_callback,
+ context_overflow = _rolling_context_policy(payload),
)
_gguf_sentinel = object()
@@ -15003,6 +15071,16 @@ async def openai_chat_completions(
# Diffusion frame (per-step canvas): pass through as a raw SSE line on the
# tool_status channel. No assistant text, so it never enters the cumulative diff.
yield f"data: {json.dumps(cumulative)}\n\n"
+ elif cumulative.get("type") == "context_truncated":
+ yield _context_truncated_sse_chunk(
+ completion_id,
+ model_name,
+ {
+ key: value
+ for key, value in cumulative.items()
+ if key != "type"
+ },
+ )
else:
logger.warning(
"gguf_stream_chunks: unexpected dict event: %s",
@@ -15377,6 +15455,7 @@ async def openai_chat_completions(
_prompt_details = None
_last_timings = None
_last_finish = None
+ _context_truncation = None
for _idx in range(_n):
# Stop spawning the remaining choices once cancelled.
if cancel_event.is_set():
@@ -15384,6 +15463,7 @@ async def openai_chat_completions(
full_text = ""
completion_usage = None
completion_finish = None
+ _choice_context_truncation = None
for token in gguf_generate(_idx):
if isinstance(token, dict):
if token.get("type") == "metadata":
@@ -15391,9 +15471,22 @@ async def openai_chat_completions(
completion_finish = token.get("finish_reason")
_last_timings = token.get("timings")
_last_finish = completion_finish
+ elif token.get("type") == "context_truncated":
+ _choice_context_truncation = _accumulate_context_truncation(
+ _choice_context_truncation, token
+ )
continue
full_text = token
+ if _choice_context_truncation is not None and (
+ _context_truncation is None
+ or int(_choice_context_truncation.get("dropped_messages") or 0)
+ >= int(_context_truncation.get("dropped_messages") or 0)
+ ):
+ # Choices share the original prompt. Keep the shortest
+ # choice's cumulative fit instead of summing choices.
+ _context_truncation = _choice_context_truncation
+
reasoning_text, visible_text = _extract_responses_reasoning(
full_text,
parse_think_markers = _responses_should_parse_think_markers(
@@ -15429,6 +15522,7 @@ async def openai_chat_completions(
_prompt_details,
_last_timings,
_last_finish,
+ _context_truncation,
)
drain_task = asyncio.create_task(asyncio.to_thread(_drain_gguf_choices))
@@ -15441,6 +15535,7 @@ async def openai_chat_completions(
_prompt_details,
_last_timings,
_last_finish,
+ _context_truncation,
) = await asyncio.shield(drain_task)
response = ChatCompletion(
@@ -15479,7 +15574,7 @@ async def openai_chat_completions(
),
)
api_monitor.finish(monitor_id)
- return _model_json_response(response)
+ return _model_json_response_with_context_truncation(response, _context_truncation)
except asyncio.CancelledError:
cancel_event.set()
@@ -22665,13 +22760,23 @@ async def _openai_passthrough_stream_admitted(
limits = httpx.Limits(max_keepalive_connections = 0),
trust_env = False,
)
- _truncate_budget = (
- _OVERFLOW_TRUNCATE_MAX_RETRIES if _overflow_truncation_requested(payload) else 0
- )
+ _truncate_policy = _overflow_truncation_policy(payload)
+ _truncate_budget = _OVERFLOW_TRUNCATE_MAX_RETRIES if _truncate_policy else 0
+ _truncated_messages = 0
+ _context_was_truncated = False
# One respawn per request: a second unreachable upstream after a successful
# relaunch is a real failure, not a stale port.
_respawn_retried = False
+ def _apply_passthrough_truncation(err_text: str) -> bool:
+ nonlocal _context_was_truncated, _truncated_messages
+ dropped = _apply_measured_overflow_truncation(body, err_text, _truncate_policy)
+ if dropped is None:
+ return False
+ _context_was_truncated = True
+ _truncated_messages += dropped
+ return True
+
while True:
try:
req = client.build_request("POST", target_url, json = body, headers = upstream_headers)
@@ -22779,7 +22884,7 @@ async def _openai_passthrough_stream_admitted(
if (
_truncate_budget > 0
and _classify_llama_generation_error(Exception(err_text))
- and _apply_overflow_truncation(body, err_text)
+ and _apply_passthrough_truncation(err_text)
):
_truncate_budget -= 1
continue
@@ -23082,7 +23187,7 @@ async def _openai_passthrough_stream_admitted(
if (
_truncate_budget > 0
and _classify_llama_generation_error(Exception(err_text))
- and _apply_overflow_truncation(body, err_text)
+ and _apply_passthrough_truncation(err_text)
):
_truncate_budget -= 1
req = client.build_request(
@@ -23113,6 +23218,15 @@ async def _openai_passthrough_stream_admitted(
yield _openai_stream_error_sse(error_payload)
return
+ if _context_was_truncated:
+ yield _context_truncated_sse_chunk(
+ completion_id,
+ model_name,
+ {
+ "dropped_messages": _truncated_messages,
+ "fits": True,
+ },
+ )
cancel_watcher = asyncio.create_task(_await_cancel_then_close(cancel_event, resp))
disconnect_watcher = asyncio.create_task(
_await_disconnect_then_close(request, resp, cancel_event)
@@ -23538,12 +23652,22 @@ async def _openai_passthrough_non_streaming_upstream(
body["stream"] = False
body.pop("stream_options", None)
- _truncate_budget = (
- _OVERFLOW_TRUNCATE_MAX_RETRIES if _overflow_truncation_requested(payload) else 0
- )
+ _truncate_policy = _overflow_truncation_policy(payload)
+ _truncate_budget = _OVERFLOW_TRUNCATE_MAX_RETRIES if _truncate_policy else 0
+ _truncated_messages = 0
+ _context_was_truncated = False
# One respawn per request, as on the streaming twin.
_respawn_retried = False
+ def _apply_nonstream_truncation(err_text: str) -> bool:
+ nonlocal _context_was_truncated, _truncated_messages
+ dropped = _apply_measured_overflow_truncation(body, err_text, _truncate_policy)
+ if dropped is None:
+ return False
+ _context_was_truncated = True
+ _truncated_messages += dropped
+ return True
+
async def _post(body_to_send):
if cancel_event is None and request is None:
return await nonstreaming_client().post(
@@ -23629,7 +23753,7 @@ async def _openai_passthrough_non_streaming_upstream(
if (
_truncate_budget > 0
and _classify_llama_generation_error(Exception(resp.text))
- and _apply_overflow_truncation(body, resp.text)
+ and _apply_nonstream_truncation(resp.text)
):
_truncate_budget -= 1
continue
@@ -23689,6 +23813,12 @@ async def _openai_passthrough_non_streaming_upstream(
logger.warning("tool-call nudge retry failed; keeping original: %s", exc)
changed = False
+ if _context_was_truncated and isinstance(data, dict):
+ data["context_truncated"] = {
+ "dropped_messages": _truncated_messages,
+ "fits": True,
+ }
+ changed = True
for choice in data.get("choices", []):
if not isinstance(choice, dict):
continue
diff --git a/studio/backend/tests/test_context_overflow_truncation.py b/studio/backend/tests/test_context_overflow_truncation.py
index 58bf8b4290d..e1569496a76 100644
--- a/studio/backend/tests/test_context_overflow_truncation.py
+++ b/studio/backend/tests/test_context_overflow_truncation.py
@@ -12,6 +12,7 @@ the real post-readback context window.
from __future__ import annotations
+import json
import sys
from pathlib import Path
@@ -22,15 +23,22 @@ if _BACKEND_DIR not in sys.path:
sys.path.insert(0, _BACKEND_DIR)
from routes.inference import (
+ _accumulate_context_truncation,
_apply_overflow_truncation,
+ _apply_measured_overflow_truncation,
_clip_long_contents,
_CLIP_MARKER,
+ _context_truncated_sse_chunk,
_estimate_message_tokens,
_openai_model_objects,
_overflow_truncation_requested,
+ _rolling_context_policy,
_parse_overflow_counts,
_truncate_middle_messages,
+ _truncate_oldest_messages,
)
+from core.inference.context_window import fit_rolling_context, messages_have_media
+from models.inference import ChatCompletion
import routes.inference as routes_mod
@@ -150,6 +158,186 @@ def test_truncation_noop_when_only_protected_turns_remain():
assert new == msgs
+def test_rolling_truncation_drops_complete_oldest_turns():
+ messages = [
+ {"role": "system", "content": "system"},
+ {"role": "user", "content": "old question"},
+ {"role": "assistant", "content": "old answer"},
+ {"role": "user", "content": "tool question"},
+ *_tool_turn(1),
+ {"role": "assistant", "content": "tool answer"},
+ {"role": "user", "content": "latest question"},
+ ]
+
+ new, dropped = _truncate_oldest_messages(messages, keep_ratio = 0.5)
+
+ assert dropped > 0
+ assert new[0] == messages[0]
+ assert new[-1] == messages[-1]
+ assert "old question" not in {message.get("content") for message in new}
+ # The tool exchange is either retained as a whole or removed as a whole.
+ surviving_call_ids = {
+ call["id"] for message in new for call in (message.get("tool_calls") or [])
+ }
+ assert all(
+ message.get("tool_call_id") in surviving_call_ids
+ for message in new
+ if message.get("role") == "tool"
+ )
+
+
+def test_rolling_truncation_can_evict_old_tool_rounds_from_one_user_task():
+ task = {"role": "user", "content": "do the task"}
+ first_round = _tool_turn(1, result_chars = 4000)
+ second_round = _tool_turn(2, result_chars = 4000)
+ messages = [
+ {"role": "system", "content": "system"},
+ task,
+ *first_round,
+ *second_round,
+ ]
+
+ new, dropped = _truncate_oldest_messages(
+ messages,
+ keep_ratio = 0.6,
+ protected_message_ids = {id(task)},
+ )
+
+ assert dropped == len(first_round)
+ assert task in new
+ assert first_round[0] not in new and first_round[1] not in new
+ assert second_round[0] in new and second_round[1] in new
+
+
+def test_rolling_truncation_keeps_task_when_a_synthetic_user_nudge_is_latest():
+ task = {"role": "user", "content": "actual task"}
+ tool_round = _tool_turn(1, result_chars = 4000)
+ nudge = {"role": "user", "content": "Use an available tool now."}
+ messages = [task, *tool_round, nudge]
+
+ new, dropped = _truncate_oldest_messages(
+ messages,
+ keep_ratio = 0.2,
+ protected_message_ids = {id(task)},
+ )
+
+ assert dropped == len(tool_round)
+ assert [message["role"] for message in new] == ["user", "assistant", "user"]
+ assert new[0] is task
+ assert new[-1] is nudge
+
+
+def test_rolling_media_detection_covers_image_and_audio_parts():
+ assert messages_have_media(
+ [{"role": "user", "content": [{"type": "image_url", "image_url": {}}]}]
+ )
+ assert messages_have_media(
+ [{"role": "user", "content": [{"type": "input_audio", "input_audio": {}}]}]
+ )
+ # llama.cpp's own part type, written by `_inject_video_part` into the very list this
+ # fit is handed. Missed, a video prompt ran the preflight that video tokens are not
+ # counted by, so it could be certified as fitting when it does not.
+ assert messages_have_media(
+ [{"role": "user", "content": [{"type": "input_video", "input_video": {"data": "AAAA"}}]}]
+ )
+ assert not messages_have_media([{"role": "user", "content": "text only"}])
+
+
+def test_rolling_truncation_preserves_nonleading_system_messages():
+ later_system = {"role": "system", "content": "new higher-priority instruction"}
+ messages = [
+ {"role": "user", "content": "old" * 1000},
+ {"role": "assistant", "content": "answer" * 1000},
+ later_system,
+ {"role": "user", "content": "latest"},
+ ]
+
+ new, dropped = _truncate_oldest_messages(messages, keep_ratio = 0.2)
+
+ assert dropped == 2
+ assert later_system in new
+
+
[email protected]("instruction_role", ["system", "developer"])
+def test_rolling_truncation_can_drop_assistant_after_instruction(instruction_role):
+ instruction = {"role": instruction_role, "content": "keep this instruction"}
+ greeting = {"role": "assistant", "content": "historical greeting" * 1000}
+ latest = {"role": "user", "content": "latest question"}
+
+ new, dropped = _truncate_oldest_messages([instruction, greeting, latest], keep_ratio = 0.1)
+
+ assert dropped == 1
+ assert new == [instruction, latest]
+
+
+def test_rolling_fit_recounts_until_the_real_template_fits():
+ messages = [
+ {"role": "system", "content": "system"},
+ {"role": "user", "content": "one" * 40},
+ {"role": "assistant", "content": "answer" * 40},
+ {"role": "user", "content": "two" * 40},
+ {"role": "assistant", "content": "answer" * 40},
+ {"role": "user", "content": "latest"},
+ ]
+
+ def count_tokens(candidate):
+ return sum(len(str(message.get("content", ""))) for message in candidate)
+
+ fitted, info = fit_rolling_context(
+ messages,
+ context_length = 500,
+ max_tokens = 100,
+ count_tokens = count_tokens,
+ )
+
+ assert info is not None
+ assert info["dropped_messages"] == 2
+ assert info["prompt_tokens_before"] > 400
+ assert info["prompt_tokens_after"] <= 400
+ assert fitted[0] == messages[0]
+ assert fitted[-1] == messages[-1]
+
+
+def test_rolling_fit_never_clips_an_irreducible_latest_turn():
+ messages = [
+ {"role": "system", "content": "system"},
+ {"role": "user", "content": "latest" * 200},
+ ]
+ fitted, info = fit_rolling_context(
+ messages,
+ context_length = 500,
+ max_tokens = 100,
+ count_tokens = lambda candidate: sum(
+ len(str(message.get("content", ""))) for message in candidate
+ ),
+ )
+
+ assert fitted is messages
+ assert fitted == messages
+ assert info is None
+
+
+def test_rolling_fit_keeps_original_when_protected_messages_still_do_not_fit():
+ latest = {"role": "user", "content": "latest" * 200}
+ messages = [
+ {"role": "user", "content": "old" * 100},
+ {"role": "assistant", "content": "answer" * 100},
+ latest,
+ ]
+ fitted, info = fit_rolling_context(
+ messages,
+ context_length = 500,
+ max_tokens = 100,
+ count_tokens = lambda candidate: sum(
+ len(str(message.get("content", ""))) for message in candidate
+ ),
+ )
+
+ assert fitted is messages
+ assert fitted == messages
+ assert info is None
+
+
# ---------------------------------------------------------------------------
# _apply_overflow_truncation
# ---------------------------------------------------------------------------
@@ -175,6 +363,83 @@ def test_apply_overflow_truncation_returns_false_when_nothing_droppable():
assert _apply_overflow_truncation(body, _NICK_ERROR) is False
+def test_rolling_overflow_never_clips_the_latest_request():
+ latest = "latest" * 10000
+ body = {
+ "messages": [
+ {"role": "system", "content": "sys"},
+ {"role": "user", "content": "old"},
+ {"role": "assistant", "content": "answer"},
+ {"role": "user", "content": latest},
+ ]
+ }
+
+ assert _apply_overflow_truncation(body, _NICK_ERROR, "truncate_oldest") is True
+ assert body["messages"][-1]["content"] == latest
+ # A second recovery has no old turn left to drop and must fail cleanly.
+ assert _apply_overflow_truncation(body, _NICK_ERROR, "truncate_oldest") is False
+
+
+def test_context_truncation_notice_is_an_openai_compatible_empty_chunk():
+ line = _context_truncated_sse_chunk(
+ "chatcmpl-test",
+ "model",
+ {"dropped_messages": 4, "fits": True},
+ )
+ payload = json.loads(line.removeprefix("data: ").strip())
+
+ assert payload["object"] == "chat.completion.chunk"
+ assert payload["choices"] == []
+ assert payload["context_truncated"] == {"dropped_messages": 4, "fits": True}
+
+
+def test_nonstream_completion_serializes_context_truncation():
+ response = ChatCompletion(choices = [])
+ body = json.loads(
+ routes_mod._model_json_response_with_context_truncation(
+ response, {"dropped_messages": 4, "fits": True}
+ ).body
+ )
+ assert body["context_truncated"] == {"dropped_messages": 4, "fits": True}
+
+
+def test_nonstream_completion_omits_context_field_when_not_truncated():
+ response = ChatCompletion(choices = [])
+ body = json.loads(routes_mod._model_json_response_with_context_truncation(response, None).body)
+
+ assert "context_truncated" not in body
+
+
+def test_tool_loop_context_truncation_accumulates_dropped_messages():
+ first = _accumulate_context_truncation(
+ None,
+ {
+ "type": "context_truncated",
+ "dropped_messages": 2,
+ "prompt_tokens_before": 1200,
+ "prompt_tokens_after": 800,
+ "fits": True,
+ },
+ )
+ combined = _accumulate_context_truncation(
+ first,
+ {
+ "type": "context_truncated",
+ "dropped_messages": 3,
+ "prompt_tokens_before": 1000,
+ "prompt_tokens_after": 700,
+ "fits": True,
+ },
+ )
+
+ assert combined == {
+ "dropped_messages": 5,
+ "prompt_tokens_before": 1200,
+ "prompt_tokens_after": 700,
+ "fits": True,
+ }
+
+
def test_apply_overflow_truncation_clips_giant_protected_tool_results():
"""One giant burst (few turn-groups, all protected) must still shrink:
stage 2 clips oversized tool contents instead of giving up."""
@@ -202,6 +467,19 @@ def test_apply_overflow_truncation_clips_giant_protected_tool_results():
assert m["tool_call_id"] in surviving_call_ids
+def test_measured_overflow_truncation_distinguishes_clipping_from_no_change():
+ body = {
+ "messages": [
+ {"role": "system", "content": "sys"},
+ {"role": "user", "content": "task"},
+ *_tool_turn(0, result_chars = 60000),
+ ]
+ }
+
+ assert _apply_measured_overflow_truncation(body, _NICK_ERROR, "truncate_middle") == 0
+ assert _CLIP_MARKER in body["messages"][-1]["content"]
+
+
def test_clip_long_contents_reaches_target_and_keeps_structure():
msgs = [
{"role": "system", "content": "sys"},
@@ -227,10 +505,17 @@ def test_overflow_truncation_requested_reads_field(monkeypatch):
class _Q:
context_overflow = None
+ class _R:
+ context_overflow = "truncate_oldest"
+
assert _overflow_truncation_requested(_P()) is True
assert _overflow_truncation_requested(_Q()) is False
+ assert _overflow_truncation_requested(_R()) is True
assert _overflow_truncation_requested(object()) is False
+ assert _rolling_context_policy(_P()) is None
+ assert _rolling_context_policy(_R()) == "truncate_oldest"
+
def test_overflow_truncation_server_default_env(monkeypatch):
"""UNSLOTH_CONTEXT_OVERFLOW enables the policy for clients that cannot
@@ -245,8 +530,12 @@ def test_overflow_truncation_server_default_env(monkeypatch):
monkeypatch.setenv("UNSLOTH_CONTEXT_OVERFLOW", "truncate_middle")
assert _overflow_truncation_requested(_Unset()) is True
assert _overflow_truncation_requested(_ExplicitError()) is False
+ assert _rolling_context_policy(_Unset()) is None
monkeypatch.setenv("UNSLOTH_CONTEXT_OVERFLOW", "error")
assert _overflow_truncation_requested(_Unset()) is False
+ monkeypatch.setenv("UNSLOTH_CONTEXT_OVERFLOW", "truncate_oldest")
+ assert _overflow_truncation_requested(_Unset()) is True
+ assert _rolling_context_policy(_Unset()) == "truncate_oldest"
# ---------------------------------------------------------------------------
diff --git a/studio/backend/tests/test_gguf_completion_usage.py b/studio/backend/tests/test_gguf_completion_usage.py
index b5fc5e9cc83..d98a1b49cb2 100644
--- a/studio/backend/tests/test_gguf_completion_usage.py
+++ b/studio/backend/tests/test_gguf_completion_usage.py
@@ -12,10 +12,24 @@ from .llama_backend_double import FakeLlamaCppBackend
class _GgufBackend(FakeLlamaCppBackend):
- def __init__(self, usage):
+ def __init__(
+ self,
+ usage,
+ context_truncation = None,
+ ):
self.usage = usage
+ self.context_truncation = context_truncation
+ self.generation_index = 0
def generate_chat_completion(self, **kwargs):
+ truncations = self.context_truncation
+ if isinstance(truncations, list):
+ truncations = truncations[self.generation_index]
+ self.generation_index += 1
+ if isinstance(truncations, dict):
+ truncations = [truncations]
+ for truncation in truncations or []:
+ yield {"type": "context_truncated", **truncation}
yield "answer"
yield {
"type": "metadata",
@@ -24,8 +38,17 @@ class _GgufBackend(FakeLlamaCppBackend):
}
-def _request_completion(monkeypatch, usage):
- monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: _GgufBackend(usage))
+def _request_completion(
+ monkeypatch,
+ usage,
+ context_truncation = None,
+ n = None,
+):
+ monkeypatch.setattr(
+ inference_route,
+ "get_llama_cpp_backend",
+ lambda: _GgufBackend(usage, context_truncation),
+ )
monkeypatch.setattr(inference_route, "_effective_enable_tools", lambda payload: False)
app = FastAPI()
@@ -37,6 +60,7 @@ def _request_completion(monkeypatch, usage):
json = {
"messages": [{"role": "user", "content": "Why is the sky blue?"}],
"stream": False,
+ **({"n": n} if n is not None else {}),
},
)
@@ -79,3 +103,62 @@ def test_non_streaming_gguf_completion_defaults_nullable_usage_to_zero(monkeypat
"accepted_prediction_tokens": 0,
"rejected_prediction_tokens": 0,
}
+
+
+def test_non_streaming_gguf_completion_includes_context_truncation(monkeypatch):
+ truncation = {
+ "dropped_messages": 4,
+ "prompt_tokens_before": 9000,
+ "prompt_tokens_after": 7000,
+ "context_length": 8192,
+ "fits": True,
+ }
+ response = _request_completion(
+ monkeypatch,
+ {"prompt_tokens": 7000, "completion_tokens": 20, "total_tokens": 7020},
+ truncation,
+ )
+
+ assert response.status_code == 200
+ assert response.json()["context_truncated"] == truncation
+
+
+def test_non_streaming_choices_keep_distinct_later_truncation_stages(monkeypatch):
+ base = {
+ "dropped_messages": 4,
+ "prompt_tokens_before": 9000,
+ "prompt_tokens_after": 7000,
+ "context_length": 8192,
+ "fits": True,
+ }
+ additional = {
+ "dropped_messages": 2,
+ "prompt_tokens_before": 7000,
+ "prompt_tokens_after": 3500,
+ "context_length": 4096,
+ "fits": True,
+ }
+ cumulative = {
+ "dropped_messages": 6,
+ "prompt_tokens_before": 9000,
+ "prompt_tokens_after": 3500,
+ "context_length": 4096,
+ "fits": True,
+ }
+
+ response = _request_completion(
+ monkeypatch,
+ {"prompt_tokens": 3500, "completion_tokens": 20, "total_tokens": 3520},
+ [[base], [base, additional], [cumulative]],
+ n = 3,
+ )
+
+ assert response.status_code == 200
+ assert len(response.json()["choices"]) == 3
+ assert response.json()["context_truncated"] == {
+ "dropped_messages": 6,
+ "prompt_tokens_before": 9000,
+ "prompt_tokens_after": 3500,
+ "context_length": 4096,
+ "fits": True,
+ }
diff --git a/studio/backend/tests/test_gguf_tool_non_streaming.py b/studio/backend/tests/test_gguf_tool_non_streaming.py
index 880dbf5864c..126828a895c 100644
--- a/studio/backend/tests/test_gguf_tool_non_streaming.py
+++ b/studio/backend/tests/test_gguf_tool_non_streaming.py
@@ -22,6 +22,7 @@ from .llama_backend_double import FakeLlamaCppBackend
class _ToolGgufBackend(FakeLlamaCppBackend):
supports_tools = True
+ context_length = 8192
def generate_chat_completion_with_tools(self, **kwargs):
# The agentic loop runs one tool, then the model answers. Event shapes
@@ -167,3 +168,37 @@ def test_non_streaming_preserves_cached_tokens(monkeypatch):
assert response.status_code == 200
assert response.json()["usage"]["prompt_tokens_details"]["cached_tokens"] == 16
+
+
+def test_non_streaming_preserves_accumulated_context_truncation(monkeypatch):
+ events = [
+ {
+ "type": "context_truncated",
+ "dropped_messages": 2,
+ "prompt_tokens_before": 9000,
+ "prompt_tokens_after": 7000,
+ "context_length": 8192,
+ "fits": True,
+ },
+ {
+ "type": "context_truncated",
+ "dropped_messages": 3,
+ "prompt_tokens_before": 8100,
+ "prompt_tokens_after": 6500,
+ "context_length": 8192,
+ "fits": True,
+ },
+ {"type": "content", "text": "hi"},
+ ]
+ response = _client(monkeypatch, _EventsBackend(events)).post(
+ "/chat/completions", json = _payload(stream = False)
+ )
+
+ assert response.status_code == 200
+ assert response.json()["context_truncated"] == {
+ "dropped_messages": 5,
+ "prompt_tokens_before": 9000,
+ "prompt_tokens_after": 6500,
+ "context_length": 8192,
+ "fits": True,
+ }
diff --git a/studio/backend/tests/test_llama_cpp_tool_loop.py b/studio/backend/tests/test_llama_cpp_tool_loop.py
index 0698d1cea94..335730a0635 100644
--- a/studio/backend/tests/test_llama_cpp_tool_loop.py
+++ b/studio/backend/tests/test_llama_cpp_tool_loop.py
@@ -3684,6 +3684,268 @@ def test_connect_error_before_tool_stream_respawns_and_retries(monkeypatch):
assert any(e.get("type") == "content" and e.get("text") == "Recovered." for e in events)
+def test_tool_loop_refits_each_preflight_path_after_context_shrinking_respawn(monkeypatch):
+ """Both an ordinary iteration and final synthesis refit without repeating old drops."""
+ import httpx
+ for max_tool_iterations in (1, 0):
+ payloads: list[dict] = []
+ backend = _make_backend(
+ monkeypatch,
+ [
+ httpx.ConnectError("server is down"),
+ [_sse({"content": "Recovered."}), _done()],
+ ],
+ payloads,
+ )
+ backend._effective_context_length = 100
+ monkeypatch.setattr(
+ backend,
+ "count_chat_tokens",
+ lambda candidate, *_args, **_kwargs: sum(
+ len(str(message.get("content", ""))) for message in candidate
+ ),
+ )
+
+ def fake_respawn():
+ backend._effective_context_length = 60
+ return True
+
+ monkeypatch.setattr(backend, "_respawn_if_dead", fake_respawn)
+ events = list(
+ backend.generate_chat_completion_with_tools(
+ messages = [
+ {"role": "user", "content": "u" * 25},
+ {"role": "assistant", "content": "a" * 25},
+ {"role": "user", "content": "u" * 25},
+ {"role": "assistant", "content": "a" * 25},
+ {"role": "user", "content": "final"},
+ ],
+ tools = [{"type": "function", "function": {"name": "python"}}],
+ max_tool_iterations = max_tool_iterations,
+ context_overflow = "truncate_oldest",
+ )
+ )
+
+ notices = [event for event in events if event.get("type") == "context_truncated"]
+ assert [notice["dropped_messages"] for notice in notices] == [2, 2]
+ assert [notice["context_length"] for notice in notices] == [100, 60]
+ assert [payload["max_tokens"] for payload in payloads] == [100, 60]
+ assert len(payloads[0]["messages"]) == 3
+ assert len(payloads[1]["messages"]) == 1
+
+
+def test_tool_loop_retries_preflight_when_counting_failed_on_the_dead_server(monkeypatch):
+ import httpx
+
+ payloads: list[dict] = []
+ backend = _make_backend(
+ monkeypatch,
+ [httpx.ConnectError("server is down"), [_sse({"content": "OK"}), _done()]],
+ payloads,
+ )
+ backend._effective_context_length = 60
+ count_calls = 0
+
+ def count_tokens(candidate, *_args, **_kwargs):
+ nonlocal count_calls
+ count_calls += 1
+ if count_calls == 1:
+ raise httpx.ConnectError("token counter is down")
+ return sum(len(str(message.get("content", ""))) for message in candidate)
+
+ monkeypatch.setattr(backend, "count_chat_tokens", count_tokens)
+ monkeypatch.setattr(backend, "_respawn_if_dead", lambda: True)
+ events = list(
+ backend.generate_chat_completion_with_tools(
+ messages = [
+ {"role": "user", "content": "u" * 25},
+ {"role": "assistant", "content": "a" * 25},
+ {"role": "user", "content": "final"},
+ ],
+ tools = [{"type": "function", "function": {"name": "python"}}],
+ max_tool_iterations = 1,
+ context_overflow = "truncate_oldest",
+ )
+ )
+
+ notices = [event for event in events if event.get("type") == "context_truncated"]
+ assert count_calls >= 2
+ assert [notice["dropped_messages"] for notice in notices] == [2]
+ assert len(payloads[0]["messages"]) == 3
+ assert len(payloads[1]["messages"]) == 1
+
+
+def test_tool_loop_does_not_send_a_stale_payload_when_respawn_refit_fails(monkeypatch):
+ import httpx
+ for max_tool_iterations in (1, 0):
+ payloads: list[dict] = []
+ backend = _make_backend(monkeypatch, [httpx.ConnectError("server is down")], payloads)
+ backend._effective_context_length = 100
+ count_calls = 0
+
+ def count_tokens(candidate, *_args, **_kwargs):
+ nonlocal count_calls
+ count_calls += 1
+ if count_calls > 1:
+ raise RuntimeError("replacement token count failed")
+ return sum(len(str(message.get("content", ""))) for message in candidate)
+
+ monkeypatch.setattr(backend, "count_chat_tokens", count_tokens)
+
+ def fake_respawn():
+ backend._effective_context_length = 60
+ return True
+
+ monkeypatch.setattr(backend, "_respawn_if_dead", fake_respawn)
+ raised = None
+ try:
+ list(
+ backend.generate_chat_completion_with_tools(
+ messages = [
+ {"role": "user", "content": "u" * 25},
+ {"role": "assistant", "content": "a" * 25},
+ {"role": "user", "content": "final"},
+ ],
+ tools = [{"type": "function", "function": {"name": "python"}}],
+ max_tool_iterations = max_tool_iterations,
+ context_overflow = "truncate_oldest",
+ )
+ )
+ except RuntimeError as exc:
+ raised = exc
+
+ assert raised is not None
+ assert str(raised) == "replacement token count failed"
+ assert len(payloads) == 1
+
+
+def test_connect_error_retry_reuses_rolling_preflight_without_duplicate_notice(monkeypatch):
+ """A respawn retries the fitted request without reporting its dropped turns twice."""
+ import httpx
+
+ payloads: list[dict] = []
+ backend = _make_backend(
+ monkeypatch,
+ [
+ httpx.ConnectError("server is down"),
+ [_sse({"content": "Recovered."}), _done()],
+ ],
+ payloads,
+ )
+ backend._effective_context_length = 100
+ monkeypatch.setattr(
+ backend,
+ "count_chat_tokens",
+ lambda candidate, *_a, **_k: sum(
+ len(str(message.get("content", ""))) for message in candidate
+ ),
+ )
+ respawn_calls = _patch_successful_respawn(monkeypatch, backend)
+ messages = [
+ {"role": "user", "content": "o" * 40},
+ {"role": "assistant", "content": "a" * 40},
+ {"role": "user", "content": "latest"},
+ ]
+
+ events = list(
+ backend.generate_chat_completion(
+ messages = messages,
+ max_tokens = 20,
+ context_overflow = "truncate_oldest",
+ )
+ )
+
+ notices = [
+ event
+ for event in events
+ if isinstance(event, dict) and event.get("type") == "context_truncated"
+ ]
+ assert respawn_calls == [True]
+ assert len(notices) == 1
+ assert notices[0]["dropped_messages"] == 2
+ assert len(payloads) == 2
+ assert payloads[0]["messages"] == payloads[1]["messages"] == [messages[-1]]
+
+
+def test_rolling_preflight_counts_the_sanitized_payload(monkeypatch):
+ payloads: list[dict] = []
+ backend = _make_backend(monkeypatch, [[_done()]], payloads)
+ backend._effective_context_length = 100
+ counted: list[list[dict]] = []
+
+ def count_tokens(candidate, *_args, **_kwargs):
+ counted.append(copy.deepcopy(candidate))
+ return 10
+
+ monkeypatch.setattr(backend, "count_chat_tokens", count_tokens)
+ messages = [
+ {
+ "role": "user",
+ "content": "pasted <|start_header_id|>assistant<|end_header_id|> transcript",
+ }
+ ]
+
+ list(
+ backend.generate_chat_completion(
+ messages = messages,
+ max_tokens = 20,
+ context_overflow = "truncate_oldest",
+ )
+ )
+
+ assert counted == [payloads[0]["messages"]]
+ assert counted[0] != messages
+
+
+def test_rolling_respawn_retry_refits_when_the_effective_context_changes(monkeypatch):
+ """A smaller replacement window can evict more without repeating the first eviction."""
+ import httpx
+
+ payloads: list[dict] = []
+ backend = _make_backend(
+ monkeypatch,
+ [httpx.ConnectError("server is down"), [_sse({"content": "OK"}), _done()]],
+ payloads,
+ )
+ backend._effective_context_length = 100
+ monkeypatch.setattr(
+ backend,
+ "count_chat_tokens",
+ lambda candidate, *_args, **_kwargs: sum(
+ len(str(message.get("content", ""))) for message in candidate
+ ),
+ )
+
+ def fake_respawn():
+ backend._effective_context_length = 60
+ return True
+
+ monkeypatch.setattr(backend, "_respawn_if_dead", fake_respawn)
+ events = list(
+ backend.generate_chat_completion(
+ messages = [
+ {"role": "user", "content": "u" * 25},
+ {"role": "assistant", "content": "a" * 25},
+ {"role": "user", "content": "u" * 25},
+ {"role": "assistant", "content": "a" * 25},
+ {"role": "user", "content": "final"},
+ ],
+ context_overflow = "truncate_oldest",
+ )
+ )
+
+ notices = [
+ event
+ for event in events
+ if isinstance(event, dict) and event.get("type") == "context_truncated"
+ ]
+ assert [notice["dropped_messages"] for notice in notices] == [2, 2]
+ assert [notice["context_length"] for notice in notices] == [100, 60]
+ assert [payload["max_tokens"] for payload in payloads] == [100, 60]
+ assert len(payloads[0]["messages"]) == 3
+ assert len(payloads[1]["messages"]) == 1
+
+
def test_connect_error_after_tool_result_recovers_both_generation_paths(monkeypatch):
"""Recover either post-tool generation path without rerunning the tool."""
import httpx
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index a2625bfa872..7a278ec1883 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -141,6 +141,7 @@ import type {
CpuFallbackReason,
MmprojFallbackReason,
GgufVariantDetail,
+ OpenAIChatChunk,
OpenAIChatCompletionsRequest,
OpenAIChatMessage,
OpenAIMessageContent,
@@ -165,6 +166,7 @@ import {
} from "../utils/last-local-model-load";
import { createRetryableSharedRead } from "../utils/retryable-shared-read";
import { getImageInputUnavailableReason } from "../utils/image-input-support";
+import { mergeContextTruncation } from "../utils/context-truncation";
import {
createThinkTagTracker,
extractDeltaText,
@@ -345,6 +347,7 @@ function isServerSideBuiltinToolPart(
}
const FIRST_THREAD_SAVE_TIMEOUT_MS = 250;
+const rollingContextNoticeThreads = new Set<string>();
type ThreadAutosaveHandle = {
registerFirstSave(threadId: string, promise: Promise<void>): Promise<void>;
@@ -4814,6 +4817,7 @@ export function createOpenAIStreamAdapter(
// STREAMED yield is what gets saved.
let codexReasoningLedger: CodexReasoningLedger = { byToolCall: {} };
let codexRoundToolCallIds: string[] = [];
+ let contextTruncation: OpenAIChatChunk["context_truncated"];
const liveAssistantContent = () =>
buildAssistantContent(mergeContinuation(cumulativeText));
@@ -4823,6 +4827,7 @@ export function createOpenAIStreamAdapter(
const liveCustom = () => ({
...reasoningDurationTracker.metadata(),
openaiCodexReasoning: codexReasoningLedger,
+ contextTruncation,
incomplete: { reason: "cancelled" as const },
});
// Why this turn stopped early. Drives the Continue affordance.
@@ -5490,6 +5495,9 @@ export function createOpenAIStreamAdapter(
// Opt into the trailing usage chunk so the context-usage bar
// and tok/s readout populate (backend gates it on include_usage).
stream_options: { include_usage: true },
+ ...(activeModel?.isGguf === true
+ ? { context_overflow: "truncate_oldest" as const }
+ : {}),
temperature: params.temperature,
top_p: params.topP,
max_tokens: params.maxTokens,
@@ -5649,6 +5657,28 @@ export function createOpenAIStreamAdapter(
continue;
}
+ if (chunk.context_truncated) {
+ contextTruncation = mergeContextTruncation(
+ contextTruncation,
+ chunk.context_truncated,
+ );
+ const activeThreadId = useChatRuntimeStore.getState().activeThreadId;
+ if (
+ resolvedThreadId &&
+ activeThreadId === resolvedThreadId &&
+ !rollingContextNoticeThreads.has(resolvedThreadId)
+ ) {
+ rollingContextNoticeThreads.add(resolvedThreadId);
+ toast.info("Older turns omitted from model context", {
+ description:
+ "The full conversation is still visible and saved. " +
+ "Studio removed complete older turns from this request so the chat can continue.",
+ duration: 8000,
+ });
+ }
+ continue;
+ }
+
// Local GGUF sends server-timed reasoning duration. Guard the type
// so a malformed or proxied chunk (string/null/NaN duration) can
// never turn the label into NaN.
@@ -6690,6 +6720,7 @@ export function createOpenAIStreamAdapter(
// Persisted so Continue survives a reload; cleared on a normal end.
openaiCodexReasoning: codexReasoningLedger,
+ contextTruncation,
incomplete: incompleteReason ? { reason: incompleteReason } : undefined,
// Persisted refusal flag driving the two-pass prune.
anthropicRefusal: anthropicRefusalSeen || undefined,
@@ -6768,6 +6799,7 @@ export function createOpenAIStreamAdapter(
timing: partialTiming,
custom: {
...reasoningDurationTracker.metadata(),
+ contextTruncation,
// This partial is unfinished too, so it also offers Continue.
incomplete: {
reason:
diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.ts
index dac40651bde..8a0b2546fe0 100644
--- a/studio/frontend/src/features/chat/types/api.ts
+++ b/studio/frontend/src/features/chat/types/api.ts
@@ -617,6 +617,8 @@ export interface OpenAIChatCompletionsRequest {
/** Run the selected tools here rather than as the provider's hosted builtins. */
run_tools_locally?: boolean;
nudge_tool_calls?: boolean;
+ /** Local GGUF overflow policy. Rolling mode preserves the transcript but omits oldest turns. */
+ context_overflow?: "error" | "truncate_middle" | "truncate_oldest";
max_tool_calls_per_message?: number;
tool_call_timeout?: number;
session_id?: string;
@@ -690,4 +692,11 @@ export interface OpenAIChatChunk {
total_tokens: number;
};
timings?: Record<string, number>;
+ context_truncated?: {
+ dropped_messages: number;
+ prompt_tokens_before?: number;
+ prompt_tokens_after?: number;
+ context_length?: number;
+ fits: boolean;
+ };
}
diff --git a/studio/frontend/src/features/chat/utils/context-truncation.ts b/studio/frontend/src/features/chat/utils/context-truncation.ts
new file mode 100644
index 00000000000..a888b5a409a
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/context-truncation.ts
@@ -0,0 +1,25 @@
+// 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 { OpenAIChatChunk } from "../types/api";
+
+export type ContextTruncation = NonNullable<
+ OpenAIChatChunk["context_truncated"]
+>;
+
+export function mergeContextTruncation(
+ current: ContextTruncation | undefined,
+ incoming: ContextTruncation,
+): ContextTruncation {
+ if (!current) return incoming;
+
+ return {
+ ...current,
+ ...incoming,
+ dropped_messages: current.dropped_messages + incoming.dropped_messages,
+ prompt_tokens_before:
+ current.prompt_tokens_before ?? incoming.prompt_tokens_before,
+ prompt_tokens_after:
+ incoming.prompt_tokens_after ?? current.prompt_tokens_after,
+ };
+}
diff --git a/studio/frontend/tests/rolling-context-window.test.ts b/studio/frontend/tests/rolling-context-window.test.ts
new file mode 100644
index 00000000000..65f2e79570b
--- /dev/null
+++ b/studio/frontend/tests/rolling-context-window.test.ts
@@ -0,0 +1,53 @@
+// 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 assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import { mergeContextTruncation } from "../src/features/chat/utils/context-truncation.ts";
+
+const adapter = readFileSync(
+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),
+ "utf8",
+);
+const transport = readFileSync(
+ new URL("../src/features/chat/api/chat-api.ts", import.meta.url),
+ "utf8",
+);
+
+test("local chat opts into the rolling context policy", () => {
+ assert.match(adapter, /isGguf === true/);
+ assert.match(adapter, /context_overflow:\s*"truncate_oldest"/);
+ assert.match(adapter, /Older turns omitted from model context/);
+});
+
+test("the transport preserves standard chunks with context metadata", () => {
+ assert.doesNotMatch(transport, /parsed\.type === "context_truncated"/);
+ assert.match(adapter, /chunk\.context_truncated/);
+ assert.match(adapter, /contextTruncation = mergeContextTruncation\(/);
+});
+
+test("tool-loop truncation metadata accumulates across stream events", () => {
+ const first = mergeContextTruncation(undefined, {
+ dropped_messages: 2,
+ prompt_tokens_before: 1200,
+ prompt_tokens_after: 800,
+ context_length: 1600,
+ fits: true,
+ });
+ const combined = mergeContextTruncation(first, {
+ dropped_messages: 3,
+ prompt_tokens_before: 1000,
+ prompt_tokens_after: 700,
+ context_length: 1400,
+ fits: true,
+ });
+
+ assert.deepEqual(combined, {
+ dropped_messages: 5,
+ prompt_tokens_before: 1200,
+ prompt_tokens_after: 700,
+ context_length: 1400,
+ fits: true,
+ });
+});