Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: extend automatic context compaction to MLX (#9399)

dre4moffaa2a6461c59d
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.py
index c82f2e3de8e..828eb103a1f 100644
--- a/studio/backend/core/inference/orchestrator.py
+++ b/studio/backend/core/inference/orchestrator.py
@@ -2731,6 +2731,176 @@ class InferenceOrchestrator:
raise RuntimeError(error)
return int(resp["input_tokens"]), resp.get("model")
+ def compact_chat_context(
+ self,
+ messages: list,
+ *,
+ system_prompt: str = "",
+ tools: Optional[list] = None,
+ context_overflow: Optional[str] = None,
+ context_policy: Optional[str] = None,
+ compaction_headroom_ratio: Optional[float] = None,
+ max_tokens: Optional[int] = None,
+ thread_id: Optional[str] = None,
+ cancel_event = None,
+ enable_thinking: Optional[bool] = None,
+ reasoning_effort: Optional[str] = None,
+ preserve_thinking: Optional[bool] = None,
+ continue_final_message: bool = False,
+ tool_loop: bool = False,
+ anchor_ids = None,
+ replay_boundary: bool = True,
+ recall_done: bool = False,
+ request_branch: Optional[list] = None,
+ live_branch: Optional[list] = None,
+ ) -> dict:
+ """Fit one MLX prompt into the served window under the policy GGUF uses.
+
+ Only a ``tool_loop`` turn that carries tools may reset the epoch: no other MLX turn
+ is offered ``search_conversation``. ``request_branch`` is the client's transcript and
+ ``live_branch`` that plus the loop's replies and tool results; both default to the prompt.
+ Never raises: a failed fit returns the request unchanged.
+ """
+ unchanged = {
+ "messages": list(messages),
+ "system_prompt": system_prompt,
+ "events": [],
+ "recalled": False,
+ "anchored": [],
+ }
+ model_info = self.models.get(self.active_model_name) or {}
+ context_length = int(model_info.get("context_length") or 0)
+ if (
+ context_overflow != "truncate_oldest"
+ or not model_info.get("is_mlx")
+ or context_length <= 1
+ ):
+ return unchanged
+
+ conversation = []
+ if system_prompt:
+ conversation.append({"role": "system", "content": system_prompt})
+ conversation.extend(messages)
+
+ try:
+ from core.inference.chat_template_helpers import trailing_assistant_resume_kind
+ from core.inference.context_window import (
+ messages_without_unpriced_media,
+ retrieval_budget,
+ )
+ from core.inference.llama_cpp import (
+ _archive_and_recall,
+ _boundary_metadata,
+ _can_reset_epoch,
+ _compaction_fit_kwargs,
+ _conversation_recall_reserve,
+ _fit_with_instruction_pins,
+ _keeps_compaction_boundary,
+ _memory_tool_withheld,
+ _records_boundary,
+ _sticky_compaction_state,
+ )
+
+ if messages_without_unpriced_media(conversation) is not conversation:
+ return unchanged
+ if cancel_event is not None and cancel_event.is_set():
+ return unchanged
+ # The count prices a new reply, not a resumed reply or thought.
+ if continue_final_message and trailing_assistant_resume_kind(conversation):
+ return unchanged
+
+ request_branch = request_branch or conversation
+ # The loop asks for its final answer without tools. That turn cannot search, so
+ # it must not reset, and its reply never comes back into the prompt.
+ calls_tools = tool_loop and bool(tools)
+ recall_offered = tool_loop and any(
+ isinstance(tool, dict)
+ and (tool.get("function") or {}).get("name") == "search_conversation"
+ for tool in tools or ()
+ )
+
+ def _count(fitted):
+ if cancel_event is not None and cancel_event.is_set():
+ raise RuntimeError("Context compaction cancelled")
+ return self.count_chat_tokens(
+ fitted,
+ "",
+ tools = tools,
+ enable_thinking = enable_thinking,
+ reasoning_effort = reasoning_effort,
+ preserve_thinking = preserve_thinking,
+ )[0]
+
+ can_reset = _can_reset_epoch(
+ thread_id,
+ calls_tools,
+ tools_withheld = _memory_tool_withheld(thread_id, tools),
+ )
+ sticky, sticky_is_checkpoint = (
+ _sticky_compaction_state(
+ thread_id,
+ request_branch,
+ context_policy = context_policy,
+ can_reset = can_reset,
+ compaction_headroom_ratio = compaction_headroom_ratio,
+ )
+ if replay_boundary
+ else (0, False)
+ )
+ fitted, truncation = _fit_with_instruction_pins(
+ conversation,
+ context_length = context_length,
+ max_tokens = max_tokens,
+ count_tokens = _count,
+ anchor_ids = anchor_ids,
+ keeps_boundary = _keeps_compaction_boundary(thread_id),
+ can_reset = can_reset,
+ recall_offered = recall_offered,
+ reserve_tokens = _conversation_recall_reserve(thread_id),
+ sticky_dropped = sticky,
+ sticky_is_checkpoint = sticky_is_checkpoint,
+ **_compaction_fit_kwargs(context_policy, compaction_headroom_ratio),
+ )
+ if not truncation:
+ return unchanged
+
+ recall = _archive_and_recall(
+ fitted,
+ conversation,
+ branch_messages = live_branch or conversation,
+ thread_id = thread_id,
+ # A forged tool exchange is only safe when the request advertises the tool.
+ style = "tool" if recall_offered else "inline",
+ force_recall = bool(truncation.get("checkpoint_started", True)),
+ # A rescued refusal may evict messages; archive them without recall.
+ recall_done = recall_done or not truncation["fits"],
+ recall_budget_tokens = retrieval_budget(
+ context_length,
+ max_tokens,
+ truncation.get("prompt_tokens_after") or 0,
+ reply_returns = calls_tools,
+ ),
+ count_tokens = _count,
+ )
+ fitted = recall["conversation"]
+ truncation = {**truncation, **recall["counts"]}
+ if _records_boundary(truncation):
+ truncation = {
+ **truncation,
+ **_boundary_metadata(fitted, request_branch, compaction_headroom_ratio),
+ }
+ return {
+ "messages": fitted,
+ "system_prompt": "",
+ # `fits` False too: it carries the does-not-fit diagnosis.
+ "events": [*recall["events"], {"type": "context_truncated", **truncation}],
+ "recalled": bool(recall["recalled"]),
+ "anchored": list(recall["anchored"]),
+ }
+ except Exception as exc:
+ logger.warning("Could not preflight the MLX context window: %s", exc)
+ return unchanged
+
def generate_chat_response(
self,
messages: list,
@@ -2899,6 +3069,9 @@ class InferenceOrchestrator:
seed: Optional[int] = None,
caller_image_indexes: "tuple[int, ...]" = (),
mcp_image = None,
+ context_overflow: Optional[str] = None,
+ context_policy: Optional[str] = None,
+ compaction_headroom_ratio: Optional[float] = None,
**_unused,
):
"""Run the safetensors agentic tool loop in the parent process, calling the worker for each
@@ -3006,6 +3179,62 @@ class InferenceOrchestrator:
# Resolved BEFORE the profile: the mapper installs its template during the render.
_mapped_tpl = mapped_chat_template(_model_info, self.active_model_name)
+ _request_branch = list(initial)
+ _request_ids = {id(message) for message in initial}
+ _sticky_boundary_applied = False
+ _conversation_recall_done = False
+ # The loop appends user-role notices, after which the fit no longer protects the
+ # request's own question as the newest user turn.
+ _rolling_anchor_ids: set[int] = set()
+ for message in reversed(initial):
+ if message.get("role") == "user":
+ _rolling_anchor_ids.add(id(message))
+ break
+
+ def _fit_iteration(conversation: list, active_tools: list, live_branch: list) -> dict:
+ nonlocal _sticky_boundary_applied, _conversation_recall_done
+ if loop_images:
+ # The count cannot price pictures.
+ return {}
+ # Once a notice or a retry follows the loop's newest tool result, the fit no longer
+ # protects it either, though the reply is to be written from it. It is pinned with
+ # the user turn before it, which would otherwise be evicted with it in tow. For
+ # this fit only: pinned for good, a long loop's results would fill the window.
+ pinned = _rolling_anchor_ids
+ for index in range(len(conversation) - 1, -1, -1):
+ message = conversation[index]
+ if message.get("role") == "tool" and id(message) not in _request_ids | pinned:
+ asked = [id(m) for m in conversation[:index] if m.get("role") == "user"]
+ pinned = pinned | {id(message), *asked[-1:]}
+ break
+ result = self.compact_chat_context(
+ conversation,
+ tools = active_tools,
+ context_overflow = context_overflow,
+ context_policy = context_policy,
+ compaction_headroom_ratio = compaction_headroom_ratio,
+ max_tokens = max_new_tokens,
+ thread_id = thread_id,
+ cancel_event = cancel_event,
+ enable_thinking = enable_thinking,
+ reasoning_effort = reasoning_effort,
+ preserve_thinking = preserve_thinking,
+ continue_final_message = continue_final_message,
+ tool_loop = True,
+ anchor_ids = pinned,
+ replay_boundary = not _sticky_boundary_applied,
+ recall_done = _conversation_recall_done,
+ request_branch = _request_branch,
+ live_branch = live_branch,
+ )
+ # The saved boundary describes the original transcript, so it applies once.
+ _sticky_boundary_applied = True
+ if result.get("recalled"):
+ _conversation_recall_done = True
+ for message in result.get("anchored") or ():
+ _rolling_anchor_ids.add(id(message))
+ return result
+
yield from run_safetensors_tool_loop(
markup = markup_for_tokenizer(_model_info.get("tokenizer"), tools, _mapped_tpl),
renderable_tools = renderable_tool_catalog(
@@ -3042,6 +3271,7 @@ class InferenceOrchestrator:
# never evicts it. Empty when the model reads no images, since there is
# then no sink to protect anything in.
caller_image_indexes = tuple(caller_image_indexes) if loop_images else (),
+ context_fitter = _fit_iteration,
)
def generate_with_adapter_control(
diff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.py
index 4dea3918ac9..8a900ea4a9b 100644
--- a/studio/backend/core/inference/safetensors_agentic.py
+++ b/studio/backend/core/inference/safetensors_agentic.py
@@ -640,6 +640,7 @@ def run_safetensors_tool_loop(
generation_stats_holder: Optional[dict] = None,
images_sink: Optional[list] = None,
caller_image_indexes: "tuple[int, ...]" = (),
+ context_fitter: Optional[Callable[[list, list, list], dict]] = None,
) -> Generator[dict, None, None]:
"""Drive an agentic tool loop on top of a cumulative-text generator.
@@ -668,11 +669,23 @@ def run_safetensors_tool_loop(
# let the prompt carry a second full allowance. The route reserves the attachment's
# slot by trimming replay to limit - 1 before interleaving it.
caller_images = tuple(caller_image_indexes)
- # The branch this request is on, before the loop appends anything. A GGUF-compacted
- # thread keeps its archive across a switch to safetensors, so search_conversation is
- # advertised here too and needs the same filtering: the stored rows are the whole
- # DAG, and Retry leaves the replaced response in them.
- request_branch = list(messages)
+ # The branch this request is on. A GGUF-compacted thread keeps its archive across a
+ # switch to safetensors, so search_conversation is advertised here too and needs the
+ # same filtering: the stored rows are the whole DAG, and Retry leaves the replaced
+ # response in them.
+ _live_branch = list(messages)
+ # ...and the replies and tool results the loop adds to it: a fit can evict this request's
+ # own earlier tool exchange into the archive, where the client's messages alone would
+ # refuse it. Not the loop's user turns: those are its own notices, and recall searches
+ # for the branch's last user turn, which has to stay the request.
+ _live_branch_ids = {id(message) for message in _live_branch}
+
+ def _extend_live_branch(current: list) -> list:
+ for message in current:
+ if id(message) not in _live_branch_ids and message.get("role") != "user":
+ _live_branch_ids.add(id(message))
+ _live_branch.append(message)
+ return _live_branch
# Mirrors the GGUF loop: "full" and bypass_permissions are the same switch;
# unset defaults to "auto", unknown falls back to the stricter "ask"; "off"
@@ -809,6 +822,15 @@ def run_safetensors_tool_loop(
# Gate the markerless bare-JSON form on enabled names so an ordinary JSON answer isn't misread as a call.
_enabled_tool_names = None if unrestricted_tools else set(_active_tool_names(active_tools))
+ # Refit every iteration: tool results grow the prompt after the first turn. Given
+ # the prompt, this turn's tools and the live branch; returns `messages` and `events`.
+ if context_fitter is not None:
+ fit_result = context_fitter(
+ conversation, active_tools, _extend_live_branch(conversation)
+ )
+ conversation = list(fit_result.get("messages") or conversation)
+ yield from fit_result.get("events") or ()
+
# This loop receives cumulative snapshots, so keep both whole-prefix scans
# incremental: the stripper settles safe prefixes, the signal detector resumes
# with enough overlap for a literal split across snapshots.
@@ -1620,7 +1642,7 @@ def run_safetensors_tool_loop(
if _strict and _accepts_kwarg(execute_tool, "tool_execution_mode"):
kwargs["tool_execution_mode"] = "required"
if _accepts_kwarg(execute_tool, "conversation_branch"):
- kwargs["conversation_branch"] = request_branch
+ kwargs["conversation_branch"] = _extend_live_branch(conversation)
if _approved and _accepts_kwarg(execute_tool, "host_access_approved"):
kwargs["host_access_approved"] = True
# And the room the model has left, as the GGUF loop does: without a
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 7a45d8a87be..317deb21f49 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -2709,16 +2709,18 @@ class ChatCompletionRequest(BaseModel):
"limited to client-tool or response_format passthrough and retries after "
"keeping the first and recent turns. 'truncate_oldest' provides a rolling "
"window for plain and Unsloth-tool chats by dropping complete oldest turns. "
- "Both truncation policies preserve system messages and tool-call groups."
+ "Both truncation policies preserve system messages and tool-call groups. "
+ "MLX models honor 'truncate_oldest' only."
),
)
context_policy: Optional[Literal["checkpoint", "rolling"]] = Field(
None,
description = (
- "[x-unsloth] How a local GGUF chat compacts once context_overflow is "
+ "[x-unsloth] How a local GGUF or MLX chat compacts once context_overflow is "
"truncate_oldest. 'checkpoint' resets to the latest turn plus standing "
"instructions (Unsloth default). 'rolling' drops oldest complete turns. "
- "Unset uses UNSLOTH_CONTEXT_POLICY."
+ "Unset uses UNSLOTH_CONTEXT_POLICY. On MLX only Unsloth-tool chats start a "
+ "reset."
),
)
compaction_headroom_ratio: Optional[float] = Field(
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 25119d40592..d67eb9b5cbf 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -6469,10 +6469,10 @@ def _apply_compaction_nudge(
archive to search and stays a no-op for chats that never compacted.
`checkpoint_fitted` is the CALLER's answer to "does this request go through
- `_fit_context`, which can reset the epoch", not the process-wide policy. Only the
- llama.cpp path fits that way; reading the global policy instead told a safetensors
- model that a carried_forward block had removed its history when no such block exists.
- Defaults to False so a new call site claims the reset rather than inheriting it."""
+ `_fit_context`, which can reset the epoch", not the process-wide policy. GGUF and MLX
+ opt in at their exact-token preflight call sites; other safetensors and external-provider
+ paths do not. Defaults to False so a new call site claims the reset rather than
+ inheriting it."""
tool_names = {(t.get("function") or {}).get("name") for t in (tools or [])}
if "search_conversation" not in tool_names:
return nudge
@@ -32067,6 +32067,8 @@ async def produce_openai_chat_completions(
# Classify capability flags from the loaded template.
_sf_model_info = backend.models.get(backend.active_model_name, {})
+ # Only MLX can count its own prompt, so only MLX is fitted before it generates.
+ _sf_fit_overflow = _rolling_context_policy(payload) if _sf_model_info.get("is_mlx") else None
if _sf_model_info.get("engine") in ("vllm", "sglang"):
if _managed_engine_unsupported_controls(payload):
raise _reject(
@@ -32335,6 +32337,7 @@ async def produce_openai_chat_completions(
tools_on = _sf_tools_on,
mcp_allowed = _sf_mcp_allowed,
supports_vision = bool(_sf_model_info.get("is_vision")),
+ checkpoint_fitted = _sf_fit_overflow is not None,
)
_reject_missing_forced_tool(payload.tool_choice, _sf_tools_to_use)
# Mirror the GGUF path: refuse to enter the tool loop when nothing
@@ -32394,9 +32397,12 @@ async def produce_openai_chat_completions(
# RAG nudge, mirroring the GGUF path.
_sf_nudge = await _apply_rag_nudge(_sf_nudge, _sf_tools_to_use, rag_scope = payload.rag_scope)
- # No `checkpoint_fitted`: this path never calls `fit_checkpoint_context`, so there
- # is no reset and no carried_forward block to describe.
- _sf_nudge = _apply_compaction_nudge(_sf_nudge, _sf_tools_to_use)
+ _sf_nudge = _apply_compaction_nudge(
+ _sf_nudge,
+ _sf_tools_to_use,
+ checkpoint_fitted = _sf_fit_overflow is not None,
+ payload = payload,
+ )
_sf_system_prompt = _apply_current_date_prompt(
_user_system_prompt,
@@ -32527,6 +32533,9 @@ async def produce_openai_chat_completions(
use_adapter = payload.use_adapter,
stats_holder = _sf_stats_holder,
reasoning_prefilled = _sf_reasoning_prefilled,
+ context_overflow = _sf_fit_overflow,
+ context_policy = _request_context_policy(payload),
+ compaction_headroom_ratio = _request_compaction_headroom_ratio(payload),
)
_sf_tool_sentinel = object()
@@ -32671,6 +32680,14 @@ async def produce_openai_chat_completions(
yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE
continue
+ if event["type"] == "context_truncated":
+ yield _context_truncated_sse_chunk(
+ completion_id,
+ model_name,
+ {key: value for key, value in event.items() if key != "type"},
+ )
+ continue
+
# Diff cumulative cleaned text against last snapshot.
raw_cumulative = event.get("text", "")
clean_cumulative = _strip_tool_xml_for_display(
@@ -32781,8 +32798,10 @@ async def produce_openai_chat_completions(
# Non-streaming JSON: drain the loop, build one ChatCompletion.
try:
+ _sf_context_truncation = None
def _drain_to_text():
+ nonlocal _sf_context_truncation
full_text = ""
# Only the resumed turn renders no generation prompt; later tool-loop turns
# prefill <think> again. The kept text is the LAST turn's, so track the
@@ -32815,6 +32834,10 @@ async def produce_openai_chat_completions(
_event_type == "status" and not event.get("text")
):
continued = False
+ elif _event_type == "context_truncated":
+ _sf_context_truncation = _accumulate_context_truncation(
+ _sf_context_truncation, event
+ )
return full_text, prefilled
content_text, _sf_drain_prefilled = await asyncio.to_thread(_drain_to_text)
@@ -32867,7 +32890,7 @@ async def produce_openai_chat_completions(
),
),
)
- return _model_json_response(response)
+ return _model_json_response_with_context_truncation(response, _sf_context_truncation)
except asyncio.CancelledError:
cancel_event.set()
backend.reset_generation_state(cancel_event)
@@ -33155,17 +33178,11 @@ async def produce_openai_chat_completions(
# Request-scoped usage/timings receptacle (filled at gen_done).
stats_holder: dict = {}
+ _sf_context_truncation_holder: dict = {"value": None}
if payload.use_adapter is not None:
- def generate(messages_override = None, choice_index = 0):
- kw = (
- gen_kwargs
- if messages_override is None
- else {**gen_kwargs, "messages": messages_override}
- )
- if choice_index:
- kw = {**kw, "seed": _choice_seed(payload.seed, choice_index)}
+ def _sf_raw_generate(kw):
return backend.generate_with_adapter_control(
use_adapter = payload.use_adapter,
cancel_event = cancel_event,
@@ -33174,20 +33191,55 @@ async def produce_openai_chat_completions(
)
else:
- def generate(messages_override = None, choice_index = 0):
- kw = (
- gen_kwargs
- if messages_override is None
- else {**gen_kwargs, "messages": messages_override}
- )
- if choice_index:
- kw = {**kw, "seed": _choice_seed(payload.seed, choice_index)}
+ def _sf_raw_generate(kw):
return backend.generate_chat_response(
cancel_event = cancel_event,
stats_holder = stats_holder,
**kw,
)
+ def generate(messages_override = None, choice_index = 0):
+ base_kwargs = (
+ gen_kwargs
+ if messages_override is None
+ else {**gen_kwargs, "messages": messages_override}
+ )
+
+ if choice_index:
+ base_kwargs = {**base_kwargs, "seed": _choice_seed(payload.seed, choice_index)}
+
+ def _run():
+ generation_kwargs = base_kwargs
+ # The count cannot price pictures or video, so those prompts are left alone.
+ if _sf_fit_overflow and all(
+ base_kwargs.get(key) is None for key in ("image", "images", "video")
+ ):
+ fitted = backend.compact_chat_context(
+ base_kwargs.get("messages") or [],
+ system_prompt = base_kwargs.get("system_prompt") or "",
+ tools = base_kwargs.get("tools"),
+ context_overflow = _sf_fit_overflow,
+ context_policy = _request_context_policy(payload),
+ compaction_headroom_ratio = _request_compaction_headroom_ratio(payload),
+ max_tokens = effective_max_tokens,
+ thread_id = payload.thread_id,
+ cancel_event = cancel_event,
+ enable_thinking = base_kwargs.get("enable_thinking"),
+ reasoning_effort = base_kwargs.get("reasoning_effort"),
+ preserve_thinking = base_kwargs.get("preserve_thinking"),
+ continue_final_message = bool(base_kwargs.get("continue_final_message", False)),
+ )
+ generation_kwargs = {
+ **base_kwargs,
+ "messages": fitted["messages"],
+ "system_prompt": fitted["system_prompt"],
+ }
+ for event in fitted.get("events") or ():
+ yield event
+ yield from _sf_raw_generate(generation_kwargs)
+
+ return _run()
+
# ── Streaming response ────────────────────────────────────────
if payload.stream:
_cancel_keys = (payload.cancel_id, payload.session_id, completion_id)
@@ -33240,6 +33292,14 @@ async def produce_openai_chat_completions(
_next_task = None
if cumulative is _DONE:
break
+ if isinstance(cumulative, dict):
+ if cumulative.get("type") == "context_truncated":
+ yield _context_truncated_sse_chunk(
+ completion_id,
+ model_name,
+ {key: value for key, value in cumulative.items() if key != "type"},
+ )
+ continue
if isinstance(cumulative, GenStreamError):
backend.reset_generation_state(cancel_event)
_msg = _friendly_gen_stream_error(cumulative)
@@ -33458,6 +33518,13 @@ async def produce_openai_chat_completions(
def _drain_generate(messages_override = None, choice_index = 0):
final = ""
for token in generate(messages_override, choice_index = choice_index):
+ if isinstance(token, dict):
+ if token.get("type") == "context_truncated":
+ # Choices and retries refit one prompt: report a fit, not their sum.
+ _sf_context_truncation_holder["value"] = _accumulate_context_truncation(
+ None, token
+ )
+ continue
if isinstance(token, GenStreamError):
return token
final = token
@@ -33758,7 +33825,9 @@ async def produce_openai_chat_completions(
timings = _last_stats.get("timings") if len(_choices) <= 1 else None,
)
api_monitor.finish(monitor_id)
- return _model_json_response(response)
+ return _model_json_response_with_context_truncation(
+ response, _sf_context_truncation_holder["value"]
+ )
except asyncio.CancelledError:
cancel_event.set()
@@ -39275,6 +39344,7 @@ async def _mlx_count_chat_tokens(payload, request = None) -> Optional[JSONRespon
tools_on = _tools_on,
mcp_allowed = False,
supports_vision = bool(entry.get("is_vision")),
+ checkpoint_fitted = _rolling_context_policy(payload) is not None,
)
) + _mcp_tools
# Nothing surviving means the completion skips the tool loop, so follow it back
@@ -39375,9 +39445,13 @@ async def _mlx_count_chat_tokens(payload, request = None) -> Optional[JSONRespon
_tools_to_use,
rag_scope = payload.rag_scope,
)
- # The safetensors completion appends this too. No `checkpoint_fitted`: only the
- # llama.cpp path fits that way, so neither this count nor its completion resets.
- _nudge = _apply_compaction_nudge(_nudge, _tools_to_use)
+ # Match the MLX completion's preflight policy and rendered nudge.
+ _nudge = _apply_compaction_nudge(
+ _nudge,
+ _tools_to_use,
+ checkpoint_fitted = _rolling_context_policy(payload) is not None,
+ payload = payload,
+ )
# The tool-loop completion reapplies the date with include_api_key, which is the
# one case an API-key request still gets it. The plain call above withholds it,
# so without this the count is short exactly that line for these completions.
diff --git a/studio/backend/tests/test_checkpoint_compaction.py b/studio/backend/tests/test_checkpoint_compaction.py
index ff856745cac..511cf937ded 100644
--- a/studio/backend/tests/test_checkpoint_compaction.py
+++ b/studio/backend/tests/test_checkpoint_compaction.py
@@ -892,23 +892,22 @@ def test_a_healthy_archive_still_starts_an_epoch(monkeypatch):
def test_only_a_checkpoint_fitted_request_is_told_the_conversation_was_reset():
"""The checkpoint half of the nudge describes THIS request's fit, not the policy.
- Only `llama_cpp._fit_context` reaches `fit_checkpoint_context`, so a safetensors
- request never resets and never grows a block -- yet it shares `_apply_compaction_nudge`,
- and reading the process-wide policy there told such a model its history was removed and
- that recall had already run, which discourages the search that would recover it.
+ Only an exact-token path that opts into checkpoint fitting may claim a reset. GGUF and
+ MLX do; other safetensors and external-provider requests still share this helper without
+ fitting, so reading process-wide policy here would describe a reset that never happened.
"""
import routes.inference as routes_mod
tools = [{"function": {"name": "search_conversation"}}]
assert routes_mod._checkpoint_needs_search() is True
- # The safetensors call site, verbatim: no claim of a reset.
+ # A non-fitting call site makes no claim of a reset.
rolling = routes_mod._apply_compaction_nudge("base.", tools)
assert "carried_forward" not in rolling
assert routes_mod._CHECKPOINT_SESSION_NUDGE not in rolling
assert routes_mod._COMPACTED_SESSION_NUDGE in rolling
- # The llama.cpp call site, which really does fit through `_fit_context`.
+ # An exact-token GGUF or MLX call site really does fit through `_fit_context`.
reset = routes_mod._apply_compaction_nudge("base.", tools, checkpoint_fitted = True)
assert routes_mod._CHECKPOINT_SESSION_NUDGE in reset
@@ -1005,10 +1004,9 @@ def test_the_first_compaction_is_not_refused_for_lacking_a_tool_that_cannot_exis
def test_the_memory_tool_override_needs_a_request_that_can_actually_reset(monkeypatch):
"""The policy says a reset is possible SOMEWHERE, not that this request can do one.
- Only the llama.cpp branch runs `fit_checkpoint_context`, yet the safetensors branch,
- the external-provider loops and the token counter share this selector, so reading the
- process-wide policy put the memory tool in front of an MCP-only request on a path where
- nothing is ever compacted.
+ Exact-token GGUF and MLX branches run `fit_checkpoint_context`, while other safetensors,
+ external-provider loops and token counters share this selector without fitting. Reading
+ process-wide policy put the memory tool in front of requests on paths that never compact.
"""
import asyncio
import types
diff --git a/studio/backend/tests/test_conversation_search_safetensors_loop.py b/studio/backend/tests/test_conversation_search_safetensors_loop.py
index b54975589fc..cb433f8568c 100644
--- a/studio/backend/tests/test_conversation_search_safetensors_loop.py
+++ b/studio/backend/tests/test_conversation_search_safetensors_loop.py
@@ -69,7 +69,9 @@ def test_the_loop_hands_its_search_the_active_branch():
_run(1, execute_tool)
- assert seen == [MESSAGES]
+ # The client's messages, then the call the loop itself appended, as the GGUF loop passes.
+ [branch] = seen
+ assert branch[: len(MESSAGES)] == MESSAGES and len(branch) == len(MESSAGES) + 1
def test_conversation_searches_share_the_per_turn_cap():
diff --git a/studio/backend/tests/test_mlx_context_compaction.py b/studio/backend/tests/test_mlx_context_compaction.py
new file mode 100644
index 00000000000..68e09bde400
--- /dev/null
+++ b/studio/backend/tests/test_mlx_context_compaction.py
@@ -0,0 +1,253 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""MLX context fitting: the orchestrator preflight and the tool loop's per-turn refit."""
+
+from unittest.mock import Mock
+
+import pytest
+
+import core.inference.tools as tools_mod
+from core.inference import llama_cpp
+from core.inference.context_window import retrieval_budget
+from core.inference.orchestrator import InferenceOrchestrator
+
+INSTRUCTION = "Standing instruction for the rest of this task: always answer in a markdown table."
+SEARCH = {"type": "function", "function": {"name": "search_conversation"}}
+WEB = {"type": "function", "function": {"name": "web_search"}}
+
+
+def _count(messages, *_args, **_kwargs):
+ return sum(max(1, len(str(m.get("content", ""))) // 4) for m in messages), "mlx-test"
+
+
+def _backend():
+ backend = InferenceOrchestrator()
+ backend.active_model_name = "mlx-test"
+ backend.models["mlx-test"] = {"is_mlx": True, "context_length": 1200}
+ backend.count_chat_tokens = _count
+ return backend
+
+
+def _thread(latest = "continue"):
+ messages = [{"role": "user", "content": INSTRUCTION}, {"role": "assistant", "content": "OK."}]
+ for index in range(8):
+ messages.append({"role": "user", "content": f"Section {index}. " + "x" * 600})
+ messages.append({"role": "assistant", "content": f"Section {index} noted."})
+ return messages + [{"role": "user", "content": latest}]
+
+
+def _fit(backend, messages, **kwargs):
+ kwargs.setdefault("context_overflow", "truncate_oldest")
+ return backend.compact_chat_context(
+ messages, system_prompt = "you are helpful", max_tokens = 200, **kwargs
+ )
+
+
+def archive_calls(monkeypatch):
+ """A saved thread with a healthy archive, so only the request's own gates decide."""
+ calls = []
+ idle = {"events": [], "counts": {}, "recalled": False, "anchored": []}
+
+ def _archive(conversation, _before, **kwargs):
+ calls.append({**kwargs, "branch_messages": list(kwargs["branch_messages"])})
+ return {"conversation": conversation, **idle}
+
+ def _can_reset(
+ thread_id,
+ supports_tools,
+ *,
+ tools_withheld = False,
+ ):
+ return bool(thread_id and supports_tools and not tools_withheld)
+
+ monkeypatch.setattr(llama_cpp, "_archive_and_recall", _archive)
+ monkeypatch.setattr(llama_cpp, "_can_reset_epoch", _can_reset)
+ monkeypatch.setattr(llama_cpp, "_archive_is_degraded", lambda: False)
+ return calls
+
+
+# A 4200-character question is over the prompt budget even alone: a rescued refusal.
[email protected]("question_chars, fits", [(8, True), (4200, False)])
+def test_an_overflowing_prompt_drops_its_oldest_turns_and_reports_the_boundary(
+ archive_calls, question_chars, fits
+):
+ messages = _thread("q" * question_chars)
+
+ result = _fit(_backend(), messages, thread_id = "thread-1")
+
+ [truncation] = result["events"]
+ assert truncation["type"] == "context_truncated"
+ assert truncation["fits"] is fits is (truncation["prompt_tokens_after"] <= 1000)
+ assert truncation["boundary_messages"] == truncation["dropped_messages"] > 0
+ # What a rescue evicts is archived, not recalled into a prompt that is already over.
+ assert archive_calls[-1]["recall_done"] is not fits
+ assert result["system_prompt"] == ""
+ assert result["messages"][0] == {"role": "system", "content": "you are helpful"}
+ assert result["messages"][-1] is messages[-1]
+
+
+ "case", ["not_opted_in", "not_mlx", "media", "resumed_reply", "resumed_thought", "no_count"]
+)
+def test_a_prompt_the_fit_must_not_touch_is_returned_unchanged(case):
+ backend, messages, kwargs = _backend(), _thread(), {}
+ if case == "not_opted_in":
+ kwargs["context_overflow"] = "error"
+ elif case == "not_mlx":
+ backend.models["mlx-test"]["is_mlx"] = False
+ elif case == "media":
+ messages[-1] = {"role": "user", "content": [{"type": "image_url", "image_url": {}}]}
+ elif case.startswith("resumed"):
+ partial = {"content": "so far"} if case == "resumed_reply" else {"reasoning_content": "hm"}
+ messages.append({"role": "assistant", "content": "", **partial})
+ kwargs["continue_final_message"] = True
+ else:
+ backend.count_chat_tokens = Mock(side_effect = RuntimeError("generation in progress"))
+
+ result = _fit(backend, messages, **kwargs)
+
+ assert result["messages"] == messages
+ assert result["system_prompt"] == "you are helpful"
+ assert result["events"] == []
+
+
+def test_only_a_tool_loop_request_resets_and_only_an_offered_search_is_named(archive_calls):
+ def fit(messages = None, **kwargs):
+ result = _fit(
+ _backend(),
+ messages or _thread(),
+ context_policy = "checkpoint",
+ thread_id = "thread-1",
+ **kwargs,
+ )
+ return result["events"][-1], result["messages"][0]["content"], archive_calls[-1]
+
+ # A client's own catalogue may reach a plain request; it is not Unsloth's search tool.
+ truncation, system, archived = fit(tools = [SEARCH])
+ assert not truncation.get("checkpoint") and "carried_forward" not in system
+ assert archived["style"] == "inline"
+
+ truncation, system, archived = fit(tool_loop = True, tools = [WEB])
+ assert truncation["checkpoint_started"] is True and "carried_forward" in system
+ assert "search_conversation tool" not in system
+ assert archived["style"] == "inline"
+
+ truncation, system, archived = fit(tool_loop = True, tools = [WEB, SEARCH])
+ assert "search_conversation tool" in system
+ assert archived["style"] == "tool"
+ halved = retrieval_budget(1200, 200, truncation["prompt_tokens_after"], reply_returns = True)
+ assert archived["recall_budget_tokens"] == halved
+ assert halved < retrieval_budget(1200, 200, truncation["prompt_tokens_after"])
+
+ # The loop's final answer carries no tools: no reset, and its reply never comes back,
+ # so recall gets all the room the fit left.
+ turns = [{"role": "user", "content": "x" * size} for size in (3200, 800, 8)]
+ truncation, _, archived = fit(messages = turns, tool_loop = True)
+ after = truncation["prompt_tokens_after"]
+ whole = retrieval_budget(1200, 200, after)
+ assert not truncation.get("checkpoint") and archived["recall_budget_tokens"] == whole
+ assert whole > retrieval_budget(1200, 200, after, reply_returns = True)
+
+
+QUESTION = {"role": "user", "content": "What changed in release 4?"}
+ANSWERED = {"role": "assistant", "content": "OK."}
+CALL = '<tool_call>{"name":"web_search","arguments":{"query":"release %d"}}</tool_call>'
+
+
+def _run_loop(monkeypatch, messages, replies, result_chars, **kwargs):
+ backend, turns, prompts, branches = _backend(), iter(replies), [], []
+
+ def _generate(**call):
+ prompts.append(list(call["messages"]))
+ yield next(turns)
+
+ def _execute(*_args, conversation_branch, **_kwargs):
+ branches.append(list(conversation_branch))
+ return f"result {len(branches)} " + "r" * result_chars
+
+ monkeypatch.setattr(backend, "generate_chat_response", _generate)
+ monkeypatch.setattr(tools_mod, "execute_tool", _execute)
+ events = backend.generate_chat_completion_with_tools(
+ messages = messages,
+ tools = [WEB],
+ max_tokens = 200,
+ nudge_tool_calls = True,
+ thread_id = "thread-1",
+ context_overflow = "truncate_oldest",
+ **kwargs,
+ )
+ truncated = [event for event in events if event.get("type") == "context_truncated"]
+ return truncated, prompts, branches
+
+
[email protected]("policy", ["checkpoint", "rolling"])
+# The client's history holds a tool result the first fit has to evict, or none: then its
+# small first turn is still there when the loop's own results start to crowd the window.
[email protected]("old_result_chars, fits", [(3900, 3), (0, 2)])
+def test_the_tool_loop_refits_every_turn_and_keeps_the_question_past_a_reprompt(
+ monkeypatch, archive_calls, policy, old_result_chars, fits
+):
+ old = {"role": "user", "content": "o" * 400}
+ old_exchange = [
+ {"role": "assistant", "content": "", "tool_calls": [{"id": "0"}]},
+ {"role": "tool", "content": "h" * old_result_chars},
+ ]
+ truncated, prompts, branches = _run_loop(
+ monkeypatch,
+ [old, *(old_exchange if old_result_chars else []), ANSWERED, QUESTION],
+ # An announced search is re-prompted with a user turn of the loop's own, as the cap is.
+ ["Let me search the web for that.", CALL % 1, CALL % 2, CALL % 3, "done"],
+ 2400,
+ # Two results fill the window; after the third the loop appends its budget notice.
+ max_tool_iterations = 3,
+ context_policy = policy,
+ )
+
+ final = prompts[-1]
+ assert final[-1]["role"] == "user" and final[-1] is not QUESTION
+ assert any(m is QUESTION for m in final) and not any(m is old for m in final)
+ # The newest result stays: the final answer is asked for without tools, so that fit never
+ # resets it away, and the re-prompt before it is not evicted with it in tow.
+ assert [m["content"][:8] for m in final if m.get("role") == "tool"] == ["result 3"]
+ # The third call can still search the first result, which a fit had already evicted,
+ # and the last fit archives against all three.
+ assert sum(m["content"].startswith("result") for m in branches[2] if m["role"] == "tool") == 2
+ last_fit = archive_calls[-1]
+ ran = [m for m in last_fit["branch_messages"] if m["role"] == "tool"][-3:]
+ assert [m["content"][:8] for m in ran] == ["result 1", "result 2", "result 3"]
+ # Recall searches for the branch's last user turn: the question, not the loop's notice.
+ assert [m for m in last_fit["branch_messages"] if m["role"] == "user"] == [old, QUESTION]
+ assert len(truncated) == fits and all(event["fits"] for event in truncated)
+ # The loop is the one MLX request that may reset, and it archives under its thread.
+ assert bool(truncated[0].get("checkpoint_started")) is (policy == "checkpoint")
+ assert last_fit["thread_id"] == "thread-1"
+
+
+# The cap's budget notice; then the no-op notice a repeated call earns, once, twice, and
+# twice with the model's own words in between.
+ "replies, chars, fits, dropped",
+ [
+ ([CALL % 1], 3900, False, 0),
+ ([CALL % 1] * 2, 3900, False, 0),
+ ([CALL % 1] * 3, 3550, True, 1),
+ ([CALL % 1] * 2 + ["I'll check that again. " + CALL % 1], 3550, True, 2),
+ ],
+)
+def test_the_only_tool_result_is_not_evicted_to_make_room_for_what_the_loop_says_next(
+ monkeypatch, archive_calls, replies, chars, fits, dropped
+):
+ [truncation], prompts, _ = _run_loop(
+ monkeypatch,
+ [QUESTION],
+ [*replies, "done"],
+ chars,
+ max_tool_iterations = 5 if len(replies) > 1 else 1,
+ )
+
+ # Dropping the result would fit, and leave nothing to answer from. Only what followed
+ # it may go; failing that, the prompt goes out over.
+ assert truncation["fits"] is fits and truncation["dropped_messages"] == dropped
+ assert [m["role"] for m in prompts[-1]].count("tool") == 1
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 0f542481aab..93e27116330 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -5353,6 +5353,10 @@ export function createOpenAIStreamAdapter(
activeNativePathToken: runtime.activeNativePathToken,
checkpoint: params.checkpoint,
});
+ // The backend's own report, for the same reason. An external id leaves it describing
+ // the local model still resident.
+ const isMlxForCompaction =
+ !isExternalModelId(params.checkpoint) && runtime.loadedIsMlx === true;
const generationUserMessage = [...survivingMessages]
.reverse()
.find((message) => message.role === "user");
@@ -6585,6 +6589,7 @@ export function createOpenAIStreamAdapter(
stream_options: { include_usage: true },
...ggufCompactionRequestFields({
isGguf: isGgufForCompaction,
+ isMlx: isMlxForCompaction,
autoCompactEnabled: runtime.autoCompactEnabled,
}),
temperature: params.temperature,
diff --git a/studio/frontend/src/features/chat/utils/auto-compaction.ts b/studio/frontend/src/features/chat/utils/auto-compaction.ts
index ffa519c9903..327bcf50c28 100644
--- a/studio/frontend/src/features/chat/utils/auto-compaction.ts
+++ b/studio/frontend/src/features/chat/utils/auto-compaction.ts
@@ -1,7 +1,7 @@
// 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. On or off; how it compacts is the server's call.
+/** Local GGUF and MLX auto-compaction. On or off; how it compacts is the server's call.
*
* Studio used to offer the policy as a setting, but the choice needed the reader to know what a
* checkpoint epoch and a rolling window were before it meant anything, and both sides of it were
@@ -12,11 +12,12 @@ export const DEFAULT_AUTO_COMPACT_ENABLED = true;
export function ggufCompactionRequestFields(options: {
isGguf: boolean;
+ isMlx?: boolean;
autoCompactEnabled: boolean;
}): {
context_overflow?: "error" | "truncate_oldest";
} {
- if (!options.isGguf) return {};
+ if (!options.isGguf && !options.isMlx) 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.
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index d98cf87abd1..3d3501d44cf 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -2234,7 +2234,7 @@ export const ar = {
rememberParamsPerModelHint:
"عند إيقافه، تستخدم جميع النماذج الإعدادات نفسها.",
autoCompactHint:
- "لمحادثات GGUF المحلية فقط. تُفهرس الأدوار التي تخرج من السياق ليتمكن النموذج من البحث عنها لاحقًا، ومع إعادة التعيين يُقتبس ما يتّسع من تعليماتك الدائمة بنصه الحرفي، مع تفضيل الأقدم والأحدث على ما بينهما. تتطلب الأرشفة محادثة محفوظة وفهرسًا متجهيًا؛ وبدونهما تُحذف الأدوار الأقدم. يعتمد على طول السياق الذي حددته، لا على ذاكرة VRAM المتاحة.",
+ "لمحادثات GGUF و MLX المحلية فقط. تُفهرس الأدوار التي تخرج من السياق ليتمكن النموذج من البحث عنها لاحقًا، ومع إعادة التعيين يُقتبس ما يتّسع من تعليماتك الدائمة بنصه الحرفي، مع تفضيل الأقدم والأحدث على ما بينهما. تتطلب الأرشفة محادثة محفوظة وفهرسًا متجهيًا؛ وبدونهما تُحذف الأدوار الأقدم. يعتمد على طول السياق الذي حددته، لا على ذاكرة VRAM المتاحة.",
pastedTextShortDescription:
"يصبح النص الملصق الذي يبلغ {count} حرفًا أو أكثر مرفقًا بصيغة .txt. يبقى النص الأقصر في مربع الرسالة.",
pastedTextOffDescription:
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index bd2a135df49..62bb8ca257c 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -2272,7 +2272,7 @@ export const de = {
rememberParamsPerModelHint:
"Wenn deaktiviert, verwenden alle Modelle dieselben Einstellungen.",
autoCompactHint:
- "Nur lokale GGUF-Chats. Verdrängte Runden werden indexiert, sodass das Modell sie zurückholen kann, und ein Reset zitiert die dauerhaft geltenden Anweisungen, die hineinpassen, wortgetreu und mit Vorrang für die ältesten und neuesten vor allem dazwischen. Archivieren setzt einen gespeicherten Chat und den Vektorindex voraus; ohne sie werden ältere Runden verworfen. Verwendet die eingestellte Kontextlänge, nicht den verfügbaren VRAM.",
+ "Nur lokale GGUF- und MLX-Chats. Verdrängte Runden werden indexiert, sodass das Modell sie zurückholen kann, und ein Reset zitiert die dauerhaft geltenden Anweisungen, die hineinpassen, wortgetreu und mit Vorrang für die ältesten und neuesten vor allem dazwischen. Archivieren setzt einen gespeicherten Chat und den Vektorindex voraus; ohne sie werden ältere Runden verworfen. Verwendet die eingestellte Kontextlänge, nicht den verfügbaren VRAM.",
pastedTextShortDescription:
"Eingefügter Text ab {count} Zeichen wird als .txt-Datei angehängt. Kürzerer Text bleibt im Nachrichtenfeld.",
pastedTextOffDescription:
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index aef31414a05..75ef8392b2a 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -2273,7 +2273,7 @@ export const en = {
"Override this setting from each chat's attachment menu.",
rememberParamsPerModelHint:
"When off, use the same settings for every model.",
- autoCompactHint: "Local GGUF chats only. Evicted turns are indexed so the model can search them back in, and a reset quotes back the standing instructions that fit, word for word, keeping the oldest and newest over the middle. Archiving needs a saved chat and the vector index; without them older turns are dropped. Uses the context length you set, not available VRAM.",
+ autoCompactHint: "Local GGUF and MLX chats only. Evicted turns are indexed so the model can search them back in, and a reset quotes back the standing instructions that fit, word for word, keeping the oldest and newest over the middle. Archiving needs a saved chat and the vector index; without them older turns are dropped. Uses the context length you set, not available VRAM.",
pastedTextShortDescription:
"Pastes of {count} characters or more become .txt attachments.",
pastedTextOffDescription: "Pasted text always stays in the message box.",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index c9d9a05d29f..b1fcd4165f6 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -2263,7 +2263,7 @@ export const es = {
rememberParamsPerModelHint:
"Al desactivarlo, todos los modelos usan los mismos ajustes.",
autoCompactHint:
- "Solo chats GGUF locales. Los turnos expulsados se indexan para que el modelo pueda recuperarlos, y un reinicio cita palabra por palabra las instrucciones permanentes que quepan, dando prioridad a las más antiguas y a las más recientes frente a las intermedias. Archivar requiere un chat guardado y el índice vectorial; sin ellos, los turnos antiguos se descartan. Usa la longitud de contexto configurada, no la VRAM disponible.",
+ "Solo chats GGUF y MLX locales. Los turnos expulsados se indexan para que el modelo pueda recuperarlos, y un reinicio cita palabra por palabra las instrucciones permanentes que quepan, dando prioridad a las más antiguas y a las más recientes frente a las intermedias. Archivar requiere un chat guardado y el índice vectorial; sin ellos, los turnos antiguos se descartan. Usa la longitud de contexto configurada, no la VRAM disponible.",
pastedTextShortDescription:
"El texto pegado de {count} caracteres o más se convierte en un adjunto .txt. El texto más corto queda en el cuadro de mensaje.",
pastedTextOffDescription:
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 169ae8bbccf..06ca0aee3bc 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -2269,7 +2269,7 @@ export const fr = {
rememberParamsPerModelHint:
"Lorsque cette option est désactivée, tous les modèles utilisent les mêmes réglages.",
autoCompactHint:
- "Uniquement les chats GGUF locaux. Les échanges évincés sont indexés pour que le modèle puisse les retrouver, et une réinitialisation cite mot pour mot les instructions permanentes qui tiennent, en gardant les plus anciennes et les plus récentes plutôt que celles du milieu. L’archivage nécessite un chat enregistré et l’index vectoriel ; sans eux, les anciens échanges sont supprimés. Utilise la longueur de contexte définie, pas la VRAM disponible.",
+ "Uniquement les chats GGUF et MLX locaux. Les échanges évincés sont indexés pour que le modèle puisse les retrouver, et une réinitialisation cite mot pour mot les instructions permanentes qui tiennent, en gardant les plus anciennes et les plus récentes plutôt que celles du milieu. L’archivage nécessite un chat enregistré et l’index vectoriel ; sans eux, les anciens échanges sont supprimés. Utilise la longueur de contexte définie, pas la VRAM disponible.",
pastedTextShortDescription:
"Le texte collé de {count} caractères ou plus devient une pièce jointe .txt. Le texte plus court reste dans le champ de message.",
pastedTextOffDescription:
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index d7c50d55504..33e8985d405 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -2240,7 +2240,7 @@ export const hi = {
rememberParamsPerModelHint:
"बंद होने पर सभी मॉडल एक ही सेटिंग इस्तेमाल करते हैं।",
autoCompactHint:
- "केवल लोकल GGUF चैट पर लागू। हटाए गए टर्न इंडेक्स किए जाते हैं ताकि मॉडल उन्हें दोबारा खोज सके, और रीसेट पर जितने स्थायी निर्देश समा सकें, वे हूबहू दोहरा दिए जाते हैं, जिनमें बीच वाले के बजाय सबसे पुराने और सबसे नए को प्राथमिकता मिलती है। आर्काइव के लिए सहेजी गई चैट और वेक्टर इंडेक्स ज़रूरी हैं; इनके बिना पुराने टर्न हटा दिए जाते हैं। उपलब्ध VRAM के बजाय आपके तय किए गए संदर्भ की लंबाई का उपयोग करता है।",
+ "केवल लोकल GGUF और MLX चैट पर लागू। हटाए गए टर्न इंडेक्स किए जाते हैं ताकि मॉडल उन्हें दोबारा खोज सके, और रीसेट पर जितने स्थायी निर्देश समा सकें, वे हूबहू दोहरा दिए जाते हैं, जिनमें बीच वाले के बजाय सबसे पुराने और सबसे नए को प्राथमिकता मिलती है। आर्काइव के लिए सहेजी गई चैट और वेक्टर इंडेक्स ज़रूरी हैं; इनके बिना पुराने टर्न हटा दिए जाते हैं। उपलब्ध VRAM के बजाय आपके तय किए गए संदर्भ की लंबाई का उपयोग करता है।",
pastedTextShortDescription:
"{count} या अधिक अक्षरों वाला पेस्ट किया गया टेक्स्ट .txt अटैचमेंट बन जाता है। छोटा टेक्स्ट संदेश बॉक्स में रहता है।",
pastedTextOffDescription:
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index e8097d41434..61d5239d666 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -2228,7 +2228,7 @@ export const it = {
rememberParamsPerModelHint:
"Quando è disattivata, tutti i modelli usano le stesse impostazioni.",
autoCompactHint:
- "Solo chat GGUF locali. I turni rimossi vengono indicizzati perché il modello possa recuperarli, e un ripristino cita parola per parola le istruzioni permanenti che rientrano, privilegiando le più vecchie e le più recenti rispetto a quelle intermedie. L’archiviazione richiede una chat salvata e l’indice vettoriale; senza di essi i turni più vecchi vengono eliminati. Usa la lunghezza del contesto impostata, non la VRAM disponibile.",
+ "Solo chat GGUF e MLX locali. I turni rimossi vengono indicizzati perché il modello possa recuperarli, e un ripristino cita parola per parola le istruzioni permanenti che rientrano, privilegiando le più vecchie e le più recenti rispetto a quelle intermedie. L’archiviazione richiede una chat salvata e l’indice vettoriale; senza di essi i turni più vecchi vengono eliminati. Usa la lunghezza del contesto impostata, non la VRAM disponibile.",
pastedTextShortDescription:
"Il testo incollato di almeno {count} caratteri diventa un allegato .txt. Il testo più breve resta nel campo del messaggio.",
pastedTextOffDescription:
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 37ae5a65b48..3e61b32004a 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -2219,7 +2219,7 @@ export const ja = {
projectAttachmentsHint: "各チャットの添付メニューで個別に変更できます。",
rememberParamsPerModelHint:
"オフの場合、すべてのモデルで同じ設定を使います。",
- autoCompactHint: "ローカルの GGUF チャットのみ。文脈から外れたターンは索引化され、モデルが検索して取り出せます。リセットでは、収まる範囲の継続的な指示がそのままの文言で引き継がれ、途中のものより最も古いものと最も新しいものが優先されます。アーカイブには保存済みのチャットとベクトル索引が必要で、それらがない場合、古いターンは破棄されます。空きVRAMではなく、設定したコンテキスト長を基準にします。",
+ autoCompactHint: "ローカルの GGUF と MLX チャットのみ。文脈から外れたターンは索引化され、モデルが検索して取り出せます。リセットでは、収まる範囲の継続的な指示がそのままの文言で引き継がれ、途中のものより最も古いものと最も新しいものが優先されます。アーカイブには保存済みのチャットとベクトル索引が必要で、それらがない場合、古いターンは破棄されます。空きVRAMではなく、設定したコンテキスト長を基準にします。",
pastedTextShortDescription:
"{count}文字以上の貼り付けテキストは .txt 添付ファイルになります。短いテキストは入力欄に残ります。",
pastedTextOffDescription:
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 35b4a277263..d8ede752dbe 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -2229,7 +2229,7 @@ export const ko = {
projectAttachmentsHint:
"각 채팅의 첨부 메뉴에서 이 설정을 개별적으로 변경할 수 있습니다.",
rememberParamsPerModelHint: "끄면 모든 모델에 같은 설정을 사용합니다.",
- autoCompactHint: "로컬 GGUF 채팅에만 적용됩니다. 밀려난 턴은 색인되어 모델이 다시 검색할 수 있고, 초기화 시에는 들어갈 수 있는 만큼의 계속 적용되는 지침이 원문 그대로 이어지며, 중간 것보다 가장 오래된 것과 가장 최근 것이 우선됩니다. 보관하려면 저장된 채팅과 벡터 색인이 필요하며, 없으면 오래된 턴은 그냥 삭제됩니다. 남은 VRAM이 아닌 설정한 컨텍스트 길이를 기준으로 합니다.",
+ autoCompactHint: "로컬 GGUF 및 MLX 채팅에만 적용됩니다. 밀려난 턴은 색인되어 모델이 다시 검색할 수 있고, 초기화 시에는 들어갈 수 있는 만큼의 계속 적용되는 지침이 원문 그대로 이어지며, 중간 것보다 가장 오래된 것과 가장 최근 것이 우선됩니다. 보관하려면 저장된 채팅과 벡터 색인이 필요하며, 없으면 오래된 턴은 그냥 삭제됩니다. 남은 VRAM이 아닌 설정한 컨텍스트 길이를 기준으로 합니다.",
pastedTextShortDescription:
"붙여넣은 텍스트가 {count}자 이상이면 .txt 첨부 파일이 됩니다. 더 짧은 텍스트는 입력창에 남습니다.",
pastedTextOffDescription:
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 1e01e53670e..5e72412b58b 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -2250,7 +2250,7 @@ export const ptBR = {
"Altere esta configuração para cada chat pelo menu de anexos.",
rememberParamsPerModelHint:
"Quando desativado, todos os modelos usam as mesmas configurações.",
- autoCompactHint: "Apenas chats GGUF locais. Os turnos removidos são indexados para que o modelo possa buscá-los de volta, e uma reinicialização cita palavra por palavra as instruções permanentes que couberem, priorizando as mais antigas e as mais recentes em vez das intermediárias. Arquivar exige um chat salvo e o índice vetorial; sem eles, os turnos antigos são descartados. Usa o tamanho de contexto definido, não a VRAM disponível.",
+ autoCompactHint: "Apenas chats GGUF e MLX locais. Os turnos removidos são indexados para que o modelo possa buscá-los de volta, e uma reinicialização cita palavra por palavra as instruções permanentes que couberem, priorizando as mais antigas e as mais recentes em vez das intermediárias. Arquivar exige um chat salvo e o índice vetorial; sem eles, os turnos antigos são descartados. Usa o tamanho de contexto definido, não a VRAM disponível.",
pastedTextShortDescription:
"Texto colado com {count} caracteres ou mais vira um anexo .txt. Textos menores ficam na caixa de mensagem.",
pastedTextOffDescription:
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 686ecd37cda..197d2e4fac7 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -2246,7 +2246,7 @@ export const ru = {
"Для отдельного чата настройку можно изменить в его меню вложений.",
rememberParamsPerModelHint:
"Если выключено, для всех моделей используются одинаковые настройки.",
- autoCompactHint: "Только локальные чаты GGUF. Вытесненные ходы индексируются, чтобы модель могла найти их снова, а сброс дословно приводит те постоянные инструкции, которые помещаются, отдавая предпочтение самым старым и самым новым, а не промежуточным. Для архивации нужны сохранённый чат и векторный индекс; без них старые ходы просто удаляются. Учитывает заданную длину контекста, а не доступную VRAM.",
+ autoCompactHint: "Только локальные чаты GGUF и MLX. Вытесненные ходы индексируются, чтобы модель могла найти их снова, а сброс дословно приводит те постоянные инструкции, которые помещаются, отдавая предпочтение самым старым и самым новым, а не промежуточным. Для архивации нужны сохранённый чат и векторный индекс; без них старые ходы просто удаляются. Учитывает заданную длину контекста, а не доступную VRAM.",
pastedTextShortDescription:
"Вставленный текст длиной от {count} символов становится вложением .txt. Более короткий текст остаётся в поле сообщения.",
pastedTextOffDescription:
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 00aa776185a..442e4a14718 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -2195,7 +2195,7 @@ export const zhCN = {
},
projectAttachmentsHint: "可在各聊天的附件菜单中单独调整此设置。",
rememberParamsPerModelHint: "关闭后,所有模型使用同一套设置。",
- autoCompactHint: "仅适用于本地 GGUF 聊天。被移出的轮次会建立索引,模型可以再检索回来;重置时会原文保留放得下的长期指令,优先保留最早和最新的,而不是中间的。归档需要已保存的聊天和向量索引,两者缺一时较早的轮次会被直接丢弃。依据你设置的上下文长度,而不是可用显存。",
+ autoCompactHint: "仅适用于本地 GGUF 和 MLX 聊天。被移出的轮次会建立索引,模型可以再检索回来;重置时会原文保留放得下的长期指令,优先保留最早和最新的,而不是中间的。归档需要已保存的聊天和向量索引,两者缺一时较早的轮次会被直接丢弃。依据你设置的上下文长度,而不是可用显存。",
pastedTextShortDescription:
"粘贴的文本达到 {count} 个字符时会转为 .txt 附件,较短的文本则保留在消息输入框中。",
pastedTextOffDescription:
diff --git a/studio/frontend/tests/auto-compaction-settings.test.ts b/studio/frontend/tests/auto-compaction-settings.test.ts
index 33169cc0877..b016b9469a2 100644
--- a/studio/frontend/tests/auto-compaction-settings.test.ts
+++ b/studio/frontend/tests/auto-compaction-settings.test.ts
@@ -119,3 +119,21 @@ test("a queued run keeps its own model's llama.cpp verdict after the picker move
{ context_overflow: "truncate_oldest" },
);
});
+
+test("MLX chats opt in on the backend's own report and honor disabling auto compaction", () => {
+ const options = { isGguf: false, isMlx: true, autoCompactEnabled: true };
+ assert.deepEqual(ggufCompactionRequestFields(options), {
+ context_overflow: "truncate_oldest",
+ });
+ assert.deepEqual(
+ ggufCompactionRequestFields({ ...options, autoCompactEnabled: false }),
+ { context_overflow: "error" },
+ );
+ // loadedIsMlx, not a catalog row, as isGguf goes through isServedByLlamaCpp.
+ const adapter = readSrc("features/chat/api/chat-adapter.ts");
+ assert.match(adapter, /isMlx: isMlxForCompaction/);
+ assert.match(
+ adapter,
+ /isMlxForCompaction =\s*!isExternalModelId\(params\.checkpoint\) && runtime\.loadedIsMlx === true/,
+ );
+});