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: add Chat settings to disable or ease GGUF auto-compaction (#9774)
Souravrajvi02ea0a3c9a316
diff --git a/studio/backend/core/inference/checkpoint.py b/studio/backend/core/inference/checkpoint.pyindex 2c4191fae03..013acd71275 100644--- a/studio/backend/core/inference/checkpoint.py+++ b/studio/backend/core/inference/checkpoint.py@@ -516,6 +516,10 @@ def fit_checkpoint_context(keeps_boundary: bool = False,can_reset: bool = False,searchable: bool = True,+ # Signature compatibility with `fit_rolling_context`. A checkpoint reset already+ # drops to the latest turn plus X; an extra bite of the window would only shrink+ # the standing-instruction block, which is the half worth keeping.+ headroom_ratio: Optional[float] = None,) -> tuple[list[dict], Optional[dict[str, Any]]]:"""Fit a chat by resetting the epoch, keeping the newest turn and a carried-forward X.diff --git a/studio/backend/core/inference/context_window.py b/studio/backend/core/inference/context_window.pyindex 18dccc67a16..c0597635f5d 100644--- a/studio/backend/core/inference/context_window.py+++ b/studio/backend/core/inference/context_window.py@@ -489,6 +489,24 @@ def turn_diagnosis(}+def clamp_compaction_headroom_ratio(value: Any) -> Optional[float]:+ """Return a usable extra-trim ratio, or None when the caller left it unset.++ ``ROLLING_COMPACTION_HEADROOM_RATIO`` already clamps the process default to+ ``[0, 0.9]``. Per-request overrides go through the same gate so a UI slider+ cannot ask the fitter to drop the entire prompt or to grow it.+ """+ if value is None:+ return None+ try:+ ratio = float(value)+ except (TypeError, ValueError):+ return None+ if ratio != ratio: # NaN+ return None+ return max(0.0, min(0.9, ratio))++def fit_rolling_context(messages: list[dict],*,@@ -499,6 +517,7 @@ def fit_rolling_context(reserve_tokens: int = 0,sticky_dropped: int = 0,keeps_boundary: bool = False,+ headroom_ratio: Optional[float] = None,) -> tuple[list[dict], Optional[dict[str, Any]]]:"""Fit a chat into its real context by dropping oldest complete turns.@@ -547,6 +566,10 @@ def fit_rolling_context(# Phase two, only if what is left still does not fit: move the boundary, taking a# chunk out rather than skimming to the brim so it can stay put for a while.trim_target = prompt_target+ # The 5% floor on each eviction bite, given up only by a caller that asked for no+ # extra trim. Keyed on the ratio and not on `headroom`, which `keeps_boundary = False`+ # zeroes for every threadless and incognito request, none of which chose anything.+ min_bite = Trueif current_tokens > prompt_target:# Summed, not max()'d: the reserve is spent immediately on recalled passages, so# counting it as headroom would hand back room that is already taken.@@ -557,11 +580,17 @@ def fit_rolling_context(# with no persisted thread, or a request whose turns are not saved gets neither# the boundary nor a recall of what went, so there it is simply 25% less history# than plain eviction would have kept.- headroom = int(prompt_target * _COMPACTION_HEADROOM_RATIO) if keeps_boundary else 0+ ratio = clamp_compaction_headroom_ratio(headroom_ratio)+ if ratio is None:+ ratio = _COMPACTION_HEADROOM_RATIO+ min_bite = ratio > 0+ headroom = int(prompt_target * ratio) if keeps_boundary else 0trim_target = max(1, prompt_target - reserve_tokens - headroom)while current_tokens > trim_target:- keep_ratio = min(0.95, trim_target / max(1, current_tokens))+ keep_ratio = trim_target / max(1, current_tokens)+ if min_bite:+ keep_ratio = min(0.95, keep_ratio)candidate, dropped = truncate_oldest_messages(fitted,keep_ratio,diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex fa48992e14b..81a84e00f5d 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -50,6 +50,8 @@ from typing import (import httpxfrom core.inference.context_window import (+ _COMPACTION_HEADROOM_RATIO,+ clamp_compaction_headroom_ratio,prompt_budget,estimate_messages_tokens,estimate_messages_tokens_dense,@@ -201,6 +203,33 @@ def _archive_is_degraded() -> bool:return False+def _compaction_fit_kwargs(+ context_policy: Optional[str] = None, compaction_headroom_ratio: Optional[float] = None+) -> dict:+ """Per-request overrides the four rolling-fit call sites share.++ Unset values keep the process defaults (UNSLOTH_CONTEXT_POLICY and+ ROLLING_COMPACTION_HEADROOM_RATIO) so an older client is unaffected.+ """+ extra: dict = {}+ if context_policy in ("checkpoint", "rolling"):+ extra["context_policy"] = context_policy+ if compaction_headroom_ratio is not None:+ extra["headroom_ratio"] = compaction_headroom_ratio+ return extra+++def _request_uses_checkpoint(requested_policy: Optional[str] = None) -> bool:+ """Process default, unless this request named checkpoint or rolling."""+ if requested_policy == "checkpoint":+ return True+ if requested_policy == "rolling":+ return False+ from core.inference import checkpoint++ return checkpoint.enabled()++def _fit_context(messages, **kwargs):"""The context policy in one place, so the five call sites do not each pick one.@@ -208,11 +237,27 @@ def _fit_context(messages, **kwargs):reachable via `UNSLOTH_CONTEXT_POLICY=rolling` as the A/B arm and the escape hatch fora misbehaving template family. A request that may not reset (see `_can_reset_epoch`)silently keeps rolling, which is why the two fits share a signature.++ ``context_policy`` on the request overrides the process default so Studio can offer+ a sliding window without restarting the server."""can_reset = bool(kwargs.pop("can_reset", False))+ # Whether `sticky_dropped` is the depth of a checkpoint RESET. Defaults to True, which+ # is what a caller with no thread state to consult has always assumed.+ sticky_is_checkpoint = bool(kwargs.pop("sticky_is_checkpoint", True))+ requested_policy = kwargs.pop("context_policy", None)+ if requested_policy not in ("checkpoint", "rolling"):+ requested_policy = Nonetry:from core.inference import checkpoint- if not can_reset and checkpoint.enabled() and int(kwargs.get("sticky_dropped") or 0) > 0:++ use_checkpoint = _request_uses_checkpoint(requested_policy)+ if (+ not can_reset+ and use_checkpoint+ and sticky_is_checkpoint+ and int(kwargs.get("sticky_dropped") or 0) > 0+ ):# An epoch is in force but THIS request may not reset. Falling straight through# to rolling was the worst of both: it replays the checkpoint-sized (near-total)# eviction WITHOUT rebuilding the block that made it survivable. Measured on a@@ -228,8 +273,12 @@ def _fit_context(messages, **kwargs):return fitted, truncation# A checkpoint boundary means nothing to rolling, which cannot rebuild what it# assumed. Recomputing loses the epoch: an un-compacted window tells no lie.+ #+ # `sticky_is_checkpoint` false skips this branch entirely and keeps the count:+ # rolling recorded it, rolling replays it, and the rolling fit reports no+ # `checkpoint_started`, so `_archive_and_recall` still runs the inline recall.kwargs.pop("sticky_dropped", None)- if can_reset and checkpoint.enabled():+ if can_reset and use_checkpoint:# A degraded archive downgrades reset to REPLAY rather than closing the door.# Refusing outright sent the request to rolling, which replays the same boundary# WITHOUT rebuilding the block, so a thread with an epoch silently lost its@@ -837,6 +886,31 @@ def _records_boundary(truncation: dict) -> bool:return bool(truncation.get("fits")) or bool(truncation.get("dropped_messages"))+def _effective_headroom_ratio(compaction_headroom_ratio: Optional[float] = None) -> float:+ """The extra-trim share this request's rolling fit actually used."""+ ratio = clamp_compaction_headroom_ratio(compaction_headroom_ratio)+ return _COMPACTION_HEADROOM_RATIO if ratio is None else ratio+++def _boundary_metadata(+ fitted: list[dict],+ before: Optional[list[dict]],+ compaction_headroom_ratio: Optional[float] = None,+) -> dict:+ """Where this fit put the boundary, and under how much extra trim.++ The ratio rides with the depth because the depth cannot be read without it: phase one+ of `fit_rolling_context` re-applies the saved count before anything else and stops once+ the result fits, so a chat whose setting has moved either way would replay the old cut+ and never reach the phase that consults the new one.+ """+ return {+ "boundary_messages": _branch_boundary(fitted, before),+ "boundary_anchor": _branch_boundary_anchor(fitted, before),+ "boundary_headroom_ratio": _effective_headroom_ratio(compaction_headroom_ratio),+ }++def _branch_non_system(branch: Optional[list[dict]]) -> list[dict]:"""The branch as ``_branch_boundary`` counts it: system and developer turns removed."""return [@@ -930,10 +1004,21 @@ def _archive_content_on_branch(content, transcript: Optional[list[str]]) -> boolreturn True-def _sticky_compaction_boundary(- thread_id: Optional[str], branch_messages: Optional[list[dict]] = None-) -> int:- """How many leading messages this thread last compacted away, or 0.+def _sticky_compaction_state(+ thread_id: Optional[str],+ branch_messages: Optional[list[dict]] = None,+ context_policy: Optional[str] = None,+ can_reset: bool = True,+ compaction_headroom_ratio: Optional[float] = None,+) -> tuple[int, bool]:+ """How many leading messages this thread last compacted away, and who compacted them.++ The provenance decides which fitter may consume the count. A rolling boundary handed+ to `fit_checkpoint_context` reads as an epoch already in force, so the fit returns+ `checkpoint_started` false and `_archive_and_recall` skips the recall the rolling+ fallback would have run. Mixed provenance across surviving rows counts as rolling:+ `min(boundaries)` below may pick either row, so the safe reading is the one that still+ recalls.The fit is otherwise stateless: the client re-sends the whole transcript each request,so "keep the newest N tokens" slides forward every turn, which tells the user nothing@@ -945,9 +1030,9 @@ def _sticky_compaction_boundary(a non-persisting API client, or a storage error all mean "no boundary"."""if not thread_id:- return 0+ return 0, False+ requested_ratio = _effective_headroom_ratio(compaction_headroom_ratio)try:- from core.inference import checkpointfrom storage import studio_db# The stored rows are the whole DAG, so the newest assistant turn can belong to a@@ -959,7 +1044,7 @@ def _sticky_compaction_boundary(_branch = _archive_branch_transcript(branch_messages, ("assistant",))if branch_messages and not _branch:# A branch with no reply of its own has no boundary to restore.- return 0+ return 0, Falsecandidates = [messagefor message in reversed(studio_db.list_chat_messages(thread_id) or [])@@ -967,7 +1052,7 @@ def _sticky_compaction_boundary(and _archive_content_on_branch(message.get("content"), _branch)]if not candidates:- return 0+ return 0, False# The newest on-branch assistant turn decides, except that the branch check is# textual, so two Retry siblings that both read "Done" are indistinguishable here@@ -988,30 +1073,59 @@ def _sticky_compaction_boundary(newest = _archive_message_text(candidates[0].get("content"))boundaries = []+ origins = []for message in candidates:if _archive_message_text(message.get("content")) != newest:continuemetadata = message.get("metadata") or {}if not isinstance(metadata, dict):- return 0+ return 0, Falsetruncation = metadata.get("contextTruncation") or (metadata.get("custom") or {}).get("contextTruncation")if not isinstance(truncation, dict):- return 0+ return 0, False# Only a fit that SUCCEEDED describes a boundary worth restoring.if not truncation.get("fits"):- return 0- # And only under the policy that recorded it. A checkpoint boundary is the depth- # of a RESET, affordable only because the block is rebuilt on every replay;- # under `UNSLOTH_CONTEXT_POLICY=rolling` nothing rebuilds it and both- # `_fit_context` guards are `checkpoint.enabled()`, so the depth replays with- # nothing handed back (18 evicted where rolling picks 6). Refused HERE, not at- # the fit: `boundary_messages` is re-recorded every turn, so a rolling turn that- # inherited 18 would persist it with no `checkpoint` key and make the- # reset-sized window permanent. Let rolling compute its own.- if truncation.get("checkpoint") and not checkpoint.enabled():- return 0+ return 0, False+ # A boundary is valid only under the fit that will consume it, and the two+ # directions fail differently.+ #+ # A checkpoint boundary is the depth of a RESET, affordable only because the+ # block is rebuilt on every replay. Under rolling nothing rebuilds it, so the+ # depth replays with nothing handed back (18 evicted where rolling picks 6).+ # Refused HERE, not at the fit: `boundary_messages` is re-recorded every turn,+ # so a rolling turn that inherited 18 would persist it with no `checkpoint` key+ # and make the reset-sized window permanent.+ #+ # The other way, a rolling boundary reaching `fit_checkpoint_context` reads as+ # an epoch already in force, so the reset returns `checkpoint_started` false+ # and the automatic recall never runs. That only happens where the request may+ # actually reset; `_can_reset_epoch` false means the fit stays rolling whatever+ # the process policy says, and there the rolling boundary is the right one to+ # replay. Rejecting it there instead let the boundary slide every turn for any+ # model whose template cannot render tools.+ recorded_checkpoint = bool(truncation.get("checkpoint"))+ effective_checkpoint = _request_uses_checkpoint(context_policy)+ if recorded_checkpoint and not effective_checkpoint:+ return 0, False+ if not recorded_checkpoint and effective_checkpoint and can_reset:+ return 0, False+ # Changing the extra trim has to change something. Phase one of+ # `fit_rolling_context` re-applies this count before anything else and stops+ # once the result fits, so a boundary cut under a DIFFERENT ratio never reaches+ # the phase that reads the new one, in either direction: measured on a+ # 121-message transcript at context_length 1600, a stored boundary of 86 gave+ # `dropped 86` whether the request asked for 0.05 or 0.25. Refusing it makes+ # the fit recompute, which is the only place the new ratio is read. Absent on+ # rows saved before the ratio was recorded, which keep replaying as they did.+ if not recorded_checkpoint:+ recorded_ratio = truncation.get("boundary_headroom_ratio")+ if (+ recorded_ratio is not None+ and abs(float(recorded_ratio) - requested_ratio) > 1e-9+ ):+ return 0, False# Counted against the request's own transcript, which is what it is applied# to. `dropped_messages` is the fallback for turns saved before that was# recorded: equal for a single fit, too large for a turn that refit often.@@ -1031,10 +1145,29 @@ def _sticky_compaction_boundary(recorded = min(recorded, index)breakboundaries.append(recorded)- return min(boundaries) if boundaries else 0+ origins.append(recorded_checkpoint)+ if not boundaries:+ return 0, False+ return min(boundaries), all(origins)except Exception:- return 0- return 0+ return 0, False+++def _sticky_compaction_boundary(+ thread_id: Optional[str],+ branch_messages: Optional[list[dict]] = None,+ context_policy: Optional[str] = None,+ can_reset: bool = True,+ compaction_headroom_ratio: Optional[float] = None,+) -> int:+ """`_sticky_compaction_state` without the provenance, for callers that only fit."""+ return _sticky_compaction_state(+ thread_id,+ branch_messages,+ context_policy = context_policy,+ can_reset = can_reset,+ compaction_headroom_ratio = compaction_headroom_ratio,+ )[0]def _prefix_user_text(message: dict, prefix: str) -> dict:@@ -25518,6 +25651,8 @@ class LlamaCppBackend:perf_callback: Optional[Callable[[dict], None]] = None,reasoning_provenance: Optional[dict] = None,context_overflow: Optional[str] = None,+ context_policy: Optional[str] = None,+ compaction_headroom_ratio: Optional[float] = None,thread_id: Optional[str] = None,tools_withheld: bool = False,_allow_respawn_retry: bool = True,@@ -25590,6 +25725,20 @@ class LlamaCppBackend:):try:_before_fit = openai_messages+ # One value for both the boundary read and the fit: a boundary the fit+ # would not consume as an epoch must not be discarded as if it would.+ _can_reset = _can_reset_epoch(+ thread_id,+ _backend_supports_tools(self),+ tools_withheld = tools_withheld,+ )+ _sticky, _sticky_is_checkpoint = _sticky_compaction_state(+ thread_id,+ _before_fit,+ context_policy = context_policy,+ can_reset = _can_reset,+ compaction_headroom_ratio = compaction_headroom_ratio,+ )openai_messages, truncation = _fit_with_instruction_pins(openai_messages,context_length = self._effective_context_length,@@ -25604,13 +25753,11 @@ class LlamaCppBackend:should_abort = lambda: bool(cancel_event and cancel_event.is_set()),),reserve_tokens = _conversation_recall_reserve(thread_id),- sticky_dropped = _sticky_compaction_boundary(thread_id, _before_fit),+ sticky_dropped = _sticky,+ sticky_is_checkpoint = _sticky_is_checkpoint,keeps_boundary = _keeps_compaction_boundary(thread_id),- can_reset = _can_reset_epoch(- thread_id,- _backend_supports_tools(self),- tools_withheld = tools_withheld,- ),+ can_reset = _can_reset,+ **_compaction_fit_kwargs(context_policy, compaction_headroom_ratio),)if truncation:# Inline, not a forged tool exchange: this path sends no tools array,@@ -25648,8 +25795,9 @@ class LlamaCppBackend:if truncation and _records_boundary(truncation):truncation = {**truncation,- "boundary_messages": _branch_boundary(openai_messages, _before_fit),- "boundary_anchor": _branch_boundary_anchor(openai_messages, _before_fit),+ **_boundary_metadata(+ openai_messages, _before_fit, compaction_headroom_ratio+ ),}payload["messages"] = neutralize_control_markup_in_messages(openai_messages, None, self.markup_profile@@ -25857,6 +26005,8 @@ class LlamaCppBackend:perf_callback = perf_callback,reasoning_provenance = reasoning_provenance,context_overflow = retry_context_overflow,+ context_policy = context_policy,+ compaction_headroom_ratio = compaction_headroom_ratio,# The retry refits for the replacement window and can evict more than# the first attempt did. Without the thread those extra turns are# archived nowhere and no reserve or boundary applies, on the one path@@ -25913,6 +26063,8 @@ class LlamaCppBackend:perf_callback: Optional[Callable[[dict], None]] = None,reasoning_provenance: Optional[dict] = None,context_overflow: Optional[str] = None,+ context_policy: Optional[str] = None,+ compaction_headroom_ratio: Optional[float] = None,tool_choice: Any = None,) -> Generator[dict, None, None]:"""@@ -26299,6 +26451,22 @@ class LlamaCppBackend:_preflight_context_length = self._effective_context_lengthtry:_before_fit = conversation+ _iteration_can_reset = _can_reset_epoch(+ thread_id,+ _backend_supports_tools(self),+ tools_withheld = _memory_tool_withheld(thread_id, tools),+ )+ _iteration_sticky, _iteration_sticky_is_checkpoint = (+ (0, True)+ if _sticky_boundary_applied+ else _sticky_compaction_state(+ thread_id,+ _request_branch,+ context_policy = context_policy,+ can_reset = _iteration_can_reset,+ compaction_headroom_ratio = compaction_headroom_ratio,+ )+ )conversation, truncation = _fit_with_instruction_pins(conversation,context_length = self._effective_context_length,@@ -26318,17 +26486,11 @@ class LlamaCppBackend:),anchor_ids = _rolling_anchor_ids,keeps_boundary = _keeps_compaction_boundary(thread_id),- can_reset = _can_reset_epoch(- thread_id,- _backend_supports_tools(self),- tools_withheld = _memory_tool_withheld(thread_id, tools),- ),+ can_reset = _iteration_can_reset,reserve_tokens = _conversation_recall_reserve(thread_id),- sticky_dropped = (- 0- if _sticky_boundary_applied- else _sticky_compaction_boundary(thread_id, _request_branch)- ),+ sticky_dropped = _iteration_sticky,+ sticky_is_checkpoint = _iteration_sticky_is_checkpoint,+ **_compaction_fit_kwargs(context_policy, compaction_headroom_ratio),)# Accounted for in this request now, whatever the fit decided._sticky_boundary_applied = True@@ -26390,9 +26552,8 @@ class LlamaCppBackend:if truncation and _records_boundary(truncation):truncation = {**truncation,- "boundary_messages": _branch_boundary(conversation, _request_branch),- "boundary_anchor": _branch_boundary_anchor(- conversation, _request_branch+ **_boundary_metadata(+ conversation, _request_branch, compaction_headroom_ratio),}# `fits` False too: it carries the does-not-fit diagnosis.@@ -26487,6 +26648,7 @@ class LlamaCppBackend:_backend_supports_tools(self),tools_withheld = _memory_tool_withheld(thread_id, tools),),+ **_compaction_fit_kwargs(context_policy, compaction_headroom_ratio),)# Recorded here, not left to the forwarding below. That list is# drained from INSIDE the reopened stream, so a replacement server@@ -26516,11 +26678,10 @@ class LlamaCppBackend:)if truncation:if _records_boundary(truncation):- truncation["boundary_messages"] = _branch_boundary(- conversation, _request_branch- )- truncation["boundary_anchor"] = _branch_boundary_anchor(- conversation, _request_branch+ truncation.update(+ _boundary_metadata(+ conversation, _request_branch, compaction_headroom_ratio+ ))# Report every shortened retry, including a rescued refusal._respawn_truncations.append(truncation)@@ -27937,6 +28098,25 @@ class LlamaCppBackend:_final_preflight_context_length = self._effective_context_lengthtry:_before_final_fit = conversation+ # Withheld, not `tools`: this is the synthesised final answer and+ # `stream_payload` below sends no tools array at all, so the request's+ # catalogue answers a question it does not pose and would let a NEW epoch+ # start on the one pass that can never call `search_conversation`.+ # Replaying an epoch already in force is unaffected.+ _final_can_reset = _can_reset_epoch(+ thread_id, _backend_supports_tools(self), tools_withheld = True+ )+ _final_sticky, _final_sticky_is_checkpoint = (+ (0, True)+ if _sticky_boundary_applied+ else _sticky_compaction_state(+ thread_id,+ _request_branch,+ context_policy = context_policy,+ can_reset = _final_can_reset,+ compaction_headroom_ratio = compaction_headroom_ratio,+ )+ )conversation, truncation = _fit_with_instruction_pins(conversation,context_length = self._effective_context_length,@@ -27951,23 +28131,11 @@ class LlamaCppBackend:),anchor_ids = _rolling_anchor_ids,keeps_boundary = _keeps_compaction_boundary(thread_id),- can_reset = _can_reset_epoch(- thread_id,- _backend_supports_tools(self),- # Withheld, not `tools`: this is the synthesised final answer- # and `stream_payload` below sends no tools array at all, so- # the request's catalogue answers a question it does not pose- # and would let a NEW epoch start on the one pass that can- # never call `search_conversation`. Replaying an epoch already- # in force is unaffected.- tools_withheld = True,- ),+ can_reset = _final_can_reset,reserve_tokens = _conversation_recall_reserve(thread_id),- sticky_dropped = (- 0- if _sticky_boundary_applied- else _sticky_compaction_boundary(thread_id, _request_branch)- ),+ sticky_dropped = _final_sticky,+ sticky_is_checkpoint = _final_sticky_is_checkpoint,+ **_compaction_fit_kwargs(context_policy, compaction_headroom_ratio),)_sticky_boundary_applied = Trueif truncation:@@ -28012,8 +28180,9 @@ class LlamaCppBackend:if truncation and _records_boundary(truncation):truncation = {**truncation,- "boundary_messages": _branch_boundary(conversation, _request_branch),- "boundary_anchor": _branch_boundary_anchor(conversation, _request_branch),+ **_boundary_metadata(+ conversation, _request_branch, compaction_headroom_ratio+ ),}# `fits` False too: it carries the diagnosis the client needs to explain# WHY. Otherwise the user only sees llama-server's error, which reports@@ -28090,6 +28259,7 @@ class LlamaCppBackend:# The final pass again, so again no tools array is sent.tools_withheld = True,),+ **_compaction_fit_kwargs(context_policy, compaction_headroom_ratio),)if truncation:# Archive only; see the iteration respawn refit above.@@ -28113,11 +28283,10 @@ class LlamaCppBackend:)if truncation:if _records_boundary(truncation):- truncation["boundary_messages"] = _branch_boundary(- conversation, _request_branch- )- truncation["boundary_anchor"] = _branch_boundary_anchor(- conversation, _request_branch+ truncation.update(+ _boundary_metadata(+ conversation, _request_branch, compaction_headroom_ratio+ ))_final_respawn_truncations.append(truncation)except Exception as exc:diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 2b1d1bf0239..027b61c614b 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -2064,6 +2064,33 @@ class ChatCompletionRequest(BaseModel):"Both truncation policies preserve system messages and tool-call groups."),)+ context_policy: Optional[Literal["checkpoint", "rolling"]] = Field(+ None,+ description = (+ "[x-unsloth] How a local GGUF chat compacts once context_overflow is "+ "truncate_oldest. 'checkpoint' resets to the latest turn plus standing "+ "instructions (Studio default). 'rolling' drops oldest complete turns. "+ "Unset uses UNSLOTH_CONTEXT_POLICY."+ ),+ )+ compaction_headroom_ratio: Optional[float] = Field(+ None,+ ge = 0.0,+ le = 0.9,+ description = (+ "[x-unsloth] Extra share of the prompt budget to drop when a rolling "+ "compaction fires, so the boundary can stay put for a stretch of turns. "+ "0.25 is the process default (ROLLING_COMPACTION_HEADROOM_RATIO). Ignored "+ "for checkpoint compaction. Unset keeps the process default."+ ),+ )+ studio_tool_history: Optional[bool] = Field(+ None,+ description = (+ "[x-unsloth] The replayed tool calls were produced by Studio's local "+ "tool loop rather than by an OpenAI-compatible client tool contract."+ ),+ )max_tool_calls_per_message: Optional[int] = Field(25,ge = 0,@@ -2476,6 +2503,15 @@ class ChatCountTokensRequest(BaseModel):None,description = "[x-unsloth] Strip leaked tool-call markup from replayed history",)+ studio_tool_history: Optional[bool] = Field(+ None,+ description = (+ "[x-unsloth] Mirrors ChatCompletionRequest: the replayed tool calls came from "+ "Studio's local tool loop, so _takes_tool_passthrough routes the count the way "+ "it routes the completion. Declared rather than left to extra='allow', which "+ "coerces nothing and would read the string 'false' as a claim of ownership."+ ),+ )permission_mode: Optional[str] = Field(None,description = "[x-unsloth] Permission level the completion would send. Only 'full' changes "diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.pyindex d1c6c13d424..ceb9ef1baee 100644--- a/studio/backend/routes/chat_history.py+++ b/studio/backend/routes/chat_history.py@@ -512,6 +512,13 @@ class ChatSettingsPayload(BaseModel):expandQuantizations: Optional[bool] = NoneshowAllQuantizations: Optional[bool] = NonefitOnDeviceOnly: Optional[bool] = None+ # Local GGUF auto-compaction. Off omits context_overflow so a full window+ # errors instead of silently dropping history. contextPolicy/headroom are+ # the per-request overrides for UNSLOTH_CONTEXT_POLICY and+ # ROLLING_COMPACTION_HEADROOM_RATIO.+ autoCompactEnabled: Optional[bool] = None+ contextPolicy: Optional[Literal["inherit", "checkpoint", "rolling"]] = None+ compactionHeadroomRatio: Optional[float] = Field(default = None, ge = 0.0, le = 0.9)@field_validator("researchModelTimeoutSeconds", mode = "before")@classmethoddiff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 73eccf62a21..f5b4dfc8fea 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -723,6 +723,20 @@ def _rolling_context_policy(payload) -> Optional[str]:return policy if policy == "truncate_oldest" else None+def _request_context_policy(payload) -> Optional[str]:+ requested = getattr(payload, "context_policy", None)+ if isinstance(requested, str):+ value = requested.strip().lower()+ if value in ("checkpoint", "rolling"):+ return value+ return None+++def _request_compaction_headroom_ratio(payload) -> Optional[float]:+ from core.inference.context_window import clamp_compaction_headroom_ratio+ return clamp_compaction_headroom_ratio(getattr(payload, "compaction_headroom_ratio", 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."""@@ -3291,7 +3305,7 @@ def _selects_only_provider_hosted_tools(payload, provider_type: str | None) -> breturn True-_STUDIO_MEMORY_TOOLS = frozenset({"search_conversation"})+_LEGACY_STUDIO_MEMORY_TOOLS = frozenset({"search_conversation"})def _tool_call_names(message) -> list[Optional[str]]:@@ -3312,33 +3326,40 @@ def _tool_call_names(message) -> list[Optional[str]]:return names-def _only_studio_memory_tool_history(payload) -> bool:- """True when the request's ONLY tool history is Unsloth's own conversation memory.+def _only_studio_tool_history(payload) -> bool:+ """True when the request's ONLY tool history was produced by Unsloth's own loop.++ Once a Studio-local tool runs, the branch keeps an assistant `tool_calls` turn and its+ `role="tool"` result and the client replays both forever. Read as a CLIENT tool+ contract, that history routes every later turn to the llama-server passthrough, which+ runs no context fit, so the epoch, the carried-forward block and the automatic recall+ vanish one turn after the compaction that created them.- Once the model uses `search_conversation`, the branch keeps an assistant `tool_calls`- turn and its `role="tool"` result and the client replays both forever. Read as a CLIENT- tool contract, that history routes every later turn to the llama-server passthrough,- which runs no context fit, so the epoch, the carried-forward block and the automatic- recall vanish one turn after the compaction that created them. It is Unsloth's own- read-only tool run by Unsloth's own loop, so it must route as a tools-on Unsloth chat.+ Current Studio clients say so directly: `studio_tool_history` is set only after every+ serialized call was checked for local provenance. Older clients send no marker, so the+ `search_conversation`-only fallback below stays, deliberately strict -- an unnamed call+ or result, or any other tool name, means "not ours", so a real client tool loop is+ never claimed.- Deliberately strict: a caller-supplied `tools` catalog, an unnamed call or result, or- any other tool name means "not ours", so a real client tool loop is never claimed.+ A caller-supplied `tools` catalog is a client contract either way."""if getattr(payload, "tools", None):return False+ messages = getattr(payload, "messages", None) or []+ if getattr(payload, "studio_tool_history", False):+ return _has_openai_tool_history(messages)saw_call = False- for message in getattr(payload, "messages", None) or []:+ for message in messages:role = message.get("role") if isinstance(message, dict) else getattr(message, "role", None)for name in _tool_call_names(message):saw_call = True- if name not in _STUDIO_MEMORY_TOOLS:+ if name not in _LEGACY_STUDIO_MEMORY_TOOLS:return Falseif role == "tool":result_name = (message.get("name") if isinstance(message, dict) else getattr(message, "name", None))- if result_name not in _STUDIO_MEMORY_TOOLS:+ if result_name not in _LEGACY_STUDIO_MEMORY_TOOLS:return Falsereturn saw_call@@ -3356,9 +3377,7 @@ def _takes_tool_passthrough(payload, llama_backend) -> bool:# Read defensively: a count request carries no tool_choice, and absent withdraws nothing.has_client_contract = (bool(payload.tools) and getattr(payload, "tool_choice", None) != "none"- ) or (- _has_openai_tool_history(payload.messages) and not _only_studio_memory_tool_history(payload)- )+ ) or (_has_openai_tool_history(payload.messages) and not _only_studio_tool_history(payload))supports_passthrough = getattr(llama_backend, "supports_tool_passthrough", supports_tools)if supports_passthrough and has_client_contract:return True@@ -4437,7 +4456,7 @@ async def _select_request_tools(# is added on that condition rather than requested.has_archive = _thread_has_conversation_archive(getattr(payload, "thread_id", None))tools = [t for t in tools if t["function"]["name"] != "search_conversation"]- if has_archive and (tools_on or (checkpoint_fitted and _checkpoint_needs_search())):+ if has_archive and (tools_on or (checkpoint_fitted and _checkpoint_needs_search(payload))):tools = tools + [t for t in ALL_TOOLS if t["function"]["name"] == "search_conversation"]if not tools_on:# After a reset, search_conversation is the only route back to what was@@ -4507,11 +4526,17 @@ _CHECKPOINT_SESSION_NUDGE = ()-def _checkpoint_needs_search() -> bool:+def _checkpoint_needs_search(payload = None) -> bool:"""Whether the context policy makes search_conversation load-bearing rather than extra.- Read at call time, so flipping UNSLOTH_CONTEXT_POLICY needs no restart.+ ``context_policy`` on the request overrides UNSLOTH_CONTEXT_POLICY, matching the+ fitter, so tool admission and the compaction nudge follow the same effective policy."""+ requested = _request_context_policy(payload)+ if requested == "checkpoint":+ return True+ if requested == "rolling":+ return Falsetry:from core.inference import checkpointreturn checkpoint.enabled()@@ -4525,7 +4550,7 @@ def _checkpoint_recall_may_enable_tools(payload) -> bool:return bool(get_tool_policy() is not Falseand _rolling_context_policy(payload) is not None- and _checkpoint_needs_search()+ and _checkpoint_needs_search(payload)and _thread_has_conversation_archive(getattr(payload, "thread_id", None))and _thread_has_checkpoint(getattr(payload, "thread_id", None), getattr(payload, "messages", None)@@ -4538,6 +4563,7 @@ def _apply_compaction_nudge(tools: list[dict],*,checkpoint_fitted: bool = False,+ payload = None,) -> str:"""Append the compacted-session nudge when the conversation-archive tool is active.@@ -4553,7 +4579,7 @@ def _apply_compaction_nudge(if "search_conversation" not in tool_names:return nudgetext = _COMPACTED_SESSION_NUDGE- if checkpoint_fitted and _checkpoint_needs_search():+ if checkpoint_fitted and _checkpoint_needs_search(payload):text = text + " " + _CHECKPOINT_SESSION_NUDGEif not nudge:return text@@ -18903,6 +18929,7 @@ async def produce_openai_chat_completions(_nudge,tools_to_use,checkpoint_fitted = _rolling_context_policy(payload) is not None,+ payload = payload,)if _nudge:@@ -18979,6 +19006,8 @@ async def produce_openai_chat_completions(permission_mode = payload.permission_mode,perf_callback = _gguf_perf_callback,context_overflow = _rolling_context_policy(payload),+ context_policy = _request_context_policy(payload),+ compaction_headroom_ratio = _request_compaction_headroom_ratio(payload),)_tool_admission_mode = "chat_tool_stream" if payload.stream else "chat_tool_nonstream"@@ -19698,6 +19727,8 @@ async def produce_openai_chat_completions(seed = _seed,perf_callback = _gguf_perf_callback,context_overflow = _rolling_context_policy(payload),+ context_policy = _request_context_policy(payload),+ compaction_headroom_ratio = _request_compaction_headroom_ratio(payload),thread_id = payload.thread_id,# These requests suppress the tool loop AND are excluded from the checkpoint# repair above, so search_conversation is offered neither now nor on thediff --git a/studio/backend/tests/test_api_profile_usage_routes.py b/studio/backend/tests/test_api_profile_usage_routes.pyindex b3ee05638f1..75f2c440d91 100644--- a/studio/backend/tests/test_api_profile_usage_routes.py+++ b/studio/backend/tests/test_api_profile_usage_routes.py@@ -32,7 +32,7 @@ def _monitor_start_keywords(function) -> list[set[str]]:@pytest.mark.parametrize("function",[- inference_route.openai_chat_completions,+ inference_route.produce_openai_chat_completions,inference_route._responses_non_streaming,inference_route.openai_responses,inference_route.anthropic_messages,diff --git a/studio/backend/tests/test_chat_settings_payload.py b/studio/backend/tests/test_chat_settings_payload.pyindex 5c3a60d4a92..eaa12009126 100644--- a/studio/backend/tests/test_chat_settings_payload.py+++ b/studio/backend/tests/test_chat_settings_payload.py@@ -208,6 +208,31 @@ def test_the_rejection_detail_can_be_rendered_as_json():json.dumps(excinfo.value.detail, allow_nan = False)+def test_auto_compact_settings_round_trip():+ payload = ChatSettingsPayload.model_validate(+ {+ "autoCompactEnabled": False,+ "contextPolicy": "rolling",+ "compactionHeadroomRatio": 0.05,+ }+ )+ assert payload.model_dump(exclude_unset = True) == {+ "autoCompactEnabled": False,+ "contextPolicy": "rolling",+ "compactionHeadroomRatio": 0.05,+ }+++def test_auto_compact_settings_can_inherit_the_server_policy():+ payload = ChatSettingsPayload.model_validate({"contextPolicy": "inherit"})+ assert payload.model_dump(exclude_unset = True) == {"contextPolicy": "inherit"}+++def test_compaction_headroom_ratio_is_bounded():+ with pytest.raises(ValidationError):+ ChatSettingsPayload.model_validate({"compactionHeadroomRatio": 1.5})++def test_a_sampling_seed_survives_the_payload():payload = ChatSettingsPayload.model_validate({"inferenceParams": {"seed": 3407}})assert payload.model_dump(exclude_unset = True) == {"inferenceParams": {"seed": 3407}}diff --git a/studio/backend/tests/test_checkpoint_compaction.py b/studio/backend/tests/test_checkpoint_compaction.pyindex a2c4fd13449..24eccc2a495 100644--- a/studio/backend/tests/test_checkpoint_compaction.py+++ b/studio/backend/tests/test_checkpoint_compaction.py@@ -570,7 +570,7 @@ def test_studios_own_memory_history_does_not_steal_the_request_from_the_context_)assert inference_route._takes_tool_passthrough(payload, _ToolCapableBackend()) is False- assert inference_route._only_studio_memory_tool_history(payload) is True+ assert inference_route._only_studio_tool_history(payload) is Truedef test_a_real_client_tool_loop_still_takes_the_passthrough():@@ -590,7 +590,7 @@ def test_a_real_client_tool_loop_still_takes_the_passthrough():stream = True,)- assert inference_route._only_studio_memory_tool_history(payload) is False+ assert inference_route._only_studio_tool_history(payload) is Falseassert inference_route._takes_tool_passthrough(payload, _ToolCapableBackend()) is True# And a client catalog alongside Unsloth's own history is still the client's request.@@ -607,10 +607,71 @@ def test_a_real_client_tool_loop_still_takes_the_passthrough():}],)- assert inference_route._only_studio_memory_tool_history(with_catalog) is False+ assert inference_route._only_studio_tool_history(with_catalog) is Falseassert inference_route._takes_tool_passthrough(with_catalog, _ToolCapableBackend()) is True+def test_marked_python_history_keeps_compaction_on_the_fitted_path():+ from models.inference import ChatCompletionRequest+ from routes import inference as inference_route++ branch = _memory_tool_branch()+ branch[2]["tool_calls"][0]["function"]["name"] = "python"+ branch[3]["name"] = "python"+ payload = ChatCompletionRequest(+ model = "local",+ messages = branch,+ thread_id = "thread-1",+ enable_tools = False,+ studio_tool_history = True,+ context_overflow = "truncate_oldest",+ context_policy = "rolling",+ compaction_headroom_ratio = 0.0,+ stream = True,+ )++ assert inference_route._only_studio_tool_history(payload) is True+ assert inference_route._takes_tool_passthrough(payload, _ToolCapableBackend()) is False+ assert inference_route._rolling_context_policy(payload) == "truncate_oldest"+ assert inference_route._request_context_policy(payload) == "rolling"+ assert inference_route._request_compaction_headroom_ratio(payload) == 0.0++ empty = ChatCompletionRequest(+ model = "local",+ messages = [{"role": "user", "content": "hello"}],+ studio_tool_history = True,+ )+ assert inference_route._only_studio_tool_history(empty) is False+++def test_the_count_request_declares_the_studio_tool_history_marker():+ """The context-usage bar prices the same prompt only if it routes the same way.++ `ChatCountTokensRequest` sets `extra = "allow"`, so an undeclared marker arrives+ uncoerced: the JSON string "false" would reach `_only_studio_tool_history` as a truthy+ value and move the count onto the Unsloth tool path the completion never takes.+ """+ from models.inference import ChatCountTokensRequest+ from routes import inference as inference_route++ branch = _memory_tool_branch()+ branch[2]["tool_calls"][0]["function"]["name"] = "python"+ branch[3]["name"] = "python"++ payload = ChatCountTokensRequest(model = "local", messages = branch, studio_tool_history = True)+ assert payload.studio_tool_history is True+ assert inference_route._only_studio_tool_history(payload) is True+ assert inference_route._takes_tool_passthrough(payload, _ToolCapableBackend()) is False++ denied = ChatCountTokensRequest(model = "local", messages = branch, studio_tool_history = "false")+ assert denied.studio_tool_history is False+ assert inference_route._only_studio_tool_history(denied) is False++ unset = ChatCountTokensRequest(model = "local", messages = branch)+ assert unset.studio_tool_history is None+ assert inference_route._only_studio_tool_history(unset) is False++def test_can_reset_false_replays_an_epoch_but_never_starts_one():"""The second lock on the same door: `_fit_context` already routes a request that maynot reset to the rolling window, so reaching here with False means something upstream@@ -762,6 +823,16 @@ def test_only_a_checkpoint_fitted_request_is_told_the_conversation_was_reset():reset = routes_mod._apply_compaction_nudge("base.", tools, checkpoint_fitted = True)assert routes_mod._CHECKPOINT_SESSION_NUDGE in reset+ import types++ rolling_override = routes_mod._apply_compaction_nudge(+ "base.",+ tools,+ checkpoint_fitted = True,+ payload = types.SimpleNamespace(context_policy = "rolling"),+ )+ assert routes_mod._CHECKPOINT_SESSION_NUDGE not in rolling_override+def test_a_request_that_withdrew_the_tool_loop_never_resets(monkeypatch):"""The process policy is not the only way `search_conversation` fails to arrive.@@ -798,7 +869,7 @@ def test_the_gguf_route_tells_the_gate_when_tool_choice_none_withdrew_the_loop()body = inspect.getsource(llama_cpp.LlamaCppBackend.generate_chat_completion)assert body.count("tools_withheld = tools_withheld") == 2- route = inspect.getsource(routes_mod.openai_chat_completions)+ route = inspect.getsource(routes_mod.produce_openai_chat_completions)# `_tool_loop_unusable` is `_client_disabled_tool_calls` plus the other two shapes that# make the loop unusable once opened.assert "tools_withheld = _tool_loop_unusable" in route@@ -856,7 +927,7 @@ def test_the_memory_tool_override_needs_a_request_that_can_actually_reset(monkeyimport routes.inference as routes_modmonkeypatch.setattr(routes_mod, "_thread_has_conversation_archive", lambda _tid: True)- monkeypatch.setattr(routes_mod, "_checkpoint_needs_search", lambda: True)+ monkeypatch.setattr(routes_mod, "_checkpoint_needs_search", lambda *_a, **_k: True)payload = types.SimpleNamespace(enabled_tools = [],@@ -879,8 +950,8 @@ def test_identical_retry_siblings_do_not_let_one_of_them_claim_the_branch(monkey"""Two Retry siblings can carry byte-identical replies with only one having reset.The exact-text filter keeps both, and taking the first match reopened the tool loop on- the branch that never reset. Where the text cannot separate them, leave the request as- it was, as the sticky boundary's `min(boundaries)` does; this pins that agreement.+ the branch that never reset. Once the siblings also disagree on policy, neither boundary+ is safe to replay: checkpoint cannot inherit rolling, and rolling cannot inherit checkpoint."""import sysimport types@@ -931,11 +1002,12 @@ def test_identical_retry_siblings_do_not_let_one_of_them_claim_the_branch(monkeybranch = [{"role": "user", "content": "q"}, {"role": "assistant", "content": reply}]- # Only the abandoned sibling reset, so the shallower (never-reset) boundary is- # replayed and no epoch is in force on this branch.+ # Only the abandoned sibling reset, so byte-identical rows of mixed policy make+ # either policy refit._install(_rows(True))assert inference_routes._thread_has_checkpoint("t1", branch) is False- assert llama_cpp._sticky_compaction_boundary("t1", branch) == 6+ assert llama_cpp._sticky_compaction_boundary("t1", branch) == 0+ assert llama_cpp._sticky_compaction_boundary("t1", branch, context_policy = "rolling") == 0# Neither reset: unchanged, and still no loop._install(_rows(False))@@ -1124,14 +1196,17 @@ def test_the_loop_is_only_reopened_for_a_request_that_can_actually_compact():import routes.inference as routes_mod- route = inspect.getsource(routes_mod.openai_chat_completions)+ route = inspect.getsource(routes_mod.produce_openai_chat_completions)gate = route.split("if (\n not use_tools", 1)[1].split("use_tools = True", 1)[0]- assert "_checkpoint_needs_search()" in gate- assert "_thread_has_conversation_archive" in gate- assert "_rolling_context_policy(payload) is not None" in gate+ assert "_checkpoint_recall_may_enable_tools(payload)" in gate# And the request must be able to USE the loop once it opens, not merely open it.assert "_tool_loop_unusable" in gate+ helper = inspect.getsource(routes_mod._checkpoint_recall_may_enable_tools)+ assert "_checkpoint_needs_search(payload)" in helper+ assert "_thread_has_conversation_archive" in helper+ assert "_rolling_context_policy(payload) is not None" in helper+def test_a_request_that_could_never_call_the_tool_keeps_the_rolling_window():"""Two more ways a request can be handed a loop it can get nothing out of.@@ -1145,7 +1220,7 @@ def test_a_request_that_could_never_call_the_tool_keeps_the_rolling_window():import routes.inference as routes_mod- route = inspect.getsource(routes_mod.openai_chat_completions)+ route = inspect.getsource(routes_mod.produce_openai_chat_completions)predicate = route.split("_tool_loop_unusable = (", 1)[1].split("\n )", 1)[0]assert "_client_disabled_tool_calls" in predicate@@ -1185,6 +1260,108 @@ def test_only_truncate_oldest_is_a_policy_that_can_reset(requested, expected, moassert routes_mod._rolling_context_policy(payload) == expected+def test_a_request_can_force_rolling_when_checkpoint_is_the_process_default(monkeypatch):+ """Studio's sliding-window control must not need UNSLOTH_CONTEXT_POLICY=rolling."""+ from core.inference import llama_cpp++ seen = {}++ def _rolling(messages, **kwargs):+ seen["rolling"] = True+ seen["headroom"] = kwargs.get("headroom_ratio")+ return messages, None++ monkeypatch.setattr("core.inference.checkpoint.enabled", lambda: True)+ monkeypatch.setattr(llama_cpp, "fit_rolling_context", _rolling)+ llama_cpp._fit_context(+ [{"role": "user", "content": "hi"}],+ context_length = 4096,+ max_tokens = 128,+ count_tokens = count,+ can_reset = True,+ context_policy = "rolling",+ headroom_ratio = 0.0,+ )++ assert seen == {"rolling": True, "headroom": 0.0}+++def test_request_compaction_overrides_are_optional():+ import types++ import routes.inference as routes_mod++ empty = types.SimpleNamespace()+ assert routes_mod._request_context_policy(empty) is None+ assert routes_mod._request_compaction_headroom_ratio(empty) is None++ payload = types.SimpleNamespace(+ context_policy = "rolling",+ compaction_headroom_ratio = 0.1,+ )+ assert routes_mod._request_context_policy(payload) == "rolling"+ assert routes_mod._request_compaction_headroom_ratio(payload) == 0.1+ assert routes_mod._request_context_policy(types.SimpleNamespace(context_policy = "nope")) is None+++def test_checkpoint_needs_search_follows_the_request_policy(monkeypatch):+ """Tool admission must use the same override `_fit_context` does.++ With UNSLOTH_CONTEXT_POLICY=rolling, a Studio (or API) request that sends+ context_policy=checkpoint still resets; the search tool and nudge have to+ follow, or a tools-off chat archives history it can never retrieve.+ """+ import types++ import routes.inference as routes_mod++ monkeypatch.setattr("core.inference.checkpoint.enabled", lambda: False)+ assert routes_mod._checkpoint_needs_search() is False+ assert (+ routes_mod._checkpoint_needs_search(types.SimpleNamespace(context_policy = "rolling"))+ is False+ )+ assert (+ routes_mod._checkpoint_needs_search(types.SimpleNamespace(context_policy = "checkpoint"))+ is True+ )++ monkeypatch.setattr("core.inference.checkpoint.enabled", lambda: True)+ assert routes_mod._checkpoint_needs_search() is True+ assert (+ routes_mod._checkpoint_needs_search(types.SimpleNamespace(context_policy = "rolling"))+ is False+ )+++def test_a_checkpoint_request_override_still_admits_the_memory_tool(monkeypatch):+ import asyncio+ import types++ import routes.inference as routes_mod++ monkeypatch.setattr(routes_mod, "_thread_has_conversation_archive", lambda _tid: True)+ monkeypatch.setattr("core.inference.checkpoint.enabled", lambda: False)++ def _names(context_policy):+ payload = types.SimpleNamespace(+ enabled_tools = [],+ rag_scope = None,+ thread_id = "t1",+ bypass_permissions = False,+ context_policy = context_policy,+ )+ tools = asyncio.run(+ routes_mod._select_request_tools(+ payload, tools_on = False, mcp_allowed = False, checkpoint_fitted = True+ )+ )+ return [tool["function"]["name"] for tool in tools]++ assert _names("checkpoint") == ["search_conversation"]+ assert "search_conversation" not in _names("rolling")++def test_a_degraded_archive_stops_the_block_promising_a_lookup_that_returns_nothing(monkeypatch):"""`degraded()` is the verdict on the last write, and the write runs AFTER the fit.@@ -1239,8 +1416,8 @@ def _stub_studio_db(monkeypatch, messages):monkeypatch.setitem(sys.modules, "storage.studio_db", module)-def test_a_checkpoint_boundary_is_not_replayed_once_the_policy_is_rolling(monkeypatch):- """The escape hatch has to escape the depth too, not just the reset.+def test_a_boundary_is_not_replayed_after_the_context_policy_changes(monkeypatch):+ """A policy switch has to discard the old depth, not just select another fitter.A checkpoint boundary is the depth of a RESET, affordable only because the block isrebuilt on every replay. Under `UNSLOTH_CONTEXT_POLICY=rolling` neither `_fit_context`@@ -1274,6 +1451,10 @@ def test_a_checkpoint_boundary_is_not_replayed_once_the_policy_is_rolling(monkeymonkeypatch.setattr(checkpoint, "CONTEXT_POLICY", "checkpoint")assert llama_cpp._sticky_compaction_boundary("t1") == 18+ assert llama_cpp._sticky_compaction_boundary("t1", context_policy = "checkpoint") == 18+ assert (+ llama_cpp._sticky_compaction_boundary("t1", context_policy = "rolling") == 0+ ), "a request that forces rolling must not replay a reset-sized checkpoint cut"monkeypatch.setattr(checkpoint, "CONTEXT_POLICY", "rolling")assert (@@ -1287,6 +1468,217 @@ def test_a_checkpoint_boundary_is_not_replayed_once_the_policy_is_rolling(monkey"boundary_messages": 6,}assert llama_cpp._sticky_compaction_boundary("t1") == 6+ assert llama_cpp._sticky_compaction_boundary("t1", context_policy = "rolling") == 6+ assert (+ llama_cpp._sticky_compaction_boundary("t1", context_policy = "checkpoint") == 0+ ), "a checkpoint request must start a new epoch instead of reusing a rolling boundary"++ monkeypatch.setattr(checkpoint, "CONTEXT_POLICY", "checkpoint")+ switched_boundary = llama_cpp._sticky_compaction_boundary("t1")+ assert (+ switched_boundary == 0+ ), "a rolling boundary must not suppress the first checkpoint reset and recall"++ monkeypatch.setattr(llama_cpp, "_archive_is_degraded", lambda: False)+ _, truncation = llama_cpp._fit_context(+ _thread() + [{"role": "user", "content": "continue"}],+ context_length = 1200,+ max_tokens = 200,+ count_tokens = count,+ can_reset = True,+ sticky_dropped = switched_boundary,+ context_policy = "checkpoint",+ )+ assert truncation["checkpoint_started"] is True+++def test_a_request_that_cannot_reset_still_replays_its_rolling_boundary(monkeypatch):+ """`UNSLOTH_CONTEXT_POLICY=checkpoint` is not the same as "this fit will reset".++ `_can_reset_epoch` refuses whenever the model's template cannot render tools, the tool+ loop is off, or the archive is unavailable, and those requests compact through+ `fit_rolling_context` and record a rolling boundary. Rejecting a rolling boundary on+ the process policy alone therefore threw it away on every later turn for exactly those+ threads: the boundary slid again, which is the thing `sticky_dropped` exists to stop.+ The rolling boundary is only unsafe where `fit_checkpoint_context` would read it as an+ epoch already in force and skip the reset's recall.+ """+ from core.inference import checkpoint, llama_cpp++ stored = [+ {"role": "user", "content": "q"},+ {+ "role": "assistant",+ "content": "a",+ "metadata": {"custom": {"contextTruncation": {"fits": True, "boundary_messages": 6}}},+ },+ ]+ _stub_studio_db(monkeypatch, stored)+ monkeypatch.setattr(checkpoint, "CONTEXT_POLICY", "checkpoint")++ assert (+ llama_cpp._sticky_compaction_boundary("t1", can_reset = False) == 6+ ), "a fit that stays rolling must replay the boundary rolling recorded"+ assert (+ llama_cpp._sticky_compaction_boundary("t1", can_reset = True) == 0+ ), "a fit that may reset must start a new epoch instead of reusing a rolling boundary"++ # A reset-sized boundary is still refused under rolling whatever the request may do,+ # because nothing rebuilds the block that made the depth affordable.+ stored[1]["metadata"]["custom"]["contextTruncation"] = {+ "fits": True,+ "boundary_messages": 18,+ "checkpoint": True,+ }+ monkeypatch.setattr(checkpoint, "CONTEXT_POLICY", "rolling")+ assert llama_cpp._sticky_compaction_boundary("t1", can_reset = False) == 0+ assert llama_cpp._sticky_compaction_boundary("t1", can_reset = True) == 0+++def test_a_rolling_boundary_never_reaches_the_checkpoint_replay(monkeypatch):+ """Replaying an epoch requires an epoch, and only the recorded policy says there is one.++ A request that may not reset still takes the checkpoint REPLAY branch under a+ checkpoint policy, so a rolling-origin count handed to `fit_checkpoint_context` reads+ as an epoch already in force: the fit returns `checkpoint_started` false, and+ `_archive_and_recall` reads that as "already recalled" and injects nothing. Measured at+ context_length 1800 with a stored boundary of 30, the reply lost the archived turns the+ rolling fallback would have pulled back.+ """+ from core.inference import checkpoint, llama_cpp++ monkeypatch.setattr(checkpoint, "CONTEXT_POLICY", "checkpoint")+ monkeypatch.setattr(llama_cpp, "_archive_is_degraded", lambda: False)++ messages = [{"role": "system", "content": "standing instruction " * 20}]+ for index in range(20):+ messages.append({"role": "user", "content": f"q{index} " * 120})+ messages.append({"role": "assistant", "content": f"a{index} " * 120})+ messages.append({"role": "user", "content": "latest question"})++ def _fit(sticky_is_checkpoint):+ _, truncation = llama_cpp._fit_context(+ list(messages),+ context_length = 1800,+ max_tokens = 100,+ count_tokens = count,+ can_reset = False,+ sticky_dropped = 30,+ context_policy = "checkpoint",+ sticky_is_checkpoint = sticky_is_checkpoint,+ )+ return truncation or {}++ rolling_origin = _fit(False)+ assert rolling_origin.get("checkpoint") is None+ assert (+ bool(rolling_origin.get("checkpoint_started", True)) is True+ ), "a rolling boundary replayed as an epoch suppresses the inline recall"++ # A real epoch still replays, block and all, and still reports no NEW reset.+ checkpoint_origin = _fit(True)+ assert checkpoint_origin.get("checkpoint") is True+ assert checkpoint_origin.get("checkpoint_started") is False+++def test_the_boundary_reader_reports_which_fitter_recorded_it(monkeypatch):+ from core.inference import checkpoint, llama_cpp++ stored = [+ {"role": "user", "content": "q"},+ {+ "role": "assistant",+ "content": "a",+ "metadata": {"custom": {"contextTruncation": {"fits": True, "boundary_messages": 6}}},+ },+ ]+ _stub_studio_db(monkeypatch, stored)+ monkeypatch.setattr(checkpoint, "CONTEXT_POLICY", "checkpoint")+ assert llama_cpp._sticky_compaction_state("t1", can_reset = False) == (6, False)++ stored[1]["metadata"]["custom"]["contextTruncation"] = {+ "fits": True,+ "boundary_messages": 18,+ "checkpoint": True,+ }+ assert llama_cpp._sticky_compaction_state("t1", can_reset = False) == (18, True)+ assert llama_cpp._sticky_compaction_state("t1", can_reset = True) == (18, True)++ # No thread, no row, no boundary: never a claim that a checkpoint recorded one.+ assert llama_cpp._sticky_compaction_state(None) == (0, False)+++def test_changing_the_extra_trim_discards_the_old_boundary(monkeypatch):+ """The "When context fills" ratio has to do something on an already-compacted chat.++ Phase one of `fit_rolling_context` re-applies the saved count before anything else and+ stops as soon as the result fits, so a boundary cut under a different ratio replays in+ full and the phase that reads the new one never runs. Moving the setting either way+ would then change nothing at all.+ """+ from core.inference import checkpoint, llama_cpp++ stored = [+ {"role": "user", "content": "q"},+ {+ "role": "assistant",+ "content": "a",+ "metadata": {+ "custom": {+ "contextTruncation": {+ "fits": True,+ "boundary_messages": 12,+ "boundary_headroom_ratio": 0.25,+ }+ }+ },+ },+ ]+ _stub_studio_db(monkeypatch, stored)+ monkeypatch.setattr(checkpoint, "CONTEXT_POLICY", "rolling")++ assert llama_cpp._sticky_compaction_boundary("t1", compaction_headroom_ratio = 0.25) == 12+ assert (+ llama_cpp._sticky_compaction_boundary("t1", compaction_headroom_ratio = 0.05) == 0+ ), "a boundary cut with more extra trim than this request wants must be recomputed"+ assert (+ llama_cpp._sticky_compaction_boundary("t1", compaction_headroom_ratio = 0.0) == 0+ ), "no extra trim has to hand back what the 25% cut took"++ # And the same the other way. Phase one stops as soon as the replayed cut fits, so a+ # DEEPER setting is just as inert if the old boundary is allowed to stand: measured on+ # a 121-message transcript at context_length 1600, a stored boundary of 86 gave+ # `dropped 86` under 0.05 and under 0.25 alike.+ assert llama_cpp._sticky_compaction_boundary("t1", compaction_headroom_ratio = 0.5) == 0++ # The ratio it was cut under still replays: this refuses a CHANGE, not every row.+ assert llama_cpp._sticky_compaction_boundary("t1", compaction_headroom_ratio = 0.25) == 12++ # Rows saved before the ratio was recorded replay exactly as they did.+ del stored[1]["metadata"]["custom"]["contextTruncation"]["boundary_headroom_ratio"]+ assert llama_cpp._sticky_compaction_boundary("t1", compaction_headroom_ratio = 0.0) == 12++ # A checkpoint reset ignores headroom, so its depth is never refused over the ratio.+ stored[1]["metadata"]["custom"]["contextTruncation"] = {+ "fits": True,+ "boundary_messages": 12,+ "boundary_headroom_ratio": 0.25,+ "checkpoint": True,+ }+ monkeypatch.setattr(checkpoint, "CONTEXT_POLICY", "checkpoint")+ assert llama_cpp._sticky_compaction_boundary("t1", compaction_headroom_ratio = 0.0) == 12+++def test_the_recorded_boundary_carries_the_ratio_that_cut_it():+ from core.inference import llama_cpp++ before = [{"role": "user", "content": f"q{i}"} for i in range(6)]+ fitted = before[4:]++ assert llama_cpp._boundary_metadata(fitted, before)["boundary_headroom_ratio"] == 0.25+ assert llama_cpp._boundary_metadata(fitted, before, 0.05)["boundary_headroom_ratio"] == 0.05+ # Out-of-range values are clamped by the same gate the fit uses, never stored raw.+ assert llama_cpp._boundary_metadata(fitted, before, 5.0)["boundary_headroom_ratio"] == 0.9def test_a_rescued_boundary_is_recorded_but_never_replayed(monkeypatch):diff --git a/studio/backend/tests/test_context_overflow_truncation.py b/studio/backend/tests/test_context_overflow_truncation.pyindex c2c726e00f1..a9ec4c2eecf 100644--- a/studio/backend/tests/test_context_overflow_truncation.py+++ b/studio/backend/tests/test_context_overflow_truncation.py@@ -1178,6 +1178,89 @@ def test_the_compaction_headroom_needs_a_boundary_to_be_worth_it():assert len(plain) > len(sticky)+def test_a_request_can_override_compaction_headroom_ratio():+ """Studio's extra-trim control is a per-request override of the process default."""+ messages = []+ for index in range(20):+ messages.append({"role": "user", "content": f"q{index} " + "u" * 80})+ messages.append({"role": "assistant", "content": f"a{index} " + "a" * 80})+ messages.append({"role": "user", "content": "latest"})++ kwargs = dict(+ context_length = 2000,+ max_tokens = 200,+ count_tokens = _length_counter,+ keeps_boundary = True,+ )+ _, default_info = fit_rolling_context(list(messages), **kwargs)+ _, none_info = fit_rolling_context(list(messages), headroom_ratio = 0.0, **kwargs)++ assert default_info["fits"] and none_info["fits"]+ assert none_info["prompt_tokens_after"] > default_info["prompt_tokens_after"]+++def test_zero_headroom_drops_only_the_oldest_turn_needed_to_fit():+ messages = []+ for _ in range(100):+ messages.append({"role": "user", "content": "u" * 5})+ messages.append({"role": "assistant", "content": "a" * 5})+ messages.append({"role": "user", "content": "x"})++ fitted, info = fit_rolling_context(+ messages,+ context_length = 1100,+ max_tokens = 100,+ count_tokens = _length_counter,+ keeps_boundary = True,+ headroom_ratio = 0.0,+ )++ assert info is not None and info["fits"]+ assert info["prompt_tokens_before"] == 1001+ assert info["prompt_tokens_after"] == 991+ assert info["dropped_messages"] == 2+ assert fitted == messages[2:]+++def test_a_request_that_chose_nothing_keeps_the_eviction_size_it_always_had():+ """`keeps_boundary = False` is not a request for no extra trim.++ Threadless API requests and incognito chats zero the headroom because there is no+ boundary to remember a deeper cut with, not because anyone picked the "no extra trim"+ option. Keying the 5% floor on `headroom` instead of the requested ratio handed them+ the new setting anyway: measured on the messages below, eviction went from 12 messages+ to 2 for a caller that sent no new field at all.+ """+ messages = []+ for _ in range(100):+ messages.append({"role": "user", "content": "u" * 5})+ messages.append({"role": "assistant", "content": "a" * 5})+ messages.append({"role": "user", "content": "x"})++ _, info = fit_rolling_context(+ messages,+ context_length = 1100,+ max_tokens = 100,+ count_tokens = _length_counter,+ keeps_boundary = False,+ )++ assert info is not None and info["fits"]+ assert info["dropped_messages"] == 12+ assert info["prompt_tokens_after"] == 941+++def test_clamp_compaction_headroom_ratio_rejects_junk():+ from core.inference.context_window import clamp_compaction_headroom_ratio++ assert clamp_compaction_headroom_ratio(None) is None+ assert clamp_compaction_headroom_ratio("nope") is None+ assert clamp_compaction_headroom_ratio(float("nan")) is None+ assert clamp_compaction_headroom_ratio(-1) == 0.0+ assert clamp_compaction_headroom_ratio(2) == 0.9+ assert clamp_compaction_headroom_ratio(0.05) == 0.05++# --- Keeping the user's standing instruction when everything else is evicted ---## `truncate_oldest_messages` protects the newest USER group, so an instruction is safe onlydiff --git a/studio/backend/tests/test_conversation_recall_injection.py b/studio/backend/tests/test_conversation_recall_injection.pyindex f231b05a67c..5dc4ea0cd39 100644--- a/studio/backend/tests/test_conversation_recall_injection.py+++ b/studio/backend/tests/test_conversation_recall_injection.py@@ -307,11 +307,18 @@ def _fake_studio_db(monkeypatch, messages):import sysimport types+ from core.inference import checkpoint+module = types.SimpleNamespace(list_chat_messages = lambda thread_id: messages)package = types.ModuleType("storage")package.studio_db = modulemonkeypatch.setitem(sys.modules, "storage", package)monkeypatch.setitem(sys.modules, "storage.studio_db", module)+ # These fixtures store rolling-shaped records (`fits` + `dropped_messages`, no+ # `checkpoint` key). Sticky replay treats a missing key as rolling, and the+ # process default is checkpoint, so pin rolling here or every omitted-key+ # record is refused. Policy-switch coverage lives in test_checkpoint_compaction.+ monkeypatch.setattr(checkpoint, "CONTEXT_POLICY", "rolling")def test_sticky_boundary_reads_the_newest_assistant_truncation(monkeypatch):@@ -938,7 +945,8 @@ def test_the_sticky_boundary_is_applied_once_per_request():text = source.read_text(encoding = "utf-8")assert "_sticky_boundary_applied = True" in text# Whitespace-insensitive: the gate is one expression however the formatter wraps it.- assert "0 if _sticky_boundary_applied" in " ".join(text.split())+ # Both halves are spent together, so the depth and its provenance cannot disagree.+ assert "(0, True) if _sticky_boundary_applied" in " ".join(text.split())def test_conversation_search_top_k_is_clamped(archived, monkeypatch):@@ -1510,8 +1518,10 @@ def test_a_tool_exchange_this_request_created_stays_on_the_branch(monkeypatch):assert "branch_messages = _request_branch" not in textassert 'kwargs["conversation_branch"] = _request_branch' not in text# And the boundary is still measured against the client's messages, which is what it- # will be re-applied to.- assert "_branch_boundary(conversation, _request_branch)" in text+ # will be re-applied to. Recorded through `_boundary_metadata`, which is the only+ # writer, so the depth, its anchor and the headroom that produced it stay together.+ assert "_boundary_metadata( conversation, _request_branch," in text+ assert '"boundary_messages": _branch_boundary(fitted, before),' in text# --- The instruction the user gave, and the follow-up that says nothing ---diff --git a/studio/backend/tests/test_nudge_tool_calls_wiring.py b/studio/backend/tests/test_nudge_tool_calls_wiring.pyindex 2af23ff2fdf..61006c2a98d 100644--- a/studio/backend/tests/test_nudge_tool_calls_wiring.py+++ b/studio/backend/tests/test_nudge_tool_calls_wiring.py@@ -112,7 +112,7 @@ def test_studio_routes_forward_the_request_flag():# (external API clients that omit it fall back to the opt-in default).from routes import inference as routes_inferencefor handler in (- routes_inference.openai_chat_completions,+ routes_inference.produce_openai_chat_completions,routes_inference.anthropic_messages,):src = inspect.getsource(handler)diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 6a4b85d7d59..5862a5b54d5 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -61,6 +61,11 @@ import {releasePreStreamRunReservation,} from "../utils/pre-stream-run-reservation";import { readThreadCreationClaim } from "../utils/chat-thread-creation-claim";+import { ggufCompactionRequestFields } from "../utils/auto-compaction";+import {+ studioToolHistoryRequestFields,+ type ToolHistoryMessage,+} from "../utils/studio-tool-history";import {newDeepResearchHandoff,readDeepResearchToolEvent,@@ -1194,6 +1199,26 @@ function canReplayToolCallWithoutRoleTool(part: ToolCallMessagePart): boolean {return getToolPartReplayMetadata(part).isServerSideBuiltin;}+function toolCallPartSurvivesOpenAIReplay(part: ToolCallMessagePart): boolean {+ if (!serializeAssistantToolCallPart(part)) return false;+ if (+ !serializeToolResultPart(part) &&+ !canReplayToolCallWithoutRoleTool(part)+ ) {+ return false;+ }+ return true;+}++function studioToolHistoryRequestFieldsAfterReplay(+ messages: readonly ToolHistoryMessage[],+): { studio_tool_history?: true } {+ return studioToolHistoryRequestFields(messages, {+ toolCallSurvives: (part) =>+ toolCallPartSurvivesOpenAIReplay(part as unknown as ToolCallMessagePart),+ });+}+function sanitizeAssistantReplayText(text: string): string {// Same reason as the tool result above: the tokens the model wrote last turn// are renderer markup scoped to that message, not prose it should repeat.@@ -1758,15 +1783,19 @@ export const CANVAS_FALLBACK_INSTRUCTION ="When the user asks for an HTML, CSS, or JavaScript canvas, return one complete self-contained fenced html code block. Embed CSS and JavaScript inside the document. Do not emit tool-call syntax.";/**- * The OpenAI-form messages a completion would send. Mirrors the prune + system-prompt half of- * createOpenAIStreamAdapter; the tool catalog is priced server-side instead, since --enable-tools- * can inject schemas the client cannot see.+ * The OpenAI-form history fields a completion would send. Mirrors the prune + system-prompt half+ * of createOpenAIStreamAdapter; the tool catalog is priced server-side instead, since+ * --enable-tools can inject schemas the client cannot see.*/-export async function buildOutboundMessagesForTokenCount(+export async function buildLocalTokenCountHistory(messages: RunMessages,threadId: string | undefined,-): Promise<OpenAIChatMessage[]> {- const outboundMessages = pruneOutboundHistory(messages, true)+): Promise<{+ messages: OpenAIChatMessage[];+ studio_tool_history?: true;+}> {+ const survivingMessages = pruneOutboundHistory(messages, true);+ const outboundMessages = survivingMessages.flatMap((message) => toOpenAIMessages(message, true)).filter((message): message is NonNullable<typeof message> =>Boolean(message),@@ -1818,7 +1847,12 @@ export async function buildOutboundMessagesForTokenCount(}}- return outboundMessages as OpenAIChatMessage[];+ return {+ messages: outboundMessages as OpenAIChatMessage[],+ ...studioToolHistoryRequestFieldsAfterReplay(+ survivingMessages as unknown as ToolHistoryMessage[],+ ),+ };}/**@@ -4703,7 +4737,6 @@ export function createOpenAIStreamAdapter(messages,!isExternalRequest,);-// toOpenAIMessages emits assistant tool_calls + role="tool"// follow-ups; the backend Gemini translator rebuilds the// functionCall / functionResponse parts (with thoughtSignature).@@ -5894,12 +5927,18 @@ export function createOpenAIStreamAdapter(messages: outboundMessages,stream: true,...(continuation ? { continue_final_message: true } : {}),+ ...studioToolHistoryRequestFieldsAfterReplay(+ survivingMessages as unknown as ToolHistoryMessage[],+ ),// 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 }- : {}),+ ...ggufCompactionRequestFields({+ isGguf: activeModel?.isGguf === true,+ autoCompactEnabled: runtime.autoCompactEnabled,+ contextPolicy: runtime.contextPolicy,+ compactionHeadroomRatio: runtime.compactionHeadroomRatio,+ }),temperature: params.temperature,top_p: params.topP,max_tokens: params.maxTokens,diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex aa879022f3a..8ffdaa73a4d 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -312,6 +312,7 @@ export async function countChatInputTokens(payload: {mcp_enabled?: boolean;rag_scope?: Record<string, unknown>;auto_heal_tool_calls?: boolean;+ studio_tool_history?: boolean;/** Run the selected tools here rather than as the provider's hosted builtins. */run_tools_locally?: boolean;// `model` is informational: the endpoint counts with whatever is resident and reports which.diff --git a/studio/frontend/src/features/chat/api/chat-settings-api.ts b/studio/frontend/src/features/chat/api/chat-settings-api.tsindex 10e6d6a7a49..dfad30e4d07 100644--- a/studio/frontend/src/features/chat/api/chat-settings-api.ts+++ b/studio/frontend/src/features/chat/api/chat-settings-api.ts@@ -73,6 +73,10 @@ export interface PersistedChatSettings {expandQuantizations?: boolean;showAllQuantizations?: boolean;fitOnDeviceOnly?: boolean;+ /** Local GGUF chats: drop oldest turns instead of erroring at the window. */+ autoCompactEnabled?: boolean;+ contextPolicy?: "inherit" | "checkpoint" | "rolling";+ compactionHeadroomRatio?: number;}interface ChatSettingsResponse {diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.tsindex 28f263e22fc..ae655b206ac 100644--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts@@ -63,6 +63,12 @@ import {normalizeStoredRagAutoInject,} from "../utils/mirrored-chat-settings";import { retryablePatchAfterFailure } from "../utils/settings-retry";+import {+ DEFAULT_AUTO_COMPACT_ENABLED,+ DEFAULT_COMPACTION_HEADROOM_RATIO,+ DEFAULT_CONTEXT_POLICY,+ type LocalContextPolicy,+} from "../utils/auto-compaction";import { preserveThinkingDefaultFromLoad } from "../lib/resolve-preserve-thinking-default";import {THREAD_SCOPED_PARAM_KEYS,@@ -2609,6 +2615,9 @@ type ChatRuntimeStore = {generatingStatus: string | null;autoHealToolCalls: boolean;nudgeToolCalls: boolean;+ autoCompactEnabled: boolean;+ contextPolicy: LocalContextPolicy;+ compactionHeadroomRatio: number;maxToolCallsPerMessage: number;toolCallTimeout: number;kvCacheDtype: string | null;@@ -2950,6 +2959,9 @@ type ChatRuntimeStore = {clearActiveDiffusionCanvasForThread: (threadId: string | null) => void;setAutoHealToolCalls: (enabled: boolean) => void;setNudgeToolCalls: (enabled: boolean) => void;+ setAutoCompactEnabled: (enabled: boolean) => void;+ setContextPolicy: (policy: LocalContextPolicy) => void;+ setCompactionHeadroomRatio: (ratio: number) => void;setMaxToolCallsPerMessage: (value: number) => void;setToolCallTimeout: (value: number) => void;setGpuMemoryMode: (mode: "auto" | "manual") => void;@@ -2994,6 +3006,9 @@ type ScalarSettingKey =| "searchImages"| "autoHealToolCalls"| "nudgeToolCalls"+ | "autoCompactEnabled"+ | "contextPolicy"+ | "compactionHeadroomRatio"| "maxToolCallsPerMessage"| "toolCallTimeout"| "reasoningEnabled"@@ -3044,6 +3059,9 @@ const SCALAR_SETTING_KEYS = ["searchImages","autoHealToolCalls","nudgeToolCalls",+ "autoCompactEnabled",+ "contextPolicy",+ "compactionHeadroomRatio","maxToolCallsPerMessage","toolCallTimeout","reasoningEnabled",@@ -3773,6 +3791,9 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({activeDiffusionCanvasByThreadId: {},autoHealToolCalls: true,nudgeToolCalls: true,+ autoCompactEnabled: DEFAULT_AUTO_COMPACT_ENABLED,+ contextPolicy: DEFAULT_CONTEXT_POLICY,+ compactionHeadroomRatio: DEFAULT_COMPACTION_HEADROOM_RATIO,maxToolCallsPerMessage: 25,toolCallTimeout: 5,kvCacheDtype: null,@@ -5165,6 +5186,42 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({queuedSettingsEpoch: state.queuedSettingsEpoch + 1,};}),+ setAutoCompactEnabled: (autoCompactEnabled) =>+ set((state) => {+ setScalarSettingVersion(+ "autoCompactEnabled",+ autoCompactEnabled,+ state.autoCompactEnabled,+ );+ return {+ autoCompactEnabled,+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,+ };+ }),+ setContextPolicy: (contextPolicy) =>+ set((state) => {+ setScalarSettingVersion(+ "contextPolicy",+ contextPolicy,+ state.contextPolicy,+ );+ return {+ contextPolicy,+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,+ };+ }),+ setCompactionHeadroomRatio: (compactionHeadroomRatio) =>+ set((state) => {+ setScalarSettingVersion(+ "compactionHeadroomRatio",+ compactionHeadroomRatio,+ state.compactionHeadroomRatio,+ );+ return {+ compactionHeadroomRatio,+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,+ };+ }),setMaxToolCallsPerMessage: (maxToolCallsPerMessage) =>set((state) => {setScalarSettingVersion(diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.tsindex ea967159075..07439761428 100644--- a/studio/frontend/src/features/chat/types/api.ts+++ b/studio/frontend/src/features/chat/types/api.ts@@ -636,6 +636,8 @@ export interface OpenAIChatCompletionsRequest {enabled_tools?: string[];/** Local models + enable_tools only. */mcp_enabled?: boolean;+ /** The replayed tool calls came from Studio's own local tool loop. */+ studio_tool_history?: boolean;/** Local models + enable_tools only. */confirm_tool_calls?: boolean;/**@@ -666,6 +668,10 @@ export interface OpenAIChatCompletionsRequest {nudge_tool_calls?: boolean;/** Local GGUF overflow policy. Rolling mode preserves the transcript but omits oldest turns. */context_overflow?: "error" | "truncate_middle" | "truncate_oldest";+ /** Override UNSLOTH_CONTEXT_POLICY for this local GGUF request. */+ context_policy?: "checkpoint" | "rolling";+ /** Extra share of the prompt budget to drop when a rolling compaction fires. */+ compaction_headroom_ratio?: number;max_tool_calls_per_message?: number;tool_call_timeout?: number;session_id?: string;@@ -773,6 +779,10 @@ export interface OpenAIChatChunk {// evicted prompt shortens that transcript; without the anchor the replayed count then// evicts live turns instead. Carried through untouched, like boundary_messages.boundary_anchor?: string;+ // How much extra trim the fit that set the boundary above used. Replayed against the+ // request's own ratio: a boundary cut under more headroom than the caller now asks for+ // is discarded, so lowering the setting hands the history back.+ boundary_headroom_ratio?: number;// Whose message that is: in a tool loop the last one is often a tool result rather// than anything the user typed.latest_turn_role?: string;diff --git a/studio/frontend/src/features/chat/utils/auto-compaction.ts b/studio/frontend/src/features/chat/utils/auto-compaction.tsnew file mode 100644index 00000000000..f89279bfae9--- /dev/null+++ b/studio/frontend/src/features/chat/utils/auto-compaction.ts@@ -0,0 +1,120 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/** Local GGUF auto-compaction preferences. Default follows the server policy. */++export const DEFAULT_AUTO_COMPACT_ENABLED = true;+export const DEFAULT_CONTEXT_POLICY = "inherit" as const;+export const DEFAULT_COMPACTION_HEADROOM_RATIO = 0.25;++export type LocalContextPolicy = "inherit" | "checkpoint" | "rolling";++export const COMPACTION_HEADROOM_CHOICES = [0.25, 0.1, 0.05, 0] as const;++export type CompactionStyleValue =+ | "inherit"+ | "checkpoint"+ | "rolling:0.25"+ | "rolling:0.1"+ | "rolling:0.05"+ | "rolling:0";++export function sanitizeContextPolicy(+ value: unknown,+): LocalContextPolicy | undefined {+ return value === "inherit" || value === "checkpoint" || value === "rolling"+ ? value+ : undefined;+}++export function sanitizeCompactionHeadroomRatio(+ value: unknown,+): number | undefined {+ if (typeof value !== "number" || !Number.isFinite(value)) return undefined;+ const clamped = Math.max(0, Math.min(0.9, Math.round(value * 100) / 100));+ let nearest: (typeof COMPACTION_HEADROOM_CHOICES)[number] =+ COMPACTION_HEADROOM_CHOICES[0];+ let best = Math.abs(clamped - nearest);+ for (const choice of COMPACTION_HEADROOM_CHOICES) {+ const distance = Math.abs(clamped - choice);+ if (distance < best) {+ nearest = choice;+ best = distance;+ }+ }+ return nearest;+}++export function compactionStyleValue(+ policy: LocalContextPolicy,+ ratio: number,+): CompactionStyleValue {+ if (policy === "inherit") return "inherit";+ if (policy !== "rolling") return "checkpoint";+ const rounded =+ sanitizeCompactionHeadroomRatio(ratio) ?? DEFAULT_COMPACTION_HEADROOM_RATIO;+ if (rounded === 0) return "rolling:0";+ if (rounded === 0.05) return "rolling:0.05";+ if (rounded === 0.1) return "rolling:0.1";+ return "rolling:0.25";+}++export function parseCompactionStyle(value: string): {+ contextPolicy: LocalContextPolicy;+ compactionHeadroomRatio: number;+} {+ switch (value) {+ case "inherit":+ return {+ contextPolicy: "inherit",+ compactionHeadroomRatio: DEFAULT_COMPACTION_HEADROOM_RATIO,+ };+ case "rolling:0":+ return { contextPolicy: "rolling", compactionHeadroomRatio: 0 };+ case "rolling:0.05":+ return { contextPolicy: "rolling", compactionHeadroomRatio: 0.05 };+ case "rolling:0.1":+ return { contextPolicy: "rolling", compactionHeadroomRatio: 0.1 };+ case "rolling:0.25":+ return { contextPolicy: "rolling", compactionHeadroomRatio: 0.25 };+ default:+ return {+ contextPolicy: "checkpoint",+ compactionHeadroomRatio: DEFAULT_COMPACTION_HEADROOM_RATIO,+ };+ }+}++export function ggufCompactionRequestFields(options: {+ isGguf: boolean;+ autoCompactEnabled: boolean;+ contextPolicy: LocalContextPolicy;+ compactionHeadroomRatio: number;+}): {+ context_overflow?: "error" | "truncate_oldest";+ context_policy?: Exclude<LocalContextPolicy, "inherit">;+ compaction_headroom_ratio?: number;+} {+ if (!options.isGguf) return {};+ if (!options.autoCompactEnabled) {+ // An omitted field falls back to UNSLOTH_CONTEXT_OVERFLOW, which may still+ // compact. "error" is an explicit refusal of that fallback.+ return { context_overflow: "error" };+ }+ if (options.contextPolicy === "rolling") {+ return {+ context_overflow: "truncate_oldest",+ context_policy: "rolling",+ compaction_headroom_ratio:+ sanitizeCompactionHeadroomRatio(options.compactionHeadroomRatio) ??+ DEFAULT_COMPACTION_HEADROOM_RATIO,+ };+ }+ if (options.contextPolicy === "inherit") {+ return { context_overflow: "truncate_oldest" };+ }+ return {+ context_overflow: "truncate_oldest",+ context_policy: "checkpoint",+ };+}diff --git a/studio/frontend/src/features/chat/utils/chat-settings-storage.ts b/studio/frontend/src/features/chat/utils/chat-settings-storage.tsindex 21326b2c2e5..30bdf943d82 100644--- a/studio/frontend/src/features/chat/utils/chat-settings-storage.ts+++ b/studio/frontend/src/features/chat/utils/chat-settings-storage.ts@@ -20,6 +20,10 @@ import {} from "../presets/preset-policy";import type { ReasoningEffort } from "../stores/chat-runtime-store";import { MAX_SAMPLING_SEED } from "../types/runtime";+import {+ sanitizeCompactionHeadroomRatio,+ sanitizeContextPolicy,+} from "./auto-compaction";import {assignSanitizedMirroredSettings,hasNoMirroredSettings,@@ -272,6 +276,11 @@ function sanitizeChatSettings(value: unknown): PersistedChatSettings {);const autoHealToolCalls = sanitizeBool(value.autoHealToolCalls);const nudgeToolCalls = sanitizeBool(value.nudgeToolCalls);+ const autoCompactEnabled = sanitizeBool(value.autoCompactEnabled);+ const contextPolicy = sanitizeContextPolicy(value.contextPolicy);+ const compactionHeadroomRatio = sanitizeCompactionHeadroomRatio(+ value.compactionHeadroomRatio,+ );const maxToolCallsPerMessage = sanitizeInt(value.maxToolCallsPerMessage, 1);const toolCallTimeout = sanitizeInt(value.toolCallTimeout, 1);@@ -303,6 +312,13 @@ function sanitizeChatSettings(value: unknown): PersistedChatSettings {if (nudgeToolCalls !== undefined) {settings.nudgeToolCalls = nudgeToolCalls;}+ if (autoCompactEnabled !== undefined) {+ settings.autoCompactEnabled = autoCompactEnabled;+ }+ if (contextPolicy) settings.contextPolicy = contextPolicy;+ if (compactionHeadroomRatio !== undefined) {+ settings.compactionHeadroomRatio = compactionHeadroomRatio;+ }if (maxToolCallsPerMessage !== undefined) {settings.maxToolCallsPerMessage = maxToolCallsPerMessage;}@@ -367,6 +383,9 @@ export function isEmptyChatSettings(settings: PersistedChatSettings): boolean {settings.allowArtifactNetworkAccess === undefined &&settings.autoHealToolCalls === undefined &&settings.nudgeToolCalls === undefined &&+ settings.autoCompactEnabled === undefined &&+ settings.contextPolicy === undefined &&+ settings.compactionHeadroomRatio === undefined &&settings.maxToolCallsPerMessage === undefined &&settings.toolCallTimeout === undefined &&hasNoMirroredSettings(settings)diff --git a/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts b/studio/frontend/src/features/chat/utils/queued-chat-run-settings.tsindex fcc08bb2cad..9c570ac036b 100644--- a/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts+++ b/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts@@ -38,6 +38,9 @@ const QUEUED_SETTING_KEYS = ["nudgeToolCalls","maxToolCallsPerMessage","toolCallTimeout",+ "autoCompactEnabled",+ "contextPolicy",+ "compactionHeadroomRatio",] as const;type ChatRuntimeState = ReturnType<typeof useChatRuntimeStore.getState>;diff --git a/studio/frontend/src/features/chat/utils/refresh-context-usage.ts b/studio/frontend/src/features/chat/utils/refresh-context-usage.tsindex 3d0b097699a..e90a8fa6406 100644--- a/studio/frontend/src/features/chat/utils/refresh-context-usage.ts+++ b/studio/frontend/src/features/chat/utils/refresh-context-usage.ts@@ -4,8 +4,8 @@import type { ThreadMessage } from "@assistant-ui/react";import {buildLocalTokenCountExtras,+ buildLocalTokenCountHistory,buildLocalTokenCountReasoning,- buildOutboundMessagesForTokenCount,findLatestUserAudioBase64,findLatestUserVideoBase64,messagesContainImage,@@ -293,7 +293,7 @@ export async function refreshContextUsage(// undefined, not null: a chat with no persisted thread has no project to resolve from.const payloadThreadId = threadId ?? undefined;- const outbound = await buildOutboundMessagesForTokenCount(+ const countHistory = await buildLocalTokenCountHistory(runMessages,payloadThreadId,);@@ -306,7 +306,7 @@ export async function refreshContextUsage(const { input_tokens: inputTokens, model: countedModel } =await countChatInputTokens({model: capturedCheckpoint,- messages: outbound,+ ...countHistory,...buildLocalTokenCountReasoning(),...countExtras,});diff --git a/studio/frontend/src/features/chat/utils/studio-tool-history.ts b/studio/frontend/src/features/chat/utils/studio-tool-history.tsnew file mode 100644index 00000000000..58dd327145c--- /dev/null+++ b/studio/frontend/src/features/chat/utils/studio-tool-history.ts@@ -0,0 +1,55 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++type ToolHistoryPart = {+ type?: unknown;+ provenance?: unknown;+ [key: string]: unknown;+};++export type ToolHistoryMessage = {+ content?: readonly ToolHistoryPart[];+ [key: string]: unknown;+};++export type StudioToolHistoryOptions = {+ /**+ * When set, only these tool-call parts count. Use this to ignore provider+ * builtins that OpenAI serialization drops, so ownership matches the payload.+ */+ toolCallSurvives?: (part: ToolHistoryPart) => boolean;+};++export function hasOnlyStudioOwnedToolHistory(+ messages: readonly ToolHistoryMessage[],+ options?: StudioToolHistoryOptions,+): boolean {+ const survives = options?.toolCallSurvives;+ let sawToolCall = false;+ for (const message of messages) {+ for (const part of message.content ?? []) {+ if (part.type !== "tool-call") continue;+ if (survives && !survives(part)) continue;+ sawToolCall = true;+ const provenance = part.provenance;+ if (+ !provenance ||+ typeof provenance !== "object" ||+ Array.isArray(provenance) ||+ (provenance as { source?: unknown }).source !== "local"+ ) {+ return false;+ }+ }+ }+ return sawToolCall;+}++export function studioToolHistoryRequestFields(+ messages: readonly ToolHistoryMessage[],+ options?: StudioToolHistoryOptions,+): { studio_tool_history?: true } {+ return hasOnlyStudioOwnedToolHistory(messages, options)+ ? { studio_tool_history: true }+ : {};+}diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.tsindex 661ac19156c..87e72778f6e 100644--- a/studio/frontend/src/features/settings/settings-search.ts+++ b/studio/frontend/src/features/settings/settings-search.ts@@ -98,6 +98,8 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {"settings.general.autoTitleNewChats","settings.chat.projectAttachments","settings.chat.rememberParamsPerModel",+ "settings.chat.autoCompact",+ "settings.chat.compactionStyle","settings.profile.greetingSloth","settings.chat.thinking.collapseByDefault","settings.chat.artifacts.title",@@ -281,4 +283,6 @@ export const SETTINGS_SEARCH_KEYWORDS: Partial<"settings.resources.modelMemory.modelMemoryKeywords","settings.resources.modelMemory.noRamReserve":"settings.resources.modelMemory.modelMemoryKeywords",+ "settings.chat.autoCompact": "settings.chat.autoCompactKeywords",+ "settings.chat.compactionStyle": "settings.chat.autoCompactKeywords",};diff --git a/studio/frontend/src/features/settings/tabs/chat-tab.tsx b/studio/frontend/src/features/settings/tabs/chat-tab.tsxindex 2ccf2fbba62..4147f3a2ab2 100644--- a/studio/frontend/src/features/settings/tabs/chat-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/chat-tab.tsx@@ -18,6 +18,10 @@ import {usePlusMenuPrefsStore,useSidebarOrganizationStore,} from "@/features/chat";+import {+ compactionStyleValue,+ parseCompactionStyle,+} from "@/features/chat/utils/auto-compaction";import { PASTED_TEXT_THRESHOLD_CHOICES } from "@/features/chat/utils/pasted-text";import { formatBindingLabel, isMacPlatform } from "../lib/keyboard-shortcuts";import { useUserProfileStore } from "@/features/profile";@@ -149,6 +153,22 @@ export function ChatTab() {const setRememberParamsPerModel = useChatRuntimeStore((state) => state.setRememberParamsPerModel,);+ const autoCompactEnabled = useChatRuntimeStore(+ (state) => state.autoCompactEnabled,+ );+ const setAutoCompactEnabled = useChatRuntimeStore(+ (state) => state.setAutoCompactEnabled,+ );+ const contextPolicy = useChatRuntimeStore((state) => state.contextPolicy);+ const compactionHeadroomRatio = useChatRuntimeStore(+ (state) => state.compactionHeadroomRatio,+ );+ const setContextPolicy = useChatRuntimeStore(+ (state) => state.setContextPolicy,+ );+ const setCompactionHeadroomRatio = useChatRuntimeStore(+ (state) => state.setCompactionHeadroomRatio,+ );const showGreetingSloth = useUserProfileStore((s) => s.showGreetingSloth);const setShowGreetingSloth = useUserProfileStore((s) => s.setShowGreetingSloth,@@ -365,6 +385,56 @@ export function ChatTab() {onCheckedChange={setRememberParamsPerModel}/></SettingsRow>+ <SettingsRow+ label={t("settings.chat.autoCompact")}+ description={t("settings.chat.autoCompactDescription")}+ >+ <Switch+ checked={autoCompactEnabled}+ onCheckedChange={setAutoCompactEnabled}+ />+ </SettingsRow>+ <SettingsRow+ label={t("settings.chat.compactionStyle")}+ description={t("settings.chat.compactionStyleDescription")}+ >+ <Select+ value={compactionStyleValue(contextPolicy, compactionHeadroomRatio)}+ onValueChange={(value) => {+ const next = parseCompactionStyle(value);+ setContextPolicy(next.contextPolicy);+ setCompactionHeadroomRatio(next.compactionHeadroomRatio);+ }}+ disabled={!autoCompactEnabled}+ >+ <SelectTrigger+ className="w-64"+ aria-label={t("settings.chat.compactionStyle")}+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="inherit">+ {t("settings.chat.compactionStyleInherit")}+ </SelectItem>+ <SelectItem value="checkpoint">+ {t("settings.chat.compactionStyleCheckpoint")}+ </SelectItem>+ <SelectItem value="rolling:0.25">+ {t("settings.chat.compactionStyleRollingDefault")}+ </SelectItem>+ <SelectItem value="rolling:0.1">+ {t("settings.chat.compactionStyleRolling10")}+ </SelectItem>+ <SelectItem value="rolling:0.05">+ {t("settings.chat.compactionStyleRolling5")}+ </SelectItem>+ <SelectItem value="rolling:0">+ {t("settings.chat.compactionStyleRollingNone")}+ </SelectItem>+ </SelectContent>+ </Select>+ </SettingsRow><SettingsRowlabel={t("settings.chat.pastedTextThreshold")}description={t("settings.chat.pastedTextThresholdDescription", {diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 55123089e19..15f053e77b8 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -1360,6 +1360,20 @@ export const ar = {rememberParamsPerModel: "تذكر الإعدادات لكل نموذج",rememberParamsPerModelDescription:"عند تبديل النموذج تُستعاد درجة الحرارة والموجّه وبقية الإعدادات التي استخدمتها آخر مرة مع ذلك النموذج. عند الإيقاف تبقى مجموعة إعدادات واحدة لكل النماذج.",+ autoCompact: "ضغط المحادثات الطويلة تلقائيًا",+ autoCompactDescription:+ "عندما تصل محادثة GGUF محلية إلى طول السياق المحدد، احذف الأدوار الأقدم بدلًا من إرجاع خطأ. لا يعتمد ذلك على ذاكرة VRAM المتاحة.",+ compactionStyle: "عند امتلاء السياق",+ compactionStyleDescription:+ "يُبقي الخيار الافتراضي للخادم UNSLOTH_CONTEXT_POLICY. تحتفظ إعادة ضبط المحادثة بأحدث دور والتعليمات الدائمة. تحذف النافذة المنزلقة الأدوار الأقدم ويمكنها الاحتفاظ بمزيد من السجل الحديث.",+ compactionStyleInherit: "استخدام إعداد الخادم الافتراضي",+ compactionStyleCheckpoint: "إعادة ضبط المحادثة",+ compactionStyleRollingDefault: "حذف الأدوار الأقدم (مساحة إضافية نحو 25%)",+ compactionStyleRolling10: "حذف الأدوار الأقدم (مساحة إضافية نحو 10%)",+ compactionStyleRolling5: "حذف الأدوار الأقدم (مساحة إضافية نحو 5%)",+ compactionStyleRollingNone: "حذف الأدوار الأقدم (دون اقتطاع إضافي)",+ autoCompactKeywords:+ "ضغط تلقائي سياق نافذة اقتطاع منزلقة نقطة تحقق هامش compaction rolling checkpoint headroom",thinking: {collapseByDefault: "طيّ التفكير افتراضيًا",collapseByDefaultDescription:diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex b43824527bd..011aadcfb85 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -1396,6 +1396,24 @@ export const de = {rememberParamsPerModel: "Einstellungen pro Modell merken",rememberParamsPerModelDescription:"Beim Modellwechsel werden Temperatur, Prompt und die weiteren Einstellungen wiederhergestellt, die Sie zuletzt mit diesem Modell verwendet haben. Aus: ein Satz Einstellungen für alle Modelle.",+ autoCompact: "Lange Chats automatisch komprimieren",+ autoCompactDescription:+ "Wenn ein lokaler GGUF-Chat die festgelegte Kontextlänge erreicht, werden ältere Gesprächsrunden verworfen, statt einen Fehler zurückzugeben. Dies richtet sich nicht nach freiem VRAM.",+ compactionStyle: "Wenn der Kontext voll ist",+ compactionStyleDescription:+ "Die Servervorgabe behält UNSLOTH_CONTEXT_POLICY bei. Gespräch zurücksetzen behält die letzte Runde und dauerhafte Anweisungen. Ein gleitendes Fenster verwirft die ältesten Runden und kann mehr aktuellen Verlauf behalten.",+ compactionStyleInherit: "Servervorgabe verwenden",+ compactionStyleCheckpoint: "Gespräch zurücksetzen",+ compactionStyleRollingDefault:+ "Älteste Runden verwerfen (~25 % zusätzlicher Platz)",+ compactionStyleRolling10:+ "Älteste Runden verwerfen (~10 % zusätzlicher Platz)",+ compactionStyleRolling5:+ "Älteste Runden verwerfen (~5 % zusätzlicher Platz)",+ compactionStyleRollingNone:+ "Älteste Runden verwerfen (keine zusätzliche Kürzung)",+ autoCompactKeywords:+ "Komprimierung automatisch Kontext Fenster kürzen gleitend Prüfpunkt Reserve compaction rolling checkpoint headroom",thinking: {collapseByDefault: "Denken standardmäßig einklappen",collapseByDefaultDescription:diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex bc7d4156ba3..ed3fc576a45 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -1353,6 +1353,20 @@ export const en = {rememberParamsPerModel: "Remember settings per model",rememberParamsPerModelDescription:"Switching models restores the temperature, prompt and other settings you last used with that model. Off keeps one set of settings for every model.",+ autoCompact: "Auto-compact long chats",+ autoCompactDescription:+ "When a local GGUF chat fills the context length you set, drop older turns instead of returning an error. This is not based on free VRAM.",+ compactionStyle: "When context fills",+ compactionStyleDescription:+ "Use server default keeps UNSLOTH_CONTEXT_POLICY. Reset conversation keeps the latest turn and standing instructions. A sliding window drops oldest turns and can keep more recent history.",+ compactionStyleInherit: "Use server default",+ compactionStyleCheckpoint: "Reset conversation",+ compactionStyleRollingDefault: "Drop oldest turns (~25% extra room)",+ compactionStyleRolling10: "Drop oldest turns (~10% extra room)",+ compactionStyleRolling5: "Drop oldest turns (~5% extra room)",+ compactionStyleRollingNone: "Drop oldest turns (no extra trim)",+ autoCompactKeywords:+ "compaction compact auto-compact context window truncate rolling checkpoint headroom",thinking: {collapseByDefault: "Collapse Thinking by default",collapseByDefaultDescription:diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 42fc4cdb5e8..6a656f2624d 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -1387,6 +1387,24 @@ export const es = {rememberParamsPerModel: "Recordar los ajustes por modelo",rememberParamsPerModelDescription:"Al cambiar de modelo se restauran la temperatura, el prompt y los demás ajustes que usaste por última vez con ese modelo. Desactivado, se mantiene un único conjunto de ajustes para todos los modelos.",+ autoCompact: "Compactar automáticamente chats largos",+ autoCompactDescription:+ "Cuando un chat GGUF local alcance la longitud de contexto configurada, descarta los turnos antiguos en vez de devolver un error. Esto no depende de la VRAM libre.",+ compactionStyle: "Cuando se llena el contexto",+ compactionStyleDescription:+ "Usar el valor del servidor conserva UNSLOTH_CONTEXT_POLICY. Restablecer la conversación mantiene el último turno y las instrucciones permanentes. Una ventana deslizante descarta los turnos más antiguos y puede conservar más historial reciente.",+ compactionStyleInherit: "Usar valor del servidor",+ compactionStyleCheckpoint: "Restablecer conversación",+ compactionStyleRollingDefault:+ "Descartar turnos antiguos (~25% de espacio extra)",+ compactionStyleRolling10:+ "Descartar turnos antiguos (~10% de espacio extra)",+ compactionStyleRolling5:+ "Descartar turnos antiguos (~5% de espacio extra)",+ compactionStyleRollingNone:+ "Descartar turnos antiguos (sin recorte adicional)",+ autoCompactKeywords:+ "compactación compactar automáticamente contexto ventana truncar deslizante checkpoint margen compaction rolling headroom",thinking: {collapseByDefault: "Contraer el razonamiento de forma predeterminada",collapseByDefaultDescription:diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 63ce45247ad..63ad4a163b3 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -1393,6 +1393,24 @@ export const fr = {rememberParamsPerModel: "Mémoriser les réglages par modèle",rememberParamsPerModelDescription:"Changer de modèle restaure la température, le prompt et les autres réglages utilisés en dernier avec ce modèle. Désactivé, un seul jeu de réglages s'applique à tous les modèles.",+ autoCompact: "Compacter automatiquement les longues discussions",+ autoCompactDescription:+ "Lorsqu’une discussion GGUF locale atteint la longueur de contexte définie, supprimez les anciens tours au lieu de renvoyer une erreur. Ce réglage ne dépend pas de la VRAM libre.",+ compactionStyle: "Lorsque le contexte est plein",+ compactionStyleDescription:+ "La valeur par défaut du serveur conserve UNSLOTH_CONTEXT_POLICY. Réinitialiser la discussion garde le dernier tour et les instructions permanentes. Une fenêtre glissante supprime les tours les plus anciens et peut conserver davantage d’historique récent.",+ compactionStyleInherit: "Utiliser la valeur du serveur",+ compactionStyleCheckpoint: "Réinitialiser la discussion",+ compactionStyleRollingDefault:+ "Supprimer les anciens tours (~25 % d’espace supplémentaire)",+ compactionStyleRolling10:+ "Supprimer les anciens tours (~10 % d’espace supplémentaire)",+ compactionStyleRolling5:+ "Supprimer les anciens tours (~5 % d’espace supplémentaire)",+ compactionStyleRollingNone:+ "Supprimer les anciens tours (sans réduction supplémentaire)",+ autoCompactKeywords:+ "compaction automatique contexte fenêtre tronquer glissante point de contrôle marge compaction rolling checkpoint headroom",thinking: {collapseByDefault: "Replier la réflexion par défaut",collapseByDefaultDescription:diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 0f17c1362c5..a41926edbbb 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -1366,6 +1366,20 @@ export const hi = {rememberParamsPerModel: "हर मॉडल के लिए सेटिंग्स याद रखें",rememberParamsPerModelDescription:"मॉडल बदलने पर उस मॉडल के साथ आपने आखिरी बार जो तापमान, प्रॉम्प्ट और अन्य सेटिंग्स इस्तेमाल की थीं, वे वापस आ जाती हैं। बंद होने पर सभी मॉडलों के लिए एक ही सेट रहता है।",+ autoCompact: "लंबी चैट को अपने आप कॉम्पैक्ट करें",+ autoCompactDescription:+ "जब लोकल GGUF चैट सेट की गई कॉन्टेक्स्ट लंबाई तक पहुँच जाए, तो त्रुटि लौटाने के बजाय पुराने टर्न हटा दें। यह खाली VRAM पर आधारित नहीं है।",+ compactionStyle: "कॉन्टेक्स्ट भरने पर",+ compactionStyleDescription:+ "सर्वर डिफ़ॉल्ट से UNSLOTH_CONTEXT_POLICY बना रहता है। बातचीत रीसेट करने पर नवीनतम टर्न और स्थायी निर्देश रहते हैं। स्लाइडिंग विंडो सबसे पुराने टर्न हटाती है और हाल का अधिक इतिहास रख सकती है।",+ compactionStyleInherit: "सर्वर डिफ़ॉल्ट उपयोग करें",+ compactionStyleCheckpoint: "बातचीत रीसेट करें",+ compactionStyleRollingDefault: "पुराने टर्न हटाएँ (~25% अतिरिक्त जगह)",+ compactionStyleRolling10: "पुराने टर्न हटाएँ (~10% अतिरिक्त जगह)",+ compactionStyleRolling5: "पुराने टर्न हटाएँ (~5% अतिरिक्त जगह)",+ compactionStyleRollingNone: "पुराने टर्न हटाएँ (कोई अतिरिक्त कटौती नहीं)",+ autoCompactKeywords:+ "कॉम्पैक्शन कॉम्पैक्ट कॉन्टेक्स्ट विंडो ट्रंकेट स्लाइडिंग चेकपॉइंट हेडरूम compaction rolling checkpoint headroom",thinking: {collapseByDefault: "थिंकिंग को डिफ़ॉल्ट रूप से संक्षिप्त रखें",collapseByDefaultDescription:diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex 11e3d66cf0d..d0e2714a03b 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -1361,6 +1361,24 @@ export const it = {rememberParamsPerModel: "Ricorda le impostazioni per modello",rememberParamsPerModelDescription:"Cambiando modello vengono ripristinati temperatura, prompt e le altre impostazioni usate l'ultima volta con quel modello. Disattivato, resta un unico set di impostazioni per tutti i modelli.",+ autoCompact: "Compatta automaticamente le chat lunghe",+ autoCompactDescription:+ "Quando una chat GGUF locale raggiunge la lunghezza di contesto impostata, elimina i turni precedenti invece di restituire un errore. Questa impostazione non dipende dalla VRAM libera.",+ compactionStyle: "Quando il contesto è pieno",+ compactionStyleDescription:+ "Il valore predefinito del server mantiene UNSLOTH_CONTEXT_POLICY. Reimpostare la conversazione conserva l'ultimo turno e le istruzioni permanenti. Una finestra scorrevole elimina i turni più vecchi e può conservare più cronologia recente.",+ compactionStyleInherit: "Usa il valore del server",+ compactionStyleCheckpoint: "Reimposta la conversazione",+ compactionStyleRollingDefault:+ "Elimina i turni precedenti (~25% di spazio aggiuntivo)",+ compactionStyleRolling10:+ "Elimina i turni precedenti (~10% di spazio aggiuntivo)",+ compactionStyleRolling5:+ "Elimina i turni precedenti (~5% di spazio aggiuntivo)",+ compactionStyleRollingNone:+ "Elimina i turni precedenti (nessun taglio aggiuntivo)",+ autoCompactKeywords:+ "compattazione automatica contesto finestra troncare scorrevole checkpoint margine compaction rolling headroom",thinking: {collapseByDefault: "Comprimi il ragionamento per impostazione predefinita",collapseByDefaultDescription:diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex f4bf4d32790..e88f7730bca 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -1347,6 +1347,20 @@ export const ja = {rememberParamsPerModel: "モデルごとに設定を記憶",rememberParamsPerModelDescription:"モデルを切り替えると、そのモデルで最後に使った温度やプロンプトなどの設定が復元されます。オフの場合は、すべてのモデルで同じ設定を使います。",+ autoCompact: "長いチャットを自動圧縮",+ autoCompactDescription:+ "ローカル GGUF チャットが設定したコンテキスト長に達したら、エラーを返す代わりに古いターンを削除します。空き VRAM には基づきません。",+ compactionStyle: "コンテキストが満杯になったとき",+ compactionStyleDescription:+ "サーバー既定値を使うと UNSLOTH_CONTEXT_POLICY が維持されます。会話をリセットすると最新ターンと継続指示が残ります。スライディングウィンドウは古いターンを削除し、より多くの最近の履歴を残せます。",+ compactionStyleInherit: "サーバー既定値を使用",+ compactionStyleCheckpoint: "会話をリセット",+ compactionStyleRollingDefault: "古いターンを削除(約 25% の追加余裕)",+ compactionStyleRolling10: "古いターンを削除(約 10% の追加余裕)",+ compactionStyleRolling5: "古いターンを削除(約 5% の追加余裕)",+ compactionStyleRollingNone: "古いターンを削除(追加の切り詰めなし)",+ autoCompactKeywords:+ "圧縮 自動圧縮 コンテキスト ウィンドウ 切り詰め スライディング チェックポイント 余裕 compaction rolling headroom",thinking: {collapseByDefault: "思考をデフォルトで折りたたむ",collapseByDefaultDescription:diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex a31c52761a8..b5fc523c7df 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -1357,6 +1357,20 @@ export const ko = {rememberParamsPerModel: "모델별로 설정 기억",rememberParamsPerModelDescription:"모델을 전환하면 해당 모델에서 마지막으로 사용한 온도, 프롬프트 등의 설정이 복원됩니다. 끄면 모든 모델이 하나의 설정을 공유합니다.",+ autoCompact: "긴 채팅 자동 압축",+ autoCompactDescription:+ "로컬 GGUF 채팅이 설정한 컨텍스트 길이에 도달하면 오류를 반환하는 대신 오래된 턴을 삭제합니다. 사용 가능한 VRAM을 기준으로 하지 않습니다.",+ compactionStyle: "컨텍스트가 가득 찼을 때",+ compactionStyleDescription:+ "서버 기본값을 사용하면 UNSLOTH_CONTEXT_POLICY가 유지됩니다. 대화 재설정은 최신 턴과 지속 지침을 남깁니다. 슬라이딩 윈도우는 가장 오래된 턴을 삭제하고 최근 기록을 더 많이 유지할 수 있습니다.",+ compactionStyleInherit: "서버 기본값 사용",+ compactionStyleCheckpoint: "대화 재설정",+ compactionStyleRollingDefault: "오래된 턴 삭제(약 25% 추가 여유)",+ compactionStyleRolling10: "오래된 턴 삭제(약 10% 추가 여유)",+ compactionStyleRolling5: "오래된 턴 삭제(약 5% 추가 여유)",+ compactionStyleRollingNone: "오래된 턴 삭제(추가 잘라내기 없음)",+ autoCompactKeywords:+ "압축 자동 컨텍스트 윈도우 자르기 슬라이딩 체크포인트 여유 compaction rolling checkpoint headroom",thinking: {collapseByDefault: "기본적으로 사고 과정 접기",collapseByDefaultDescription:diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 4ad08ab47c6..10ec06f8d98 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -1375,6 +1375,24 @@ export const ptBR = {rememberParamsPerModel: "Lembrar as configurações por modelo",rememberParamsPerModelDescription:"Ao trocar de modelo, a temperatura, o prompt e as demais configurações usadas por último com aquele modelo são restauradas. Desativado, um único conjunto de configurações vale para todos os modelos.",+ autoCompact: "Compactar automaticamente chats longos",+ autoCompactDescription:+ "Quando um chat GGUF local atingir o tamanho de contexto definido, descarte turnos antigos em vez de retornar um erro. Isso não depende da VRAM livre.",+ compactionStyle: "Quando o contexto estiver cheio",+ compactionStyleDescription:+ "Usar o padrão do servidor preserva UNSLOTH_CONTEXT_POLICY. Redefinir a conversa mantém o turno mais recente e as instruções permanentes. Uma janela deslizante descarta os turnos mais antigos e pode manter mais histórico recente.",+ compactionStyleInherit: "Usar padrão do servidor",+ compactionStyleCheckpoint: "Redefinir conversa",+ compactionStyleRollingDefault:+ "Descartar turnos antigos (~25% de espaço extra)",+ compactionStyleRolling10:+ "Descartar turnos antigos (~10% de espaço extra)",+ compactionStyleRolling5:+ "Descartar turnos antigos (~5% de espaço extra)",+ compactionStyleRollingNone:+ "Descartar turnos antigos (sem corte extra)",+ autoCompactKeywords:+ "compactação compactar automaticamente contexto janela truncar deslizante checkpoint margem compaction rolling headroom",thinking: {collapseByDefault: "Recolher o raciocínio por padrão",collapseByDefaultDescription:diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex d9f0d1f7f90..b16ff7c1dde 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -1372,6 +1372,24 @@ export const ru = {rememberParamsPerModel: "Запоминать настройки для каждой модели",rememberParamsPerModelDescription:"При переключении модели восстанавливаются температура, промпт и другие настройки, которые вы использовали с ней в последний раз. Если выключено, для всех моделей действует один набор настроек.",+ autoCompact: "Автоматически сжимать длинные чаты",+ autoCompactDescription:+ "Когда локальный чат GGUF достигает заданной длины контекста, удалять старые ходы вместо возврата ошибки. Это не зависит от свободной VRAM.",+ compactionStyle: "Когда контекст заполнен",+ compactionStyleDescription:+ "Настройка сервера сохраняет UNSLOTH_CONTEXT_POLICY. Сброс беседы оставляет последний ход и постоянные инструкции. Скользящее окно удаляет самые старые ходы и может сохранить больше недавней истории.",+ compactionStyleInherit: "Использовать настройку сервера",+ compactionStyleCheckpoint: "Сбросить беседу",+ compactionStyleRollingDefault:+ "Удалять старые ходы (~25% дополнительного места)",+ compactionStyleRolling10:+ "Удалять старые ходы (~10% дополнительного места)",+ compactionStyleRolling5:+ "Удалять старые ходы (~5% дополнительного места)",+ compactionStyleRollingNone:+ "Удалять старые ходы (без дополнительного сокращения)",+ autoCompactKeywords:+ "сжатие автоматически контекст окно обрезка скользящее контрольная точка запас compaction rolling checkpoint headroom",thinking: {collapseByDefault: "Сворачивать размышления по умолчанию",collapseByDefaultDescription:diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 4913557d5e6..8ee58bdc757 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -1331,6 +1331,20 @@ export const zhCN = {rememberParamsPerModel: "按模型记住设置",rememberParamsPerModelDescription:"切换模型时会恢复你上次在该模型上使用的温度、提示词等设置。关闭后,所有模型共用一套设置。",+ autoCompact: "自动压缩长聊天",+ autoCompactDescription:+ "当本地 GGUF 聊天达到你设置的上下文长度时,丢弃较早的轮次而不是返回错误。此设置与可用显存无关。",+ compactionStyle: "上下文已满时",+ compactionStyleDescription:+ "使用服务器默认值会保留 UNSLOTH_CONTEXT_POLICY。重置对话会保留最新轮次和持续指令。滑动窗口会丢弃最早的轮次,并可保留更多近期历史。",+ compactionStyleInherit: "使用服务器默认值",+ compactionStyleCheckpoint: "重置对话",+ compactionStyleRollingDefault: "丢弃最早的轮次(约 25% 额外空间)",+ compactionStyleRolling10: "丢弃最早的轮次(约 10% 额外空间)",+ compactionStyleRolling5: "丢弃最早的轮次(约 5% 额外空间)",+ compactionStyleRollingNone: "丢弃最早的轮次(不额外裁剪)",+ autoCompactKeywords:+ "压缩 自动压缩 上下文 窗口 截断 滑动 检查点 余量 compaction rolling checkpoint headroom",thinking: {collapseByDefault: "默认折叠思考过程",collapseByDefaultDescription:diff --git a/studio/frontend/tests/auto-compaction-settings.test.ts b/studio/frontend/tests/auto-compaction-settings.test.tsnew file mode 100644index 00000000000..c58b29dccbf--- /dev/null+++ b/studio/frontend/tests/auto-compaction-settings.test.ts@@ -0,0 +1,119 @@+// 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 {+ DEFAULT_CONTEXT_POLICY,+ compactionStyleValue,+ ggufCompactionRequestFields,+ parseCompactionStyle,+ sanitizeCompactionHeadroomRatio,+} from "../src/features/chat/utils/auto-compaction.ts";++test("the default preserves the server context policy", () => {+ assert.equal(DEFAULT_CONTEXT_POLICY, "inherit");+ assert.equal(compactionStyleValue("inherit", 0.25), "inherit");+ assert.deepEqual(parseCompactionStyle("inherit"), {+ contextPolicy: "inherit",+ compactionHeadroomRatio: 0.25,+ });+ assert.deepEqual(+ ggufCompactionRequestFields({+ isGguf: true,+ autoCompactEnabled: true,+ contextPolicy: "inherit",+ compactionHeadroomRatio: 0.25,+ }),+ { context_overflow: "truncate_oldest" },+ );+});++test("auto-compact off sends an explicit error overflow policy", () => {+ assert.deepEqual(+ ggufCompactionRequestFields({+ isGguf: true,+ autoCompactEnabled: false,+ contextPolicy: "checkpoint",+ compactionHeadroomRatio: 0.25,+ }),+ { context_overflow: "error" },+ );+});++test("checkpoint compaction sends truncate_oldest and the checkpoint policy", () => {+ assert.deepEqual(+ ggufCompactionRequestFields({+ isGguf: true,+ autoCompactEnabled: true,+ contextPolicy: "checkpoint",+ compactionHeadroomRatio: 0.25,+ }),+ { context_overflow: "truncate_oldest", context_policy: "checkpoint" },+ );+});++test("a sliding window sends rolling policy and the extra-trim ratio", () => {+ assert.deepEqual(+ ggufCompactionRequestFields({+ isGguf: true,+ autoCompactEnabled: true,+ contextPolicy: "rolling",+ compactionHeadroomRatio: 0.05,+ }),+ {+ context_overflow: "truncate_oldest",+ context_policy: "rolling",+ compaction_headroom_ratio: 0.05,+ },+ );+});++test("external models never opt into GGUF compaction", () => {+ assert.deepEqual(+ ggufCompactionRequestFields({+ isGguf: false,+ autoCompactEnabled: true,+ contextPolicy: "rolling",+ compactionHeadroomRatio: 0,+ }),+ {},+ );+});++test("the settings select round-trips style values", () => {+ assert.equal(compactionStyleValue("checkpoint", 0.25), "checkpoint");+ assert.equal(compactionStyleValue("rolling", 0), "rolling:0");+ assert.deepEqual(parseCompactionStyle("rolling:0.1"), {+ contextPolicy: "rolling",+ compactionHeadroomRatio: 0.1,+ });+});++test("unsupported headroom ratios snap to an exposed choice", () => {+ assert.equal(sanitizeCompactionHeadroomRatio(0.9), 0.25);+ assert.equal(sanitizeCompactionHeadroomRatio(0.07), 0.05);+ assert.equal(compactionStyleValue("rolling", 0.9), "rolling:0.25");+ assert.deepEqual(+ ggufCompactionRequestFields({+ isGguf: true,+ autoCompactEnabled: true,+ contextPolicy: "rolling",+ compactionHeadroomRatio: 0.9,+ }),+ {+ context_overflow: "truncate_oldest",+ context_policy: "rolling",+ compaction_headroom_ratio: 0.25,+ },+ );+});++test("the chat adapter sends compaction fields through the shared helper", () => {+ const adapter = readFileSync(+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),+ "utf8",+ );+ assert.match(adapter, /ggufCompactionRequestFields\(/);+});diff --git a/studio/frontend/tests/cancelled-turn-history-prune.test.ts b/studio/frontend/tests/cancelled-turn-history-prune.test.tsindex 2034f5d731e..b1e92a78f1b 100644--- a/studio/frontend/tests/cancelled-turn-history-prune.test.ts+++ b/studio/frontend/tests/cancelled-turn-history-prune.test.ts@@ -67,7 +67,7 @@ test("a trailing abandoned turn keeps the prompt it followed", () => {test("the send and token-count paths prune through the same helper", () => {assert.match(adapter,- /const outboundMessages = pruneOutboundHistory\(messages, true\)/,+ /const survivingMessages = pruneOutboundHistory\(messages, true\)/,);assert.match(adapter,diff --git a/studio/frontend/tests/rolling-context-window.test.ts b/studio/frontend/tests/rolling-context-window.test.tsindex f6875675ad2..89c3a31fe99 100644--- a/studio/frontend/tests/rolling-context-window.test.ts+++ b/studio/frontend/tests/rolling-context-window.test.ts@@ -22,7 +22,8 @@ const transport = readFileSync(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, /autoCompactEnabled/);+ assert.match(adapter, /ggufCompactionRequestFields\(/);assert.match(adapter, /This conversation was compacted/);});diff --git a/studio/frontend/tests/studio-tool-history.test.ts b/studio/frontend/tests/studio-tool-history.test.tsnew file mode 100644index 00000000000..eaa85f72cb6--- /dev/null+++ b/studio/frontend/tests/studio-tool-history.test.ts@@ -0,0 +1,158 @@+// 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 { fileURLToPath } from "node:url";++import {+ hasOnlyStudioOwnedToolHistory,+ studioToolHistoryRequestFields,+} from "../src/features/chat/utils/studio-tool-history.ts";++function assistantToolCall(provenance?: unknown) {+ return {+ role: "assistant",+ content: [+ {+ type: "tool-call",+ toolName: "python",+ toolCallId: "call_1",+ args: { code: "print(1)" },+ result: "1",+ ...(provenance === undefined ? {} : { provenance }),+ },+ ],+ };+}++test("local tool provenance marks studio-owned history", () => {+ assert.equal(+ hasOnlyStudioOwnedToolHistory([+ { role: "user", content: [{ type: "text", text: "run python" }] },+ assistantToolCall({ source: "local" }),+ ]),+ true,+ );+});++test("mixed or unmarked tool history remains a client contract", () => {+ assert.equal(+ hasOnlyStudioOwnedToolHistory([+ assistantToolCall({ source: "local" }),+ assistantToolCall({ source: "external" }),+ ]),+ false,+ );+ assert.equal(hasOnlyStudioOwnedToolHistory([assistantToolCall()]), false);+ assert.equal(+ hasOnlyStudioOwnedToolHistory([+ { role: "assistant", content: [{ type: "text", text: "plain reply" }] },+ ]),+ false,+ );+});++test("only studio-owned tool history emits the request marker", () => {+ assert.deepEqual(+ studioToolHistoryRequestFields([assistantToolCall({ source: "local" })]),+ { studio_tool_history: true },+ );+ assert.deepEqual(+ studioToolHistoryRequestFields([+ assistantToolCall({ source: "local" }),+ assistantToolCall({ source: "external" }),+ ]),+ {},+ );+});++function hostedServerSearchCall() {+ return {+ role: "assistant",+ content: [+ {+ type: "tool-call",+ toolName: "web_search",+ toolCallId: "call_search",+ args: { _server_tool: true, query: "news" },+ result: { text: "hits" },+ provenance: { source: "external" },+ },+ ],+ };+}++test("ownership ignores hosted builtins that OpenAI replay drops", () => {+ const mixed = [+ hostedServerSearchCall(),+ assistantToolCall({ source: "local" }),+ ];+ assert.deepEqual(studioToolHistoryRequestFields(mixed), {});+ assert.deepEqual(+ studioToolHistoryRequestFields(mixed, {+ toolCallSurvives: (part) => {+ const args = part.args;+ return !(+ args &&+ typeof args === "object" &&+ !Array.isArray(args) &&+ (args as { _server_tool?: unknown })._server_tool === true+ );+ },+ }),+ { studio_tool_history: true },+ );+});++test("the live request and token-count paths mark ownership after replay", () => {+ const adapter = readFileSync(+ fileURLToPath(+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),+ ),+ "utf8",+ );+ const helper = adapter.indexOf(+ "function studioToolHistoryRequestFieldsAfterReplay",+ );+ const surviveFn = adapter.indexOf(+ "function toolCallPartSurvivesOpenAIReplay",+ );+ const serializeGate = adapter.indexOf(+ "serializeAssistantToolCallPart",+ surviveFn,+ );+ const first = adapter.indexOf("...studioToolHistoryRequestFieldsAfterReplay(");+ const second = adapter.indexOf(+ "...studioToolHistoryRequestFieldsAfterReplay(",+ first + 1,+ );+ assert.ok(helper >= 0);+ assert.ok(surviveFn >= 0 && surviveFn < helper);+ assert.ok(serializeGate > surviveFn);+ assert.ok(first >= 0 && second > first);+ assert.equal(+ adapter.indexOf("...studioToolHistoryRequestFields(survivingMessages)"),+ -1,+ );+});++test("the context recount forwards the tool-history request fields", () => {+ const source = readFileSync(+ fileURLToPath(+ new URL(+ "../src/features/chat/utils/refresh-context-usage.ts",+ import.meta.url,+ ),+ ),+ "utf8",+ );+ const historyBuild = source.indexOf(+ "const countHistory = await buildLocalTokenCountHistory(",+ );+ const countRequest = source.indexOf("await countChatInputTokens({", historyBuild);+ const historySpread = source.indexOf("...countHistory", countRequest);+ assert.ok(historyBuild >= 0 && countRequest > historyBuild);+ assert.ok(historySpread > countRequest);+});diff --git a/tests/studio/test_cancelled_turn_history_prune.py b/tests/studio/test_cancelled_turn_history_prune.pyindex 378b23556ad..811755a208e 100644--- a/tests/studio/test_cancelled_turn_history_prune.py+++ b/tests/studio/test_cancelled_turn_history_prune.py@@ -95,7 +95,9 @@ def _send_path_slice() -> str:"""body = slice_between(read(ADAPTER),- "const survivingMessages = pruneOutboundHistory(",+ " const survivingMessages = pruneOutboundHistory(\n"+ " messages,\n"+ " !isExternalRequest,\n","if (selectedImageEditReference) {",)return (diff --git a/tests/studio/test_chat_title_generation.py b/tests/studio/test_chat_title_generation.pyindex 2a1ac2cb562..7e04076d4f1 100644--- a/tests/studio/test_chat_title_generation.py+++ b/tests/studio/test_chat_title_generation.py@@ -76,7 +76,7 @@ def test_generate_title_passes_first_assistant_reply_after_first_user():)assert 'const firstUserIndex = messages.findIndex((m) => m.role === "user");' in block- assert '.find((m, i) => m.role === "assistant" && i > firstUserIndex)' in block+ assert 'm.role === "assistant" && i > firstUserIndex' in blockassert "const assistantText = extractTextParts(firstAssistant);" in blockassert "generateTitleWithModel({" in blockassert "userText," in blockdiff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.pyindex 7fef8190335..9749a5b7aca 100644--- a/tests/studio/test_model_picker_contracts.py+++ b/tests/studio/test_model_picker_contracts.py@@ -669,8 +669,9 @@ def test_a_pinned_cached_row_loads_from_the_id_the_backend_pinned():# the same meta and so has to carry the pin. Counted rather than matched# loosely, so a new row that forgets it is a failure here rather than a load# that silently follows the default ref. #7736 added the third: the collapsed- # single-quant GGUF row, which is a load site like the other two.- assert picker.count("loadId: c.load_id") == 3, (+ # single-quant GGUF row. #7880 added the fourth: the per-quant VRAM bar, which+ # has to price the pinned snapshot rather than the default ref.+ assert picker.count("loadId: c.load_id") == 4, ("a row or gear that can start a load is missing the pin, or a new one was ""added and this count needs to follow it")diff --git a/tests/studio/test_new_chat_context_recount.py b/tests/studio/test_new_chat_context_recount.pyindex b688eb54b4d..84008c391f7 100644--- a/tests/studio/test_new_chat_context_recount.py+++ b/tests/studio/test_new_chat_context_recount.py@@ -97,7 +97,9 @@ def _store_reducers() -> str:"setCheckpoint: (modelId, ggufVariant, options) =>"," // Re-apply the incoming thread's own usage",)- active = slice_between(text, "setActiveThreadId: (activeThreadId) =>", "setActiveProjectId:")+ active = slice_between(+ text, "setActiveThreadId: (activeThreadId) =>", "applyThreadScopedSettings:"+ )usage = slice_between(text, "setContextUsage: (contextUsage) =>", "setThreadContextUsage:")thread_usage = slice_between(text, "setThreadContextUsage: (threadId, usage) =>", "}));")return (@@ -318,9 +320,10 @@ function messagesContainImage(messages: any): boolean {}// The adapter's own prompt build is exercised by the request tests; here it only has-// to turn the reconstructed branch into something countable.-async function buildOutboundMessagesForTokenCount(messages: any): Promise<any[]> {- return messages.map((m: any) => ({ role: m.role, content: "x" }));+// to turn the reconstructed branch into something countable. Same shape+// refreshContextUsage spreads into countChatInputTokens.+async function buildLocalTokenCountHistory(messages: any): Promise<{ messages: any[] }> {+ return { messages: messages.map((m: any) => ({ role: m.role, content: "x" })) };}async function buildLocalTokenCountExtras(): Promise<Record<string, unknown>> {diff --git a/tests/studio/test_token_count_prompt_parity.py b/tests/studio/test_token_count_prompt_parity.pyindex d2030c45255..5611039d332 100644--- a/tests/studio/test_token_count_prompt_parity.py+++ b/tests/studio/test_token_count_prompt_parity.py@@ -42,7 +42,7 @@ def _canvas_constants() -> str:return slice_between(read(ADAPTER),"export const CANVAS_TOOL_INSTRUCTION =",- "/**\n * The OpenAI-form messages",+ "export async function buildLocalTokenCountHistory(",)@@ -58,7 +58,7 @@ def _prune_helpers() -> str:def _outbound_builder() -> str:return slice_between(read(ADAPTER),- "export async function buildOutboundMessagesForTokenCount(",+ "export async function buildLocalTokenCountHistory(","/**\n * The reasoning fields a completion would send",)@@ -195,12 +195,12 @@ def _count_script(seed_patch: str) -> str:f"""// @ts-nocheckimport {{- buildOutboundMessagesForTokenCount,+ buildLocalTokenCountHistory,estimateTokens,seed,}} from "./harness.ts";seed({seed_patch});- const outbound = await buildOutboundMessagesForTokenCount(+ const {{ messages: outbound }} = await buildLocalTokenCountHistory([{{ role: "user", text: "draw me a bar chart" }}],"thread-a",);diff --git a/tests/studio/test_usage_examples_model_source_contract.py b/tests/studio/test_usage_examples_model_source_contract.pyindex 3580a10d849..cfdb53c69d6 100644--- a/tests/studio/test_usage_examples_model_source_contract.py+++ b/tests/studio/test_usage_examples_model_source_contract.py@@ -13,6 +13,7 @@ USAGE_EXAMPLES_TSX = SETTINGS / "components/usage-examples.tsx"OPENAI_MODELS_TS = SETTINGS / "api/openai-models.ts"API_KEYS_TAB_TSX = SETTINGS / "tabs/api-keys-tab.tsx"KEYLESS_SECTION_TSX = SETTINGS / "components/keyless-api-access-section.tsx"+KEYLESS_ELIGIBILITY_TS = SETTINGS / "components/keyless-example-eligibility.ts"def test_examples_name_a_model_the_server_can_serve():@@ -223,9 +224,11 @@ def test_keyless_examples_match_transport_tool_and_full_scope_policy():assert "keylessBase && keylessTools" in srcassert "apiKey || (keylessBase ? KEYLESS_KEY_PLACEHOLDER : KEY_PLACEHOLDER)" in srcassert 'const KEYLESS_KEY_PLACEHOLDER = "not-needed"' in src- assert 'exposure === "colab" || exposure === "public_url"' in src- assert "if (isLoopbackHost(host)) return true;" in src- assert 'exposure === "private_lan"' in src+ assert "keylessBaseEligible(base, keylessScope, keylessExposure)" in src+ eligibility = KEYLESS_ELIGIBILITY_TS.read_text(encoding = "utf-8")+ assert 'exposure === "colab" || exposure === "public_url"' in eligibility+ assert "if (isLoopbackHost(host)) return true;" in eligibility+ assert 'return scope === "inference";' in eligibilityassert "!(useTunnel && cloudflareUrl)" in srcassert "useExampleModelName(keylessBase && !apiKey)" in srcsection = KEYLESS_SECTION_TSX.read_text(encoding = "utf-8")