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.

feat(studio): give MLX models a real context length, from the model config to the KV cache (#8125)

Long Yixinga09bb58d371c
diff --git a/.github/workflows/studio-backend-ci.yml b/.github/workflows/studio-backend-ci.yml
index f7ccf9267c7..a7bd72242e1 100644
--- a/.github/workflows/studio-backend-ci.yml
+++ b/.github/workflows/studio-backend-ci.yml
@@ -457,6 +457,7 @@ jobs:
--ignore=tests/studio/test_hardware_dispatch_matrix.py \
--ignore=tests/studio/test_is_mlx_dispatch_gate.py \
--ignore=tests/studio/test_xpu_spoof_pipeline.py \
+ --ignore=tests/studio/test_mlx_context_platform_matrix.py \
--ignore=tests/vllm_compat \
--ignore=tests/version_compat \
-m 'not server and not e2e' \
@@ -477,7 +478,8 @@ jobs:
python -m pytest -q --tb=short \
tests/studio/test_hardware_dispatch_matrix.py \
tests/studio/test_is_mlx_dispatch_gate.py \
- tests/studio/test_xpu_spoof_pipeline.py
+ tests/studio/test_xpu_spoof_pipeline.py \
+ tests/studio/test_mlx_context_platform_matrix.py
- name: Event-loop latency tests (wall clock, run without CPU contention)
env:
diff --git a/studio/backend/core/inference/mlx_inference.py b/studio/backend/core/inference/mlx_inference.py
index 2d45532dda3..76bae9bbb46 100644
--- a/studio/backend/core/inference/mlx_inference.py
+++ b/studio/backend/core/inference/mlx_inference.py
@@ -7,11 +7,15 @@ instead of torch/transformers for model loading and generation.
import json
import os
+import re
import threading
from contextlib import contextmanager
from typing import Optional, Generator
from core.inference.message_content import content_to_text
-from core.inference.runtime_context import runtime_context_length
+from core.inference.runtime_context import (
+ MAX_REQUESTABLE_CONTEXT,
+ runtime_context_length,
+)
from core.inference.chat_template_helpers import (
detect_reasoning_channel_markers,
make_reasoning_normalizer,
@@ -104,6 +108,77 @@ def _mlx_vlm_model_config(model):
return (configs[0] if configs else None), None
+# Matched on the context-bearing term, not a field list: mlx-lm alone spells it four ways.
+# max_length is a generation default and n_sequences a batch count, so neither qualifies.
+_MLX_CONTEXT_KEY = re.compile(
+ r"(?:position(?:s|_embeddings)|(?:^|_)ctx|context_len(?:gth)?"
+ r"|seq(?:uence)?_len(?:gth)?|model_max_length)$"
+)
+# A vision tower's token count reads like a length but bounds one image, not the window.
+_MLX_CONTEXT_KEY_EXCLUDE = re.compile(r"(?:^|_)image_")
+# Below one cache block is not a window; above, configs carry sentinel "unlimited" lengths.
+_MLX_MIN_PLAUSIBLE_CONTEXT = 256
+_MLX_MAX_PLAUSIBLE_CONTEXT = 1 << 24
+
+
+def _mlx_config_candidates(model):
+ """Config-ish objects that may carry text-tower dims, most specific first."""
+ language_model = getattr(model, "language_model", None)
+ config, _ = _mlx_vlm_model_config(model)
+ text_config = None
+ if config is not None:
+ text_config = (
+ config.get("text_config")
+ if isinstance(config, dict)
+ else getattr(config, "text_config", None)
+ )
+ return [
+ cfg
+ for cfg in (
+ getattr(language_model, "args", None),
+ text_config,
+ getattr(model, "args", None),
+ config,
+ )
+ if cfg is not None
+ ]
+
+
+def _positive_int(value):
+ if isinstance(value, bool):
+ return None
+ try:
+ value_int = int(value)
+ except (TypeError, ValueError, OverflowError):
+ # json.loads accepts Infinity: unusable, but must not abort the load.
+ return None
+ return value_int if value_int > 0 else None
+
+
+def mlx_native_context_length(model):
+ """The window the model was trained for, or None when it isn't readable.
+
+ The widest plausible length across every config wins, so a stub text config the
+ blocks were never built from cannot shorten the window the weights support --
+ mlx-vlm's Phi-3-V carries a 4096 text config beside the 131072 its attention uses.
+ """
+ lengths = []
+ for cfg in _mlx_config_candidates(model):
+ try:
+ items = cfg.items() if isinstance(cfg, dict) else vars(cfg).items()
+ except TypeError:
+ continue
+ lengths += [
+ length
+ for name, value in items
+ if _MLX_CONTEXT_KEY.search(str(name))
+ and not _MLX_CONTEXT_KEY_EXCLUDE.search(str(name))
+ and (length := _positive_int(value)) is not None
+ and _MLX_MIN_PLAUSIBLE_CONTEXT <= length <= _MLX_MAX_PLAUSIBLE_CONTEXT
+ ]
+ return max(lengths) if lengths else None
+
+
def _ascii_registry_key(value):
"""An mlx-vlm registry key lowered within ASCII, else None. Not `casefold`:
it folds non-ASCII onto ASCII, so "ſmolvlm" would reach `smolvlm`."""
@@ -483,6 +558,12 @@ MLX_KV_QUANT_NO_REUSE = (
MLX_KV_QUANT_VLM_CACHE_NOTE = (
"On vision models, quantization starts once the cache reaches {start} tokens."
)
+# RotatingKVCache.to_quantized raises and mlx-lm converts from the first token, so the
+# two are resolved here rather than failing generation on its first step.
+MLX_KV_QUANT_PINNED_CONTEXT = (
+ "Context Length is set for this model, which limits the KV cache, and the installed "
+ "mlx-lm cannot quantize a limited cache. Reset it to quantize instead."
+)
def _kv_entry_nbytes(entry):
@@ -952,7 +1033,50 @@ def _install_template_override(override, tokenizer, processor, probe):
return status
-def _kv_quant_status(requested_bits, model, is_vlm):
+def _kv_entry_is_bounded(entry, window):
+ """Whether this cache entry declares a cap that holds it at or below *window*.
+
+ Only a declared cap counts, and only up to the requested size. mlx-vlm's Florence2
+ hands back a class that concatenates forever and declares nothing; a model that
+ declares a cap wider than the request is bounded, but not at what was asked for.
+ """
+ cap = getattr(entry, "max_size", None) or getattr(entry, "chunk_size", None)
+ if not cap or cap > window:
+ return False
+ # Retaining as much as it holds means it never rotates: the write index resets past
+ # the buffer end and updates stop landing.
+ return cap > getattr(entry, "keep", 0)
+
+
+def _kv_window_enforced(model, is_vlm, window):
+ """Whether a cache built for this model at *window* is bounded in every layer.
+
+ Both runtimes defer to a model's own make_cache when it has one and ignore
+ max_kv_size there. Returns None when no cache could be built to judge.
+ """
+ language_model = getattr(model, "language_model", model) if is_vlm else model
+ try:
+ if is_vlm:
+ from mlx_vlm.models import cache as vlm_cache
+ entries = vlm_cache.make_prompt_cache(language_model, max_kv_size = window)
+ else:
+ from mlx_lm.models import cache as lm_cache
+ entries = lm_cache.make_prompt_cache(language_model, max_kv_size = window)
+ # Inside the guard with the build: an unjudgeable shape must read as unknown,
+ # since load_model calls this unguarded and a raise would fail the load.
+ flattened = list(_flatten_kv_entries(entries))
+ return bool(flattened) and all(_kv_entry_is_bounded(entry, window) for entry in flattened)
+ except Exception as exc:
+ logger.debug("MLX context limit probe failed: %s", exc)
+ return None
+
+
+def _kv_quant_status(
+ requested_bits,
+ model,
+ is_vlm,
+ context_pinned = False,
+):
"""Resolve a requested bit width against this model into a status dict."""
status = {
"requested_kv_bits": requested_bits,
@@ -963,6 +1087,11 @@ def _kv_quant_status(requested_bits, model, is_vlm):
}
if requested_bits is None:
return status
+ if context_pinned:
+ status["eligibility"] = "refused"
+ status["reason"] = MLX_KV_QUANT_PINNED_CONTEXT
+ logger.info("MLX KV quantization not applied: %s", MLX_KV_QUANT_PINNED_CONTEXT)
+ return status
verdict, reason, retainable = _kv_quant_eligibility(model, is_vlm, requested_bits)
status["eligibility"] = verdict
status["reason"] = reason
@@ -1045,11 +1174,17 @@ def _kv_prefix_coverage(cache):
class _MLXPromptCacheHistory:
- def __init__(self, max_entries, max_bytes):
+ def __init__(
+ self,
+ max_entries,
+ max_bytes,
+ max_kv_size = None,
+ ):
api = _mlx_prompt_cache_api()
if api is None:
raise RuntimeError("mlx-lm is too old for LRUPromptCache")
lru_cls, make, can_trim, trim = api
+ self._max_kv_size = max_kv_size
self._make_prompt_cache = make
self._can_trim = can_trim
self._trim = trim
@@ -1069,7 +1204,9 @@ class _MLXPromptCacheHistory:
if cache is not None:
covered = len(head) - len(rest)
return cache, list(tokens[covered:])
- return self._make_prompt_cache(model), list(tokens)
+ if self._max_kv_size is None:
+ return self._make_prompt_cache(model), list(tokens)
+ return self._make_prompt_cache(model, max_kv_size = self._max_kv_size), list(tokens)
def insert(self, key, tokens, cache):
# An over-budget entry evicts itself and every other conversation.
@@ -1326,6 +1463,13 @@ def _mlx_sampling_processors(
return processors or None
+# Families that mlx_vlm inlined before should_add_special_tokens existed: their template
+# already emits the markers, so tokenization must not add them again. Deliberately not the
+# current helper's list, which carries laguna -- only 0.6.9 stopped tokenizing laguna with
+# the markers, and 0.6.0-0.6.8 are what this stands in for.
+_VLM_INLINE_SPECIAL_TOKEN_FAMILIES = ("gemma3", "gemma3n", "gemma4", "gemma4_unified")
+
+
class MLXInferenceBackend:
def __init__(self):
self.models = {}
@@ -1354,6 +1498,7 @@ class MLXInferenceBackend:
# than from per-request kwargs. Bound now so a load that fails before
# installing leaves readers a dict rather than raising.
self._kv_quant = _kv_quant_status(None, None, False)
+ self._kv_cache_window = None
self._template_override = _template_override_status(None, None, None)[1]
self._prompt_cache_history = None
@@ -1371,6 +1516,7 @@ class MLXInferenceBackend:
self._prompt_cache_history = _MLXPromptCacheHistory(
PROMPT_CACHE_ENTRIES,
max_bytes,
+ self._kv_cache_window,
)
except Exception as exc:
self._prompt_cache_unavailable = True
@@ -1392,10 +1538,7 @@ class MLXInferenceBackend:
if history is None:
return prompt, None, None, None, 0
try:
- tokenizer = self._tokenizer
- bos = getattr(tokenizer, "bos_token", None)
- add_special_tokens = bos is None or not prompt.startswith(bos)
- tokens = list(tokenizer.encode(prompt, add_special_tokens = add_special_tokens))
+ tokens = self._encode_prompt(prompt)
if not tokens:
return prompt, None, None, None, 0
key = f"{self.active_model_name}|{adapter_state!r}"
@@ -1414,6 +1557,28 @@ class MLXInferenceBackend:
kv_bits = (getattr(self, "_kv_quant", None) or {}).get("kv_bits")
return {} if kv_bits is None else {"kv_bits": kv_bits}
+ def _kv_window_generate_kwargs(self):
+ """The cache bound for a generation that builds its own cache, empty when unset.
+
+ Both runtimes read it only when no prompt_cache is passed, so this covers the
+ request that reaches generation without one rather than duplicating the bound.
+ """
+ window = getattr(self, "_kv_cache_window", None)
+ return {} if window is None else {"max_kv_size": window}
+
+ def _encode_prompt(self, prompt):
+ """The tokens a generation sends for this prompt.
+
+ A template that already emitted the BOS would otherwise get a second one, shifting
+ every cached-prefix comparison and overstating a counted prompt by one.
+ """
+ bos = getattr(self._tokenizer, "bos_token", None)
+ return list(
+ self._tokenizer.encode(
+ prompt, add_special_tokens = bos is None or not prompt.startswith(bos)
+ )
+ )
+
def _configure_memory_limits(self):
"""Apply Metal memory caps before loading a model.
@@ -1445,6 +1610,79 @@ class MLXInferenceBackend:
wired_limit_gb,
)
+ def _resolve_context_lengths(self, model, max_seq_length):
+ """Resolve (served, native, ceiling) for a freshly loaded model.
+
+ Mirrors the GGUF resolution order: whatever the load attached or was asked for is
+ honored verbatim, while asking for nothing takes the trained window. The served
+ length is what bounds the KV cache, where the architecture allows it.
+
+ The served value is held to the same ceiling a request is (LoadRequest bounds
+ max_seq_length at MAX_REQUESTABLE_CONTEXT), because it drives the cache and the
+ usage bar's denominator. Llama-4 Scout declares 10,485,760, ten times that: served
+ unclamped would make the bar meaningless and name a length no control can ask for.
+ The native window is reported as read, since it is metadata about the model.
+ """
+ native = mlx_native_context_length(model)
+ served = runtime_context_length(model, max_seq_length) or native
+ if served:
+ served = min(int(served), MAX_REQUESTABLE_CONTEXT)
+ logger.info("MLX context: served=%s native=%s", served, native)
+ return served, native, native
+
+ def _kv_cache_window_enforceable(self, served):
+ """Whether a cache built for this model would really cap at *served*.
+
+ A probe that could not run counts as not enforceable: claiming a bound nobody
+ confirmed is what makes the setting look like it works.
+ """
+ if not served or served <= 0:
+ return False
+ enforced = _kv_window_enforced(self._model, self._is_vlm, int(served))
+ if enforced is False:
+ logger.warning(
+ "MLX context limit of %d tokens is not enforced: this model builds at "
+ "least one cache layer that declares no limit at that length.",
+ int(served),
+ )
+ elif enforced is None:
+ logger.warning(
+ "MLX context limit of %d tokens is not enforced: no cache could be built "
+ "to confirm it.",
+ int(served),
+ )
+ return enforced
+
+ def _resolve_kv_policy(self, is_vlm, kv_bits, max_seq_length, served):
+ """The quantization status and cache window this load will run with.
+
+ Rotation is what keeps a long conversation inside the window, so nothing here can
+ refuse a request; the model simply stops attending to the oldest tokens.
+
+ Quantization cannot coexist with a bound -- a rotating cache has no conversion,
+ and mlx-lm converts from the first token -- so an enforceable pin, an explicit
+ instruction about memory, outranks it. A window the backend chose for itself
+ yields to an explicitly requested quantization, and so does a pin that cannot be
+ enforced, which would otherwise spend the quantization and bound nothing.
+ """
+ pinned = _positive_int(max_seq_length) is not None
+ # Tri-state: True bounded, False confirmed unbounded, None unjudgeable. Only True
+ # installs a bound; the other two stay apart so a client can tell them apart.
+ confirmed = self._kv_cache_window_enforceable(served)
+ enforceable = confirmed is True
+ quant = _kv_quant_status(
+ _normalize_mlx_kv_bits(kv_bits),
+ self._model,
+ is_vlm,
+ pinned and enforceable,
+ )
+ if not enforceable or (quant["kv_bits"] is not None and not pinned):
+ # No bound installed, so False wherever the probe answered at all; None only
+ # where nothing could be built to judge.
+ return quant, None, None if confirmed is None else False
+ logger.info("MLX KV cache limited to %d tokens", int(served))
+ return quant, int(served), True
+
def load_model(
self,
config,
@@ -1561,10 +1799,15 @@ class MLXInferenceBackend:
is_vision,
config_audio_type = getattr(config, "audio_type", None),
)
+ _served_ctx, _native_ctx, _max_ctx = self._resolve_context_lengths(
+ self._model, max_seq_length
+ )
# Classify before the first generation: an ineligible cache would otherwise
# raise inside maybe_quantize_kv_cache mid-stream, after converting the
# leading entries.
- self._kv_quant = _kv_quant_status(_normalize_mlx_kv_bits(kv_bits), self._model, is_vision)
+ self._kv_quant, self._kv_cache_window, _ctx_enforced = self._resolve_kv_policy(
+ is_vision, kv_bits, max_seq_length, _served_ctx
+ )
if self._kv_quant["kv_bits"] is not None:
logger.info(
"MLX KV cache quantization: %s-bit (%s eligibility)",
@@ -1628,7 +1871,17 @@ class MLXInferenceBackend:
"is_audio": _audio_type is not None and _audio_type != "audio_vlm",
"audio_type": _audio_type,
"has_audio_input": is_audio_input_type(_audio_type),
- "context_length": runtime_context_length(self._model, max_seq_length),
+ "context_length": _served_ctx,
+ # Parity with llama.cpp's requested_n_ctx: the served window cannot say
+ # whether anything was asked for, and that decides reuse and "pinned".
+ "requested_context_length": _positive_int(max_seq_length) or 0,
+ # Nothing measures the machine, so window and ceiling coincide.
+ "native_context_length": _native_ctx,
+ "max_context_length": _max_ctx,
+ # Whether the served window actually bounds the cache: True confirmed on a
+ # real cache, False confirmed unbounded, None nothing could be built to judge.
+ # Without it the API reports a limit a client cannot tell from an enforced one.
+ "context_length_enforced": _ctx_enforced,
"mlx_kv_bits": self._kv_quant["kv_bits"],
"mlx_kv_bits_requested": self._kv_quant["requested_kv_bits"],
"mlx_kv_quant_eligibility": self._kv_quant["eligibility"],
@@ -1748,6 +2001,126 @@ class MLXInferenceBackend:
logger.info("Model %s unloaded", model_name)
return True
+ def _render_text_prompt(
+ self,
+ messages,
+ *,
+ tools = None,
+ enable_thinking = None,
+ reasoning_effort = None,
+ preserve_thinking = None,
+ continue_final_message = False,
+ ):
+ """Render the prompt a text generation sends, with its template metadata.
+
+ Shared with counting, so a count cannot price a prompt the model never sees.
+ """
+ from core.inference.chat_template_helpers import (
+ apply_chat_template_for_generation,
+ render_with_native_template_fallback,
+ )
+
+ prompt = apply_chat_template_for_generation(
+ self._tokenizer,
+ messages,
+ tools = tools,
+ enable_thinking = enable_thinking,
+ reasoning_effort = reasoning_effort,
+ preserve_thinking = preserve_thinking,
+ continue_final_message = continue_final_message,
+ )
+ if prompt is None:
+ raise RuntimeError("apply_chat_template returned None — tokenizer may be incompatible")
+
+ # Parity with the transformers backend: if the template dropped the requested
+ # tools, fall back to the native template so MLX text models keep advertising
+ # them. self._tokenizer is this entry's tokenizer, so probe and native render
+ # share a renderer. (VLM renders via the processor for image tokens.)
+ model_info = self.models.get(self.active_model_name, {})
+ return render_with_native_template_fallback(
+ formatted_prompt = prompt,
+ tokenizer = self._tokenizer,
+ model_info = model_info,
+ active_model_name = self.active_model_name,
+ messages = messages,
+ tools = tools,
+ enable_thinking = enable_thinking,
+ reasoning_effort = reasoning_effort,
+ preserve_thinking = preserve_thinking,
+ continue_final_message = continue_final_message,
+ hf_token = model_info.get("hf_token"),
+ return_metadata = True,
+ )
+
+ @staticmethod
+ def _with_system_prompt(messages, system_prompt):
+ """The conversation a request carrying this system prompt turns into.
+
+ Shared with generation, which takes the system prompt beside the messages rather
+ than inside them.
+ """
+ full_messages = []
+ if system_prompt:
+ full_messages.append({"role": "system", "content": system_prompt})
+ full_messages.extend(messages)
+ return full_messages
+
+ def count_chat_tokens(
+ self,
+ messages,
+ system_prompt = "",
+ *,
+ tools = None,
+ enable_thinking = None,
+ reasoning_effort = None,
+ preserve_thinking = None,
+ ) -> int:
+ """Prompt tokens this model would receive for these messages.
+
+ Renders and tokenizes exactly as generation does.
+ """
+ if self._model is None:
+ raise RuntimeError("No model loaded")
+ full_messages = self._with_system_prompt(messages, system_prompt)
+
+ if self._is_vlm:
+ # Through the processor, which is what a vision generation renders with; the
+ # text renderer would not recover the template failures it recovers from.
+ # images=None: an image anywhere in the conversation makes the structured-item
+ # check raise, and the caller declines rather than pricing a prompt without it.
+ prompt, _ = self._render_vlm_prompt(
+ full_messages,
+ None,
+ tools = tools,
+ enable_thinking = enable_thinking,
+ reasoning_effort = reasoning_effort,
+ preserve_thinking = preserve_thinking,
+ )
+ # Whether the markers belong to the template or to tokenization is a per-model
+ # answer mlx_vlm makes for every generation; ask it rather than guess, or the
+ # count is off by whatever the generation's own choice would have added.
+ _model_type = getattr(getattr(self._model, "config", None), "model_type", None)
+ try:
+ from mlx_vlm.utils import should_add_special_tokens
+ add_special = should_add_special_tokens(_model_type, self._processor)
+ except Exception:
+ # The rule those releases inline, which Studio's runtime gate still accepts.
+ add_special = (
+ getattr(self._processor, "chat_template", None) is None
+ if _model_type in _VLM_INLINE_SPECIAL_TOKEN_FAMILIES
+ else True
+ )
+ return len(self._tokenizer.encode(prompt, add_special_tokens = add_special))
+
+ render_result = self._render_text_prompt(
+ full_messages,
+ tools = tools,
+ enable_thinking = enable_thinking,
+ reasoning_effort = reasoning_effort,
+ preserve_thinking = preserve_thinking,
+ )
+ return len(self._encode_prompt(render_result.prompt))
+
def generate_chat_response(
self,
messages,
@@ -1779,10 +2152,7 @@ class MLXInferenceBackend:
# Reset so a failed run cannot surface stale stats.
self.last_generation_stats = None
- full_messages = []
- if system_prompt:
- full_messages.append({"role": "system", "content": system_prompt})
- full_messages.extend(messages)
+ full_messages = self._with_system_prompt(messages, system_prompt)
# Inject image into the last user message for VLM
if self._is_vlm and image is not None:
@@ -1878,14 +2248,9 @@ class MLXInferenceBackend:
from mlx_lm import stream_generate
from mlx_lm.sample_utils import make_sampler
- from core.inference.chat_template_helpers import (
- apply_chat_template_for_generation,
- detect_think_prefill,
- render_with_native_template_fallback,
- )
+ from core.inference.chat_template_helpers import detect_think_prefill
- prompt = apply_chat_template_for_generation(
- self._tokenizer,
+ render_result = self._render_text_prompt(
messages,
tools = tools,
enable_thinking = enable_thinking,
@@ -1893,29 +2258,6 @@ class MLXInferenceBackend:
preserve_thinking = preserve_thinking,
continue_final_message = continue_final_message,
)
- if prompt is None:
- raise RuntimeError("apply_chat_template returned None — tokenizer may be incompatible")
-
- # Parity with the transformers backend: if the template dropped the
- # requested tools, fall back to the native template so MLX text models
- # keep advertising them. self._tokenizer is this entry's tokenizer, so
- # probe and native render share a renderer. (VLM renders via the
- # processor for image tokens and is not wired here.)
- model_info = self.models.get(self.active_model_name, {})
- render_result = render_with_native_template_fallback(
- formatted_prompt = prompt,
- tokenizer = self._tokenizer,
- model_info = model_info,
- active_model_name = self.active_model_name,
- messages = messages,
- tools = tools,
- enable_thinking = enable_thinking,
- reasoning_effort = reasoning_effort,
- preserve_thinking = preserve_thinking,
- continue_final_message = continue_final_message,
- hf_token = model_info.get("hf_token"),
- return_metadata = True,
- )
prompt = render_result.prompt
reasoning_channel_markers = render_result.reasoning_channel_markers
# Not the request flag: a later tool-loop pass keeps it but renders an
@@ -2000,6 +2342,7 @@ class MLXInferenceBackend:
sampler = sampler,
)
gen_kwargs.update(self._kv_quant_generate_kwargs())
+ gen_kwargs.update(self._kv_window_generate_kwargs())
if prompt_cache is not None:
gen_kwargs["prompt_cache"] = prompt_cache
if logits_processors is not None:
@@ -2102,32 +2445,22 @@ class MLXInferenceBackend:
if stopped:
self._mark_stopped()
- def _generate_vlm(
+ def _render_vlm_prompt(
self,
messages,
- image,
- temperature,
- top_p,
- top_k,
- min_p,
- max_new_tokens,
- repetition_penalty,
- cancel_event,
+ images,
*,
tools = None,
enable_thinking = None,
reasoning_effort = None,
preserve_thinking = None,
continue_final_message = False,
- presence_penalty = 0.0,
- seed = None,
- frequency_penalty = 0.0,
- logit_bias = None,
- _adapter_state = None,
- stop = None,
):
- from mlx_vlm import stream_generate as vlm_stream
+ """Render the prompt a vision generation sends, and the target that rendered it.
+ Shared with counting, as _render_text_prompt is for text models, so a count cannot
+ price a prompt the model never sees. A text-only conversation passes images=None.
+ """
from core.inference.chat_template_helpers import (
apply_chat_template_for_generation,
chat_render_target,
@@ -2139,8 +2472,6 @@ class MLXInferenceBackend:
# to authorize against the same template this line selects (#7066).
chat_target = chat_render_target(self._processor)
- # mlx_vlm's stream_generate handles pixel_values (None for text-only)
- images = [image] if image is not None else None
attached_images = 0 if images is None else len(images)
structured_images = sum(
_count_vlm_images(message.get("content"))
@@ -2222,6 +2553,44 @@ class MLXInferenceBackend:
prompt = recovered_prompt
elif prompt_issue:
raise RuntimeError(f"VLM chat template returned {prompt_issue}.") from prompt_error
+ return prompt, chat_target
+
+ def _generate_vlm(
+ self,
+ messages,
+ image,
+ temperature,
+ top_p,
+ top_k,
+ min_p,
+ max_new_tokens,
+ repetition_penalty,
+ cancel_event,
+ *,
+ tools = None,
+ enable_thinking = None,
+ reasoning_effort = None,
+ preserve_thinking = None,
+ continue_final_message = False,
+ presence_penalty = 0.0,
+ seed = None,
+ frequency_penalty = 0.0,
+ logit_bias = None,
+ _adapter_state = None,
+ stop = None,
+ ):
+ from mlx_vlm import stream_generate as vlm_stream
+
+ images = [image] if image is not None else None
+ prompt, chat_target = self._render_vlm_prompt(
+ messages,
+ images,
+ tools = tools,
+ enable_thinking = enable_thinking,
+ reasoning_effort = reasoning_effort,
+ preserve_thinking = preserve_thinking,
+ continue_final_message = continue_final_message,
+ )
from core.inference.chat_template_helpers import detect_think_prefill
@@ -2247,6 +2616,7 @@ class MLXInferenceBackend:
min_p = float(min_p or 0.0),
)
vlm_kwargs.update(self._kv_quant_generate_kwargs())
+ vlm_kwargs.update(self._kv_window_generate_kwargs())
if seed is not None:
# generate_step builds its temperature/top_p/min_p/top_k sampler only
# when sampler is None, so a seeded request must supply the whole
@@ -2420,6 +2790,7 @@ class MLXInferenceBackend:
# Greedy; the knobs below are load-time state, not caller kwargs.
temperature = 0.0,
**self._kv_quant_generate_kwargs(),
+ **self._kv_window_generate_kwargs(),
):
final_response = response
sampled += response.text if hasattr(response, "text") else str(response)
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.py
index 14c5ed250a8..d1e3c27a2a5 100644
--- a/studio/backend/core/inference/orchestrator.py
+++ b/studio/backend/core/inference/orchestrator.py
@@ -220,6 +220,29 @@ def _summed_tool_loop_stats(total, turn):
return summed
+def _mirrored_model_entry(model_info: dict, model_name: str) -> dict:
+ """The parent's view of a model the worker holds.
+
+ Measured or classified in the subprocess and unrecoverable once the model lives
+ there, so a field the worker sends and this does not copy is one the API can never
+ report.
+ """
+ return {
+ "is_vision": model_info.get("is_vision", False),
+ "is_lora": model_info.get("is_lora", False),
+ "is_mlx": model_info.get("is_mlx", False),
+ "display_name": model_info.get("display_name", model_name),
+ "is_audio": model_info.get("is_audio", False),
+ "audio_type": model_info.get("audio_type"),
+ "has_audio_input": model_info.get("has_audio_input", False),
+ "context_length": model_info.get("context_length"),
+ "native_context_length": model_info.get("native_context_length"),
+ "max_context_length": model_info.get("max_context_length"),
+ "requested_context_length": model_info.get("requested_context_length"),
+ "context_length_enforced": model_info.get("context_length_enforced"),
+ }
+
+
class InferenceOrchestrator:
"""
Inference backend orchestrator — subprocess-based.
@@ -1773,16 +1796,9 @@ class InferenceOrchestrator:
# self.models" guard, and the worker's absent-name fallback would unload
# its *active* model, not the already-gone one.
self.models = {}
- self.models[self.active_model_name] = {
- "is_vision": model_info.get("is_vision", False),
- "is_lora": model_info.get("is_lora", False),
- "is_mlx": model_info.get("is_mlx", False),
- "display_name": model_info.get("display_name", model_name),
- "is_audio": model_info.get("is_audio", False),
- "audio_type": model_info.get("audio_type"),
- "has_audio_input": model_info.get("has_audio_input", False),
- "context_length": model_info.get("context_length"),
- }
+ self.models[self.active_model_name] = _mirrored_model_entry(
+ model_info, model_name
+ )
self.models[self.active_model_name].update(
_mlx_runtime_mirror_fields(model_info)
)
@@ -2021,6 +2037,67 @@ class InferenceOrchestrator:
if self._drain_event is not None:
self._drain_event.clear()
+ def count_chat_tokens(
+ self,
+ messages: list,
+ system_prompt: str = "",
+ *,
+ tools: Optional[list] = None,
+ enable_thinking: Optional[bool] = None,
+ reasoning_effort: Optional[str] = None,
+ preserve_thinking: Optional[bool] = None,
+ timeout: float = 30.0,
+ ) -> tuple[int, Optional[str]]:
+ """Prompt tokens the loaded model would receive, and whose tokenizer counted them.
+
+ Reads through an addressed mailbox, as generations do: compare mode bypasses the
+ generation lock and leaves a dispatcher owning the response queue, which would
+ route this reply nowhere.
+ """
+ if not self._gen_lock.acquire(blocking = False):
+ raise RuntimeError("Cannot count tokens while a generation is in progress")
+ request_id = str(uuid.uuid4())
+ read_one, _drain, release_mailbox = self._direct_reader(request_id)
+ try:
+ self._send_cmd(
+ {
+ "type": "count_tokens",
+ "request_id": request_id,
+ "messages": messages,
+ "system_prompt": system_prompt,
+ "tools": tools,
+ "enable_thinking": enable_thinking,
+ "reasoning_effort": reasoning_effort,
+ "preserve_thinking": preserve_thinking,
+ }
+ )
+ deadline = time.monotonic() + timeout
+ resp = None
+ while time.monotonic() < deadline:
+ candidate = read_one(timeout = min(1.0, deadline - time.monotonic()))
+ if candidate is None:
+ if not self._ensure_subprocess_alive():
+ raise RuntimeError(self._subprocess_crash_message("count"))
+ continue
+ # A reply whose own mailbox is gone -- an earlier count that timed out
+ # while the worker still held its command -- is handed back to whoever is
+ # reading, and the type alone cannot tell it from this one's.
+ if (
+ candidate.get("type") == "count_tokens_response"
+ and candidate.get("request_id") == request_id
+ ):
+ resp = candidate
+ break
+ if resp is None:
+ raise RuntimeError("Timed out counting tokens")
+ finally:
+ release_mailbox()
+ self._gen_lock.release()
+ error = resp.get("error")
+ if error:
+ raise RuntimeError(error)
+ return int(resp["input_tokens"]), resp.get("model")
+
def generate_chat_response(
self,
messages: list,
diff --git a/studio/backend/core/inference/runtime_context.py b/studio/backend/core/inference/runtime_context.py
index e1b874542a1..3acca130e2e 100644
--- a/studio/backend/core/inference/runtime_context.py
+++ b/studio/backend/core/inference/runtime_context.py
@@ -9,6 +9,11 @@ from collections.abc import Iterator, Mapping
from itertools import chain
from typing import Any, Optional
+#: Longest context a load may ask for, and the ceiling a resolved window is held to.
+#: LoadRequest.max_seq_length bounds requests by this; a backend that reads a wider
+#: window from the model reports it as native but does not serve past it.
+MAX_REQUESTABLE_CONTEXT = 1048576
+
def _field(source: Any, name: str) -> Any:
"""Key or attribute, since mlx.nn.Module is a dict; a raiser is absent, never a failed load."""
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 9d9a327fc51..4612984c1e6 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -11157,17 +11157,18 @@ def build_conversation_recall(
return built
-def build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> dict | None:
- """Pre-retrieve the latest user turn; if a hit clears the cosine floor return
- ``{"events": [...], "messages": [...]}`` to splice into the loop, else ``None``.
- Toggle via ``rag_scope.autoinject`` (else env ``RAG_AUTOINJECT``); floor via
- ``rag_scope.autoinject_min_score`` (else env ``RAG_AUTOINJECT_MIN_SCORE``).
+def rag_autoinject_reaches_retrieval(
+ conversation: list[dict], rag_scope: dict | None
+) -> tuple[bool, bool]:
+ """Everything checked before pre-retrieval searches: switched on, something to search
+ for, somewhere to search, and a store to search it in. Whether a hit then clears the
+ score floor is the one part not knowable without running the search.
- Also the small-model fallback: models below ~4B often answer from memory
- instead of calling ``search_knowledge_base``, so forcing retrieval here keeps
- attachments consulted regardless of model size."""
+ Shared with token counting, which cannot run it and so must not decline a turn that
+ stops short of the search here.
+ """
if not rag_scope:
- return None
+ return False, False
enabled = rag_scope.get("autoinject")
if enabled is None:
enabled = _autoinject_enabled()
@@ -11175,15 +11176,41 @@ def build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> di
whole_doc_requested = (
bool(thread_id) and not rag_scope.get("kb_id") and _thread_whole_doc_enabled(rag_scope)
)
+ if not enabled and not whole_doc_requested:
+ return False, False
+ # What _resolve_scope resolves to nothing: an unpersisted New Chat carries a scope with
+ # none of the three ids, and the search stops there.
+ if not (rag_scope.get("kb_id") or rag_scope.get("project_id") or thread_id):
+ return False, False
+ if not _last_user_text(conversation):
+ return False, False
+ try:
+ from storage import rag_db
+
+ # rag_available(), not the import flag: the vec0 native library is a separate file a
+ # venv can be missing, and nothing finds out until a connection tries.
+ if not rag_db.rag_available():
+ return False, False
+ except Exception: # noqa: BLE001
+ return False, False
+ return bool(enabled), whole_doc_requested
+
+
+def build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> dict | None:
+ """Pre-retrieve the latest user turn; if a hit clears the cosine floor return
+ ``{"events": [...], "messages": [...]}`` to splice into the loop, else ``None``.
+ Toggle via ``rag_scope.autoinject`` (else env ``RAG_AUTOINJECT``); floor via
+ ``rag_scope.autoinject_min_score`` (else env ``RAG_AUTOINJECT_MIN_SCORE``).
+
+ Also the small-model fallback: models below ~4B often answer from memory
+ instead of calling ``search_knowledge_base``, so forcing retrieval here keeps
+ attachments consulted regardless of model size."""
+ enabled, whole_doc_requested = rag_autoinject_reaches_retrieval(conversation, rag_scope)
if not enabled and not whole_doc_requested:
return None
+ thread_id = rag_scope.get("thread_id")
query = _last_user_text(conversation)
- if not query:
- return None
try:
- from storage import rag_db
- if not rag_db.RAG_AVAILABLE:
- return None
from core.rag.tool import render_sources, search_for_autoinject, whole_document_context
except Exception as exc: # noqa: BLE001
logger.warning("RAG auto-inject unavailable: %s", exc)
diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.py
index 086599a5689..c3ef6c9d578 100644
--- a/studio/backend/core/inference/worker.py
+++ b/studio/backend/core/inference/worker.py
@@ -492,12 +492,24 @@ def _handle_load(backend, config: dict, resp_queue: Any) -> None:
_entry = (
_bm.get(mc.identifier) or _bm.get(getattr(backend, "active_model_name", None)) or {}
)
- try:
- _context_length = _entry.get("context_length")
- if _context_length is not None:
- model_info["context_length"] = int(_context_length)
- except Exception as _ctx_exc:
- logger.warning("context_length forward failed: %s", _ctx_exc)
+ # The whole group: the parent reports all four and can recompute none of
+ # them once the worker holds the model.
+ for _ctx_field in (
+ "context_length",
+ "native_context_length",
+ "max_context_length",
+ "requested_context_length",
+ ):
+ try:
+ _ctx_value = _entry.get(_ctx_field)
+ if _ctx_value is not None:
+ model_info[_ctx_field] = int(_ctx_value)
+ except Exception as _ctx_exc:
+ logger.warning("%s forward failed: %s", _ctx_field, _ctx_exc)
+ # Tri-state, so it is forwarded as it is rather than coerced: None means the
+ # backend does not answer, which is not the same as a confirmed False.
+ if _entry.get("context_length_enforced") is not None:
+ model_info["context_length_enforced"] = bool(_entry["context_length_enforced"])
# Backend post-load audio classification outranks pre-load config.
model_info.update(
{k: _entry[k] for k in ("is_audio", "audio_type", "has_audio_input") if k in _entry}
@@ -741,6 +753,52 @@ def _handle_generate(backend, cmd: dict, resp_queue: Any, cancel_event) -> None:
)
+def _handle_count_tokens(backend, cmd: dict, resp_queue: Any) -> None:
+ """Count prompt tokens for the loaded model and reply with the total."""
+ try:
+ count = backend.count_chat_tokens(
+ cmd.get("messages") or [],
+ cmd.get("system_prompt") or "",
+ tools = cmd.get("tools"),
+ enable_thinking = cmd.get("enable_thinking"),
+ reasoning_effort = cmd.get("reasoning_effort"),
+ preserve_thinking = cmd.get("preserve_thinking"),
+ )
+ except Exception as exc:
+ _send_response(
+ resp_queue,
+ {
+ "type": "count_tokens_response",
+ "request_id": cmd.get("request_id"),
+ "error": str(exc),
+ },
+ )
+ return
+ _send_response(
+ resp_queue,
+ {
+ "type": "count_tokens_response",
+ # Echoed so the dispatcher can address the caller's mailbox; an unaddressed
+ # reply is dropped and the caller waits out its timeout.
+ "request_id": cmd.get("request_id"),
+ "input_tokens": int(count),
+ "model": backend.active_model_name,
+ },
+ )
+
+
+def _decline_count_tokens(cmd: dict, resp_queue: Any) -> None:
+ """Answer a count this backend cannot serve; dropping it costs the caller its timeout."""
+ _send_response(
+ resp_queue,
+ {
+ "type": "count_tokens_response",
+ "request_id": cmd.get("request_id"),
+ "error": "Counting is not supported on the transformers backend.",
+ },
+ )
+
+
def _handle_share_object(backend, cmd: dict, resp_queue: Any) -> None:
"""Share a small Python object across MLX distributed ranks."""
request_id = cmd.get("request_id", "")
@@ -1166,6 +1224,8 @@ def run_inference_process(
),
},
)
+ elif cmd_type == "count_tokens":
+ _handle_count_tokens(backend, cmd, resp_queue)
elif cmd_type == "share_object":
_handle_share_object(backend, cmd, resp_queue)
elif cmd_type == "load":
@@ -1418,6 +1478,9 @@ def run_inference_process(
continue
_handle_generate(backend, cmd, resp_queue, cancel_event)
+ elif cmd_type == "count_tokens":
+ _decline_count_tokens(cmd, resp_queue)
+
elif cmd_type == "share_object":
_handle_share_object(backend, cmd, resp_queue)
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 3cd90687a60..e114f9a6a2d 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -27,6 +27,7 @@ from core.inference.llama_server_args import (
PARALLEL_MAX,
PARALLEL_MIN,
)
+from core.inference.runtime_context import MAX_REQUESTABLE_CONTEXT
from core.inference.video_families import MAX_VIDEO_NUM_FRAMES
from picker.schemas import MAX_CHAT_TEMPLATE_BYTES
@@ -54,8 +55,11 @@ class LoadRequest(BaseModel):
max_seq_length: int = Field(
0,
ge = 0,
- le = 1048576,
- description = "Maximum sequence length (0 = model default for GGUF)",
+ le = MAX_REQUESTABLE_CONTEXT,
+ description = (
+ "Maximum sequence length. Send 0 to let a backend that sizes its own window "
+ "(llama.cpp or MLX) choose the context itself."
+ ),
)
load_in_4bit: bool = Field(True, description = "Load model in 4-bit quantization")
is_lora: bool = Field(False, description = "Whether this is a LoRA adapter")
@@ -427,7 +431,7 @@ class ValidateModelRequest(BaseModel):
)
# Intended load settings so validate's coexistence check matches the follow-up
# /load; defaults preserve old behavior for callers that omit them.
- max_seq_length: int = Field(0, ge = 0, le = 1048576)
+ max_seq_length: int = Field(0, ge = 0, le = MAX_REQUESTABLE_CONTEXT)
load_in_4bit: bool = Field(True)
cache_type_kv: Optional[str] = Field(None)
tensor_parallel: bool = Field(False)
@@ -1063,11 +1067,24 @@ class _InferenceRuntimeFields(BaseModel):
None, description = "Runtime context length in tokens for the loaded model"
)
max_context_length: Optional[int] = Field(
- None, description = "Maximum context length currently available on this hardware"
+ None,
+ description = (
+ "The ceiling to show for this model: llama.cpp estimates what the machine can "
+ "hold, while MLX reports the model's own window. Neither reserves memory, and "
+ "an explicit request above it is still honored."
+ ),
)
native_context_length: Optional[int] = Field(
None,
- description = "Model's native context length from GGUF metadata (not capped by VRAM)",
+ description = "Model's native context length, from GGUF metadata or the MLX model config",
+ )
+ context_length_enforced: Optional[bool] = Field(
+ None,
+ description = (
+ "Whether context_length actually bounds the runtime's KV cache. True confirmed, "
+ "false confirmed unbounded, null the backend does not answer. MLX builds a cache "
+ "to check, since a model with its own make_cache ignores the requested size."
+ ),
)
supports_reasoning: bool = Field(
False,
@@ -1464,10 +1481,11 @@ class InferenceStatusResponse(_InferenceRuntimeFields):
requested_context_length: Optional[int] = Field(
None,
description = (
- "The max_seq_length the active load was invoked with (0 = Auto). Lets the "
- "UI re-seed a Manual + Auto-layers context pin on hydration, and lets a CLI "
- "attach tell a no-op from a reload, where context_length only exposes the "
- "resolved value. None when the running model predates this field."
+ "The context length the active load was invoked with: 0 means the load asked "
+ "the backend to choose, and null means the serving backend records no request "
+ "at all. Both local backends size their own window, so context_length reports "
+ "only what was resolved and cannot say whether anyone chose it; this is what "
+ "lets a client restore the user's choice after a reload."
),
)
load_in_4bit: Optional[bool] = Field(
@@ -1821,6 +1839,50 @@ class ThinkingConfig(BaseModel):
type: Literal["disabled", "enabled"] = "disabled"
+def resolve_thinking_onto_enable_thinking(request):
+ """Map Anthropic-style ``thinking`` onto the internal ``enable_thinking``.
+
+ ``enable_thinking`` wins when both are given. Shared with counting, which must resolve
+ the reasoning preamble exactly as the completion does.
+ """
+ if request.thinking is not None and request.enable_thinking is None:
+ request.enable_thinking = request.thinking.type == "enabled"
+ return request
+
+
+class ReasoningControlsRequest(BaseModel):
+ """The reasoning controls a request may carry, resolved the way a completion does.
+
+ ChatCompletionRequest shares the resolution above rather than inheriting: pydantic
+ orders inherited fields ahead of a subclass's own, reordering its OpenAPI properties
+ and validation errors.
+ """
+
+ enable_thinking: Optional[bool] = Field(
+ None,
+ description = "[x-unsloth] Enable/disable thinking/reasoning mode for supported models",
+ )
+ reasoning_effort: Optional[
+ Literal["none", "minimal", "low", "medium", "high", "max", "xhigh"]
+ ] = Field(
+ None,
+ description = "[x-unsloth] Reasoning effort level ('none'|'minimal'|'low'|'medium'|'high'|'max'|'xhigh'). OpenAI `/v1/responses` accepts model-dependent subsets; Anthropic adaptive thinking uses `max` as the top tier on Claude 4.6 Opus/Sonnet (inbound `xhigh` is mapped to `max`) and `xhigh` on Claude 4.7 Opus; local Harmony/gpt-oss templates support low|medium|high.",
+ )
+ preserve_thinking: Optional[bool] = Field(
+ None,
+ description = "[x-unsloth] When true, keep historical <think> blocks from past assistant turns in the prompt (Qwen3.6 templates). Independent of enable_thinking / reasoning_effort.",
+ )
+ thinking: Optional[ThinkingConfig] = Field(
+ None,
+ description = "[Anthropic-compatible] Thinking configuration. "
+ "Use {type: 'disabled'} to disable thinking, {type: 'enabled'} to enable.",
+ )
+
+ @model_validator(mode = "after")
+ def _map_thinking_to_enable_thinking(self):
+ return resolve_thinking_onto_enable_thinking(self)
+
+
# Recognized permission_mode values. The field accepts a plain string rather than
# a Literal so an unrecognized value from a newer UI/client degrades to the safest
# gate ("ask") instead of a 422. None stays unset at the request boundary: the tool
@@ -2408,17 +2470,7 @@ class ChatCompletionRequest(BaseModel):
@model_validator(mode = "after")
def _map_thinking_to_enable_thinking(self) -> "ChatCompletionRequest":
- """Map Anthropic-style ``thinking`` parameter to internal ``enable_thinking``.
-
- ``thinking: {type: 'enabled'}`` sets ``enable_thinking = True`` and
- ``thinking: {type: 'disabled'}`` sets ``enable_thinking = False``.
- ``enable_thinking`` takes precedence when both are provided so that
- callers who already use the internal field are unaffected. Invalid
- ``thinking`` shapes are rejected at validation time (422).
- """
- if self.thinking is not None and self.enable_thinking is None:
- self.enable_thinking = self.thinking.type == "enabled"
- return self
+ return resolve_thinking_onto_enable_thinking(self)
@field_validator("permission_mode", mode = "before")
@classmethod
@@ -2482,8 +2534,8 @@ class ChatCompletionRequest(BaseModel):
return self
-class ChatCountTokensRequest(BaseModel):
- """Count prompt tokens for a local GGUF chat without generating."""
+class ChatCountTokensRequest(ReasoningControlsRequest):
+ """Count prompt tokens for a local chat without generating."""
model_config = {"extra": "allow"}
@@ -2499,18 +2551,6 @@ class ChatCountTokensRequest(BaseModel):
None,
description = "Optional OpenAI tool definitions included in the prompt",
)
- enable_thinking: Optional[bool] = Field(
- None,
- description = "[x-unsloth] Render the template in thinking mode, as a completion would",
- )
- reasoning_effort: Optional[str] = Field(
- None,
- description = "[x-unsloth] Reasoning effort level the completion would request",
- )
- preserve_thinking: Optional[bool] = Field(
- None,
- description = "[x-unsloth] Keep historical <think> blocks in the rendered prompt",
- )
enable_tools: Optional[bool] = Field(
None,
description = "[x-unsloth] Enable tool calling for supported models",
@@ -2530,6 +2570,14 @@ class ChatCountTokensRequest(BaseModel):
"whenever the composer armed research, so the count carries it too."
),
)
+ thread_id: Optional[str] = Field(
+ None,
+ description = (
+ "[x-unsloth] The thread being counted. A thread with a conversation archive puts "
+ "search_conversation and its compaction nudge in the prompt, so the count needs "
+ "the same id the completion sends to price them."
+ ),
+ )
rag_scope: Optional[dict] = Field(
None,
description = "[x-unsloth] Hidden RAG retrieval scope for search_knowledge_base",
@@ -2549,10 +2597,11 @@ class ChatCountTokensRequest(BaseModel):
)
permission_mode: Optional[str] = Field(
None,
- description = "[x-unsloth] Permission level the completion would send. Only 'full' changes "
- "the prompt: it swaps the python/terminal descriptions for the unsandboxed pair and adds a "
- "sentence to the tool nudge, so a count that omits it prices a prompt the completion will "
- "not send.",
+ description = "[x-unsloth] Permission level the completion would send. 'full' swaps the "
+ "python/terminal descriptions for the unsandboxed pair and adds a sentence to the tool "
+ "nudge; 'ask' holds the tool loop's first-pass retrieval behind its confirmation gate, so "
+ "a pending turn under a retrieval scope is countable. A count that omits this prices a "
+ "prompt the completion will not send, or declines one it could have priced.",
)
bypass_permissions: Optional[bool] = Field(
None,
@@ -2560,11 +2609,29 @@ class ChatCountTokensRequest(BaseModel):
"left to extra='allow') so an omitted flag reads as None instead of raising AttributeError.",
)
+ confirm_tool_calls: Optional[bool] = Field(
+ None,
+ description = "[x-unsloth] Whether the completion's tool loop would gate each call. "
+ "Declared so it is typed and folded into permission_mode as it is on a completion.",
+ )
+ max_tool_calls_per_message: Optional[int] = Field(
+ None,
+ ge = 0,
+ description = "[x-unsloth] Tool-call budget the completion would send. Zero suppresses the "
+ "tool loop, so a count that never sees it prices a catalog the relay does not render.",
+ )
+
@field_validator("permission_mode", mode = "before")
@classmethod
def _coerce_permission_mode(cls, value: Any) -> Any:
return _normalize_permission_mode(value)
+ # The very function the completion request runs, not a copy: a count renders replayed
+ # tool history through the same templates, which read the id off the result message.
+ _resolve_missing_tool_call_ids = model_validator(mode = "after")(
+ ChatCompletionRequest._resolve_missing_tool_call_ids
+ )
+
@model_validator(mode = "after")
def _fold_full_permission_into_bypass(self) -> "ChatCountTokensRequest":
"""Mirrors ChatCompletionRequest: the prompt builders read only the
@@ -2573,6 +2640,11 @@ class ChatCountTokensRequest(BaseModel):
self.bypass_permissions = True
elif self.bypass_permissions:
self.permission_mode = "full"
+ elif self.permission_mode is None and self.confirm_tool_calls is True:
+ # The same reading a completion gives it: gating every call is the
+ # pre-permission-mode way of asking for "ask", and the loop's retrieval
+ # gate turns on that. No provider clause -- this endpoint is local only.
+ self.permission_mode = "ask"
return self
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 4d97ed006f2..d1e687761f9 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -606,6 +606,22 @@ def _has_openai_tool_history(messages) -> bool:
return False
+def _extra_body_enable_thinking(payload) -> Optional[bool]:
+ """``enable_thinking`` sent through the OpenAI SDK's ``extra_body``, or None.
+
+ The SDK spreads ``chat_template_kwargs`` into the request body, where ``extra="allow"``
+ stashes it in ``model_extra``; every render consumes the typed field instead, so each
+ entry point lifts it first.
+ """
+ extra = getattr(payload, "model_extra", None)
+ if not isinstance(extra, dict):
+ return None
+ template_kwargs = extra.get("chat_template_kwargs")
+ if isinstance(template_kwargs, dict) and "enable_thinking" in template_kwargs:
+ return bool(template_kwargs["enable_thinking"])
+ return None
+
+
def _raise_unsupported_openai_parameter(param: str, message: str) -> None:
raise HTTPException(
status_code = 400,
@@ -3770,8 +3786,9 @@ def _permission_mode_confirm(payload) -> bool:
health checks keep working. Used at the pre-switch guard and the per-backend
tool paths so a forced tool loop (CLI --enable-tools) still gates streaming.
"""
- if payload.confirm_tool_calls is not None:
- return bool(payload.confirm_tool_calls)
+ _confirm = getattr(payload, "confirm_tool_calls", None)
+ if _confirm is not None:
+ return bool(_confirm)
mode = getattr(payload, "permission_mode", None)
if mode in ("ask", "auto"):
return True
@@ -4806,8 +4823,8 @@ async def _select_request_tools(
# Same rule for the conversation archive: offered only once this thread has had turns
# evicted, so a short chat never sees the extra schema. On the first compaction the
# tool is still absent (the archive is written mid-request) and the forced recall
- # covers that turn. getattr, because this helper also serves the token-count request
- # model, which carries no thread_id.
+ # covers that turn. getattr because the count request model reaches here too; it
+ # carries the same thread_id so both price the archive alike.
# Follows the ARCHIVE, not the caller's allowlist: Unsloth always sends an explicit
# enabled_tools array and has no reason to name an internal tool it shows no pill for,
# so the filter above removed search_conversation and neither it nor the compaction
@@ -6385,6 +6402,8 @@ def _llama_runtime_fields(llama_backend: LlamaCppBackend) -> dict:
mlx_kv_quant_reason = None,
mlx_kv_quant_note = None,
chat_template_override_reason = None,
+ # llama.cpp allocates the window it reports: bounded by construction.
+ context_length_enforced = True,
# Older/custom backend doubles predate this additive runtime field.
preserve_thinking_default = bool(getattr(llama_backend, "preserve_thinking_default", False)),
speculative_type = llama_backend.requested_spec_mode,
@@ -13332,6 +13351,10 @@ async def _load_model_impl(
_same_loaded_identifier(backend.active_model_name, model_identifier)
and _mlx_runtime_settings_match(backend, request)
and _non_gguf_runtime_settings_match(backend, request)
+ and _resident_context_satisfies(
+ backend.models.get(backend.active_model_name) or {},
+ request.max_seq_length,
+ )
):
api_monitor.discard(_load_event) # nothing loaded, no monitor row
logger.info(f"Model already loaded (Unsloth): {model_log_label}, skipping reload")
@@ -13388,6 +13411,11 @@ async def _load_model_impl(
preserve_thinking_default = _sf_flags.get("preserve_thinking_default", False),
supports_tools = _sf_flags["supports_tools"],
context_length = _positive_int_or_none(_model_info.get("context_length")),
+ native_context_length = _positive_int_or_none(
+ _model_info.get("native_context_length")
+ ),
+ max_context_length = _positive_int_or_none(_model_info.get("max_context_length")),
+ context_length_enforced = _model_info.get("context_length_enforced"),
chat_template = _chat_template,
)
@@ -14130,6 +14158,9 @@ async def _load_model_impl(
preserve_thinking_default = _sf_flags.get("preserve_thinking_default", False),
supports_tools = _sf_flags["supports_tools"],
context_length = _positive_int_or_none(_model_info.get("context_length")),
+ native_context_length = _positive_int_or_none(_model_info.get("native_context_length")),
+ max_context_length = _positive_int_or_none(_model_info.get("max_context_length")),
+ context_length_enforced = _model_info.get("context_length_enforced"),
chat_template = _chat_template,
)
@@ -16229,7 +16260,17 @@ async def get_status(current_subject: str = Depends(get_current_subject)):
preserve_thinking_default = _sf_flags.get("preserve_thinking_default", False),
supports_tools = _sf_flags["supports_tools"],
context_length = _positive_int_or_none(model_info.get("context_length")),
- requested_context_length = model_info.get("max_seq_length_requested"),
+ native_context_length = _positive_int_or_none(model_info.get("native_context_length")),
+ max_context_length = _positive_int_or_none(model_info.get("max_context_length")),
+ context_length_enforced = model_info.get("context_length_enforced"),
+ # 0 is an answer (size it yourself); None means no request is recorded. Either
+ # spelling: the route stamps max_seq_length_requested on every non-GGUF load,
+ # and the MLX mirror carries requested_context_length.
+ requested_context_length = _nonnegative_int_or_none(
+ model_info.get("requested_context_length")
+ if model_info.get("requested_context_length") is not None
+ else model_info.get("max_seq_length_requested")
+ ),
load_in_4bit = model_info.get("load_in_4bit_requested"),
requested_gpu_ids = model_info.get("gpu_ids_requested"),
chat_template = chat_template,
@@ -19807,19 +19848,12 @@ async def produce_openai_chat_completions(
llama_backend = get_llama_cpp_backend()
using_gguf = llama_backend.is_loaded
- # OpenAI-SDK clients send ``chat_template_kwargs`` via ``extra_body``, which
- # the SDK spreads into the request body at the top level. Unsloth's
- # ChatCompletionRequest has ``extra="allow"`` so pydantic stashes them in
- # ``model_extra``, but downstream generators consume the typed
- # ``payload.enable_thinking``. Lift ``enable_thinking`` from the extra-body
- # chat_template_kwargs onto the typed field so clients that only know the
- # OpenAI shape (data_designer recipe runs, etc.) can still control the
- # reasoning preamble.
- _extra = getattr(payload, "model_extra", None)
- if payload.enable_thinking is None and isinstance(_extra, dict):
- _tpl_kw = _extra.get("chat_template_kwargs")
- if isinstance(_tpl_kw, dict) and "enable_thinking" in _tpl_kw:
- payload.enable_thinking = bool(_tpl_kw["enable_thinking"])
+ # Clients that only know the OpenAI shape (data_designer recipe runs, etc.) control
+ # the reasoning preamble this way, so lift it onto the typed field the generators read.
+ if payload.enable_thinking is None:
+ _lifted_enable_thinking = _extra_body_enable_thinking(payload)
+ if _lifted_enable_thinking is not None:
+ payload.enable_thinking = _lifted_enable_thinking
# ── Determine which backend is active ─────────────────────
# Single-model server: any model name serves the loaded model (drop-in
@@ -23806,6 +23840,13 @@ def _openai_model_objects() -> list[dict]:
and (model_info.get("audio_type") in _TRANSFORMERS_TTS_AUDIO_TYPES)
):
entry["task"] = _TTS_MODEL_TASK
+
+ for _field in ("native_context_length", "max_context_length"):
+ _value = _positive_int_or_none(model_info.get(_field))
+ if _value is not None:
+ entry[_field] = _value
+ if model_info.get("context_length_enforced") is not None:
+ entry["context_length_enforced"] = bool(model_info["context_length_enforced"])
models.append(entry)
return models
@@ -25544,21 +25585,15 @@ def _build_chat_request(
if payload.parallel_tool_calls is not None:
chat_kwargs["parallel_tool_calls"] = payload.parallel_tool_calls
- # ``chat_template_kwargs`` (e.g. ``{"enable_thinking": true}``) arrives via
- # the Responses extra-body: ResponsesRequest has ``extra="allow"``, so the
- # OpenAI SDK's ``extra_body`` spread lands the dict in ``model_extra``. The
- # downstream Chat Completions paths consume the typed ``enable_thinking``
- # field -- the non-streaming path lifts it in ``openai_chat_completions``
- # only when it is still ``None``, and the streaming pass-through reads
- # ``payload.enable_thinking`` directly -- so lift it here, mirroring that
- # handler, to cover both Responses paths.
+ # Both Responses paths reach a Chat Completions render, and the streaming
+ # pass-through reads the typed field directly rather than re-lifting, so lift here.
explicit_enable_thinking = False
+ _lifted_enable_thinking = _extra_body_enable_thinking(payload)
+ if _lifted_enable_thinking is not None:
+ chat_kwargs["enable_thinking"] = _lifted_enable_thinking
+ explicit_enable_thinking = True
_extra = getattr(payload, "model_extra", None)
if isinstance(_extra, dict):
- _tpl_kw = _extra.get("chat_template_kwargs")
- if isinstance(_tpl_kw, dict) and "enable_thinking" in _tpl_kw:
- chat_kwargs["enable_thinking"] = bool(_tpl_kw["enable_thinking"])
- explicit_enable_thinking = True
# auto_heal_tool_calls / nudge_tool_calls are not typed on
# ResponsesRequest; lift them from the extra-body so passthrough
# healing (and the opt-in nudge) honor them on both paths.
@@ -27215,6 +27250,273 @@ def _append_to_system_message(messages: list[dict], addition: str) -> list[dict]
return [{"role": "system", "content": addition}, *copied]
+def _resident_context_satisfies(model_info: dict, max_seq_length: Any) -> bool:
+ """Whether the resident model already serves the context this load asks for.
+
+ A change made while a chat generates skips the preliminary unload, so nothing else
+ forces the reload. Requests are compared rather than served windows, which cannot
+ distinguish asking for a length from letting the backend choose one.
+ """
+ recorded = _nonnegative_int_or_none(model_info.get("requested_context_length"))
+ if recorded is None:
+ return True
+ return _positive_int_or_none(max_seq_length) == _positive_int_or_none(recorded)
+
+
+async def _mlx_count_chat_tokens(payload, request = None) -> Optional[JSONResponse]:
+ """Count with the resident MLX model's tokenizer, or None if MLX is not serving one.
+
+ This has to answer the question the safetensors completion answers -- which of its two
+ paths claims the request, and what each renders -- because a count that decides any of
+ it differently prices a prompt the model never sees. Where a helper carries a decision
+ it is called rather than restated; the admission conditions themselves are restated,
+ so they have to be kept in step with the completion above.
+ """
+ # Off the loop: building the singleton runs the torch import, and a count is not
+ # worth stalling login and the health probe behind it.
+ backend = await asyncio.to_thread(get_inference_backend)
+ active = getattr(backend, "active_model_name", None)
+ # The name cannot see a same-ID reload, which is how a template override lands, so
+ # the generation is captured with it and both are re-read at the end.
+ _load_generation = getattr(backend, "load_generation", 0)
+ if not active:
+ return None
+ entry = getattr(backend, "models", {}).get(active) or {}
+ # Audio is routed off the chat path, so a text render prices nothing that is sent.
+ # Vision is not: it serves text turns through the same render, and an image anywhere
+ # in the request was declined above.
+ if not entry.get("is_mlx") or entry.get("is_audio"):
+ return None
+
+ # The completion's own helper: rebuilding it here is how a count prices a prompt
+ # nobody sends.
+ system_prompt, messages, _image = _extract_content_parts(payload.messages)
+ # The completion applies this once for both non-GGUF backends before it branches.
+ # Only with a request: the helper's requestless mode injects the date unconditionally.
+ if request is not None:
+ system_prompt = _apply_current_date_prompt(system_prompt, request)
+
+ from state.tool_policy import get_tool_policy as _get_tool_policy_mlx
+
+ _tools_on = bool(_effective_enable_tools(payload))
+ # The launcher's default answers a request that said nothing about tools; one that
+ # stated its intent goes to the passthrough, not the tool loop.
+ if (
+ _tools_on
+ and _tools_on_by_launcher_default_only(payload)
+ and _request_states_tool_intent(payload)
+ ):
+ _tools_on = False
+ _mcp_on = bool(getattr(payload, "mcp_enabled", False)) and _get_tool_policy_mlx() is not False
+
+ # Classified from the template the way the completion classifies it. A named template
+ # exposes tool markup only in its tool_use branch, and which branch is read depends on
+ # the tools handed in -- so hand it a placeholder for the schemas selected below.
+ # Without them it reads the plain branch and prices away the whole catalog.
+ _tpl = (entry.get("chat_template_info") or {}).get("template")
+ _template_tools = payload.tools if getattr(payload, "tool_choice", None) != "none" else None
+ if not _template_tools and (_tools_on or _explicit_studio_tool_loop_requested(payload)):
+ _template_tools = ({},)
+ _takes_tools = bool(
+ _detect_safetensors_features(backend, _tpl, tools = _template_tools).get(
+ "supports_tools", False
+ )
+ )
+ # A budget of zero never enters the loop, so the relay is what renders.
+ _budget = getattr(payload, "max_tool_calls_per_message", None)
+ _tools_to_use = None
+ if _takes_tools and (_tools_on or _mcp_on) and (_budget is None or _budget > 0):
+ # Never discovery on a count: get_enabled_mcp_tools spawns stdio servers and
+ # blocks on a probe timeout. Schemas come from the completion's cache and an
+ # incomplete view is declined; mcp_allowed stays False as the network flag.
+ _mcp_tools: list[dict] = []
+ if _mcp_on:
+ from core.inference.mcp_client import mcp_server_snapshot_guard
+ from core.inference.tools import cached_mcp_tools
+
+ # A database read, so off the loop. Guarded as the GGUF count guards it, or
+ # an interleaving edit pairs a new row with the schema cached before it.
+ async with mcp_server_snapshot_guard():
+ _mcp_tools, _mcp_complete = await asyncio.to_thread(cached_mcp_tools)
+ if not _mcp_complete:
+ raise HTTPException(
+ status_code = 503,
+ detail = "Cannot count tokens until enabled MCP tools have been discovered.",
+ )
+ _tools_to_use = (
+ await _select_request_tools(payload, tools_on = _tools_on, mcp_allowed = False)
+ ) + _mcp_tools
+ # Nothing surviving means the completion skips the tool loop, so follow it back
+ # to the plain render rather than passing an empty catalog.
+ if not _tools_to_use:
+ _tools_to_use = None
+
+ if (
+ not _tools_to_use
+ and _takes_tools
+ and not _tools_on
+ and (payload.tools or _has_openai_tool_history(payload.messages))
+ ):
+ # The relay claims a request the tool loop did not, and renders it from a message list
+ # rebuilt to keep the structured tool_calls the shared extraction flattens away, with
+ # the caller's own catalog and no separate system prompt. Counting the flattened
+ # conversation instead priced a shorter prompt than the one that gets sent.
+ _tool_choice = getattr(payload, "tool_choice", None)
+ _forced = (
+ _tool_choice["function"].get("name")
+ if isinstance(_tool_choice, dict) and isinstance(_tool_choice.get("function"), dict)
+ else None
+ )
+ if _tool_choice == "none":
+ _tools_to_use = None
+ elif isinstance(_forced, str):
+ _tools_to_use = [
+ _tool
+ for _tool in payload.tools or []
+ if isinstance(_tool, dict)
+ and isinstance(_tool.get("function"), dict)
+ and _tool["function"].get("name") == _forced
+ ] or None
+ else:
+ _tools_to_use = payload.tools or None
+ messages = _set_or_prepend_system_message(
+ _structured_tool_history_for_local_template(
+ _flatten_content_parts_for_local_template(_openai_messages_for_passthrough(payload))
+ ),
+ system_prompt,
+ )
+ system_prompt = ""
+ elif _tools_to_use:
+ # A PENDING turn is the shape this loop answers from exactly these messages, splicing
+ # in whatever build_rag_autoinject retrieves -- thousands of tokens this never sees.
+ # Only the loop retrieves: the relay above never does, so a request that never reaches
+ # the loop is counted rather than refused. "ask" without a bypass is the one mode that
+ # holds retrieval behind the confirm gate, so the loop skips it and the count stands.
+ _asks_first = (
+ payload.permission_mode is not None
+ and payload.permission_mode not in ("auto", "off", "full")
+ and not payload.bypass_permissions
+ and _permission_mode_confirm(payload)
+ )
+ # Only where the answer can change this one, because answering it opens the database,
+ # loads the vec0 extension and creates the schema, and this runs on every keystroke.
+ if not _asks_first and messages and messages[-1].get("role") in ("user", "tool"):
+ from core.inference.tools import rag_autoinject_reaches_retrieval
+
+ # Retrieval that never reaches the store leaves the loop rendering exactly these
+ # messages, so the scope alone is not the question. Where it does reach the store
+ # it may still find nothing, but this cannot run it to find out, so the turn is
+ # declined rather than priced short. Off the loop, since it waits out a busy
+ # timeout under a concurrent ingest.
+ _retrieves, _whole_doc = await asyncio.to_thread(
+ rag_autoinject_reaches_retrieval, messages, payload.rag_scope
+ )
+ if _retrieves or _whole_doc:
+ raise HTTPException(
+ status_code = 503,
+ detail = "Cannot count tokens for a pending turn that would retrieve documents.",
+ )
+
+ # Schemas are not the whole cost of turning tools on: the completion appends an
+ # action nudge to the system prompt and strips stale call markup out of replayed
+ # assistant turns before it renders. Counting without either prices a prompt that
+ # is both short a nudge and long the markup.
+ _nudge = await _apply_rag_nudge(
+ _build_tool_action_nudge(
+ tools = _tools_to_use,
+ model_name = public_model_id(active) or payload.model,
+ full_access = bool(payload.bypass_permissions),
+ ),
+ _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)
+ # 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.
+ if request is not None:
+ system_prompt = _apply_current_date_prompt(
+ system_prompt,
+ request,
+ include_api_key = True,
+ )
+ if _nudge:
+ system_prompt = (system_prompt.rstrip() + "\n\n" + _nudge) if system_prompt else _nudge
+ _auto_heal = (
+ payload.auto_heal_tool_calls if payload.auto_heal_tool_calls is not None else True
+ )
+ _name_gate = _display_tool_name_gate(_tools_to_use)
+ messages = [
+ {
+ **_msg,
+ "content": _strip_tool_xml_for_display(
+ _msg["content"],
+ auto_heal_tool_calls = _auto_heal,
+ enabled_tool_names = _name_gate,
+ ).strip(),
+ }
+ if _msg.get("role") == "assistant" and isinstance(_msg.get("content"), str)
+ else _msg
+ for _msg in messages
+ ]
+
+ # Nothing to price: the template would render its generation marker alone and the
+ # total would describe a conversation nobody has started (#8882). The GGUF branch
+ # refuses the same shape after resolving its own prompt.
+ if not messages and not system_prompt and not _tools_to_use:
+ raise HTTPException(
+ status_code = 503,
+ detail = "Cannot count tokens for an empty prompt.",
+ )
+ # The same lift the completion applies before it renders.
+ enable_thinking = payload.enable_thinking
+ if enable_thinking is None:
+ enable_thinking = _extra_body_enable_thinking(payload)
+ # Re-checked immediately before the only work that takes the orchestrator's lock:
+ # everything since the endpoint's entry check awaits, so a chat can have started in
+ # the gap and would then wait on this count. The GGUF path re-checks for this reason.
+ if active_generations.count() > 0:
+ raise HTTPException(
+ status_code = 503,
+ detail = "Cannot count tokens while a generation is in progress.",
+ )
+ try:
+ count, model = await asyncio.to_thread(
+ backend.count_chat_tokens,
+ messages,
+ system_prompt or "",
+ tools = _tools_to_use,
+ enable_thinking = enable_thinking,
+ reasoning_effort = payload.reasoning_effort,
+ preserve_thinking = payload.preserve_thinking,
+ )
+ except Exception:
+ raise HTTPException(
+ status_code = 503,
+ detail = "Unable to count tokens with the loaded model tokenizer.",
+ )
+ # A load landing mid-count leaves the total attributable to neither model.
+ if (
+ getattr(backend, "active_model_name", None) != active
+ or getattr(backend, "load_generation", 0) != _load_generation
+ ):
+ raise HTTPException(
+ status_code = 503,
+ detail = "The loaded model changed while counting tokens.",
+ )
+ # The advertised id, not the resident path: an auto-switch loads from a resolved
+ # snapshot while publishing the repo id, and the caller drops a count whose model
+ # does not match the checkpoint it captured.
+ return JSONResponse(
+ content = {
+ "input_tokens": int(count),
+ "model": _orchestrator_public_model_id(backend) or model or active,
+ }
+ )
+
+
@router.post("/chat/count_tokens")
async def chat_count_tokens(
payload: ChatCountTokensRequest,
@@ -27239,6 +27541,21 @@ async def chat_count_tokens(
detail = "Cannot count tokens while a generation is in progress.",
)
+ # Same normalization /chat/completions does on entry: a template that renders roles
+ # literally would otherwise price a "developer" turn the completion renders as "system".
+ for _m in payload.messages:
+ if _m.role == "developer":
+ _m.role = "system"
+ # And the same default it applies to a function tool that omits the discriminator: a
+ # template serializing the whole entry renders it, so the count has to carry it too.
+ for _tool in payload.tools or []:
+ if (
+ isinstance(_tool, dict)
+ and _tool.get("type") is None
+ and isinstance(_tool.get("function"), dict)
+ ):
+ _tool["type"] = "function"
+
# /apply-template swaps each image for a short media marker, so refuse rather than undercount.
if _request_has_image(payload):
raise HTTPException(
@@ -27260,6 +27577,11 @@ async def chat_count_tokens(
llama_backend = get_llama_cpp_backend()
if not llama_backend.is_loaded:
+ # The refusals above are about the request and so are shared; the ones below are
+ # llama.cpp's own render concerns, so this returns rather than falling through.
+ _mlx_count = await _mlx_count_chat_tokens(payload, request)
+ if _mlx_count is not None:
+ return _mlx_count
raise HTTPException(
status_code = 503,
detail = _no_model_loaded_detail("No GGUF model loaded. Load a GGUF model first."),
diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.py
index 756608ecf11..349af239b2a 100644
--- a/studio/backend/routes/models.py
+++ b/studio/backend/routes/models.py
@@ -2248,12 +2248,16 @@ async def list_models(current_subject: str = Depends(get_current_subject)):
def _get_max_position_embeddings(config) -> Optional[int]:
- """Extract max_position_embeddings from a config, with text_config fallback."""
- if hasattr(config, "max_position_embeddings"):
- return config.max_position_embeddings
- if hasattr(config, "text_config") and hasattr(config.text_config, "max_position_embeddings"):
- return config.text_config.max_position_embeddings
- return None
+ """The window this model was trained for, by the rule a load resolves it with.
+
+ Reading one field name showed a dash for a model spelling it another way -- Kimi
+ Linear carries model_max_length alone -- and a number as soon as it loaded.
+ """
+ from types import SimpleNamespace
+
+ from core.inference.mlx_inference import mlx_native_context_length
+
+ return mlx_native_context_length(SimpleNamespace(config = config))
_MODEL_WEIGHT_EXTENSIONS = (".safetensors", ".bin", ".pt", ".pth", ".gguf")
diff --git a/studio/backend/tests/test_gguf_load_cache_reuse.py b/studio/backend/tests/test_gguf_load_cache_reuse.py
index 34b1d739521..d2e2f8950bd 100644
--- a/studio/backend/tests/test_gguf_load_cache_reuse.py
+++ b/studio/backend/tests/test_gguf_load_cache_reuse.py
@@ -865,6 +865,8 @@ class TestLoadHubDownloadExclusion:
"mlx_kv_quant_reason",
"mlx_kv_quant_note",
"chat_template_override_reason",
+ # Constant True: llama.cpp allocates the window it reports.
+ "context_length_enforced",
# Read from requested_extra_args, which is what the load was invoked
# with rather than the rewritten launch list.
"requested_llama_extra_args",
diff --git a/studio/backend/tests/test_llama_cpp_max_context_threshold.py b/studio/backend/tests/test_llama_cpp_max_context_threshold.py
index de824f3132b..1fb99bb6e6d 100644
--- a/studio/backend/tests/test_llama_cpp_max_context_threshold.py
+++ b/studio/backend/tests/test_llama_cpp_max_context_threshold.py
@@ -7,7 +7,7 @@ The ctx slider in the chat settings sheet reads
``/api/inference/status.max_context_length`` to decide when to render the
"Exceeds estimated VRAM capacity. The model may use system RAM." warning:
- ctxDisplayValue > ggufMaxContextLength → show warning
+ ctxDisplayValue > maxContextLength → show warning
When weights fit on some GPU subset, the threshold is the largest ctx that
fits fully in VRAM (the binary-search cap from ``_fit_context_to_vram``).
diff --git a/studio/backend/tests/test_mlx_inference_backend.py b/studio/backend/tests/test_mlx_inference_backend.py
index 880b29bc777..f8e7908fec7 100644
--- a/studio/backend/tests/test_mlx_inference_backend.py
+++ b/studio/backend/tests/test_mlx_inference_backend.py
@@ -1,6 +1,8 @@
# SPDX-License-Identifier: AGPL-3.0-only
+import asyncio
import contextlib
+import copy
import json
import subprocess
import sys
@@ -3283,3 +3285,666 @@ def test_rng_capture_stays_quiet_when_the_state_cannot_be_read(monkeypatch):
assert mlx_inference._mlx_rng_key_words() is None
assert warnings == []
+
+
+# Llama 3.1 carries the second beside its scaled window, mlx-lm's Kimi Linear the third.
[email protected]("name", ["n_ctx", "original_max_position_embeddings", "model_max_length"])
+def test_mlx_native_context_length_reads_every_spelling_and_every_config(name):
+ from core.inference.mlx_inference import mlx_native_context_length
+
+ # One term per family, matched by shape rather than by name.
+ args = SimpleNamespace(**{name: 40960})
+ assert mlx_native_context_length(SimpleNamespace(args = args)) == 40960
+ # Pre-load metadata answers by the same rule.
+ from routes.models import _get_max_position_embeddings
+
+ assert _get_max_position_embeddings(SimpleNamespace(**{name: 40960})) == 40960
+ # The wrapper counts too: mlx-vlm's Phi-3-V keeps a 4096 text config beside its real 131072.
+ stub = SimpleNamespace(args = SimpleNamespace(**{name: 4096}))
+ text = SimpleNamespace(**{name: 4096})
+ cfg = SimpleNamespace(model_type = "x", text_config = text, **{name: 131072})
+ vlm = SimpleNamespace(language_model = stub, config = cfg)
+ assert mlx_native_context_length(vlm) == 131072
+
+
+# Real enough for the capability classifier to read. The named one is the shape that made
+# classifying without tools wrong: its tool markup lives only in the tool_use branch.
+_PLAIN_TEMPLATE = "{% for m in messages %}{{ m['content'] }}{% endfor %}"
+_TOOL_TEMPLATE = (
+ "{% if tools %}{% for t in tools %}{{ t.function.name }}{% endfor %}{% endif %}"
+ "{% for m in messages %}{{ m['content'] }}"
+ "{% if m.tool_calls %}<tool_call>{{ m.tool_calls[0].function.name }}</tool_call>{% endif %}"
+ "{% endfor %}"
+)
+_NAMED_TOOL_TEMPLATE = {"default": _PLAIN_TEMPLATE, "tool_use": _TOOL_TEMPLATE}
+
+
+def _mirror(template = None):
+ """The parent's view of a worker-held MLX model, template included."""
+ return {
+ "mlx/model": {
+ "is_mlx": True,
+ "is_vision": False,
+ "is_audio": False,
+ "chat_template_info": {"template": template},
+ }
+ }
+
+
+class _RenderRecordingBackend:
+ active_model_name = "mlx/model"
+
+ def __init__(self):
+ self.messages = self.system = self.tools = None
+
+ def count_chat_tokens(
+ self,
+ messages,
+ system_prompt = "",
+ **kwargs,
+ ):
+ self.messages, self.system = messages, system_prompt
+ self.tools = kwargs.get("tools")
+ return 11, "mlx/model"
+
+
+def _count_route(
+ monkeypatch,
+ backend,
+ template = _TOOL_TEMPLATE,
+ models = None,
+ request = None,
+ generations = None,
+ **fields,
+):
+ """Drive the endpoint against `backend`, classifying from a real template."""
+ backend_dir = str(Path(__file__).resolve().parent.parent)
+ if backend_dir not in sys.path:
+ sys.path.insert(0, backend_dir)
+ from routes import inference as route
+
+ backend.models = models or _mirror(template)
+ monkeypatch.setattr(route, "get_inference_backend", lambda: backend)
+ monkeypatch.setattr(route, "get_llama_cpp_backend", lambda: SimpleNamespace(is_loaded = False))
+ monkeypatch.setattr(route.active_generations, "count", generations or (lambda: 0))
+ return asyncio.run(
+ route.chat_count_tokens(
+ route.ChatCountTokensRequest(**fields),
+ request = request,
+ current_subject = "tester",
+ )
+ )
+
+
+def test_an_mlx_count_is_served_where_llama_cpp_would_have_refused(monkeypatch):
+ """llama.cpp not being loaded used to be the whole answer, for vision models too."""
+ from fastapi import HTTPException
+
+ hello = [{"role": "user", "content": "hello"}]
+ served = _count_route(monkeypatch, _RenderRecordingBackend(), messages = hello)
+ assert json.loads(served.body) == {"input_tokens": 11, "model": "mlx/model"}
+ served = _count_route(
+ monkeypatch,
+ _RenderRecordingBackend(),
+ messages = hello,
+ models = {"mlx/model": {"is_mlx": True, "is_vision": True, "is_audio": False}},
+ )
+ assert json.loads(served.body)["input_tokens"] == 11
+
+ with pytest.raises(HTTPException) as refused:
+ _count_route(monkeypatch, _RenderRecordingBackend(), messages = [])
+ assert refused.value.status_code == 503
+
+
+ "template, expected_tools",
+ [
+ (_PLAIN_TEMPLATE, None),
+ (_TOOL_TEMPLATE, ["web_search"]),
+ # Tool markup only in tool_use: classifying with no tools reads `default`.
+ (_NAMED_TOOL_TEMPLATE, ["web_search"]),
+ ],
+ ids = ["renders-none", "renders-tools", "renders-tools-in-a-named-branch"],
+)
+def test_an_mlx_count_prices_the_tools_the_completion_would_render(
+ monkeypatch, template, expected_tools
+):
+ """`unsloth studio run` defaults tools on, so a count naming none inherits that: mostly
+ the nudge's length, but not stale markup the completion strips."""
+ from state import tool_policy
+
+ monkeypatch.setattr(tool_policy, "_tool_policy_default", True)
+ backend = _RenderRecordingBackend()
+ _count_route(
+ monkeypatch,
+ backend,
+ template = template,
+ messages = [
+ {"role": "user", "content": "hi"},
+ {"role": "assistant", "content": "sure <tool_call>{}</tool_call> done"},
+ ],
+ enabled_tools = ["web_search"],
+ )
+ names = None if backend.tools is None else [t["function"]["name"] for t in backend.tools]
+ assert names == expected_tools, "the count must render what the completion would"
+ if expected_tools is None:
+ assert not backend.system, "no tools rendered, so no nudge either"
+ return
+
+ from routes.inference import _apply_rag_nudge, _build_tool_action_nudge
+
+ plain = _build_tool_action_nudge(tools = backend.tools, model_name = "mlx/model", full_access = False)
+ nudge = asyncio.run(_apply_rag_nudge(plain, backend.tools, rag_scope = None))
+ assert backend.system == nudge
+ assert backend.messages[-1]["content"] == "sure done", "stale markup the completion removes"
+
+
+def test_an_mlx_count_prices_the_relay_the_tool_loop_did_not_claim(monkeypatch):
+ """A declined request carrying tool history goes to the relay, which keeps the
+ structured tool_calls the extraction flattens away."""
+ fn = {"name": "web_search", "arguments": '{"q": "x"}'}
+ call = {"id": "c1", "type": "function", "function": fn}
+ history = [
+ {"role": "user", "content": "hello"},
+ {"role": "assistant", "content": "", "tool_calls": [call]},
+ {"role": "tool", "tool_call_id": "c1", "content": "a result"},
+ ]
+
+ backend = _RenderRecordingBackend()
+ _count_route(monkeypatch, backend, messages = history, enable_tools = False)
+ assert backend.messages[1].get("tool_calls"), "the relay renders structured calls, not prose"
+ assert backend.messages[1]["tool_calls"][0]["function"]["arguments"] == {"q": "x"}
+ assert backend.tools is None, "the loop declined it, so no server catalog is rendered"
+
+ backend = _RenderRecordingBackend()
+ _count_route(
+ monkeypatch,
+ backend,
+ messages = [{"role": "developer", "content": ""}, *history],
+ enable_tools = False,
+ )
+ assert backend.messages[0]["role"] == "system"
+
+ backend = _RenderRecordingBackend()
+ _count_route(
+ monkeypatch,
+ backend,
+ messages = history,
+ enable_tools = False,
+ tools = [{"function": {"name": "mine", "parameters": {}}}],
+ )
+ assert backend.tools[0]["type"] == "function"
+
+ # Outside the MLX branch it returns before normalizing anything, yet the request
+ # still arrives normalized.
+ route = sys.modules["routes.inference"]
+ monkeypatch.setattr(route, "get_inference_backend", lambda: SimpleNamespace(models = {}))
+ payload = route.ChatCountTokensRequest(
+ messages = [{"role": "developer", "content": ""}],
+ tools = [{"function": {"name": "mine", "parameters": {}}}],
+ )
+ with contextlib.suppress(Exception):
+ asyncio.run(route.chat_count_tokens(payload, current_subject = "tester"))
+ assert payload.messages[0].role == "system"
+ assert payload.tools[0]["type"] == "function"
+
+
+def test_a_load_serves_the_request_or_the_window_the_model_was_trained_for():
+ """A request wins verbatim; asking for nothing takes the trained window; unreadable
+ dims resolve to nothing rather than to a number of their own."""
+ from core.inference.mlx_inference import MLXInferenceBackend
+
+ resolve = MLXInferenceBackend._resolve_context_lengths
+ wide = SimpleNamespace(args = SimpleNamespace(max_position_embeddings = 262144))
+ blank = SimpleNamespace(args = SimpleNamespace())
+ assert resolve(None, wide, 0) == (262144, 262144, 262144)
+ assert resolve(None, wide, 8192) == (8192, 262144, 262144)
+ assert resolve(None, wide, 1048576) == (1048576, 262144, 262144) # above native, still verbatim
+ held = SimpleNamespace(args = wide.args, max_seq_length = 4096)
+ assert resolve(None, held, 0) == (4096, 262144, 262144) # what the load attached wins
+ assert resolve(None, blank, 0) == (None, None, None)
+ assert resolve(None, blank, 8192) == (8192, None, None)
+
+
+def test_the_resident_context_gate_compares_requests_not_served_windows():
+ """Reuse on model identity alone leaves a context change with no reload to carry it.
+ Served windows cannot answer it: auto-sized to 32768 and pinned at 32768 are equal."""
+ backend_dir = str(Path(__file__).resolve().parent.parent)
+ if backend_dir not in sys.path:
+ sys.path.insert(0, backend_dir)
+ from routes.inference import _resident_context_satisfies as gate
+
+ # Absent or null: the mirror always writes the key, so reading presence alone would
+ # reload every transformers model on its own reuse path.
+ assert gate({}, 8192) is True
+ assert gate({"requested_context_length": None}, 8192) is True
+
+ # Same request, either spelling of "size it yourself".
+ assert gate({"requested_context_length": 8192}, 8192) is True
+ assert gate({"requested_context_length": 0}, 0) is True
+ assert gate({"requested_context_length": 0}, None) is True
+
+ # Different request: pinning and unpinning both reload.
+ assert gate({"requested_context_length": 0}, 8192) is False
+ assert gate({"requested_context_length": 8192}, 0) is False
+
+ # The served window is not the request and cannot stand in for it.
+ assert gate({"requested_context_length": 0, "context_length": 32768}, 32768) is False
+
+
+def test_the_load_policy_bounds_a_pin_only_where_the_bound_can_be_enforced(monkeypatch):
+ """mlx-lm cannot quantize a rotating cache (to_quantized raises, from the first token),
+ so exactly one applies. A pin is an explicit memory instruction; a self-chosen window
+ is not. An unenforceable pin buys nothing, so it does not spend the quantization."""
+ pytest.importorskip("mlx_lm.models.cache")
+ from core.inference import mlx_inference
+ from core.inference.mlx_inference import MLXInferenceBackend
+ from mlx_lm.models.cache import KVCache
+
+ # About the pin/enforceability combination, not the eligibility probe.
+ monkeypatch.setattr(
+ mlx_inference, "_kv_quant_eligibility", lambda *_a, **_k: ("full", "", True)
+ )
+ honours = SimpleNamespace(layers = [object(), object()])
+ # llama without sliding layers: quantizable, never bounded.
+ owns = SimpleNamespace(layers = [object(), object()], make_cache = lambda: [KVCache(), KVCache()])
+
+ unset = object()
+
+ def policy(
+ model,
+ kv_bits,
+ requested,
+ served = unset,
+ ):
+ backend = MLXInferenceBackend()
+ backend._model = model
+ backend._is_vlm = False
+ quant, window, enforced = backend._resolve_kv_policy(
+ False, kv_bits, requested, requested if served is unset else served
+ )
+ return quant["kv_bits"], window, enforced
+
+ assert policy(honours, 4, 8192) == (None, 8192, True) # enforceable pin outranks quant
+ # Auto yields to quantization, and a window that bounds nothing says so.
+ assert policy(honours, 4, 0, 262144) == (4, None, False)
+ assert policy(honours, None, 8192) == (None, 8192, True)
+ assert policy(honours, None, 0, 262144) == (None, 262144, True) # nothing to yield to
+
+ # An unenforceable pin spends nothing, and the verdict still travels to the API.
+ assert policy(owns, 4, 8192) == (4, None, False)
+ assert policy(owns, None, 8192) == (None, None, False)
+
+ # A window nobody could read bounds nothing rather than bounding at zero.
+ assert policy(honours, None, 0, None) == (None, None, False) # unreadable
+ assert policy(honours, None, 0, 0) == (None, None, False) # non-positive
+
+ # A shape the probe cannot judge is null, not a confirmed "not enforced".
+ unreadable = SimpleNamespace(layers = [object()], make_cache = lambda: None)
+ assert policy(unreadable, None, 8192) == (None, None, None)
+
+
+def test_quantization_is_refused_for_a_pinned_context_rather_than_raising_mid_stream():
+ """Left to mlx-lm this surfaces as NotImplementedError on the first generated token."""
+ from core.inference.mlx_inference import _kv_quant_status
+
+ status = _kv_quant_status(4, None, False, context_pinned = True)
+
+ assert status["kv_bits"] is None
+ assert status["eligibility"] == "refused"
+ assert "quantize a limited cache" in status["reason"]
+
+
+def test_the_bound_is_checked_on_a_real_cache_at_the_size_that_was_asked_for():
+ """make_cache ignores max_kv_size, and those caches range from constant-state to
+ unbounded, so the argument does not say whether it applied. Nor does an
+ architecture-chosen cap serve a narrower request."""
+ pytest.importorskip("mlx_lm.models.cache")
+ from core.inference.mlx_inference import _kv_window_enforced
+ from mlx_lm.models.cache import ArraysCache, ChunkedKVCache, KVCache, RotatingKVCache
+
+ honours = SimpleNamespace(layers = [object(), object()])
+ hybrid = SimpleNamespace(
+ layers = [object(), object()],
+ make_cache = lambda: [RotatingKVCache(1024), KVCache()],
+ )
+ undeclared = SimpleNamespace(layers = [object()], make_cache = lambda: [ArraysCache(2)])
+ chunked = SimpleNamespace(layers = [object()], make_cache = lambda: [ChunkedKVCache(512)])
+ native = SimpleNamespace(layers = [object()], make_cache = lambda: [RotatingKVCache(2048)])
+ # mlx-vlm's Florence2: tuples of a class that concatenates forever.
+ nested = SimpleNamespace(
+ layers = [object()],
+ make_cache = lambda: [(SimpleNamespace(keys = None), SimpleNamespace(keys = None))],
+ )
+
+ assert _kv_window_enforced(honours, False, 4096) is True
+ assert _kv_window_enforced(hybrid, False, 4096) is False # a full-attention layer survives
+ assert _kv_window_enforced(chunked, False, 4096) is True
+ # Nothing that declares no cap is taken on trust, however it is packaged.
+ assert _kv_window_enforced(undeclared, False, 4096) is False
+ assert _kv_window_enforced(nested, False, 4096) is False
+ # Recurrent Gemma: its own window outlives a narrower pin.
+ assert _kv_window_enforced(native, False, 128) is False
+ assert _kv_window_enforced(native, False, 4096) is True
+ # A window a rotating cache cannot rotate within retains everything instead.
+ assert _kv_window_enforced(honours, False, 4) is False
+ assert _kv_window_enforced(SimpleNamespace(), False, 4096) is None # unreadable
+ # The VLM branch reaches mlx-vlm's factory and unwraps the language tower.
+ assert _kv_window_enforced(SimpleNamespace(language_model = honours), True, 4096) is True
+
+
+def test_the_probe_reads_a_cache_shape_without_needing_the_mlx_wheels(monkeypatch):
+ """Same branches as the real-cache test, through an injected factory. That one
+ importorskips, so it proves nothing without mlx; this runs everywhere."""
+ from core.inference.mlx_inference import _kv_window_enforced
+
+ def factory(make):
+ """Stand in for mlx_lm.models.cache, present or not; return a model."""
+ cache_mod = types.ModuleType("mlx_lm.models.cache")
+ cache_mod.make_prompt_cache = make
+ models_mod = types.ModuleType("mlx_lm.models")
+ models_mod.cache = cache_mod
+ root = types.ModuleType("mlx_lm")
+ root.models = models_mod
+ for name, module in (
+ ("mlx_lm", root),
+ ("mlx_lm.models", models_mod),
+ ("mlx_lm.models.cache", cache_mod),
+ ):
+ monkeypatch.setitem(sys.modules, name, module)
+ return SimpleNamespace(layers = [object()])
+
+ def caches(*entries):
+ return factory(lambda _model, max_kv_size = None: list(entries))
+
+ bounded = SimpleNamespace(max_size = 4096, keep = 4)
+ wider = SimpleNamespace(max_size = 8192, keep = 4)
+ undeclared = SimpleNamespace()
+ unrotatable = SimpleNamespace(max_size = 4, keep = 4)
+ chunked = SimpleNamespace(chunk_size = 512)
+
+ assert _kv_window_enforced(caches(bounded, bounded), False, 4096) is True
+ assert _kv_window_enforced(caches(bounded, undeclared), False, 4096) is False
+ assert _kv_window_enforced(caches(wider), False, 4096) is False
+ assert _kv_window_enforced(caches(unrotatable), False, 4096) is False
+ assert _kv_window_enforced(caches(chunked), False, 4096) is True
+ assert _kv_window_enforced(caches(), False, 4096) is False
+ # A factory that answers with a shape this cannot walk is unknown, not a failed load.
+ for broken in (None, object(), SimpleNamespace(caches = 7)):
+ model = factory(lambda _m, max_kv_size = None, _b = broken: _b)
+ assert _kv_window_enforced(model, False, 4096) is None
+
+
+def test_the_window_reaches_the_runtime_on_every_generation_route(monkeypatch):
+ """The runtimes read max_kv_size only when no prompt_cache is passed, so each route
+ building its own cache carries the bound. The audio route once did not."""
+ import types as _types
+
+ from core.inference.mlx_inference import MLXInferenceBackend
+
+ kwargs = MLXInferenceBackend._kv_window_generate_kwargs
+ assert kwargs(SimpleNamespace(_kv_cache_window = None)) == {}
+ assert kwargs(SimpleNamespace()) == {}
+ assert kwargs(SimpleNamespace(_kv_cache_window = 8192)) == {"max_kv_size": 8192}
+
+ # The prompt-cache history builds its own cache; it has to carry the window too.
+ pytest.importorskip("mlx_lm.models.cache")
+ from core.inference.mlx_inference import _MLXPromptCacheHistory
+
+ model = SimpleNamespace(layers = [object(), object()])
+ bounded = _MLXPromptCacheHistory(4, 1 << 20, 512).fetch(model, "k", [1, 2])[0]
+ unbounded = _MLXPromptCacheHistory(4, 1 << 20, None).fetch(model, "k", [1, 2])[0]
+ assert {getattr(e, "max_size", None) for e in bounded} == {512}
+ assert {getattr(e, "max_size", None) for e in unbounded} == {None}
+
+ captured: list = []
+ backend = _install_fake_text_stack(monkeypatch, {"P1": [1], "generated": [1]}, captured)
+ backend._kv_cache_window = 8192
+ _run_turn(backend, "P1")
+ assert captured[0]["max_kv_size"] == 8192
+
+ seen: list = []
+
+ def _vlm_stream(*_args, **kw):
+ seen.append(kw)
+ yield SimpleNamespace(text = "ok", prompt_tokens = 1, generation_tokens = 1)
+
+ mlx_vlm = _types.ModuleType("mlx_vlm")
+ mlx_vlm.stream_generate = _vlm_stream
+ mlx_vlm.prompt_utils = SimpleNamespace(
+ MODEL_CONFIG = {"m": object()},
+ apply_chat_template = lambda *_a, **_k: "<image> p",
+ )
+ monkeypatch.setitem(sys.modules, "mlx_vlm", mlx_vlm)
+ monkeypatch.setattr(
+ "core.inference.mlx_inference._temporary_mlx_adapter_state",
+ lambda _m, _s: contextlib.nullcontext(),
+ )
+ vlm = MLXInferenceBackend()
+ vlm._kv_cache_window = 4096
+ vlm._model = SimpleNamespace(config = {"model_type": "m"})
+ vlm._processor = SimpleNamespace(tokenizer = SimpleNamespace())
+ next(
+ vlm._generate_vlm(
+ [{"role": "user", "content": [{"type": "image"}]}],
+ object(),
+ 0,
+ 1,
+ 0,
+ 0,
+ 1,
+ 1,
+ None,
+ _adapter_state = False,
+ )
+ )
+ assert seen[-1]["max_kv_size"] == 4096
+
+ vlm.active_model_name = "m"
+ vlm.models["m"] = {"audio_type": "audio_vlm"}
+ next(vlm.generate_audio_input_response([{"role": "user", "content": "x"}], "", object()))
+ assert seen[-1]["max_kv_size"] == 4096, "the audio route must carry the bound too"
+
+
+class _BlockMLX:
+ """Make `import mlx_lm...` fail the way it does on a box without the wheels."""
+
+ def __init__(self, *names):
+ self.names = names
+
+ def find_spec(
+ self,
+ fullname,
+ path = None,
+ target = None,
+ ):
+ if fullname in self.names or fullname.startswith(tuple(f"{n}." for n in self.names)):
+ raise ModuleNotFoundError(f"No module named {fullname!r}", name = fullname)
+ return None
+
+
+@contextmanager
+def _without_mlx(*names):
+ blocker = _BlockMLX(*names)
+ dropped = {k: v for k, v in sys.modules.items() if k.split(".")[0] in names}
+ for key in dropped:
+ del sys.modules[key]
+ sys.meta_path.insert(0, blocker)
+ try:
+ yield
+ finally:
+ sys.meta_path.remove(blocker)
+ sys.modules.update(dropped)
+
+
+def test_the_mlx_module_imports_on_a_machine_with_no_mlx_wheels():
+ """Linux and Windows import this tree without mlx. The backend is constructed behind
+ the Darwin gate, but an mlx import at module scope would fail every non-Mac boot."""
+ import importlib
+
+ with _without_mlx("mlx", "mlx_lm", "mlx_vlm"):
+ module = importlib.reload(importlib.import_module("core.inference.mlx_inference"))
+ assert (
+ module.mlx_native_context_length(
+ SimpleNamespace(config = SimpleNamespace(max_position_embeddings = 131072))
+ )
+ == 131072
+ )
+ importlib.reload(module)
+
+
+def test_the_probe_answers_unknown_rather_than_raising_without_mlx():
+ """Nothing can be built to judge, which is "unknown", not "unbounded"."""
+ from core.inference.mlx_inference import _kv_window_enforced
+ with _without_mlx("mlx", "mlx_lm", "mlx_vlm"):
+ assert _kv_window_enforced(SimpleNamespace(layers = [object()]), False, 4096) is None
+
+
+def test_an_mlx_count_prices_the_current_date_the_completion_prepends(monkeypatch):
+ """The completion applies this once for both non-GGUF backends before it branches, so
+ skipping it under-reports every interactive MLX prompt and the usage bar claims room."""
+ from starlette.datastructures import Headers
+
+ # No API key, which is what makes the prompt Studio's to compose.
+ interactive = SimpleNamespace(headers = Headers({}), query_params = {}, cookies = {})
+ backend = _RenderRecordingBackend()
+ _count_route(
+ monkeypatch,
+ backend,
+ template = _PLAIN_TEMPLATE,
+ request = interactive,
+ messages = [{"role": "user", "content": "hi"}],
+ )
+ from routes.inference import current_date_prompt_line
+
+ line = current_date_prompt_line(request = interactive)
+ assert line, "the harness must actually produce a date line"
+ assert backend.system.startswith(
+ line
+ ), f"the count dropped the date line the completion prepends: {backend.system!r}"
+
+
+def test_an_mlx_count_prices_the_archive_tool_and_its_compaction_nudge(monkeypatch):
+ """An archive adds search_conversation and a compaction nudge, both gated on the
+ thread id, so a count that drops it under-reports."""
+ from routes import inference as route
+ from state import tool_policy
+
+ monkeypatch.setattr(tool_policy, "_tool_policy_default", True)
+ monkeypatch.setattr(route, "_thread_has_conversation_archive", lambda tid: bool(tid))
+ backend = _RenderRecordingBackend()
+ _count_route(
+ monkeypatch,
+ backend,
+ template = _TOOL_TEMPLATE,
+ messages = [{"role": "user", "content": "hi"}],
+ enabled_tools = ["web_search"],
+ thread_id = "thread-with-an-archive",
+ )
+ names = [t["function"]["name"] for t in (backend.tools or [])]
+ assert (
+ "search_conversation" in names
+ ), f"the archive tool the completion renders was not priced: {names}"
+ from routes.inference import _apply_compaction_nudge
+
+ assert _apply_compaction_nudge("", backend.tools), "the nudge must be non-empty here"
+ assert (
+ _apply_compaction_nudge("", backend.tools) in backend.system
+ ), "the count omitted the compaction nudge the completion appends"
+
+
+def test_an_mlx_count_prices_the_date_an_api_key_tool_loop_still_gets(monkeypatch):
+ """`_wants_current_date` is false for an API-key request, but the tool-loop completion
+ reapplies it with include_api_key, so a count that did not would be short that line."""
+ from starlette.datastructures import Headers
+ from state import tool_policy
+
+ monkeypatch.setattr(tool_policy, "_tool_policy_default", True)
+ keyed = SimpleNamespace(
+ headers = Headers({"authorization": "Bearer sk-unsloth-test"}),
+ query_params = {},
+ cookies = {},
+ )
+ backend = _RenderRecordingBackend()
+ _count_route(
+ monkeypatch,
+ backend,
+ template = _TOOL_TEMPLATE,
+ request = keyed,
+ enabled_tools = ["web_search"],
+ messages = [{"role": "user", "content": "hi"}],
+ )
+ from routes.inference import current_date_prompt_line
+
+ line = current_date_prompt_line(request = keyed)
+ assert line, "the harness must produce a date line"
+ assert (
+ line in backend.system
+ ), f"the count dropped the date the tool-loop completion adds: {backend.system!r}"
+
+
+def test_an_mlx_count_reports_the_advertised_model_id(monkeypatch):
+ """The caller drops a count naming a different model, so one loaded from a resolved
+ path must still answer as the repo id."""
+ from routes import inference as route
+
+ backend = _RenderRecordingBackend()
+ monkeypatch.setattr(route, "_orchestrator_public_model_id", lambda _b: "org/advertised-repo-id")
+ served = _count_route(monkeypatch, backend, messages = [{"role": "user", "content": "hello"}])
+ assert json.loads(served.body)["model"] == "org/advertised-repo-id"
+
+
+def test_an_mlx_count_is_dropped_when_a_same_model_reload_lands_under_it(monkeypatch):
+ """The active name cannot see a same-ID reload, which is how a template override lands.
+ A count routed from the old entry must not be published."""
+ from fastapi import HTTPException
+ from routes import inference as route
+
+ backend = _RenderRecordingBackend()
+ backend.load_generation = 7
+
+ real_count = backend.count_chat_tokens
+
+ def _reload_midway(*args, **kwargs):
+ # Lands while the tokenizer runs: same name, new generation.
+ backend.load_generation = 8
+ return real_count(*args, **kwargs)
+
+ backend.count_chat_tokens = _reload_midway
+ with pytest.raises(HTTPException) as excinfo:
+ _count_route(monkeypatch, backend, messages = [{"role": "user", "content": "hi"}])
+ assert excinfo.value.status_code == 503
+ assert "changed while counting" in str(excinfo.value.detail)
+
+
+def test_an_mlx_count_yields_to_a_generation_that_started_while_it_prepared(monkeypatch):
+ """Everything between admission and the tokenizer awaits, so a chat starting in the gap
+ would wait behind this count for the orchestrator lock. GGUF re-checks; this must too."""
+ from fastapi import HTTPException
+ from routes import inference as route
+
+ backend = _RenderRecordingBackend()
+ counts = iter([0, 1]) # admitted at the entry check, busy by the last checkpoint
+ with pytest.raises(HTTPException) as excinfo:
+ _count_route(
+ monkeypatch,
+ backend,
+ generations = lambda: next(counts, 1),
+ messages = [{"role": "user", "content": "hi"}],
+ )
+ assert excinfo.value.status_code == 503
+ assert "generation is in progress" in str(excinfo.value.detail)
+
+
+def test_the_mlx_mcp_snapshot_is_taken_under_the_same_guard_the_gguf_count_uses():
+ """The MCP handlers hold this guard across the row change and the schema-cache
+ invalidation, so a snapshot outside it can pair a new row with a stale schema."""
+ import inspect
+
+ from routes import inference as route
+
+ body = inspect.getsource(route._mlx_count_chat_tokens)
+ assert "mcp_server_snapshot_guard" in body, "the MLX snapshot is unguarded"
+ guard = body.index("async with mcp_server_snapshot_guard():")
+ snapshot = body.index("asyncio.to_thread(cached_mcp_tools)")
+ assert guard < snapshot, "the guard must be held across the snapshot, not after it"
diff --git a/studio/backend/tests/test_native_context_length.py b/studio/backend/tests/test_native_context_length.py
index 25b6a4882d2..28279c91e1b 100644
--- a/studio/backend/tests/test_native_context_length.py
+++ b/studio/backend/tests/test_native_context_length.py
@@ -12,6 +12,7 @@ Needs no GPU, network, or libraries beyond pytest and pydantic.
import io
import json
+import re
import struct
import sys
import types as _types
@@ -36,6 +37,9 @@ sys.modules.setdefault("loggers", _loggers_stub)
# structlog
_structlog_stub = _types.ModuleType("structlog")
+_structlog_stub.get_logger = lambda *a, **kw: __import__("logging").getLogger(
+ a[0] if a else __name__
+)
sys.modules.setdefault("structlog", _structlog_stub)
# httpx -- stub only names referenced at import / class-definition time
@@ -420,16 +424,20 @@ class TestRouteCompleteness:
), f"GGUF LoadResponse block #{i} missing runtime fields:\n{block[:200]}"
assert "for name in _InferenceRuntimeFields.model_fields" in self._source
- def test_non_gguf_load_responses_omit_field(self):
- """Non-GGUF LoadResponse blocks do not set native_context_length (defaults to None)."""
+ def test_non_gguf_load_responses_report_the_native_window(self):
+ """Non-GGUF LoadResponse blocks carry native_context_length and max_context_length.
+
+ These once had to be absent, back when only GGUF knew its own window; a non-GGUF
+ block that leaves them off now defaults them to None and blanks the control.
+ """
blocks = self._find_construction_blocks("LoadResponse")
non_gguf = [b for b in blocks if "is_gguf = True" not in b and "is_gguf=True" not in b]
- # Non-GGUF paths shouldn't reference native_context_length
- # (Pydantic defaults it to None, so omitting it is correct).
+ assert non_gguf, "Expected at least one non-GGUF LoadResponse block"
for block in non_gguf:
- assert (
- "native_context_length" not in block
- ), f"Non-GGUF LoadResponse should not set native_context_length:\n{block[:200]}"
+ for field in ("native_context_length", "max_context_length"):
+ assert re.search(
+ rf"{field} = _positive_int_or_none\(\s*_model_info\.get\(", block
+ ), f"Non-GGUF LoadResponse should read {field} from _model_info:\n{block[:200]}"
def test_non_gguf_load_responses_set_runtime_context_length(self):
"""Non-GGUF LoadResponse blocks report runtime context_length."""
@@ -584,3 +592,25 @@ class TestCrossPlatform:
json2 = resp.model_dump_json()
assert json1 == json2
assert '"native_context_length":131072' in json1
+
+
+def test_the_status_route_reports_what_a_self_sizing_load_asked_for():
+ """The UI re-seeds its context pin from it, because the resolved window cannot say
+ whether anyone chose that length; without it a pin is invisible after a refresh."""
+ route_src = (Path(__file__).resolve().parents[1] / "routes" / "inference.py").read_text(
+ encoding = "utf-8"
+ )
+ assert "requested_context_length = llama_backend.requested_n_ctx" in route_src
+ # 0 is "size it yourself"; None is "records no request", and the UI tells them apart.
+ # Either spelling of the recorded request, since the route stamps one and the MLX
+ # mirror carries the other, but always through the non-negative reader.
+ assert (
+ "requested_context_length = _nonnegative_int_or_none(\n"
+ ' model_info.get("requested_context_length")\n'
+ ' if model_info.get("requested_context_length") is not None\n'
+ ' else model_info.get("max_seq_length_requested")\n'
+ " )," in route_src
+ )
+ # The parent cannot recompute the group once the worker holds the model: it mirrors all.
+ src = (Path(__file__).resolve().parents[1] / "core/inference/worker.py").read_text("utf-8")
+ assert '"native_context_length",\n "max_context_length",' in src
diff --git a/studio/backend/tests/test_rag_retrieval.py b/studio/backend/tests/test_rag_retrieval.py
index a2b8ffb7313..71230d322e7 100644
--- a/studio/backend/tests/test_rag_retrieval.py
+++ b/studio/backend/tests/test_rag_retrieval.py
@@ -326,6 +326,12 @@ def test_search_for_autoinject_bm25_gates_on_dense_probe(rag_conn, bow_embedding
)
+def _rag_is_available(monkeypatch, rag_db) -> None:
+ # The import flag, and the connection check the pre-retrieval gate asks.
+ monkeypatch.setattr(rag_db, "RAG_AVAILABLE", True, raising = False)
+ monkeypatch.setattr(rag_db, "rag_available", lambda: True, raising = False)
+
+
def test_search_for_autoinject_empty_query_or_scope(rag_home):
assert tool.search_for_autoinject(query = " ", scope_kb_id = "a") is None
assert tool.search_for_autoinject(query = "hello") is None # no scope
@@ -336,7 +342,7 @@ def test_build_rag_autoinject_emits_pipeline(monkeypatch):
from core.inference import tools
from storage import rag_db
- monkeypatch.setattr(rag_db, "RAG_AVAILABLE", True, raising = False)
+ _rag_is_available(monkeypatch, rag_db)
monkeypatch.setattr(
tool,
"search_for_autoinject",
@@ -361,7 +367,7 @@ def test_build_rag_autoinject_skips_without_hit(monkeypatch):
from core.inference import tools
from storage import rag_db
- monkeypatch.setattr(rag_db, "RAG_AVAILABLE", True, raising = False)
+ _rag_is_available(monkeypatch, rag_db)
monkeypatch.setattr(tool, "search_for_autoinject", lambda **k: None)
assert (
tools.build_rag_autoinject([{"role": "user", "content": "hi"}], {"thread_id": "t1"}) is None
@@ -374,7 +380,7 @@ def test_build_rag_autoinject_enabled_by_default(monkeypatch):
monkeypatch.delenv("RAG_AUTOINJECT", raising = False)
monkeypatch.delenv("RAG_AUTOINJECT_MIN_SCORE", raising = False)
- monkeypatch.setattr(rag_db, "RAG_AVAILABLE", True, raising = False)
+ _rag_is_available(monkeypatch, rag_db)
seen: dict = {}
def fake(**k):
@@ -393,7 +399,7 @@ def test_build_rag_autoinject_caps_top_k(monkeypatch):
monkeypatch.setenv("RAG_AUTOINJECT", "1")
monkeypatch.setenv("RAG_AUTOINJECT_TOP_K", "4")
- monkeypatch.setattr(rag_db, "RAG_AVAILABLE", True, raising = False)
+ _rag_is_available(monkeypatch, rag_db)
seen: dict = {}
def fake(**k):
@@ -462,7 +468,7 @@ def test_scope_overrides_reach_retrieval(monkeypatch):
from core.inference import tools
from storage import rag_db
- monkeypatch.setattr(rag_db, "RAG_AVAILABLE", True, raising = False)
+ _rag_is_available(monkeypatch, rag_db)
seen: dict = {}
def fake_search(**kw):
@@ -486,7 +492,7 @@ def test_build_rag_autoinject_scope_overrides_env(monkeypatch):
from core.inference import tools
from storage import rag_db
- monkeypatch.setattr(rag_db, "RAG_AVAILABLE", True, raising = False)
+ _rag_is_available(monkeypatch, rag_db)
seen: dict = {}
def fake_autoinject(**k):
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 27821afcaaa..42613a66b60 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -22,7 +22,11 @@ import {
listLocalModels,
} from "@/features/hub/inventory/api";
import { isHiddenModelId } from "@/features/hub/lib/hidden-models";
-import { resolveInitialConfig } from "@/features/model-picker";
+import {
+ isServedByMlx,
+ loadedContextFields,
+ resolveInitialConfig,
+} from "@/features/model-picker";
import { isMlxId } from "@/features/model-picker/components/model-selector/recommended-fit";
import { loadManagedLlamaFlags } from "@/features/model-picker/api/llama-flags";
import { fetchLoadExtraArgs } from "@/features/model-picker/api/model-overrides";
@@ -161,8 +165,13 @@ import {
useChatRuntimeStore,
} from "../stores/chat-runtime-store";
import {
+ loadedContextForParams,
+ localMaxTokensCeiling,
+ unreportedWindowMaxTokens,
resolveFitMaxSeqLength,
resolveExplicitCtxPin,
+ retainedContextPin,
+ replayMaxTokensCap,
} from "../presets/preset-policy";
import { ensureGpuDeviceCache } from "@/hooks/use-gpu-info";
import { useExternalProvidersStore } from "../stores/external-providers-store";
@@ -1927,8 +1936,19 @@ export async function buildLocalTokenCountExtras(
autoHealToolCalls,
bypassPermissions,
deepResearchEnabled,
+ permissionMode,
+ maxToolCallsPerMessage,
+ ragAutoInject,
+ ragAutoInjectMinScore,
+ residentCheckpoint,
} = useChatRuntimeStore.getState();
- if (!supportsTools) return {};
+ // Explicit false, as the completion sends: an omitted field lets the launcher's
+ // tools-on default answer and the server renders a catalog the completion does not.
+ // No budget, because the completion sends none either, so a policy that injects tools
+ // past this false gets the server default on both sides.
+ if (!supportsTools) {
+ return { enable_tools: false, bypass_permissions: bypassPermissions };
+ }
const ragProjectId = await resolveProjectId(threadId);
const projectRagEnabled = ragProjectId
@@ -1957,6 +1977,11 @@ export async function buildLocalTokenCountExtras(
enable_tools: true,
// Auto-Heal off leaves leaked tool markup in the real prompt, so the count keeps it.
auto_heal_tool_calls: autoHealToolCalls,
+ // Ask holds first-pass retrieval behind the gate, so the count prices a pending RAG
+ // turn rather than declining one the completion never retrieves for.
+ permission_mode: permissionMode,
+ // Off suppresses the loop, and the relay renders no schemas or nudge: same zero.
+ max_tool_calls_per_message: maxToolCallsPerMessage,
// Full access swaps the python/terminal descriptions and adds a nudge
// sentence, so the count needs the flag to price the same prompt.
bypass_permissions: bypassPermissions,
@@ -1967,9 +1992,13 @@ export async function buildLocalTokenCountExtras(
...(artifactsEnabled ? ["render_html"] : []),
],
mcp_enabled: mcpEnabledForChat,
+ // Top level, not inside rag_scope: an archived thread puts search_conversation and its
+ // compaction nudge in the prompt whether or not RAG is on, and the completion sends it here.
+ ...(threadId ? { thread_id: threadId } : {}),
// Armed research puts the deep_research schema in the prompt, so the count carries it.
...(deepResearchEnabled ? { deep_research_armed: true } : {}),
- // the ids name the attached documents in the nudge server-side; no retrieval runs for a count.
+ // Keeps search_knowledge_base and its grounding nudge in the prompt. No retrieval runs for
+ // a count, but the scope's ids and switches are read to decide whether one would.
...(ragOn
? {
rag_scope: {
@@ -1985,6 +2014,11 @@ export async function buildLocalTokenCountExtras(
// and {} is falsy in Python, so the count alone would drop the tool and its nudge.
default_top_k: ragTopK,
mode: ragMode,
+ // Retrieval turned off means the loop renders exactly these messages, so the
+ // count can price the turn instead of declining a retrieval that never runs.
+ autoinject: resolveAutoInject(ragAutoInject, residentCheckpoint ?? ""),
+ autoinject_min_score: ragAutoInjectMinScore,
+ ...(ragAutoInject === "off" ? { whole_doc: false } : {}),
},
}
: {}),
@@ -2245,7 +2279,7 @@ type QueuedResolvedModelRuntime = {
>["reasoningEffortLevels"];
supportsPreserveThinking: boolean;
preserveThinking: boolean;
- ggufContextLength: number | null;
+ loadedContextLength: number | null;
loadedIsMultimodal: boolean;
modelCapabilities: QueuedModelCapabilities | null;
};
@@ -2259,9 +2293,11 @@ const VISIBLE_MODEL_RUNTIME_KEYS = [
"activeLoadId",
"activeGgufVariant",
"activeModelIsLocal",
- "ggufContextLength",
- "ggufMaxContextLength",
- "ggufNativeContextLength",
+ "loadedContextLength",
+ "maxContextLength",
+ "nativeContextLength",
+ "loadedIsGguf",
+ "loadedIsMlx",
"modelRequiresTrustRemoteCode",
"supportsReasoning",
"reasoningAlwaysOn",
@@ -2389,7 +2425,7 @@ function queuedResolvedModelFromStore(
reasoningEffortLevels: state.reasoningEffortLevels,
supportsPreserveThinking: state.supportsPreserveThinking,
preserveThinking: state.preserveThinking,
- ggufContextLength: state.ggufContextLength,
+ loadedContextLength: state.loadedContextLength,
loadedIsMultimodal: state.loadedIsMultimodal,
modelCapabilities: activeModel
? {
@@ -3080,15 +3116,22 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
candidate.id,
candidate.ggufVariant,
);
+ const platform = usePlatformStore.getState();
const effectiveMaxSeqLength = resolveLoadMaxSeqLength({
modelId: candidate.id,
ggufVariant: candidate.ggufVariant,
isGguf: candidate.kind === "gguf",
customContextLength: config.customContextLength,
- ggufContextLength: null,
+ loadedContextLength: null,
currentCheckpoint: currentStore.params.checkpoint,
activeGgufVariant: currentStore.activeGgufVariant,
- maxSeqLength: config.maxSeqLength ?? candidate.maxSeqLength,
+ isMlx: isServedByMlx(
+ candidate.kind === "gguf",
+ platform.deviceType,
+ platform.chatOnlyReason,
+ ),
+ pinnedMaxSeqLength: config.maxSeqLength,
+ defaultMaxSeqLength: candidate.maxSeqLength,
presetSource: currentStore.activePresetSource,
});
// The GPU knobs are per-model, so read them from the same per-model config
@@ -3268,6 +3311,15 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
);
return false;
}
+ const autoLoadPin = retainedContextPin({
+ isMlx: isServedByMlx(
+ candidate.kind === "gguf",
+ platform.deviceType,
+ platform.chatOnlyReason,
+ ),
+ // What the load asked for, so a pin carried in either field is kept.
+ requestedContextLength: fitMaxSeqLength,
+ });
loadAttempts += 1;
options?.abortSignal?.throwIfAborted();
const loadResp = await loadModel({
@@ -3345,26 +3397,36 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
store.setModelRequiresTrustRemoteCode(
loadResp.requires_trust_remote_code ?? false,
);
+ // The window the model serves. Neither backend's own request will do: when it
+ // sizes its own window that request is the auto-size sentinel.
+ const loadedWindow = loadedContextForParams(
+ loadedContextFields(loadResp).loadedContextLength,
+ effectiveMaxSeqLength,
+ store.params.maxSeqLength,
+ );
store.setParams(
{
...store.params,
- ...(candidate.kind === "gguf"
- ? {}
- : { maxSeqLength: effectiveMaxSeqLength }),
- maxTokens:
- candidate.kind === "gguf"
- ? (loadResp.context_length ?? 131072)
- : effectiveMaxSeqLength,
+ ...(candidate.kind === "gguf" ? {} : { maxSeqLength: loadedWindow }),
+ // Through the ceiling, so the value and its slider agree at both ends. The app
+ // default would halve Max Tokens for a model whose record carries a longer one.
+ maxTokens: localMaxTokensCeiling(
+ loadedContextFields(loadResp).loadedContextLength,
+ loadedWindow,
+ ),
},
{
persist: !options?.preserveVisibleSettings,
trackQueuedSettings: !options?.preserveVisibleSettings,
fromModelDefaults: true,
- // A budget remembered from a larger context does not fit this load.
- maxTokensCap:
+ // A budget remembered from a larger context does not fit this load. The
+ // window, not the request: a backend that sizes its own was sent the
+ // auto-size sentinel, which as a budget is zero.
+ maxTokensCap: replayMaxTokensCap(
candidate.kind === "gguf"
- ? (loadResp.context_length ?? undefined)
- : effectiveMaxSeqLength,
+ ? loadedContextFields(loadResp).loadedContextLength
+ : loadedWindow,
+ ),
},
);
// Upsert: a pre-load catalog entry has no backend-derived audio
@@ -3389,10 +3451,7 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
const committedNUbatch =
(loadResp.is_diffusion ?? false) ? null : (config.nUbatch ?? null);
useChatRuntimeStore.setState({
- ggufContextLength: loadResp.context_length ?? 131072,
- ggufMaxContextLength:
- loadResp.max_context_length ?? loadResp.context_length ?? 131072,
- ggufNativeContextLength: loadResp.native_context_length ?? null,
+ ...loadedContextFields(loadResp),
supportsReasoning: loadResp.supports_reasoning ?? false,
reasoningAlwaysOn: loadResp.reasoning_always_on ?? false,
reasoningEnabled: loadResp.supports_reasoning ?? false,
@@ -3484,7 +3543,14 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
defaultChatTemplate: loadResp.chat_template ?? null,
chatTemplateOverride: effectiveChatTemplateOverride,
loadedChatTemplateOverride: effectiveChatTemplateOverride,
- customContextLength: null,
+ // The whole of the previous model's serving state, not just the window: a
+ // retained lease token still reads as a GGUF pick. This model's own pin is
+ // kept, though -- clearing it would reload it auto-sized next time.
+ customContextLength: autoLoadPin,
+ loadedCustomContextLength: autoLoadPin,
+ ...loadedContextFields(loadResp),
+ activeNativePathToken: null,
+ activeNativePathExpiresAtMs: null,
...resolveLoadedSpeculativeSettings(loadResp),
loadedIsMultimodal: isMultimodalResponse(loadResp),
mmprojFallbackReason: loadResp.mmproj_fallback_reason ?? null,
@@ -3754,13 +3820,18 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
store.setParams(
{
...store.params,
- maxTokens: loadResp.context_length ?? 131072,
+ maxTokens: localMaxTokensCeiling(
+ loadedContextFields(loadResp).loadedContextLength,
+ unreportedWindowMaxTokens(loadResp.is_gguf ?? false, store.params.maxTokens),
+ ),
},
{
persist: !options?.preserveVisibleSettings,
trackQueuedSettings: !options?.preserveVisibleSettings,
fromModelDefaults: true,
- maxTokensCap: loadResp.context_length ?? undefined,
+ maxTokensCap: replayMaxTokensCap(
+ loadedContextFields(loadResp).loadedContextLength,
+ ),
},
);
const defaultModel: ChatModelRow = {
@@ -3777,9 +3848,7 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
store.setModels([...store.models, defaultModel]);
}
useChatRuntimeStore.setState({
- ggufContextLength: loadResp.context_length ?? 131072,
- ggufMaxContextLength:
- loadResp.max_context_length ?? loadResp.context_length ?? 131072,
+ ...loadedContextFields(loadResp),
supportsReasoning: loadResp.supports_reasoning ?? false,
reasoningAlwaysOn: loadResp.reasoning_always_on ?? false,
reasoningEnabled: loadResp.supports_reasoning ?? false,
@@ -3898,9 +3967,7 @@ async function resolveQueuedEmptyLocalModel(abortSignal: AbortSignal): Promise<{
supportsPreserveThinking:
status.supports_preserve_thinking ?? false,
preserveThinking: resolvePreserveThinkingOnLoad(status),
- ggufContextLength: status.is_gguf
- ? (status.context_length ?? null)
- : null,
+ loadedContextLength: loadedContextFields(status).loadedContextLength,
loadedIsMultimodal: isMultimodalResponse(status),
modelCapabilities: {
isVision: status.is_vision ?? false,
@@ -4147,7 +4214,7 @@ export function createOpenAIStreamAdapter(
supportsPreserveThinking:
queuedEmptyModelRuntime.supportsPreserveThinking,
preserveThinking: queuedEmptyModelRuntime.preserveThinking,
- ggufContextLength: queuedEmptyModelRuntime.ggufContextLength,
+ loadedContextLength: queuedEmptyModelRuntime.loadedContextLength,
models: mergeQueuedModelCapabilities(
base.models,
queuedEmptyModelRuntime.checkpoint,
@@ -4528,10 +4595,10 @@ export function createOpenAIStreamAdapter(
preserveThinking:
queuedEmptyModelRuntime?.preserveThinking ??
liveRuntime.preserveThinking,
- ggufContextLength:
+ loadedContextLength:
queuedEmptyModelRuntime !== null
- ? queuedEmptyModelRuntime.ggufContextLength
- : liveRuntime.ggufContextLength,
+ ? queuedEmptyModelRuntime.loadedContextLength
+ : liveRuntime.loadedContextLength,
loadedIsMultimodal:
queuedEmptyModelRuntime?.loadedIsMultimodal ??
liveRuntime.loadedIsMultimodal,
@@ -6092,7 +6159,7 @@ export function createOpenAIStreamAdapter(
? { whole_doc: false }
: {}),
context_length:
- runtime.ggufContextLength ??
+ runtime.loadedContextLength ??
params.maxSeqLength ??
undefined,
},
@@ -6314,7 +6381,7 @@ export function createOpenAIStreamAdapter(
? { whole_doc: false }
: {}),
context_length:
- runtime.ggufContextLength ??
+ runtime.loadedContextLength ??
params.maxSeqLength ??
undefined,
},
@@ -6484,7 +6551,7 @@ export function createOpenAIStreamAdapter(
: streamChatCompletions(
requestPayload,
runSignal,
- // Only when the request targets the LOCAL model. ggufContextLength
+ // Only when the request targets the LOCAL model. loadedContextLength
// stays populated for a resident GGUF even while an external model is
// selected, so an external request with a 16K cap was being measured
// against an unrelated 4096-token local window and reported as having
@@ -6503,7 +6570,7 @@ export function createOpenAIStreamAdapter(
isExternalRequest
? null
: (runtime.loadedCustomContextLength ??
- runtime.ggufContextLength ??
+ runtime.loadedContextLength ??
(params.maxSeqLength || null)),
);
// Per run, not per module: two turns must not share a cycle.
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index e9572becba8..f8da044ab18 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -12,11 +12,14 @@ import {
ModelSelector,
type ModelSelectorChangeMeta,
type PerModelConfig,
+ isServedByMlx,
+ loadedContextFields,
resolveInitialConfig,
SidebarModelConfig,
useActiveModelConfig,
} from "@/features/model-picker";
import { ProjectComposer, Thread } from "@/components/assistant-ui/thread";
+import { usePlatformStore } from "@/config/env";
import { CopyableErrorChip } from "@/components/ui/copyable-error-chip";
import {
DropdownMenu,
@@ -2309,13 +2312,21 @@ export function ChatPage({
const residentCheckpoint = useChatRuntimeStore(
(state) => state.residentCheckpoint,
);
- const ggufContextLength = useChatRuntimeStore(
- (state) => state.ggufContextLength,
+ const loadedContextLength = useChatRuntimeStore(
+ (state) => state.loadedContextLength,
);
- const ggufNativeContextLength = useChatRuntimeStore(
- (state) => state.ggufNativeContextLength,
+ const nativeContextLength = useChatRuntimeStore(
+ (state) => state.nativeContextLength,
);
const contextUsage = useChatRuntimeStore((state) => state.contextUsage);
+ const loadedIsGguf = useChatRuntimeStore((state) => state.loadedIsGguf);
+ const loadedContextEnforced = useChatRuntimeStore(
+ (state) => state.loadedContextEnforced,
+ );
+ const platformDeviceType = usePlatformStore((state) => state.deviceType);
+ const platformChatOnlyReason = usePlatformStore(
+ (state) => state.chatOnlyReason,
+ );
const modelsFromStore = useChatRuntimeStore((state) => state.models);
const lorasFromStore = useChatRuntimeStore((state) => state.loras);
const modelsError = useChatRuntimeStore((state) => state.modelsError);
@@ -2454,7 +2465,7 @@ export function ChatPage({
[inferenceParams.checkpoint],
);
const contextWindowKnown = hasKnownContextWindow({
- ggufContextLength,
+ loadedContextLength,
modelLoading,
isExternalModel,
residentCheckpoint,
@@ -3265,9 +3276,7 @@ export function ChatPage({
: false;
useChatRuntimeStore.setState({
activeGgufVariant: null,
- ggufContextLength: null,
- ggufMaxContextLength: null,
- ggufNativeContextLength: null,
+ ...loadedContextFields(null),
activeNativePathToken: null,
activeNativePathExpiresAtMs: null,
// Clear previous-model counters, else the relaxed external-provider render gate shows
@@ -3613,7 +3622,11 @@ export function ChatPage({
}
// For local turns, also require the restored count to fit in
// the active window. Skip when unknown (external provider).
- const limit = store.ggufContextLength;
+ //
+ // llama.cpp only: it stops at the window, so a count past it is stale by
+ // definition. MLX generates straight past instead, where an over-window count
+ // is the true one and the bar has a state for it.
+ const limit = store.loadedIsGguf ? store.loadedContextLength : null;
if (
typeof limit === "number" &&
limit > 0 &&
@@ -4045,7 +4058,7 @@ export function ChatPage({
})}
activeGgufVariant={activeGgufVariant}
activeModelConfig={activeModelConfig}
- activeGgufContextLength={ggufContextLength}
+ activeLoadedContextLength={loadedContextLength}
onValueChange={handleCheckpointChange}
onEject={handleEject}
onFoldersChange={refreshLocalModels}
@@ -4134,11 +4147,17 @@ export function ChatPage({
<ContextUsageBar
used={contextUsage?.totalTokens ?? null}
// null on external providers; the bar handles that.
- total={ggufContextLength}
+ total={loadedContextLength}
cached={contextUsage?.cachedTokens}
cacheWrites={contextUsage?.cacheWriteTokens}
promptTokens={contextUsage?.promptTokens}
completionTokens={contextUsage?.completionTokens}
+ isMlx={isServedByMlx(
+ Boolean(loadedIsGguf),
+ platformDeviceType,
+ platformChatOnlyReason,
+ )}
+ contextEnforced={loadedContextEnforced}
className="h-[var(--studio-chat-control-height,34px)]"
/>
) : null}
@@ -4350,8 +4369,8 @@ export function ChatPage({
ggufVariant={activeGgufVariant ?? null}
isGguf={activeModelIsGguf}
isDiffusion={activeModelIsDiffusion}
- nativeContextLength={ggufNativeContextLength}
- loadedContextLength={ggufContextLength}
+ nativeContextLength={nativeContextLength}
+ loadedContextLength={loadedContextLength}
loadedConfig={activeModelConfig}
onReload={handleReloadActiveModel}
/>
diff --git a/studio/frontend/src/features/chat/chat-settings-sheet.tsx b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
index 8ed9842587e..9f620cf4f58 100644
--- a/studio/frontend/src/features/chat/chat-settings-sheet.tsx
+++ b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
@@ -45,6 +45,7 @@ import { Tooltip, TooltipContent } from "@/components/ui/tooltip";
import { usePlatformStore } from "@/config/env";
import {
NumericValueInput,
+ isServedByLlamaCpp,
presetLoadSettingNames,
snapToStep,
} from "@/features/model-picker";
@@ -85,6 +86,8 @@ import {
getPresetSaveState,
getPresetSource,
isSamePresetConfig,
+ MAX_TOKENS_MIN,
+ localMaxTokensCeiling,
toPresetParams,
} from "./presets/preset-policy";
import {
@@ -505,20 +508,22 @@ export function ChatSettingsPanel({
const showPresencePenalty =
!isExternalModel || Boolean(providerCapabilities?.presencePenalty);
const isMobile = useIsMobile();
- const isLoadedGguf = useChatRuntimeStore((s) => s.activeGgufVariant) != null;
+ const activeGgufVariant = useChatRuntimeStore((s) => s.activeGgufVariant);
+ const loadedIsGguf = useChatRuntimeStore((s) => s.loadedIsGguf);
+ const activeNativePathToken = useChatRuntimeStore(
+ (s) => s.activeNativePathToken,
+ );
const currentCheckpoint = params.checkpoint;
const activeModelIsLocal = useChatRuntimeStore(
(s) => s.activeModelIsLocal,
);
- const ggufContextLength = useChatRuntimeStore((s) => s.ggufContextLength);
- // Direct-file / custom-folder GGUFs load without a variant label but still
- // report a GGUF context, so detect them via the context and the checkpoint
- // suffix too (mirrors the chat page's activeModelIsGguf). Otherwise Max Tokens
- // would fall back to params.maxSeqLength instead of the loaded GGUF context.
- const isGguf =
- isLoadedGguf ||
- ggufContextLength != null ||
- (currentCheckpoint?.toLowerCase().endsWith(".gguf") ?? false);
+ const loadedContextLength = useChatRuntimeStore((s) => s.loadedContextLength);
+ const isGguf = isServedByLlamaCpp({
+ loadedIsGguf,
+ activeGgufVariant,
+ activeNativePathToken,
+ checkpoint: currentCheckpoint,
+ });
const activeModel = useChatRuntimeStore(
(s) => s.models.find((m) => m.id === currentCheckpoint) ?? null,
);
@@ -542,8 +547,8 @@ export function ChatSettingsPanel({
// reads a one-slash org/name.gguf as a repository id, not a file.
const isLocalGguf =
isGguf && (activeModelIsLocal || isLocalModelPath(currentCheckpoint ?? ""));
- const ggufMaxContextLength = useChatRuntimeStore(
- (s) => s.ggufMaxContextLength,
+ const maxContextLength = useChatRuntimeStore(
+ (s) => s.maxContextLength,
);
const customContextLength = useChatRuntimeStore((s) => s.customContextLength);
const kvCacheDtype = useChatRuntimeStore((s) => s.kvCacheDtype);
@@ -595,7 +600,7 @@ export function ChatSettingsPanel({
);
}
}, [applyLlamaUpdate, speculativeDrafterLabel]);
- const loadedEffectiveContext = customContextLength ?? ggufContextLength;
+ const loadedEffectiveContext = customContextLength ?? loadedContextLength;
const showSpecFallback =
!isExternalModel &&
isGguf &&
@@ -608,9 +613,9 @@ export function ChatSettingsPanel({
const showContextVramWarning =
!isExternalModel &&
isGguf &&
- ggufMaxContextLength != null &&
+ maxContextLength != null &&
loadedEffectiveContext != null &&
- loadedEffectiveContext > ggufMaxContextLength;
+ loadedEffectiveContext > maxContextLength;
const showLoadedDiagnostics = showSpecFallback || showContextVramWarning;
const hasModelContent = showLoadedDiagnostics;
const setActivePresetSource = useChatRuntimeStore(
@@ -623,7 +628,7 @@ export function ChatSettingsPanel({
const setActivePreset = useChatRuntimeStore((s) => s.setActivePreset);
const settingsHydrated = useChatRuntimeStore((s) => s.settingsHydrated);
- const baseContext = ggufContextLength;
+ const baseContext = loadedContextLength;
const [presetNameInput, setPresetNameInput] = useState(activePreset);
const [systemPromptEditorOpen, setSystemPromptEditorOpen] = useState(false);
const [systemPromptDraft, setSystemPromptDraft] = useState("");
@@ -721,7 +726,7 @@ export function ChatSettingsPanel({
committedSeed,
paramsWithCommittedSeed,
customContextLength,
- ggufContextLength,
+ loadedContextLength,
kvCacheDtype,
mlxKvBits,
gpuMemoryMode,
@@ -744,7 +749,7 @@ export function ChatSettingsPanel({
() => formatPresetLoadConfigSummary(capturePresetLoadConfig()),
[
customContextLength,
- ggufContextLength,
+ loadedContextLength,
kvCacheDtype,
mlxKvBits,
gpuMemoryMode,
@@ -789,14 +794,12 @@ export function ChatSettingsPanel({
? parseExternalModelId(currentCheckpoint)
: null;
const maxTokensMax = isExternalModel
- ? getExternalMaxOutputTokens(
- externalProviderType,
- externalSelection?.modelId,
- activeExternalProvider?.maxOutputTokens,
- )
- : isGguf && baseContext
- ? baseContext
- : Math.max(64, params.maxSeqLength);
+ ? getExternalMaxOutputTokens(
+ externalProviderType,
+ externalSelection?.modelId,
+ activeExternalProvider?.maxOutputTokens,
+ )
+ : localMaxTokensCeiling(baseContext, params.maxSeqLength);
const showOpenAICodeExecSection =
activeExternalProvider != null &&
providerSupportsBuiltinCodeExecution(
@@ -1119,7 +1122,7 @@ export function ChatSettingsPanel({
{isUnifiedMemory ? (
<>
Context length exceeds what fits in unified memory (
- {ggufMaxContextLength?.toLocaleString()} tokens). The GPU
+ {maxContextLength?.toLocaleString()} tokens). The GPU
and the rest of the system share one pool here, so there
is nothing to offload to. Lower the context, leave it on
Auto, or set the KV cache to q8_0.
@@ -1127,7 +1130,7 @@ export function ChatSettingsPanel({
) : (
<>
Context length exceeds the estimated VRAM capacity (
- {ggufMaxContextLength?.toLocaleString()} tokens). The
+ {maxContextLength?.toLocaleString()} tokens). The
model may use system RAM.
</>
)}
@@ -1524,19 +1527,15 @@ export function ChatSettingsPanel({
min={
isExternalModel
? getExternalMinOutputTokens(externalProviderType)
- : 64
+ : MAX_TOKENS_MIN
}
max={maxTokensMax}
step={64}
onChange={set("maxTokens")}
displayValue={
- isGguf && baseContext && params.maxTokens >= baseContext
+ !isExternalModel && params.maxTokens >= maxTokensMax
? "Max"
- : !isExternalModel &&
- !isGguf &&
- params.maxTokens >= maxTokensMax
- ? "Max"
- : undefined
+ : undefined
}
info="Maximum number of tokens to generate per response. Generation stops at this limit or when the model emits an end-of-sequence token."
/>
diff --git a/studio/frontend/src/features/chat/components/context-usage-bar.tsx b/studio/frontend/src/features/chat/components/context-usage-bar.tsx
index 830eaacb738..14e7c922a9c 100644
--- a/studio/frontend/src/features/chat/components/context-usage-bar.tsx
+++ b/studio/frontend/src/features/chat/components/context-usage-bar.tsx
@@ -31,6 +31,8 @@ export const ContextUsageBar: FC<
cacheWrites,
promptTokens,
completionTokens,
+ isMlx,
+ contextEnforced,
className,
}) => {
const state = deriveContextUsageBar({
@@ -40,10 +42,12 @@ export const ContextUsageBar: FC<
cacheWrites,
promptTokens,
completionTokens,
+ isMlx,
+ contextEnforced,
});
if (!state) return null;
- const { percent } = state;
+ const { percent, advice } = state;
const severity = getSeverityColor(percent ?? 0);
return (
@@ -122,11 +126,38 @@ export const ContextUsageBar: FC<
<span className="text-muted-foreground">{state.totalRowName}</span>
<span className="font-mono tabular-nums">{state.totalRowValue}</span>
</div>
- {percent !== null && percent > 85 ? (
+ {advice !== "none" ? (
<div className="mt-1 max-w-64 text-ui-11 leading-snug text-muted-foreground/90">
- Close to the context limit. Generation will stop at 100%.
- Increase <span className="font-medium">Context Length</span> in
- the chat Settings panel to keep going.
+ {advice === "mlx-past-limit" ? (
+ <>
+ Past the context limit. The chat keeps going rather than
+ stopping here, but the model can no longer hold the whole
+ conversation: answers get slower and less accurate, and a
+ long enough chat can still run out of memory. Increase{" "}
+ <span className="font-medium">Context Length</span> in the
+ chat Settings panel to fit it all.
+ </>
+ ) : advice === "mlx-near-limit" ? (
+ <>
+ Close to the context limit. Past it the chat keeps going, but
+ answers get slower and less accurate. Increase{" "}
+ <span className="font-medium">Context Length</span> in the
+ chat Settings panel to fit the whole conversation.
+ </>
+ ) : advice === "unenforced-limit" ? (
+ <>
+ This model builds its own cache, so{" "}
+ <span className="font-medium">Context Length</span> is the
+ window it was sized for, not a limit on it: the cache keeps
+ growing and lowering the setting will not save memory.
+ </>
+ ) : (
+ <>
+ Close to the context limit. Generation will stop at 100%.
+ Increase <span className="font-medium">Context Length</span> in
+ the chat Settings panel to keep going.
+ </>
+ )}
</div>
) : null}
</div>
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
index 59b3f44b927..501060f835b 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
@@ -86,10 +86,15 @@ import {
} from "../lib/resident-config-match";
import { residentModelMatchesPick } from "../lib/resident-model-match";
import {
+ loadedContextForParams,
mergeBackendRecommendedInference,
resolveFitMaxSeqLength,
+ unpinnedDefaultRequest,
+ unpinnedLoadContext,
resolveLoadMaxSeqLength,
resolveExplicitCtxPin,
+ loadRequestContextPin,
+ replayMaxTokensCap,
} from "../presets/preset-policy";
import { recordLastLocalModelLoad } from "../utils/last-local-model-load";
import { loadFallbackNotice } from "../utils/mmproj-fallback";
@@ -104,16 +109,22 @@ import {
} from "../types/api";
import { isExternalModelId } from "../external-providers";
import {
+ DEFAULT_MAX_SEQ_LENGTH,
DEFAULT_PER_MODEL_CONFIG,
applyPerModelConfigToRuntime,
currentRuntimePerModelConfig,
+ isServedByMlx,
normalizeMaxSeqLength,
+ residentIsServedByMlx,
+ resolveInitialConfig,
type PerModelConfig,
+ loadedContextFields,
} from "@/features/model-picker";
import {
invalidateLlamaFlagCatalog,
loadManagedLlamaFlags,
} from "@/features/model-picker/api/llama-flags";
+import { usePlatformStore } from "@/config/env";
import type {
ChatLoraSummary,
ChatModelRow,
@@ -478,15 +489,15 @@ async function syncInferenceStatusToStore(options?: {
// capability. Re-apply live status so attach gates survive a refresh.
syncModelCapabilities(checkpointId, statusRes);
- // Unsloth starting against an already-resident GGUF: history can load before this first
- // status refresh has a checkpoint or window, so its own recount never runs. A null thread
- // would publish an empty count, hence the mounted-thread guard.
+ // Against an already-resident model, history can load before this first status
+ // has a checkpoint, so its own recount never runs. The thread guard stops a null
+ // thread publishing an empty count.
const hydrated = useChatRuntimeStore.getState();
if (
!selectedCheckpoint &&
hydrated.contextUsage == null &&
hydrated.activeThreadId != null &&
- hydrated.ggufContextLength != null &&
+ hydrated.loadedContextLength != null &&
!isExternalModelId(checkpointId)
) {
void refreshContextUsage({ threadId: hydrated.activeThreadId });
@@ -890,20 +901,33 @@ export function useChatModelRuntime() {
gpuMemoryMode: readPersistedGpuMemoryMode(),
gpuLayers: GPU_LAYERS_AUTO,
nCpuMoe: 0,
- // The n_ctx /load would send. Built from the live store, as performLoad
- // builds it, so an unset length resolves the same way on both sides.
+ // The n_ctx /load would send, from performLoad's own inputs, so an unset
+ // length resolves the same way on both sides.
resolveContextLength: (customContextLength) => {
const live = useChatRuntimeStore.getState();
+ const platform = usePlatformStore.getState();
+ // Identity matched above, so the resident model is this pick.
+ const residentIsGguf = status.is_gguf ?? false;
return resolveLoadMaxSeqLength({
modelId,
ggufVariant,
- // Identity matched above, so the resident model is this pick.
- isGguf: status.is_gguf,
+ isGguf: residentIsGguf,
customContextLength,
- ggufContextLength: live.ggufContextLength,
+ loadedContextLength: live.loadedContextLength,
currentCheckpoint: live.params.checkpoint,
activeGgufVariant: live.activeGgufVariant,
- maxSeqLength: live.params.maxSeqLength,
+ isMlx: isServedByMlx(
+ residentIsGguf,
+ platform.deviceType,
+ platform.chatOnlyReason,
+ ),
+ pinnedMaxSeqLength: normalizeMaxSeqLength(
+ pendingConfig
+ ? pendingConfig.maxSeqLength
+ : resolveInitialConfig(modelId, ggufVariant).config
+ .maxSeqLength,
+ ),
+ defaultMaxSeqLength: live.params.maxSeqLength || DEFAULT_MAX_SEQ_LENGTH,
presetSource: live.activePresetSource,
});
},
@@ -1195,11 +1219,18 @@ export function useChatModelRuntime() {
const currentCheckpoint =
useChatRuntimeStore.getState().params.checkpoint;
const stateBeforeUnload = useChatRuntimeStore.getState();
+ const platform = usePlatformStore.getState();
let trustRemoteCode = stateBeforeUnload.params.trustRemoteCode ?? false;
let approvedRemoteCodeFingerprint: string | null = null;
+ // A staged config carries its pin; one that applied the saved record and then
+ // selected carries none, so the pre-move field is where it survives.
+ const pinnedMaxSeqLength = normalizeMaxSeqLength(
+ pendingLoadConfig
+ ? pendingLoadConfig.maxSeqLength
+ : resolveInitialConfig(modelId, ggufVariant).config.maxSeqLength,
+ );
const maxSeqLength =
- normalizeMaxSeqLength(pendingLoadConfig?.maxSeqLength) ??
- stateBeforeUnload.params.maxSeqLength;
+ pinnedMaxSeqLength ?? stateBeforeUnload.params.maxSeqLength;
const previousActiveNativePathToken =
stateBeforeUnload.activeNativePathToken;
const previousActiveLoadId = stateBeforeUnload.activeLoadId;
@@ -1216,18 +1247,31 @@ export function useChatModelRuntime() {
(typeof selection !== "string"
? selection.previousConfig?.maxSeqLength
: null) ?? maxSeqLength;
- // Respect the rolled-back model's auto-layers mode: a Manual+Auto model
- // with an unpinned context must reload with 0 (so --fit re-auto-sizes),
- // not the positive context it picked (which the backend treats as a pin).
- const rollbackMaxSeqLength = resolveFitMaxSeqLength(
+ // The intent the model had, not the length it ended up at: sending the
+ // resolved length would pin a model nobody pinned.
+ // The resident backend's own answer, so a native-audio checkpoint the worker
+ // served off the MLX path does not roll back at the sentinel.
+ const previousIsMlx = residentIsServedByMlx(
previousIsGguf,
- stateBeforeUnload.loadedGpuMemoryMode ?? "auto",
- stateBeforeUnload.loadedGpuLayers ?? GPU_LAYERS_AUTO,
- stateBeforeUnload.loadedCustomContextLength,
- previousIsGguf
- ? (stateBeforeUnload.ggufContextLength ?? 0)
- : previousMaxSeqLength,
+ platform.deviceType,
+ platform.chatOnlyReason,
+ stateBeforeUnload.loadedIsMlx,
);
+ // What the outgoing model loaded with, not the control's value: a pin typed
+ // and never applied would change a window the failed switch never touched.
+ const previousPin = stateBeforeUnload.loadedCustomContextLength;
+ // It reloads at the pin it loaded with, whichever backend served it; only
+ // llama.cpp's placement rules override that, where they own sizing.
+ const rollbackMaxSeqLength = previousIsGguf
+ ? resolveFitMaxSeqLength(
+ previousIsGguf,
+ stateBeforeUnload.loadedGpuMemoryMode ?? "auto",
+ stateBeforeUnload.loadedGpuLayers ?? GPU_LAYERS_AUTO,
+ stateBeforeUnload.loadedCustomContextLength,
+ stateBeforeUnload.loadedContextLength ?? 0,
+ )
+ : (previousPin ??
+ unpinnedLoadContext(false, previousIsMlx, previousMaxSeqLength));
const hfToken = stateBeforeUnload.hfToken || null;
const previousModelRequiresTrustRemoteCode =
stateBeforeUnload.modelRequiresTrustRemoteCode;
@@ -1253,7 +1297,7 @@ export function useChatModelRuntime() {
let loadCustomContextLength =
pendingLoadConfig?.customContextLength ??
stateBeforeUnload.customContextLength;
- const loadGgufContextLength = stateBeforeUnload.ggufContextLength;
+ const loadContextLength = stateBeforeUnload.loadedContextLength;
const loadTensorParallel = targetIsDiffusion
? false
: (pendingLoadConfig?.tensorParallel ??
@@ -1401,10 +1445,16 @@ export function useChatModelRuntime() {
ggufVariant,
isGguf,
customContextLength: validateCustomContextLength,
- ggufContextLength: loadGgufContextLength,
+ loadedContextLength: loadContextLength,
currentCheckpoint,
activeGgufVariant: loadActiveGgufVariant,
- maxSeqLength,
+ isMlx: isServedByMlx(isGguf, platform.deviceType, platform.chatOnlyReason),
+ pinnedMaxSeqLength,
+ defaultMaxSeqLength: unpinnedDefaultRequest(
+ previousIsMlx,
+ stateBeforeUnload.params.maxSeqLength,
+ DEFAULT_MAX_SEQ_LENGTH,
+ ),
presetSource: loadActivePresetSource,
}),
);
@@ -1599,13 +1649,22 @@ export function useChatModelRuntime() {
// the wire, is what the completed load pins: several send rules put a
// positive n_ctx on the wire with the control on Auto, and a pin read
// back out of one of those is a number the user never chose.
- const explicitCtxPin = loadCustomContextLength;
+ const targetIsMlx = isServedByMlx(
+ isGguf,
+ platform.deviceType,
+ platform.chatOnlyReason,
+ );
+ const explicitCtxPin = loadRequestContextPin(
+ loadCustomContextLength,
+ targetIsMlx,
+ pinnedMaxSeqLength,
+ );
// Pinning layers on the SAME model keeps the currently resolved
// context: with no explicit pin, a manual+pinned reload would send 0,
// which the backend's --fit off branch treats as the NATIVE context --
// far larger than the sheet shows when the load was fit-sized (Default
// or Manual + Auto layers may auto-reduce context to fit VRAM), a
- // likely OOM. ggufContextLength is that resolved value; a model already
+ // likely OOM. loadedContextLength is that resolved value; a model already
// at native reloads unchanged, so this is safe for any prior mode.
if (
isGguf &&
@@ -1613,19 +1672,25 @@ export function useChatModelRuntime() {
loadGpuMemoryMode === "manual" &&
loadGpuLayers >= 0 &&
loadCustomContextLength == null &&
- (loadGgufContextLength ?? 0) > 0
+ (loadContextLength ?? 0) > 0
) {
- loadCustomContextLength = loadGgufContextLength;
+ loadCustomContextLength = loadContextLength;
}
const effectiveMaxSeqLength = resolveLoadMaxSeqLength({
modelId,
ggufVariant,
isGguf,
customContextLength: loadCustomContextLength,
- ggufContextLength: loadGgufContextLength,
+ loadedContextLength: loadContextLength,
currentCheckpoint,
activeGgufVariant: loadActiveGgufVariant,
- maxSeqLength,
+ isMlx: targetIsMlx,
+ pinnedMaxSeqLength,
+ defaultMaxSeqLength: unpinnedDefaultRequest(
+ previousIsMlx,
+ stateBeforeUnload.params.maxSeqLength,
+ DEFAULT_MAX_SEQ_LENGTH,
+ ),
presetSource: loadActivePresetSource,
});
const loadMaxSeqLength = resolveFitMaxSeqLength(
@@ -1707,18 +1772,37 @@ export function useChatModelRuntime() {
persistGpuMemoryModeOnLoad(loadResponse, loadGpuMemoryMode);
const currentParams = useChatRuntimeStore.getState().params;
- // The context this load actually has: the server's for a GGUF, the
- // sequence length the load was invoked with otherwise.
- const loadedContextCap = loadResponse.is_gguf
- ? (loadResponse.context_length ?? undefined)
- : effectiveMaxSeqLength;
+ const loadedFields = loadedContextFields(loadResponse);
+ // The reported window, or where nothing sized one the requested length.
+ // The request answers only for a backend that sizes nothing: a self-sizing
+ // one was sent the sentinel, which as a budget is zero.
+ const loadedContextCap = replayMaxTokensCap(
+ loadedFields.loadedContextLength ??
+ (!loadResponse.is_gguf && effectiveMaxSeqLength > 0
+ ? effectiveMaxSeqLength
+ : null),
+ );
setParams(
- mergeBackendRecommendedInference({
- current: currentParams,
- response: loadResponse,
- modelId,
- presetSource: useChatRuntimeStore.getState().activePresetSource,
- }),
+ {
+ ...mergeBackendRecommendedInference({
+ current: currentParams,
+ response: loadResponse,
+ modelId,
+ presetSource: useChatRuntimeStore.getState().activePresetSource,
+ loadedContextLength: loadedFields.loadedContextLength,
+ }),
+ // The served window, as background and compare loads already record,
+ // or the active model reports a context it is not running at.
+ ...(isGguf
+ ? {}
+ : {
+ maxSeqLength: loadedContextForParams(
+ loadedFields.loadedContextLength,
+ loadMaxSeqLength,
+ currentParams.maxSeqLength,
+ ),
+ }),
+ },
// Lay this model's remembered settings back over its defaults,
// but not a budget larger than the context it just loaded with.
{
@@ -1781,19 +1865,11 @@ export function useChatModelRuntime() {
!(loadResponse.is_diffusion ?? false)
? committedServerTuningState(loadServerTuning)
: clearedServerTuningState();
- const nativeCtx = loadResponse.is_gguf
- ? (loadResponse.context_length ?? 131072)
- : null;
- const reportedMaxCtx = loadResponse.is_gguf
- ? (loadResponse.max_context_length ?? null)
- : null;
- const reportedNativeCtx = loadResponse.is_gguf
- ? (loadResponse.native_context_length ?? null)
- : null;
// The user's own Context Length (see explicitCtxPin), so an Auto load
- // stays Auto whatever n_ctx the send rules resolved for it.
+ // stays Auto whatever n_ctx the send rules resolved for it. MLX pins the
+ // same way, so it is admitted here rather than cleared as a non-GGUF.
const keepCustomCtx = resolveExplicitCtxPin(
- loadResponse.is_gguf ? explicitCtxPin : null,
+ loadResponse.is_gguf || targetIsMlx ? explicitCtxPin : null,
);
const reasoningAlwaysOn = loadResponse.reasoning_always_on ?? false;
const reasoningStyle = loadResponse.reasoning_style ?? "enable_thinking";
@@ -1817,7 +1893,6 @@ export function useChatModelRuntime() {
reasoningEffortLevels,
)
: clampLocalReasoningEffort(existingReasoningEffort);
- const ggufMaxContextLength = reportedMaxCtx;
const nextReasoningEnabled = reasoningAlwaysOn
? true
: reloadingSameModel && supportsReasoning
@@ -1827,9 +1902,7 @@ export function useChatModelRuntime() {
// A later rollback reads the snapshot path, not the id this was stored under.
rememberApprovedRemoteCode(loadPath, approvedRemoteCodeFingerprint);
useChatRuntimeStore.setState({
- ggufContextLength: nativeCtx,
- ggufMaxContextLength,
- ggufNativeContextLength: reportedNativeCtx,
+ ...loadedContextFields(loadResponse),
modelRequiresTrustRemoteCode:
loadResponse.requires_trust_remote_code ?? false,
supportsReasoning,
diff --git a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
index ae72899501b..27f324cfad4 100644
--- a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
+++ b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
@@ -3,12 +3,19 @@
// Barrel import (lint rule); the model-picker cycle is fine because the call
// happens at runtime, not module eval.
-import { resolveResidentInitialConfig } from "@/features/model-picker";
+import {
+ loadedContextFields,
+ resolveResidentInitialConfig,
+ savedContextPin,
+} from "@/features/model-picker";
// eslint-disable-next-line no-restricted-imports -- Avoid the hub barrel's React and download-manager exports.
import { modelDisplayName } from "@/features/hub/lib/model-identity";
import { getInferenceStatus } from "../api/chat-api";
import { isSpeechOnlyStatus } from "./speech-only-status";
-import { mergeBackendRecommendedInference } from "../presets/preset-policy";
+import {
+ mergeBackendRecommendedInference,
+ replayMaxTokensCap,
+} from "../presets/preset-policy";
import { clampReasoningEffortToLevels } from "../provider-capabilities";
import {
CHAT_REASONING_ENABLED_KEY,
@@ -161,6 +168,7 @@ export function applyActiveModelStatusToStore(
response: status,
modelId: checkpointId,
presetSource: store.activePresetSource,
+ loadedContextLength: loadedContextFields(status).loadedContextLength,
}),
// The model's own remembered settings outrank the recommendation, or
// every poll would undo them, but not past the context it loaded with.
@@ -168,7 +176,7 @@ export function applyActiveModelStatusToStore(
// narrowed to GGUF; absent, there is nothing to cap against.
{
fromModelDefaults: true,
- maxTokensCap: status.context_length ?? undefined,
+ maxTokensCap: replayMaxTokensCap(status.context_length),
},
);
}
@@ -193,15 +201,6 @@ export function applyActiveModelStatusToStore(
const preserveThinkingOnLoad = resolvePreserveThinkingOnLoad(status);
const supportsTools = status.supports_tools ?? false;
const storedReasoningEnabled = loadOptionalBool(CHAT_REASONING_ENABLED_KEY);
- const currentGgufContextLength = status.is_gguf
- ? (status.context_length ?? null)
- : null;
- const ggufMaxContextLength = status.is_gguf
- ? (status.max_context_length ?? null)
- : null;
- const ggufNativeContextLength = status.is_gguf
- ? (status.native_context_length ?? null)
- : null;
const currentSpecType = normalizeSpeculativeType(status.speculative_type);
const prevState = useChatRuntimeStore.getState();
const clampedReasoningEffort =
@@ -225,7 +224,9 @@ export function applyActiveModelStatusToStore(
// model can report the old count.
const slotsModelChanged = hydratingExistingModel;
// This model's remembered override, read only on a fresh store or a model
- // change, so a steady poll cannot re-pin a control the user just blanked.
+ // change, so a steady poll cannot re-pin a control the user just blanked. A
+ // self-sizing backend has no slot fields, so an unseeded store says nothing
+ // about it and it goes by the checkpoint alone.
// Through the resident resolver, not the raw id: an API-driven load reports the
// snapshot path a cached repo loaded from, while its settings are keyed by the
// repo id, and the plain lookup misses that record.
@@ -238,18 +239,23 @@ export function applyActiveModelStatusToStore(
prevState.loadedNUbatch === null &&
prevState.nUbatch === null;
const remembered =
- status.is_gguf && (slotsUnseeded || batchesUnseeded || slotsModelChanged)
+ (status.is_gguf
+ ? slotsUnseeded || batchesUnseeded || slotsModelChanged
+ : hydratingExistingModel)
? resolveResidentInitialConfig(checkpointId, status.gguf_variant ?? null)
: null;
- const rememberedNParallel = remembered?.remembered
- ? (remembered.config.nParallel ?? null)
- : null;
- const rememberedNBatch = remembered?.remembered
- ? (remembered.config.nBatch ?? null)
- : null;
- const rememberedNUbatch = remembered?.remembered
- ? (remembered.config.nUbatch ?? null)
- : null;
+ const rememberedNParallel =
+ status.is_gguf && remembered?.remembered
+ ? (remembered.config.nParallel ?? null)
+ : null;
+ const rememberedNBatch =
+ status.is_gguf && remembered?.remembered
+ ? (remembered.config.nBatch ?? null)
+ : null;
+ const rememberedNUbatch =
+ status.is_gguf && remembered?.remembered
+ ? (remembered.config.nUbatch ?? null)
+ : null;
const nBatchSeed = resolveBatchSizeSeed({
incoming: status.requested_n_batch,
isGguf: status.is_gguf ?? true,
@@ -312,12 +318,15 @@ export function applyActiveModelStatusToStore(
// status still answers for the OUTGOING model.
const ctxPinFields = resolveCtxPinSeed({
incoming: status.requested_context_length,
- isGguf: status.is_gguf ?? true,
+ // MLX reports a requested context as well, so the rule below is about any
+ // backend that sizes its own window, not llama.cpp alone.
+ isGguf: (status.is_gguf ?? true) || (status.is_mlx ?? false),
+ isMlx: status.is_mlx ?? false,
seedLoadParams,
modelChanged: slotsModelChanged,
- remembered: remembered?.remembered
- ? (remembered.config.customContextLength ?? null)
- : null,
+ // Both fields: a record written before the MLX pin moved still carries it
+ // in maxSeqLength.
+ remembered: remembered?.remembered ? savedContextPin(remembered.config) : null,
// Raw, not the normalised incomingGpuMode/incomingGpuLayers below: the rule
// needs "Manual with AUTO layers", and those normalise layers to null off
// manual, which would read as "no layers reported" rather than as Auto.
@@ -337,7 +346,7 @@ export function applyActiveModelStatusToStore(
const incomingGpuFields = loadedGpuMemoryFields(status);
const incomingGpuIds = incomingGpuFields.loadedGpuIds;
const incomingGpuIndexKind = incomingGpuFields.loadedGpuIndexKind;
- const gpuStatusChanged =
+ const placementOrContextChanged =
prevState.loadedGpuMemoryMode !== incomingGpuMode ||
prevState.loadedGpuLayers !== incomingGpuLayers ||
prevState.loadedNCpuMoe !== incomingNCpuMoe ||
@@ -374,8 +383,8 @@ export function applyActiveModelStatusToStore(
);
// A same-model reload from another client advances every loaded baseline.
// Preserve each editable group only when this tab has an unapplied change.
- const preserveSameModelEdits = gpuStatusChanged && !hydratingExistingModel;
- const gpuStatusFields = {
+ const preserveSameModelEdits = placementOrContextChanged && !hydratingExistingModel;
+ const placementAndContextFields = {
...incomingGpuFields,
...ctxPinFields,
...(preserveSameModelEdits &&
@@ -411,9 +420,7 @@ export function applyActiveModelStatusToStore(
? true
: useChatRuntimeStore.getState().reasoningEnabled
: true,
- ggufContextLength: currentGgufContextLength,
- ggufMaxContextLength,
- ggufNativeContextLength,
+ ...loadedContextFields(status),
...(status.is_gguf
? {}
: { activeNativePathToken: null, activeNativePathExpiresAtMs: null }),
@@ -620,13 +627,13 @@ export function applyActiveModelStatusToStore(
nUbatch: rememberedNUbatch,
}),
// Re-seed on first hydration, model/variant changes, or a same-model backend
- // placement change. gpuStatusFields preserves dirty local edits in the last
+ // placement change. placementAndContextFields preserves dirty local edits in the last
// case while advancing their loaded baselines.
...(seedLoadParams &&
(prevState.loadedGpuMemoryMode === null ||
hydratingExistingModel ||
- gpuStatusChanged) &&
- gpuStatusFields),
+ placementOrContextChanged) &&
+ placementAndContextFields),
// The one load param that only ever seeded from null, so a switch left the previous model's
// template in the store, which the Hub settings page reads as the new model's loaded config:
// Apply then saves A's template under B. A same-model reload from another client moves it
@@ -693,7 +700,7 @@ export function applyActiveModelStatusToStore(
{ ...current.params, ...qwenParams },
{
fromModelDefaults: true,
- maxTokensCap: status.context_length ?? undefined,
+ maxTokensCap: replayMaxTokensCap(status.context_length),
},
);
}
diff --git a/studio/frontend/src/features/chat/lib/context-usage-bar-state.ts b/studio/frontend/src/features/chat/lib/context-usage-bar-state.ts
index eba518e7592..d607511ba4b 100644
--- a/studio/frontend/src/features/chat/lib/context-usage-bar-state.ts
+++ b/studio/frontend/src/features/chat/lib/context-usage-bar-state.ts
@@ -22,8 +22,45 @@ export type ContextUsageBarInput = {
cacheWrites?: number;
promptTokens?: number;
completionTokens?: number;
+ // MLX keeps generating past the window instead of stopping there, so it needs the
+ // opposite advice from llama.cpp once a conversation outgrows the limit.
+ isMlx?: boolean;
+ /** context_length_enforced as the load reported it; null where it does not answer. */
+ contextEnforced?: boolean | null;
};
+/**
+ * Which limit warning the tooltip carries, if any.
+ *
+ * llama.cpp stops generating at the window, so its advice is to raise the limit before
+ * hitting it. MLX generates straight past instead, so the same wording would promise a
+ * stop that never comes -- and once a conversation is over the window there is something
+ * different to say about it. Read from the unclamped ratio: the reported percent caps at
+ * 100%, which is exactly the state being reported on.
+ */
+export type ContextLimitAdvice =
+ | "none"
+ | "stops-at-limit"
+ | "mlx-near-limit"
+ | "mlx-past-limit"
+ | "unenforced-limit";
+
+function contextLimitAdvice(
+ used: number,
+ total: number,
+ isMlx: boolean | undefined,
+ enforced: boolean | null | undefined,
+): ContextLimitAdvice {
+ if ((used / total) * 100 <= 85) return "none";
+ // A window the backend confirmed does not bound the cache is not a limit at all:
+ // nothing rotates and nothing stops, so neither of the other two is true of it. An
+ // unjudged MLX window says the same thing operationally: the probe could not build a
+ // cache, so none was bounded and it grows exactly as a confirmed false one does.
+ if (enforced === false || (isMlx && enforced == null)) return "unenforced-limit";
+ if (!isMlx) return "stops-at-limit";
+ return used > total ? "mlx-past-limit" : "mlx-near-limit";
+}
+
export type ContextUsageBarState = {
face: string;
label: string;
@@ -33,6 +70,7 @@ export type ContextUsageBarState = {
percent: number | null;
// whether any per-turn row renders, so the tooltip rule never floats above nothing
hasUsageDetails: boolean;
+ advice: ContextLimitAdvice;
};
// a counted zero and an uncounted chat differ: an unmeasured prompt must not read as 0% of the window
@@ -43,6 +81,8 @@ export function deriveContextUsageBar({
cacheWrites,
promptTokens,
completionTokens,
+ isMlx,
+ contextEnforced,
}: ContextUsageBarInput): ContextUsageBarState | null {
const limit = typeof total === "number" && total > 0 ? total : null;
const usedTokens =
@@ -64,6 +104,7 @@ export function deriveContextUsageBar({
totalRowValue: formatTokenCountFull(usedTokens),
percent: null,
hasUsageDetails,
+ advice: "none",
};
}
@@ -75,6 +116,7 @@ export function deriveContextUsageBar({
totalRowValue: formatTokenCountFull(limit),
percent: null,
hasUsageDetails,
+ advice: "none",
};
}
@@ -85,5 +127,6 @@ export function deriveContextUsageBar({
totalRowValue: `${formatTokenCountFull(usedTokens)} / ${formatTokenCountFull(limit)}`,
percent: Math.min((usedTokens / limit) * 100, 100),
hasUsageDetails,
+ advice: contextLimitAdvice(usedTokens, limit, isMlx, contextEnforced),
};
}
diff --git a/studio/frontend/src/features/chat/lib/context-window-known.ts b/studio/frontend/src/features/chat/lib/context-window-known.ts
index 28360cb674f..ec4dca96426 100644
--- a/studio/frontend/src/features/chat/lib/context-window-known.ts
+++ b/studio/frontend/src/features/chat/lib/context-window-known.ts
@@ -4,8 +4,8 @@
// its own plain module so the node suite can drive it: chat-page.tsx pulls in the whole chat runtime
export type KnownContextWindowInput = {
- // the resident GGUF's n_ctx; null for external providers and non-GGUF models
- ggufContextLength: number | null;
+ // the window the resident backend serves; null where none sizes one
+ loadedContextLength: number | null;
// a load in flight still carries the outgoing model's window
modelLoading: boolean;
isExternalModel: boolean;
@@ -15,13 +15,13 @@ export type KnownContextWindowInput = {
// the recount that fills the bar stands down for images, audio, Deep Research and a busy backend
export function hasKnownContextWindow({
- ggufContextLength,
+ loadedContextLength,
modelLoading,
isExternalModel,
residentCheckpoint,
}: KnownContextWindowInput): boolean {
if (modelLoading || isExternalModel) return false;
- if (ggufContextLength == null || ggufContextLength <= 0) return false;
+ if (loadedContextLength == null || loadedContextLength <= 0) return false;
// matches chatModelLoaded: undefined is "status not read yet", not "evicted"
return residentCheckpoint !== null;
}
diff --git a/studio/frontend/src/features/chat/lib/resolve-ctx-pin-seed.ts b/studio/frontend/src/features/chat/lib/resolve-ctx-pin-seed.ts
index 4eca65b9922..176ee696764 100644
--- a/studio/frontend/src/features/chat/lib/resolve-ctx-pin-seed.ts
+++ b/studio/frontend/src/features/chat/lib/resolve-ctx-pin-seed.ts
@@ -50,6 +50,9 @@ export function resolveCtxPinSeed(options: {
/** ``status.is_gguf``. A non-GGUF status reports ``incoming`` too, so this flag, not
* its presence, is what keeps a non-GGUF load out of the pin. */
isGguf: boolean;
+ /** MLX sizes its own window, and an unpinned MLX load sends 0, so a positive echo
+ * from it is proof of a pin rather than the ambiguous resolved n_ctx GGUF reports. */
+ isMlx?: boolean;
/** No load of this tab's own is in flight (``!modelLoading``). */
seedLoadParams: boolean;
/** The model/variant changed underneath this tab, so nothing recorded here survives it. */
@@ -66,6 +69,7 @@ export function resolveCtxPinSeed(options: {
const {
incoming,
isGguf,
+ isMlx,
seedLoadParams,
modelChanged,
remembered,
@@ -87,6 +91,12 @@ export function resolveCtxPinSeed(options: {
// 0 is the wire value for Auto and only an Auto load sends it, so this is the
// one echo that proves its own meaning.
if (incoming === null || !(incoming > 0)) return CLEAR;
+ // Unambiguous on MLX, so it is adopted without needing a saved config to corroborate
+ // it: another tab or an API client leaving a pinned model resident would otherwise
+ // read as Auto here, and the next Apply would send 0 and drop their pin.
+ if (isMlx) {
+ return { customContextLength: incoming, loadedCustomContextLength: incoming };
+ }
// One placement mode has no ambiguity to reason around: under Manual memory
// with Auto layers the load sends its pin as max_seq_length through
// resolveFitMaxSeqLength, which answers `customContextLength > 0 ? it : 0`.
diff --git a/studio/frontend/src/features/chat/presets/preset-load-config.ts b/studio/frontend/src/features/chat/presets/preset-load-config.ts
index 328cd9d6cbb..f912f822e3d 100644
--- a/studio/frontend/src/features/chat/presets/preset-load-config.ts
+++ b/studio/frontend/src/features/chat/presets/preset-load-config.ts
@@ -9,6 +9,7 @@ import {
import {
CONTEXT_LENGTH_MIN,
DEFAULT_PER_MODEL_CONFIG,
+ MAX_SEQ_LENGTH_MAX,
DEFAULT_MAX_SEQ_LENGTH,
KV_CACHE_DTYPES,
MLX_KV_BITS,
@@ -17,9 +18,12 @@ import {
N_PARALLEL_MAX,
N_PARALLEL_MIN,
canonicalizeLoadMode,
+ isServedByLlamaCpp,
+ isServedByMlx,
normalizeCacheRam,
normalizeCtxCheckpoints,
normalizeMaxSeqLength,
+ savedContextPin,
type PerModelConfig,
} from "@/features/model-picker/model-config/per-model-config";
import {
@@ -31,6 +35,8 @@ import {
useChatRuntimeStore,
normalizeSpeculativeType,
} from "../stores/chat-runtime-store";
+import { usePlatformStore } from "@/config/env";
+import { capturedContextLength } from "./preset-policy";
/** Load/runtime knobs saved in a chat preset (excludes per-model-only blobs). */
export type PresetLoadConfig = Pick<
@@ -79,14 +85,33 @@ export const EMPTY_PRESET_LOAD_CONFIG: PresetLoadConfig = {
function toComparablePerModelConfig(
config: PresetLoadConfig,
): PerModelConfig {
+ // Compared as a pin, not as whichever field the backend of the moment writes it in:
+ // the same preset replayed elsewhere holds that length in the other field.
+ const pin = savedContextPin(config);
return {
...DEFAULT_PER_MODEL_CONFIG,
...config,
+ customContextLength: pin,
+ maxSeqLength: null,
chatTemplateOverride: null,
selectedGpuIds: null,
};
}
+/** A context as a preset may carry it, or null if it is not a length at all.
+ *
+ * One bound for capture and for reading a saved preset back, since clamping only on the
+ * way to storage would send one window on the first replay and another after saving. The
+ * upper bound is what `/load` accepts; the lower is the control's own minimum, because a
+ * pin the control cannot represent is one the user cannot undo.
+ */
+function requestableContextLength(value: unknown): number | null {
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
+ return null;
+ }
+ return Math.min(MAX_SEQ_LENGTH_MAX, Math.max(CONTEXT_LENGTH_MIN, Math.floor(value)));
+}
+
export function normalizePresetLoadConfig(
raw: unknown,
): PresetLoadConfig | undefined {
@@ -118,12 +143,7 @@ export function normalizePresetLoadConfig(
}
const normalized: PresetLoadConfig = {
- customContextLength:
- typeof partial.customContextLength === "number" &&
- Number.isFinite(partial.customContextLength) &&
- partial.customContextLength > 0
- ? Math.max(CONTEXT_LENGTH_MIN, Math.floor(partial.customContextLength))
- : null,
+ customContextLength: requestableContextLength(partial.customContextLength),
maxSeqLength: normalizeMaxSeqLength(partial.maxSeqLength as number | null),
mlxKvBits:
typeof partial.mlxKvBits === "number" &&
@@ -202,16 +222,25 @@ export function isSamePresetLoadConfig(
export function capturePresetLoadConfig(): PresetLoadConfig | undefined {
const snapshot = currentRuntimePerModelConfig({ includeMaxSeqLength: true });
const store = useChatRuntimeStore.getState();
- const isGguf =
- store.activeGgufVariant != null ||
- store.ggufContextLength != null ||
- (store.params.checkpoint?.toLowerCase().endsWith(".gguf") ?? false);
- const effectiveContextLength =
- snapshot.customContextLength ??
- (isGguf ? store.ggufContextLength : null);
+ const isGguf = isServedByLlamaCpp({
+ loadedIsGguf: store.loadedIsGguf,
+ activeGgufVariant: store.activeGgufVariant,
+ activeNativePathToken: store.activeNativePathToken,
+ checkpoint: store.params.checkpoint,
+ });
+ const platform = usePlatformStore.getState();
+ const isMlx = isServedByMlx(isGguf, platform.deviceType, platform.chatOnlyReason);
+ // The same bound a saved preset is read back under; this one replays from memory first.
+ const effectiveContextLength = requestableContextLength(
+ capturedContextLength({
+ isGguf,
+ controlPin: snapshot.customContextLength,
+ loadedContextLength: store.loadedContextLength,
+ }),
+ );
const captured: PresetLoadConfig = {
customContextLength: effectiveContextLength ?? null,
- maxSeqLength: normalizeMaxSeqLength(snapshot.maxSeqLength),
+ maxSeqLength: isMlx ? null : normalizeMaxSeqLength(snapshot.maxSeqLength),
kvCacheDtype: snapshot.kvCacheDtype ?? null,
mlxKvBits: snapshot.mlxKvBits ?? null,
speculativeType: normalizeSpeculativeType(snapshot.speculativeType),
diff --git a/studio/frontend/src/features/chat/presets/preset-policy.ts b/studio/frontend/src/features/chat/presets/preset-policy.ts
index b27591f33e2..cc1b7bfea65 100644
--- a/studio/frontend/src/features/chat/presets/preset-policy.ts
+++ b/studio/frontend/src/features/chat/presets/preset-policy.ts
@@ -9,6 +9,9 @@ import type { PresetLoadConfig } from "./preset-load-config";
export const defaultInferenceParams = DEFAULT_INFERENCE_PARAMS;
+/** The fewest tokens the Max Tokens control offers, and so the least any ceiling may be. */
+export const MAX_TOKENS_MIN = 64;
+
export interface Preset {
name: string;
params: InferenceParams;
@@ -267,11 +270,15 @@ export function mergeBackendRecommendedInference({
response,
modelId,
presetSource,
+ loadedContextLength,
}: {
current: InferenceParams;
response: BackendInferenceEnvelope;
modelId: string;
presetSource: ChatPresetSource;
+ /** The window the response reports, as the context constructor reads it -- not the raw
+ * field, where a backend that sizes nothing echoes the length it was asked for. */
+ loadedContextLength: number | null;
}): InferenceParams {
const inference = response.inference;
const next: InferenceParams = {
@@ -287,9 +294,12 @@ export function mergeBackendRecommendedInference({
return next;
}
- const defaultMaxTokens = response.is_gguf
- ? (response.context_length ?? current.maxTokens)
- : 4096;
+ // An unreported window leaves Max Tokens on the settings sheet's ceiling, not on
+ // whatever the previous model left behind.
+ const defaultMaxTokens = localMaxTokensCeiling(
+ loadedContextLength,
+ unreportedWindowMaxTokens(response.is_gguf ?? false, current.maxTokens),
+ );
return {
...next,
maxTokens: defaultMaxTokens,
@@ -310,20 +320,24 @@ export function resolveLoadMaxSeqLength({
ggufVariant,
isGguf,
customContextLength,
- ggufContextLength,
+ loadedContextLength,
currentCheckpoint,
activeGgufVariant,
- maxSeqLength,
+ isMlx,
+ pinnedMaxSeqLength,
+ defaultMaxSeqLength,
presetSource,
}: {
modelId: string;
ggufVariant?: string | null;
isGguf?: boolean | null;
customContextLength: number | null;
- ggufContextLength: number | null;
+ loadedContextLength: number | null;
currentCheckpoint: string;
activeGgufVariant?: string | null;
- maxSeqLength: number;
+ isMlx?: boolean | null;
+ pinnedMaxSeqLength: number | null;
+ defaultMaxSeqLength: number;
presetSource: ChatPresetSource;
}): number {
const isDirectGgufFile = modelId.toLowerCase().endsWith(".gguf");
@@ -340,12 +354,147 @@ export function resolveLoadMaxSeqLength({
return 0;
}
if (isReloadingCurrentGguf) {
- return ggufContextLength ?? 0;
+ return loadedContextLength ?? 0;
}
if (isGgufLoad) {
return 0;
}
- return maxSeqLength;
+ if (pinnedMaxSeqLength != null) {
+ return pinnedMaxSeqLength;
+ }
+ return unpinnedLoadContext(isGgufLoad, isMlx, defaultMaxSeqLength);
+}
+
+/** The user's own context pin behind a load request, or null where the request is not one.
+ *
+ * A record written before the MLX pin moved fields carries it in `maxSeqLength`, which is
+ * the value `resolveLoadMaxSeqLength` builds the request from, so the completed load has
+ * to pin the same number or the UI reads a pinned runtime as Auto. llama.cpp's
+ * `maxSeqLength` is not a context pin, so only MLX admits it.
+ */
+export function loadRequestContextPin(
+ customContextLength: number | null,
+ isMlx: boolean | null | undefined,
+ pinnedMaxSeqLength: number | null,
+): number | null {
+ return customContextLength ?? (isMlx ? pinnedMaxSeqLength : null);
+}
+
+/** The context pin to keep for a model that has just loaded, or null if it has none.
+ *
+ * They pin for different reasons: llama.cpp's matters only under manual memory with
+ * auto layers, where `--fit` owns sizing; MLX sizes itself when asked for nothing, so
+ * any positive request was the user's choice.
+ */
+export function retainedContextPin({
+ isMlx,
+ requestedContextLength,
+}: {
+ isMlx?: boolean | null;
+ requestedContextLength: number | null;
+}): number | null {
+ return isMlx && (requestedContextLength ?? 0) > 0 ? requestedContextLength : null;
+}
+
+/** The context a preset records, in the one field that replays as a pin.
+ *
+ * A window nobody pinned is not recorded: replaying asks for nothing and the backend
+ * arrives there again, while storing it would turn it into a request. llama.cpp is the
+ * exception, since its window depends on the machine.
+ */
+export function capturedContextLength({
+ isGguf,
+ controlPin,
+ loadedContextLength,
+}: {
+ isGguf: boolean;
+ controlPin: number | null | undefined;
+ loadedContextLength: number | null | undefined;
+}): number | null {
+ return controlPin ?? (isGguf ? (loadedContextLength ?? null) : null);
+}
+
+/** The context length to record for a model that has just loaded.
+ *
+ * The reported window, not the request: a self-sizing backend was asked with the
+ * non-positive sentinel. Only where nothing was reported does the request stand.
+ */
+export function loadedContextForParams(
+ reportedContextLength: number | null | undefined,
+ requestedMaxSeqLength: number,
+ previousMaxSeqLength: number,
+): number {
+ if (reportedContextLength != null) {
+ return reportedContextLength;
+ }
+ return requestedMaxSeqLength > 0 ? requestedMaxSeqLength : previousMaxSeqLength;
+}
+
+/** What bounds Max Tokens when the model reported no window at all.
+ *
+ * llama.cpp reports one whenever it can read it, so a missing one is a failed read and
+ * the held value stands. A backend that never reports keeps the app default, since the
+ * session's length is a request and on a model change is the outgoing model's.
+ */
+export function unreportedWindowMaxTokens(
+ isGguf: boolean,
+ currentMaxTokens: number,
+): number {
+ return isGguf ? currentMaxTokens : defaultInferenceParams.maxSeqLength;
+}
+
+/** The most tokens a local model may be asked to generate.
+ *
+ * The control's minimum outranks the window: a slider whose maximum is below its
+ * minimum cannot be operated. Reachable, since MLX honours a tiny positive request.
+ */
+export function localMaxTokensCeiling(
+ loadedContextLength: number | null,
+ unreportedWindowFallback: number,
+): number {
+ return Math.max(MAX_TOKENS_MIN, loadedContextLength ?? unreportedWindowFallback);
+}
+
+/** The cap a load hands `getReplayedParams`, floored the same way the ceiling above is.
+ *
+ * That clamp only lowers Max Tokens, so a raw window below the control's minimum would
+ * leave the value outside its own slider. `undefined` means nothing sized a window.
+ */
+export function replayMaxTokensCap(
+ loadedContextLength: number | null | undefined,
+): number | undefined {
+ return loadedContextLength == null
+ ? undefined
+ : Math.max(MAX_TOKENS_MIN, loadedContextLength);
+}
+
+/** The app-level request to fall back on when the target has no pin of its own.
+ *
+ * `params.maxSeqLength` holds a REQUEST only while the backend serving it does not size
+ * its own window. A load that sized one wrote its RESOLVED window there instead, so
+ * carrying that value into the next model asks transformers to allocate the outgoing
+ * model's window: leaving a 131072 MLX model for an unconfigured one loads it at 131072.
+ */
+export function unpinnedDefaultRequest(
+ outgoingSizedItsOwnWindow: boolean | null | undefined,
+ sessionMaxSeqLength: number | null | undefined,
+ appDefault: number,
+): number {
+ if (outgoingSizedItsOwnWindow) return appDefault;
+ return sessionMaxSeqLength || appDefault;
+}
+
+/** What a load asks for when the user has pinned no context of their own.
+ *
+ * Both local backends take the same non-positive sentinel to mean "size it yourself".
+ * The app default covers the remaining case, where nothing fits a window.
+ */
+export function unpinnedLoadContext(
+ isGgufLoad: boolean,
+ isMlx: boolean | null | undefined,
+ appDefault: number,
+): number {
+ return isGgufLoad || isMlx ? 0 : appDefault;
}
/**
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsx
index d6349ad3b2a..35e586cd984 100644
--- a/studio/frontend/src/features/chat/runtime-provider.tsx
+++ b/studio/frontend/src/features/chat/runtime-provider.tsx
@@ -1971,17 +1971,20 @@ function useStudioRuntimeAdapters(
| undefined;
const store = useChatRuntimeStore.getState();
// Window check applies only when a local GGUF window is known; external
- // providers have ggufContextLength === null.
+ // providers have loadedContextLength === null. llama.cpp stops at the window, so
+ // a saved count past it is stale; MLX runs past it by design, and a thread whose
+ // recount is unsupported -- a VLM, or one carrying tool history -- would never
+ // get another count to replace the one rejected here.
+ const localLimit = store.loadedIsGguf ? store.loadedContextLength : null;
const withinLocalLimit =
- !store.ggufContextLength ||
- (savedUsage?.totalTokens ?? 0) <= store.ggufContextLength;
+ !localLimit || (savedUsage?.totalTokens ?? 0) <= localLimit;
// Legacy unscoped usage (no modelId) is trusted only when a known local
// window bounds the totals, so an old local turn can't be misattributed
// to a newly-selected external provider.
const modelMatches = savedUsage?.modelId
? savedUsage.modelId === store.params.checkpoint
- : typeof store.ggufContextLength === "number" &&
- store.ggufContextLength > 0;
+ : typeof store.loadedContextLength === "number" &&
+ store.loadedContextLength > 0;
// The value, not a boolean: the writes below need the narrowing.
const restoredUsage =
savedUsage && withinLocalLimit && modelMatches ? savedUsage : null;
@@ -2426,7 +2429,7 @@ function ThreadNewChatSwitch({
const isLoading = useAuiState(({ threads }) => threads.isLoading);
const mainThreadId = useAuiState(({ threads }) => threads.mainThreadId);
const checkpoint = useChatRuntimeStore((s) => s.params.checkpoint);
- const ggufContextLength = useChatRuntimeStore((s) => s.ggufContextLength);
+ const loadedContextLength = useChatRuntimeStore((s) => s.loadedContextLength);
const modelLoading = useChatRuntimeStore((s) => s.modelLoading);
// Read only by the recount below: New Chat itself must not care whether a run is still going.
const runActive = useChatRuntimeStore((s) =>
@@ -2639,7 +2642,7 @@ function ThreadNewChatSwitch({
modelLoading ||
runActive ||
!checkpoint ||
- ggufContextLength == null
+ loadedContextLength == null
) {
return;
}
@@ -2652,7 +2655,7 @@ function ThreadNewChatSwitch({
// cannot cover for it -- an unpersisted New Chat has no activeThreadId.
}, [
checkpoint,
- ggufContextLength,
+ loadedContextLength,
isLoading,
modelLoading,
nonce,
@@ -2977,7 +2980,7 @@ function ThreadContextUsageRecount({
}: { enabled: boolean }): ReactElement | null {
const activeThreadId = useChatRuntimeStore((s) => s.activeThreadId);
const checkpoint = useChatRuntimeStore((s) => s.params.checkpoint);
- const ggufContextLength = useChatRuntimeStore((s) => s.ggufContextLength);
+ const loadedContextLength = useChatRuntimeStore((s) => s.loadedContextLength);
const modelLoading = useChatRuntimeStore((s) => s.modelLoading);
// A DEPENDENCY, not just a guard: nothing else here changes when a run ends, so a count skipped
// for being busy would never be retried. Every run, not just local ones, since that is what the
@@ -2993,7 +2996,7 @@ function ThreadContextUsageRecount({
modelLoading ||
runActive ||
!checkpoint ||
- ggufContextLength == null
+ loadedContextLength == null
) {
return;
}
@@ -3004,7 +3007,7 @@ function ThreadContextUsageRecount({
activeThreadId,
checkpoint,
enabled,
- ggufContextLength,
+ loadedContextLength,
runActive,
modelLoading,
]);
diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsx
index 94b84ee391b..8e396044120 100644
--- a/studio/frontend/src/features/chat/shared-composer.tsx
+++ b/studio/frontend/src/features/chat/shared-composer.tsx
@@ -111,13 +111,16 @@ import { confirmRemoteCodeIfNeeded } from "@/features/security";
import {
DEFAULT_MAX_SEQ_LENGTH,
DEFAULT_PER_MODEL_CONFIG,
- normalizeMaxSeqLength,
+ isServedByMlx,
+ savedContextPin,
resolveInitialConfig,
type PerModelConfig,
+ loadedContextFields,
} from "@/features/model-picker";
import { loadManagedLlamaFlags } from "@/features/model-picker/api/llama-flags";
import { fetchLoadExtraArgs } from "@/features/model-picker/api/model-overrides";
import { sanitizeStoredExtraArgs } from "@/features/model-picker/model-config/llama-extra-args";
+import { usePlatformStore } from "@/config/env";
import {
confirmTransformersUpgradeIfNeeded,
useTransformersUpgradeDialogStore,
@@ -128,7 +131,14 @@ import {
loadModel,
validateModel,
} from "./api/chat-api";
-import { resolveFitMaxSeqLength, resolveExplicitCtxPin } from "./presets/preset-policy";
+import {
+ loadedContextForParams,
+ resolveExplicitCtxPin,
+ resolveFitMaxSeqLength,
+ retainedContextPin,
+ unpinnedLoadContext,
+ replayMaxTokensCap,
+} from "./presets/preset-policy";
import { ensureGpuDeviceCache } from "@/hooks/use-gpu-info";
import {
parseExternalModelId,
@@ -1303,6 +1313,7 @@ export function SharedComposer({
const targetIsGguf =
(sel.ggufVariant ?? null) != null ||
sel.id.toLowerCase().endsWith(".gguf");
+ const platform = usePlatformStore.getState();
let resolvedIsDiffusion = sel.isDiffusion;
// Set when the preflight could not classify the GGUF, so a false
// resolvedIsDiffusion below must not be read as "ordinary".
@@ -1378,16 +1389,19 @@ export function SharedComposer({
// The load still works; a real overrides outage surfaces there.
}
}
- // Mirror single-view resolveLoadMaxSeqLength: a GGUF pane with no explicit
- // context loads at native (0 -> n_ctx_train), not the session maxSeqLength,
- // which would silently shrink the shown context.
- // A non-GGUF pane with no saved maxSeqLength falls back to the app default,
- // not the active model's shared runtime snapshot: else comparing a saved
- // 128K model against an unconfigured one loads the latter at 128K and OOMs.
+ // Mirror single-view resolveLoadMaxSeqLength: a pane with no explicit context
+ // hands sizing to whichever local backend serves it, not the session
+ // maxSeqLength, which would silently shrink the shown context. One no local
+ // backend serves falls back to the app default rather than the active model's
+ // runtime snapshot, else comparing a saved 128K model against an unconfigured
+ // one loads the latter at 128K and OOMs.
const effectiveMaxSeqLength =
- ownConfig.customContextLength ??
- normalizeMaxSeqLength(ownConfig.maxSeqLength) ??
- (targetIsGguf ? 0 : DEFAULT_MAX_SEQ_LENGTH);
+ savedContextPin(ownConfig) ??
+ unpinnedLoadContext(
+ targetIsGguf,
+ isServedByMlx(targetIsGguf, platform.deviceType, platform.chatOnlyReason),
+ DEFAULT_MAX_SEQ_LENGTH,
+ );
const effectiveChatTemplateOverride = cleanCompareChatTemplate(
ownConfig.chatTemplateOverride,
);
@@ -1618,9 +1632,15 @@ export function SharedComposer({
// remembered settings, and a budget kept from a larger context does
// not fit the one it just loaded with.
{
- maxTokensCap: resp.is_gguf
- ? (resp.context_length ?? undefined)
- : effectiveMaxSeqLength,
+ // The reported window leads and the request stands in only for a backend
+ // that sizes nothing, as on the interactive load: an unpinned pane sends
+ // the auto-size sentinel, and capping a budget at 0 asks for no output.
+ maxTokensCap: replayMaxTokensCap(
+ loadedContextFields(resp).loadedContextLength ??
+ (!resp.is_gguf && effectiveMaxSeqLength > 0
+ ? effectiveMaxSeqLength
+ : null),
+ ),
},
);
store.setModelRequiresTrustRemoteCode(
@@ -1629,11 +1649,17 @@ export function SharedComposer({
// This pane's own saved Context Length, not compareMaxSeqLength: the wire
// value is Auto-resolved for a same-model reload, so pinning it would
// convert Auto into a number the user never set (see resolveExplicitCtxPin).
- // Non-GGUF compare loads send a sequence length rather than an n_ctx, so
- // their baseline clears.
+ // A non-GGUF pane keeps an MLX pin instead of clearing its baseline.
const keepCustomCtx = targetIsGguf
? resolveExplicitCtxPin(effectiveCustomContextLength)
- : null;
+ : retainedContextPin({
+ isMlx: isServedByMlx(
+ targetIsGguf,
+ platform.deviceType,
+ platform.chatOnlyReason,
+ ),
+ requestedContextLength: compareMaxSeqLength,
+ });
// Slots this compare load committed. Diffusion ignores --parallel, so a
// count there would mint a phantom override a preset carries onto a GGUF.
const committedSlots =
@@ -1686,11 +1712,11 @@ export function SharedComposer({
defaultChatTemplate: resp.chat_template ?? null,
chatTemplateOverride: effectiveChatTemplateOverride,
loadedChatTemplateOverride: effectiveChatTemplateOverride,
- // The context baseline this pane loaded with (see keepCustomCtx above),
- // so a later Apply/Reset can't silently revert a Manual+Auto pin.
+ // The context baseline this pane loaded with (see keepCustomCtx above), so a
+ // later Apply/Reset can't silently revert the pin it was serving.
loadedCustomContextLength: keepCustomCtx,
// Adopt the load response's GPU-memory fields (mode/layers/MoE/split/pick
- // plus loaded baselines) so the GPU controls round-trip. (gguf context,
+ // plus loaded baselines) so the GPU controls round-trip. (The context group,
// customContextLength and native-path token/expiry clear in the tail below.)
...loadedGpuMemoryFields(resp),
// Drives the GPU Memory controls' diffusion gate; set alongside the
@@ -1706,13 +1732,7 @@ export function SharedComposer({
// active model the UI and later reload/save use the context it actually
// loaded with, not the previous/default one.
customContextLength: keepCustomCtx,
- ggufContextLength: resp.is_gguf ? (resp.context_length ?? null) : null,
- ggufNativeContextLength: resp.is_gguf
- ? (resp.native_context_length ?? null)
- : null,
- ggufMaxContextLength: resp.is_gguf
- ? (resp.max_context_length ?? null)
- : null,
+ ...loadedContextFields(resp),
// Compare selections load by repo/variant, never from the file picker,
// so they carry no native lease. Clear any prior picked file's
// token/expiry so the reload path never sends a stale lease.
@@ -1722,9 +1742,14 @@ export function SharedComposer({
});
if (!targetIsGguf) {
// Non-GGUF panes carry their context in params.maxSeqLength.
+ const paneParams = useChatRuntimeStore.getState().params;
store.setParams({
- ...useChatRuntimeStore.getState().params,
- maxSeqLength: effectiveMaxSeqLength,
+ ...paneParams,
+ maxSeqLength: loadedContextForParams(
+ loadedContextFields(resp).loadedContextLength,
+ effectiveMaxSeqLength,
+ paneParams.maxSeqLength,
+ ),
});
}
loadedFromConfig = config != null;
diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
index b90525cce2a..f838f4a4d7c 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -6,6 +6,7 @@ import {
mirrorHfTokenInto,
useHfTokenStore,
} from "@/features/hub/stores/hf-token-store";
+import { loadedContextFields } from "@/features/model-picker/model-config/per-model-config";
import {
cachedPinnableGpuIndexKind,
reconcileCachedGpuSelection,
@@ -2484,9 +2485,18 @@ type ChatRuntimeStore = {
residentCheckpoint: string | null | undefined;
/** Whether the backend loaded the active model from a filesystem path. */
activeModelIsLocal: boolean;
- ggufContextLength: number | null;
- ggufMaxContextLength: number | null;
- ggufNativeContextLength: number | null;
+ loadedContextLength: number | null;
+ maxContextLength: number | null;
+ nativeContextLength: number | null;
+ /** The backend's own is_gguf for the loaded model; null until one loads. Set wherever
+ * loadedContextLength is, so a context never arrives unattributed. */
+ loadedIsGguf: boolean | null;
+ /** The backend's own is_mlx for the loaded model; null until one loads. The platform
+ * cannot answer it: the worker serves native-audio checkpoints off the MLX path. */
+ loadedIsMlx: boolean | null;
+ /** Whether loadedContextLength actually bounds the cache. Null where the backend does
+ * not answer, which is not the same as a confirmed false. */
+ loadedContextEnforced: boolean | null;
modelRequiresTrustRemoteCode: boolean;
supportsReasoning: boolean;
reasoningAlwaysOn: boolean;
@@ -3397,8 +3407,9 @@ function pickLocallyEditedParams(
}
/** The context the last load or status published for the model on screen.
- * ggufContextLength covers only GGUF, so without this a safetensors model has
- * nothing to clamp the hydration replay against. Keyed by checkpoint. */
+ * loadedContextLength covers only a backend that sizes a window, so without this
+ * a safetensors model has nothing to clamp the hydration replay against. Keyed
+ * by checkpoint. */
let loadedContext: { checkpoint: string; cap: number } | null = null;
function noteLoadedContext(checkpoint: string, cap: number | undefined): void {
@@ -3672,12 +3683,12 @@ function getHydratedSettingsState(
// Outside the replay: an install with only a global set has no entry, and the
// budget restored from it does not fit the load either.
const capped = nextState.params ?? params;
- // ggufContextLength describes whatever is resident, which an external pick
+ // loadedContextLength describes whatever is resident, which an external pick
// leaves loaded, so it is not this checkpoint's context to clamp against.
- const residentGgufCap = isExternalModelId(checkpoint)
+ const residentContextCap = isExternalModelId(checkpoint)
? null
- : state.ggufContextLength;
- const cap = loadedContextFor(checkpoint) ?? residentGgufCap;
+ : state.loadedContextLength;
+ const cap = loadedContextFor(checkpoint) ?? residentContextCap;
if (cap !== null && capped.maxTokens > cap) {
nextState.params = { ...capped, maxTokens: cap };
}
@@ -3733,9 +3744,12 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
activeGgufVariant: null,
residentCheckpoint: undefined,
activeModelIsLocal: false,
- ggufContextLength: null,
- ggufMaxContextLength: null,
- ggufNativeContextLength: null,
+ loadedContextLength: null,
+ maxContextLength: null,
+ nativeContextLength: null,
+ loadedIsGguf: null,
+ loadedIsMlx: null,
+ loadedContextEnforced: null,
modelRequiresTrustRemoteCode: false,
supportsReasoning: false,
reasoningAlwaysOn: false,
@@ -4548,9 +4562,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
activeLoadId: null,
activeNativePathToken: null,
activeNativePathExpiresAtMs: null,
- ggufContextLength: null,
- ggufMaxContextLength: null,
- ggufNativeContextLength: null,
+ ...loadedContextFields(null),
modelRequiresTrustRemoteCode: false,
contextUsage: null,
contextUsageByThreadId: {},
diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.ts
index e7e78ad4809..65d464601b2 100644
--- a/studio/frontend/src/features/chat/types/api.ts
+++ b/studio/frontend/src/features/chat/types/api.ts
@@ -249,6 +249,7 @@ export interface LoadModelResponse {
context_length?: number | null;
max_context_length?: number | null;
native_context_length?: number | null;
+ context_length_enforced?: boolean | null;
supports_reasoning?: boolean;
reasoning_style?:
| "enable_thinking"
@@ -366,6 +367,7 @@ export interface InferenceStatusResponse {
context_length?: number | null;
max_context_length?: number | null;
native_context_length?: number | null;
+ context_length_enforced?: boolean | null;
cache_type_kv?: string | null;
mlx_kv_bits?: number | null;
mlx_kv_bits_requested?: number | null;
@@ -393,8 +395,8 @@ export interface InferenceStatusResponse {
mmproj_fallback_reason?: MmprojFallbackReason | null;
n_cpu_moe?: number;
tensor_split?: number[] | null;
- /** n_ctx the active GGUF load was invoked with (0 = Auto); re-seeds a
- * Manual + Auto-layers context pin on hydration. Null for non-GGUF. */
+ /** The context the active load was invoked with (0 = let the backend choose); re-seeds
+ * the pin on hydration. Null where the serving backend records no request. */
requested_context_length?: number | null;
/** Effective GPU placement after fit-time narrowing. */
gpu_ids?: number[] | null;
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.ts
index 9c570ac036b..d61feac5f1a 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
@@ -33,7 +33,7 @@ const QUEUED_SETTING_KEYS = [
"ragTopK",
"ragAutoInject",
"ragAutoInjectMinScore",
- "ggufContextLength",
+ "loadedContextLength",
"autoHealToolCalls",
"nudgeToolCalls",
"maxToolCallsPerMessage",
diff --git a/studio/frontend/src/features/chat/utils/refresh-context-usage.ts b/studio/frontend/src/features/chat/utils/refresh-context-usage.ts
index bbc634778dc..c1e301f626b 100644
--- a/studio/frontend/src/features/chat/utils/refresh-context-usage.ts
+++ b/studio/frontend/src/features/chat/utils/refresh-context-usage.ts
@@ -184,7 +184,7 @@ type RefreshOptions =
}
| undefined;
-/** Re-count prompt tokens for the active local GGUF chat and fill the usage bar. */
+/** Re-count prompt tokens for the active local chat and fill the usage bar. */
export async function refreshContextUsage(
options?: RefreshOptions,
): Promise<void> {
@@ -196,7 +196,7 @@ export async function refreshContextUsage(
!checkpoint ||
isExternalModelId(checkpoint) ||
(!options?.afterModelLoad && store.modelLoading) ||
- store.ggufContextLength == null
+ store.loadedContextLength == null
) {
return;
}
diff --git a/studio/frontend/src/features/hub/hub-page.tsx b/studio/frontend/src/features/hub/hub-page.tsx
index 87cb729f62b..da6d8693400 100644
--- a/studio/frontend/src/features/hub/hub-page.tsx
+++ b/studio/frontend/src/features/hub/hub-page.tsx
@@ -426,8 +426,8 @@ export function ModelsPage() {
? checkpoint
: null;
const activeGgufVariant = useChatRuntimeStore((s) => s.activeGgufVariant);
- const activeGgufContextLength = useChatRuntimeStore(
- (s) => s.ggufContextLength,
+ const activeLoadedContextLength = useChatRuntimeStore(
+ (s) => s.loadedContextLength,
);
const [initialResidentStatusSettled, setInitialResidentStatusSettled] =
useState(false);
@@ -2112,7 +2112,7 @@ export function ModelsPage() {
target={settingsTarget}
loadedConfig={settingsTargetIsResident ? activeModelConfig : null}
loadedContextLength={
- settingsTargetIsResident ? activeGgufContextLength : null
+ settingsTargetIsResident ? activeLoadedContextLength : null
}
onBack={() => setSettingsTarget(null)}
onRun={runSettingsTarget}
diff --git a/studio/frontend/src/features/model-picker/api/model-overrides.ts b/studio/frontend/src/features/model-picker/api/model-overrides.ts
index 18ef6daf10b..b19d2b67914 100644
--- a/studio/frontend/src/features/model-picker/api/model-overrides.ts
+++ b/studio/frontend/src/features/model-picker/api/model-overrides.ts
@@ -319,11 +319,20 @@ export function fromApiOverride(
// Only a physical pin travels (toApiOverride drops the rest), so a row without ids
// says nothing about placement and a local Vulkan ordinal keeps its own namespace.
const serverGpuIds = override.gpu_ids?.length ? override.gpu_ids : null;
+ // The pin is ONE setting in one of two fields, and an edit clears the other
+ // (contextPinPatch). Filling them from different sources mints a record that loads at
+ // two lengths, since the picker reads customContextLength first and the API's
+ // auto-switch max_seq_length first. So a row stating either field owns both.
+ const serverStatesPin =
+ override.custom_context_length != null || override.max_seq_length != null;
const normalized = normalizePerModelConfig({
...DEFAULT_PER_MODEL_CONFIG,
- customContextLength:
- override.custom_context_length ?? local.customContextLength,
- maxSeqLength: override.max_seq_length ?? local.maxSeqLength,
+ customContextLength: serverStatesPin
+ ? (override.custom_context_length ?? null)
+ : local.customContextLength,
+ maxSeqLength: serverStatesPin
+ ? (override.max_seq_length ?? null)
+ : local.maxSeqLength,
kvCacheDtype: override.kv_cache_dtype ?? local.kvCacheDtype,
mlxKvBits: override.mlx_kv_bits ?? local.mlxKvBits,
speculativeType: override.speculative_type ?? local.speculativeType,
diff --git a/studio/frontend/src/features/model-picker/components/model-config-page.tsx b/studio/frontend/src/features/model-picker/components/model-config-page.tsx
index b3c53a8eb4f..8f1f6dd968d 100644
--- a/studio/frontend/src/features/model-picker/components/model-config-page.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-config-page.tsx
@@ -133,7 +133,9 @@ import {
deletePerModelConfig,
floorMaxSeqLength,
isDefaultConfig,
+ contextPinPatch,
isServedByMlx,
+ savedContextPin,
normalizeMaxSeqLength,
normalizePerModelConfig,
perModelConfigStorageChanged,
@@ -386,20 +388,32 @@ function MaxSeqLengthSetting({
inputMax,
onChange,
inputRef,
+ isMlx,
+ pinned,
+ windowUnknown,
}: {
value: number;
max: number;
inputMax: number;
onChange: (value: number) => void;
inputRef?: Ref<NumericValueInputHandle>;
+ isMlx?: boolean;
+ pinned?: boolean;
+ windowUnknown?: boolean;
}) {
+ // MLX sizes itself when unpinned, so the control is the GGUF path's Context Length and
+ // shows the length that will be served, not "Auto". A dash only while it is unknown.
+ const label = isMlx ? "Context Length" : "Max Seq Length";
return (
<div className="space-y-3">
<div className={ROW_CLASS}>
<div className="flex min-w-0 items-center gap-1.5">
- <span className={LABEL_CLASS}>Max Seq Length</span>
+ <span className={LABEL_CLASS}>{label}</span>
<InfoHint>
- Maximum context window size in tokens. Applies when the model loads.
+ {isMlx
+ ? "Tokens of context the model is sized for. Whether it also caps the " +
+ "cache depends on the architecture."
+ : "Maximum context window size in tokens. Applies when the model loads."}
</InfoHint>
</div>
<NumericValueInput
@@ -409,7 +423,9 @@ function MaxSeqLengthSetting({
max={inputMax}
step={MAX_SEQ_LENGTH_STEP}
onChange={onChange}
- ariaLabel="Max Seq Length"
+ displayValue={isMlx && windowUnknown ? "—" : undefined}
+ derived={isMlx && !pinned}
+ ariaLabel={label}
className={NUMBER_INPUT_CLASS}
size={8}
/>
@@ -418,10 +434,12 @@ function MaxSeqLengthSetting({
min={MAX_SEQ_LENGTH_MIN}
max={max}
step={MAX_SEQ_LENGTH_STEP}
- value={[value]}
+ // Outside the control's range it sits at the nearer edge, or the first nudge
+ // would step from the shown number onto the bound.
+ value={[Math.min(Math.max(value, MAX_SEQ_LENGTH_MIN), max)]}
onValueChange={([next]) => onChange(next)}
className="panel-slider"
- aria-label="Max Seq Length"
+ aria-label={label}
/>
</div>
);
@@ -2035,7 +2053,7 @@ export function ModelConfigPage({
(s) => s.defaultChatTemplate,
);
const loadedMaxContextLength = useChatRuntimeStore(
- (s) => s.ggufMaxContextLength,
+ (s) => s.maxContextLength,
);
// What settings are stored under, which is not always what loads; the probes keep target.id.
const configId = target.configId ?? target.id;
@@ -2695,10 +2713,19 @@ export function ModelConfigPage({
const baseline = resolvedIsDiffusion
? withoutUnsupportedDiffusionSettings(rawBaseline, gpuIndexKind)
: rawBaseline;
+ const platform = usePlatformStore();
+ const targetIsMlx = isServedByMlx(
+ target.isGguf,
+ platform.deviceType,
+ platform.chatOnlyReason,
+ );
const atBaseline = perModelConfigsEqual(config, baseline);
// The fitted value is an outcome, not an override. Auto stays at the default even
- // when a loaded model reports less than its native context.
- const contextAtDefault = !target.isGguf || config.customContextLength == null;
+ // when a loaded model reports less than its native context. A non-GGUF pin is an
+ // override too, read from whichever field it was saved in.
+ const contextAtDefault = !target.isGguf
+ ? savedContextPin(config) == null
+ : config.customContextLength == null;
const atDefault =
contextAtDefault &&
perModelConfigsEqual(
@@ -2708,15 +2735,40 @@ export function ModelConfigPage({
const nativeMaxSeqLength =
floorMaxSeqLength(modelMaxPosition.maxPositionEmbeddings) ??
MAX_SEQ_LENGTH_MAX;
- // A non-GGUF active model seeds maxSeqLength from its loaded value. Once cleared, fall back to
- // the app default, not the loaded runtime value, else the override can never be cleared.
+ // The pin, else the length a self-sizing backend would serve, so the control states a
+ // context rather than declining to. Only an unread window falls back to the app default,
+ // and Reset clears the pin to null so no fallback may rebuild one from a runtime value.
+ // Reported as it stands, not snapped to the request step: 2,056 would read 2,048.
+ const servedWindow = (value: unknown) =>
+ typeof value === "number" && Number.isFinite(value) && value > 0
+ ? Math.floor(value)
+ : null;
+ const mlxNativeWindow = targetIsMlx
+ ? servedWindow(modelMaxPosition.maxPositionEmbeddings)
+ : null;
+ // What a load would serve. The backend clamps an auto-sized window to the request
+ // ceiling, so a wider native one (Scout declares 10,485,760) would name a length no
+ // load can serve. Native above stays raw: metadata, not a promise.
+ const mlxProspectiveWindow =
+ mlxNativeWindow == null
+ ? null
+ : Math.min(mlxNativeWindow, MAX_SEQ_LENGTH_MAX);
+ const mlxServedWindow =
+ (targetIsMlx && isActiveModel ? servedWindow(loadedContextLength) : null) ??
+ mlxProspectiveWindow;
const maxSeqLengthValue =
- normalizeMaxSeqLength(config.maxSeqLength) ??
+ servedWindow(savedContextPin(config)) ??
+ mlxServedWindow ??
clampMaxSeqLength(DEFAULT_MAX_SEQ_LENGTH, nativeMaxSeqLength);
- const maxSeqLengthMax = Math.max(nativeMaxSeqLength, maxSeqLengthValue);
- // An auto-fit-below-native GGUF shows activeLoadedContext while customContextLength stays null.
- // If the user fixes GPU Layers (Manual) and remembers, pin that shown context so a later fresh
- // load keeps the fitted placement instead of sending native/0 and recreating the OOM.
+ // The slider picks a request, so it stops at the widest a load may make.
+ const maxSeqLengthMax = Math.min(
+ MAX_SEQ_LENGTH_MAX,
+ Math.max(nativeMaxSeqLength, maxSeqLengthValue),
+ );
+ // An auto-fit-below-native GGUF shows activeLoadedContext while
+ // customContextLength stays null. If the user fixes GPU Layers (Manual) and
+ // remembers, pin that shown context so a later fresh load keeps the fitted
+ // placement instead of sending native/0 for fixed layers and recreating the OOM.
const loadableConfig = resolvedIsDiffusion
? withoutUnsupportedDiffusionSettings(config, gpuIndexKind)
: config;
@@ -2737,8 +2789,8 @@ export function ModelConfigPage({
loadableConfig.gpuLayers >= 0 &&
loadableConfig.customContextLength == null &&
activeLoadedContext != null;
- // Persisted record: keep config as-is (non-GGUF keeps maxSeqLength null) so isDefaultConfig
- // recognises it and clears a remembered override instead of pinning the app default.
+ // Kept as-is so isDefaultConfig clears a remembered override rather than pinning the
+ // app default; the write rule already settled which field holds the pin.
const runtimeConfig = target.isGguf
? pinFixedLayerContext
? { ...loadableConfig, customContextLength: activeLoadedContext }
@@ -3018,10 +3070,7 @@ export function ModelConfigPage({
pendingPatch.customContextLength = committedContext;
}
if (committedMaxSeqLength != null) {
- pendingPatch.maxSeqLength = clampMaxSeqLength(
- committedMaxSeqLength,
- MAX_SEQ_LENGTH_MAX,
- );
+ Object.assign(pendingPatch, contextPinPatch(committedMaxSeqLength, targetIsMlx));
}
if (committedGpuLayers != null) {
pendingPatch.gpuLayers = committedGpuLayers;
@@ -3124,9 +3173,12 @@ export function ModelConfigPage({
if (saveFailed) {
toast.error("Couldn't save these settings, loading with them anyway.");
}
+ // MLX pins in customContextLength as GGUF does, so unpinned sends nothing.
const effectiveLoadConfig = target.isGguf
? effectiveRuntimeConfig
- : { ...effectiveRuntimeConfig, maxSeqLength: effectiveMaxSeqLengthValue };
+ : targetIsMlx
+ ? effectiveRuntimeConfig
+ : { ...effectiveRuntimeConfig, maxSeqLength: effectiveMaxSeqLengthValue };
// Same reason as the numeric commits above: the budget row flushes on unmount,
// which for this click lands after onRun has staged the load, so that load (the
// very one the control promises) would use the old fraction. A failed save must
@@ -3328,11 +3380,12 @@ export function ModelConfigPage({
max={maxSeqLengthMax}
inputMax={MAX_SEQ_LENGTH_MAX}
inputRef={maxSeqLengthInputRef}
- onChange={(value) =>
- update({
- maxSeqLength: clampMaxSeqLength(value, MAX_SEQ_LENGTH_MAX),
- })
+ isMlx={targetIsMlx}
+ pinned={savedContextPin(config) != null}
+ windowUnknown={
+ savedContextPin(config) == null && mlxServedWindow == null
}
+ onChange={(value) => update(contextPinPatch(value, targetIsMlx))}
/>
{showAdvanced && (
<MlxAdvancedSettings
diff --git a/studio/frontend/src/features/model-picker/components/model-selector.tsx b/studio/frontend/src/features/model-picker/components/model-selector.tsx
index 8bda5ffb14c..8dc3649e2e2 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-selector.tsx
@@ -155,7 +155,7 @@ interface ModelSelectorProps {
loaded?: boolean;
activeGgufVariant?: string | null;
activeModelConfig?: PerModelConfig | null;
- activeGgufContextLength?: number | null;
+ activeLoadedContextLength?: number | null;
selectedConfig?: PerModelConfig | null;
selectedGgufVariant?: string | null;
onValueChange?: (value: string, meta: ModelSelectorChangeMeta) => void;
@@ -363,7 +363,7 @@ function ModelSelectorContent({
value,
activeGgufVariant,
activeModelConfig,
- activeGgufContextLength,
+ activeLoadedContextLength,
selectedConfig,
selectedGgufVariant,
onSelect,
@@ -388,7 +388,7 @@ function ModelSelectorContent({
value?: string;
activeGgufVariant?: string | null;
activeModelConfig?: PerModelConfig | null;
- activeGgufContextLength?: number | null;
+ activeLoadedContextLength?: number | null;
selectedConfig?: PerModelConfig | null;
selectedGgufVariant?: string | null;
onSelect: (id: string, meta: ModelSelectorChangeMeta) => void;
@@ -587,7 +587,7 @@ function ModelSelectorContent({
value === visibleConfigTarget.id &&
(activeGgufVariant ?? null) ===
(visibleConfigTarget.ggufVariant ?? null)
- ? (activeGgufContextLength ?? null)
+ ? (activeLoadedContextLength ?? null)
: null
}
initialConfig={
@@ -651,7 +651,7 @@ export function ModelSelector({
defaultValue,
activeGgufVariant,
activeModelConfig,
- activeGgufContextLength,
+ activeLoadedContextLength,
selectedConfig,
selectedGgufVariant,
onValueChange,
@@ -824,7 +824,7 @@ export function ModelSelector({
value={selected}
activeGgufVariant={activeGgufVariant}
activeModelConfig={activeModelConfig}
- activeGgufContextLength={activeGgufContextLength}
+ activeLoadedContextLength={activeLoadedContextLength}
selectedConfig={selectedConfig}
selectedGgufVariant={selectedGgufVariant}
onSelect={handleSelect}
diff --git a/studio/frontend/src/features/model-picker/components/numeric-value-input.tsx b/studio/frontend/src/features/model-picker/components/numeric-value-input.tsx
index be9aa7745c1..27c823602ea 100644
--- a/studio/frontend/src/features/model-picker/components/numeric-value-input.tsx
+++ b/studio/frontend/src/features/model-picker/components/numeric-value-input.tsx
@@ -48,6 +48,7 @@ export const NumericValueInput = forwardRef<
step: number;
onChange: (v: number) => void;
displayValue?: string;
+ derived?: boolean;
className?: string;
ariaLabel?: string;
size?: number;
@@ -61,6 +62,7 @@ export const NumericValueInput = forwardRef<
step,
onChange,
displayValue,
+ derived = false,
className,
ariaLabel,
size: sizeAttr,
@@ -91,13 +93,26 @@ export const NumericValueInput = forwardRef<
lastBlurCommittedRef.current = null;
});
+ // The shown number is not always the user's -- a placeholder hides it, and a derived
+ // one stands in for a choice never made -- but typing it is still a choice.
+ const isEdit = (final: number) =>
+ final !== value || displayValue != null || derived;
+
const commitDraft = (raw: string): number | null => {
const parsed = Number.parseFloat(raw);
if (!Number.isFinite(parsed)) {
return null;
}
- const final = snapToStep(parsed, step, min, max);
- if (final !== value) {
+ // Committing the number already shown means that number, not the nearest one on the
+ // control's grid: a derived value describes what a load resolves to and need not sit
+ // on the grid. Outside what the control accepts it cannot be asked for at all, so it
+ // reads as no commit rather than as a value the blur bridge would hold.
+ const shown = parsed === value;
+ if (shown && ((max != null && parsed > max) || (min != null && parsed < min))) {
+ return null;
+ }
+ const final = shown ? parsed : snapToStep(parsed, step, min, max);
+ if (isEdit(final)) {
onChange(final);
}
return final;
@@ -134,7 +149,7 @@ export const NumericValueInput = forwardRef<
return null;
},
}),
- [draft, focused, max, min, onChange, step, value],
+ [derived, displayValue, draft, focused, max, min, onChange, step, value],
);
const displayed = focused ? draft : (displayValue ?? String(value));
@@ -175,12 +190,13 @@ export const NumericValueInput = forwardRef<
} else {
draftRef.current = String(final);
// Only bridge the still-stale parent value when the blur actually
- // dispatched onChange (final !== value). When final === value the
- // parent is already current, so there is nothing to bridge; caching
- // here would leave a stale pin that a later Reset or external edit
- // (which doesn't change the displayed value) can never clear, so a
- // following Load/Save would recreate the override Reset removed.
- lastBlurCommittedRef.current = final !== value ? final : null;
+ // dispatched onChange. Otherwise the parent is already current and
+ // there is nothing to bridge; caching here would leave a stale pin
+ // that a later Reset or external edit (which doesn't change the
+ // displayed value) can never clear, so a following Load/Save would
+ // recreate the override Reset removed. Same test as the dispatch, so
+ // a click in the same turn as the blur cannot see them disagree.
+ lastBlurCommittedRef.current = isEdit(final) ? final : null;
}
}
setFocused(false);
diff --git a/studio/frontend/src/features/model-picker/hooks/use-active-model-config.ts b/studio/frontend/src/features/model-picker/hooks/use-active-model-config.ts
index 6521942967a..dd204f2d0a1 100644
--- a/studio/frontend/src/features/model-picker/hooks/use-active-model-config.ts
+++ b/studio/frontend/src/features/model-picker/hooks/use-active-model-config.ts
@@ -2,10 +2,13 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { isExternalModelId, useChatRuntimeStore } from "@/features/chat";
-import { useMemo } from "react";
import { usePlatformStore } from "@/config/env";
-import type { PerModelConfig } from "../model-config/per-model-config";
-import { isServedByMlx } from "../model-config/per-model-config";
+import { useMemo } from "react";
+import {
+ type PerModelConfig,
+ isServedByLlamaCpp,
+ residentIsServedByMlx,
+} from "../model-config/per-model-config";
export interface ActiveModelConfigState {
checkpoint: string | null;
@@ -15,11 +18,13 @@ export interface ActiveModelConfigState {
export function useActiveModelConfig(): ActiveModelConfigState {
const checkpoint = useChatRuntimeStore((s) => s.params.checkpoint) || null;
- const deviceType = usePlatformStore((s) => s.deviceType);
- const chatOnlyReason = usePlatformStore((s) => s.chatOnlyReason);
const maxSeqLength = useChatRuntimeStore((s) => s.params.maxSeqLength);
const activeGgufVariant = useChatRuntimeStore((s) => s.activeGgufVariant);
- const ggufContextLength = useChatRuntimeStore((s) => s.ggufContextLength);
+ const loadedIsGguf = useChatRuntimeStore((s) => s.loadedIsGguf);
+ const loadedIsMlx = useChatRuntimeStore((s) => s.loadedIsMlx);
+ const activeNativePathToken = useChatRuntimeStore(
+ (s) => s.activeNativePathToken,
+ );
const customContextLength = useChatRuntimeStore((s) => s.customContextLength);
const kvCacheDtype = useChatRuntimeStore((s) => s.kvCacheDtype);
const mlxKvBits = useChatRuntimeStore((s) => s.mlxKvBits);
@@ -47,16 +52,23 @@ export function useActiveModelConfig(): ActiveModelConfigState {
(s) => s.selectedGpuIndexKind,
);
- const isGguf =
- activeGgufVariant != null ||
- ggufContextLength != null ||
- (checkpoint?.toLowerCase().endsWith(".gguf") ?? false);
+ const isGguf = isServedByLlamaCpp({
+ loadedIsGguf,
+ activeGgufVariant,
+ activeNativePathToken,
+ checkpoint,
+ });
+ const platform = usePlatformStore();
+ const isMlx = residentIsServedByMlx(
+ isGguf,
+ platform.deviceType,
+ platform.chatOnlyReason,
+ loadedIsMlx,
+ );
// Off-backend this stays null, or the model compares unequal to its own defaults
// over a field it cannot show.
- const effectiveMlxKvBits = isServedByMlx(isGguf, deviceType, chatOnlyReason)
- ? (mlxKvBits ?? null)
- : null;
+ const effectiveMlxKvBits = isMlx ? (mlxKvBits ?? null) : null;
const config = useMemo<PerModelConfig | null>(() => {
if (!checkpoint || isExternalModelId(checkpoint)) {
@@ -64,7 +76,10 @@ export function useActiveModelConfig(): ActiveModelConfigState {
}
const base: PerModelConfig = {
customContextLength: customContextLength ?? null,
- maxSeqLength: isGguf ? null : maxSeqLength,
+ // A self-sizing backend carries no pin here, exactly as the GGUF path does: this
+ // is the runtime's resolved length, and reading it back as the user's choice would
+ // pin every reload to whatever the first load happened to get.
+ maxSeqLength: isGguf || isMlx ? null : maxSeqLength,
kvCacheDtype: kvCacheDtype ?? null,
mlxKvBits: effectiveMlxKvBits,
speculativeType: speculativeType ?? "auto",
@@ -94,6 +109,7 @@ export function useActiveModelConfig(): ActiveModelConfigState {
}, [
checkpoint,
isGguf,
+ isMlx,
maxSeqLength,
customContextLength,
kvCacheDtype,
diff --git a/studio/frontend/src/features/model-picker/index.ts b/studio/frontend/src/features/model-picker/index.ts
index 245eb697757..e1d67ae6747 100644
--- a/studio/frontend/src/features/model-picker/index.ts
+++ b/studio/frontend/src/features/model-picker/index.ts
@@ -54,8 +54,13 @@ export {
PER_MODEL_CONFIG_STORAGE_KEY,
PER_MODEL_CONFIG_UPDATED_EVENT,
adoptLegacyConfigKey,
+ isServedByLlamaCpp,
+ contextPinPatch,
listPerModelConfigs,
isServedByMlx,
+ residentIsServedByMlx,
+ savedContextPin,
+ loadedContextFields,
presetLoadSettingNames,
resolveInitialConfig,
resolveResidentInitialConfig,
diff --git a/studio/frontend/src/features/model-picker/model-config/per-model-config.ts b/studio/frontend/src/features/model-picker/model-config/per-model-config.ts
index 562cd99a7eb..28954fe1e17 100644
--- a/studio/frontend/src/features/model-picker/model-config/per-model-config.ts
+++ b/studio/frontend/src/features/model-picker/model-config/per-model-config.ts
@@ -10,6 +10,7 @@ import {
normalizeModelIdentity,
publicModelId,
} from "./model-identity";
+import { isExternalModelId } from "@/features/chat/external-providers";
import {
DRAFT_N_MAX_SPEC_TYPES,
SEPARATE_DRAFT_MODEL_SPEC_TYPES,
@@ -115,8 +116,8 @@ export const N_BATCH_LLAMA_DEFAULT = 2048;
export const MAX_SEQ_LENGTH_MIN = 128;
export const MAX_SEQ_LENGTH_MAX = 1048576;
export const MAX_SEQ_LENGTH_STEP = 128;
-// App-default max sequence length when a non-GGUF model has no override. Both paths fall back
-// here rather than an active model's runtime value, so an unconfigured pane never OOMs.
+// App default for a model no local backend sizes itself. Every path falls back here, not
+// to an active model's runtime value, so an unconfigured pane never inherits and OOMs.
export const DEFAULT_MAX_SEQ_LENGTH = 4096;
export const CONTEXT_LENGTH_MIN = 128;
@@ -144,6 +145,22 @@ export function isServedByMlx(
);
}
+/** Whether MLX serves the RESIDENT model.
+ *
+ * The platform cannot answer it alone: the worker picks NativeAudioBackend for a
+ * native-audio checkpoint before the MLX fast-path, so those load on Apple Silicon
+ * without MLX serving them. `loadedIsMlx` is the backend's own answer, and null there
+ * means nothing is loaded yet, where the platform is still the best available one.
+ */
+export function residentIsServedByMlx(
+ isGguf: boolean,
+ deviceType: string | null | undefined,
+ chatOnlyReason: string | null | undefined,
+ loadedIsMlx: boolean | null | undefined,
+): boolean {
+ return isServedByMlx(isGguf, deviceType, chatOnlyReason) && loadedIsMlx !== false;
+}
+
export function presetLoadSettingNames(
isGguf: boolean,
deviceType: string | null | undefined,
@@ -157,6 +174,93 @@ export function presetLoadSettingNames(
: "max seq length";
}
+/** Whether llama.cpp serves the active model.
+ *
+ * `loadedIsGguf` is the backend's own answer; the rest identify a GGUF that has not
+ * reported one yet. A context length is not among them -- MLX reports one too, so it
+ * says a model is loaded, not which backend loaded it. An external provider is excluded
+ * because its id keeps a `.gguf` suffix while the flag describes a local load.
+ */
+export function isServedByLlamaCpp(x: {
+ loadedIsGguf?: boolean | null;
+ activeGgufVariant?: string | null;
+ activeNativePathToken?: string | null;
+ checkpoint?: string | null;
+}): boolean {
+ if (isExternalModelId(x.checkpoint)) return false;
+ // A reported non-GGUF backend settles it: the variant and path token outlive the pick
+ // that set them, so neither is evidence past a reload.
+ if (x.loadedIsGguf === false) return false;
+ return (
+ x.loadedIsGguf === true ||
+ x.activeGgufVariant != null ||
+ x.activeNativePathToken != null ||
+ String(x.checkpoint ?? "").toLowerCase().endsWith(".gguf")
+ );
+}
+
+/** The store's record of the context window a load left behind.
+ *
+ * A window counts when the backend that reported it sized one. MLX always does, so its
+ * `context_length` stands alone even with no trained window in the config. Transformers
+ * sizes nothing and echoes the requested max_seq_length, so without a native length it
+ * contributes no window.
+ *
+ * One constructor because the four move together: a window without the backend that
+ * produced it is what made a context length read as proof of a GGUF.
+ */
+export function loadedContextFields(resp: {
+ is_gguf?: boolean;
+ is_mlx?: boolean;
+ context_length?: number | null;
+ native_context_length?: number | null;
+ max_context_length?: number | null;
+ context_length_enforced?: boolean | null;
+} | null): {
+ loadedContextLength: number | null;
+ maxContextLength: number | null;
+ nativeContextLength: number | null;
+ loadedIsGguf: boolean | null;
+ loadedIsMlx: boolean | null;
+ loadedContextEnforced: boolean | null;
+} {
+ if (!resp) {
+ return {
+ loadedContextLength: null,
+ maxContextLength: null,
+ nativeContextLength: null,
+ loadedIsGguf: null,
+ loadedIsMlx: null,
+ loadedContextEnforced: null,
+ };
+ }
+ const isGguf = resp.is_gguf ?? false;
+ // Unknown, not a default: a response omits it when reading the model's window failed.
+ const loaded = resp.context_length ?? null;
+ if (!isGguf && !resp.is_mlx && resp.native_context_length == null) {
+ return {
+ loadedContextLength: null,
+ maxContextLength: null,
+ nativeContextLength: null,
+ loadedIsGguf: false,
+ loadedIsMlx: resp.is_mlx ?? null,
+ loadedContextEnforced: null,
+ };
+ }
+ return {
+ loadedContextLength: loaded,
+ maxContextLength: resp.max_context_length ?? loaded,
+ nativeContextLength: resp.native_context_length ?? null,
+ loadedIsGguf: isGguf,
+ // The backend's own answer, so a checkpoint the worker serves off the MLX path
+ // (native audio) is not taken for MLX by the platform alone.
+ loadedIsMlx: resp.is_mlx ?? null,
+ // llama.cpp allocates what it reports, so GGUF is enforced by construction.
+ // Everything else answers for itself, or says nothing.
+ loadedContextEnforced: isGguf ? true : (resp.context_length_enforced ?? null),
+ };
+}
+
// Matches studio/backend/core/inference/llama_cpp.py _valid_cache_types (f16 is the UI default).
export const KV_CACHE_DTYPES = [
"bf16",
@@ -402,6 +506,49 @@ export function normalizeMaxSeqLength(value: unknown): number | null {
return Math.max(MAX_SEQ_LENGTH_MIN, Math.min(MAX_SEQ_LENGTH_MAX, snapped));
}
+/** The context a saved record pins, whichever field it was written in.
+ *
+ * MLX's pin moved into `customContextLength` beside llama.cpp's, while transformers
+ * keeps its own in `maxSeqLength` and a record written before the move still carries an
+ * MLX pin there. The same record is read on a host that serves it with a different
+ * backend, so every read has to honour both.
+ *
+ * A *saved* record only. `currentRuntimePerModelConfig` builds the same shape from the
+ * live store, where `maxSeqLength` is the length the model resolved to rather than one
+ * anybody chose; read that through `customContextLength` alone.
+ */
+export function savedContextPin(config: {
+ customContextLength?: number | null;
+ maxSeqLength?: number | null;
+}): number | null {
+ return config.customContextLength ?? normalizeMaxSeqLength(config.maxSeqLength ?? null);
+}
+
+/** The patch that pins a context for a non-GGUF target, on the backend serving it.
+ *
+ * An edit leaves a pin in exactly one field, clearing whichever the record arrived with:
+ * a record holding both loads at a different length depending on who asked -- the picker
+ * resolves `customContextLength` first, the API's auto-switch load `maxSeqLength`.
+ */
+export function contextPinPatch(value: number, isMlx: boolean): Partial<PerModelConfig> {
+ // Held to what a load may ask for, but not rounded to the control's step: a pin taken
+ // from a resolved window need not sit on that grid.
+ const pin = boundContextPin(value) ?? MAX_SEQ_LENGTH_MIN;
+ return isMlx
+ ? { customContextLength: pin, maxSeqLength: null }
+ : { customContextLength: null, maxSeqLength: pin };
+}
+
+function boundContextPin(value: unknown): number | null {
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
+ return null;
+ }
+ return Math.max(
+ MAX_SEQ_LENGTH_MIN,
+ Math.min(MAX_SEQ_LENGTH_MAX, Math.floor(value)),
+ );
+}
+
export function floorMaxSeqLength(value: unknown): number | null {
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
return null;
diff --git a/studio/frontend/src/features/recipe-studio/hooks/use-recipe-executions.ts b/studio/frontend/src/features/recipe-studio/hooks/use-recipe-executions.ts
index bc4bc2a391e..92a2973f9f8 100644
--- a/studio/frontend/src/features/recipe-studio/hooks/use-recipe-executions.ts
+++ b/studio/frontend/src/features/recipe-studio/hooks/use-recipe-executions.ts
@@ -2,6 +2,12 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { getInferenceStatus, loadModel } from "@/features/chat";
+import { unpinnedLoadContext } from "@/features/chat/presets/preset-policy";
+import { usePlatformStore } from "@/config/env";
+import {
+ DEFAULT_MAX_SEQ_LENGTH,
+ isServedByMlx,
+} from "@/features/model-picker";
import { createLoadingToastIcon, toast } from "@/lib/toast";
import { toastError } from "@/shared/toast";
import { useCallback, useEffect, useState } from "react";
@@ -68,6 +74,11 @@ type LocalModelSelection = {
target: string;
ggufVariant: string;
aliases: string[];
+ /** The context that model's own load asked for, for a selection captured to be
+ * restored. Absent for a recipe's own target, which pins nothing. */
+ requestedContextLength?: number | null;
+ /** Whether MLX served it. Only there is a positive request above unambiguous. */
+ isMlx?: boolean;
};
type LocalModelLoadPlan =
@@ -215,18 +226,44 @@ function localSelectionMatchesActive(input: {
);
}
+/** A context request, read only where it means something.
+ *
+ * An unpinned MLX load sends 0, so a positive value there is a pin. llama.cpp is
+ * ambiguous: a same-model reload echoes the resolved n_ctx while the control is still
+ * Auto (see resolve-ctx-pin-seed.ts), so reading that as a pin would reload the model
+ * on every run and then re-pin an Auto-sized one. 0 is Auto on both.
+ */
+function contextIntent(
+ value: number | null | undefined,
+ isMlx: boolean | null | undefined,
+): number | null {
+ return isMlx && typeof value === "number" && value > 0 ? value : null;
+}
+
async function isLocalModelAlreadyLoaded(
selection: LocalModelSelection,
): Promise<boolean> {
- const { target, ggufVariant } = selection;
+ const { target, ggufVariant, requestedContextLength } = selection;
try {
const status = await getInferenceStatus();
- return localSelectionMatchesActive({
- target,
- ggufVariant,
- activeModel: status.model_identifier ?? status.active_model,
- activeVariant: status.gguf_variant?.trim() ?? "",
- });
+ if (
+ !localSelectionMatchesActive({
+ target,
+ ggufVariant,
+ activeModel: status.model_identifier ?? status.active_model,
+ activeVariant: status.gguf_variant?.trim() ?? "",
+ })
+ ) {
+ return false;
+ }
+ // Same checkpoint, different context intent is still a different load: a recipe that
+ // asked for nothing must not inherit whatever window Chat pinned.
+ // The resident backend decides, since both values describe the load that is running.
+ const residentIsMlx = status.is_mlx ?? false;
+ return (
+ contextIntent(requestedContextLength, residentIsMlx) ===
+ contextIntent(status.requested_context_length, residentIsMlx)
+ );
} catch {
// Fall through to load attempt; the backend will re-error if needed.
return false;
@@ -236,7 +273,7 @@ async function isLocalModelAlreadyLoaded(
async function loadLocalModelSelection(
selection: LocalModelSelection,
): Promise<string | null> {
- const { target, ggufVariant } = selection;
+ const { target, ggufVariant, requestedContextLength } = selection;
const modelLabel = ggufVariant ? `${target} (${ggufVariant})` : target;
let loadToastDismissed = false;
const toastId = toast.message(`Loading ${modelLabel}...`, {
@@ -250,13 +287,22 @@ async function loadLocalModelSelection(
});
try {
const isGguf = GGUF_MODEL_PATTERN.test(target) || Boolean(ggufVariant);
+ // A recipe's own target loads the way an unpinned chat model does; restoring the
+ // model it displaced replays what that model's own load asked for.
+ const platform = usePlatformStore.getState();
await loadModel({
// biome-ignore lint/style/useNamingConvention: api schema
model_path: target,
// biome-ignore lint/style/useNamingConvention: api schema
hf_token: null,
// biome-ignore lint/style/useNamingConvention: api schema
- max_seq_length: isGguf ? 0 : 4096,
+ max_seq_length:
+ requestedContextLength ??
+ unpinnedLoadContext(
+ isGguf,
+ isServedByMlx(isGguf, platform.deviceType, platform.chatOnlyReason),
+ DEFAULT_MAX_SEQ_LENGTH,
+ ),
// biome-ignore lint/style/useNamingConvention: api schema
load_in_4bit: true,
// biome-ignore lint/style/useNamingConvention: api schema
@@ -314,6 +360,8 @@ async function getActiveLocalModelSelection(): Promise<LocalModelSelection | nul
target,
ggufVariant: status.gguf_variant?.trim() ?? "",
aliases: ["previous Chat model"],
+ requestedContextLength: status.requested_context_length ?? null,
+ isMlx: status.is_mlx ?? false,
};
} catch {
return null;
@@ -338,6 +386,8 @@ async function getRestorableActiveLocalModelSelection(): Promise<RestorableLocal
target,
ggufVariant: status.gguf_variant?.trim() ?? "",
aliases: ["previous Chat model"],
+ requestedContextLength: status.requested_context_length ?? null,
+ isMlx: status.is_mlx ?? false,
},
unrestorableLabel: null,
};
@@ -353,7 +403,9 @@ function isSameLocalModelSelection(
return Boolean(
left &&
left.target.toLowerCase() === right.target.toLowerCase() &&
- left.ggufVariant === right.ggufVariant,
+ left.ggufVariant === right.ggufVariant &&
+ contextIntent(left.requestedContextLength, left.isMlx) ===
+ contextIntent(right.requestedContextLength, right.isMlx),
);
}
diff --git a/studio/frontend/src/features/settings/components/usage-examples.tsx b/studio/frontend/src/features/settings/components/usage-examples.tsx
index 06ddb4a84ca..116b6949ea9 100644
--- a/studio/frontend/src/features/settings/components/usage-examples.tsx
+++ b/studio/frontend/src/features/settings/components/usage-examples.tsx
@@ -14,6 +14,7 @@ import {
} from "@/components/ui/tooltip";
import { fetchDeviceType, usePlatformStore } from "@/config/env";
import { useChatRuntimeStore } from "@/features/chat";
+import { isServedByLlamaCpp } from "@/features/model-picker";
import { useT } from "@/i18n";
import type { TranslationKey } from "@/i18n";
import { isTauri } from "@/lib/api-base";
@@ -663,24 +664,22 @@ export function UsageExamples({
// quant variant string) -- a direct local .gguf file (custom folder /
// LM Studio / drag-drop) is just as much a GGUF the codex preflight would
// accept, but never has a "variant" to report, and would otherwise read as
- // non-GGUF here. activeNativePathToken covers the drag-drop/picked-file
- // case; ggufContextLength is only ever populated when the backend's
- // /api/inference/status last reported is_gguf: true for the active model
- // (see applyActiveModelStatusToStore), so together these three cover every
- // path a model can be GGUF through, matching the same is_gguf-or-equivalent
- // check hasGgufSource applies to a staged pick.
+ // non-GGUF here.
const activeGgufVariant = useChatRuntimeStore((s) => s.activeGgufVariant);
const activeNativePathToken = useChatRuntimeStore(
(s) => s.activeNativePathToken,
);
- const ggufContextLength = useChatRuntimeStore((s) => s.ggufContextLength);
+ const loadedIsGguf = useChatRuntimeStore((s) => s.loadedIsGguf);
+ const checkpoint = useChatRuntimeStore((s) => s.params.checkpoint);
useEffect(() => {
if (agentPickedByUserRef.current) return;
if (detectedAgents.length === 0) return;
- const isGguf =
- activeGgufVariant != null ||
- activeNativePathToken != null ||
- ggufContextLength != null;
+ const isGguf = isServedByLlamaCpp({
+ loadedIsGguf,
+ activeGgufVariant,
+ activeNativePathToken,
+ checkpoint,
+ });
const preferred = detectedAgents.find((a) => a !== "codex" || isGguf);
if (preferred) {
setAgent(preferred);
@@ -696,7 +695,8 @@ export function UsageExamples({
detectedAgents,
activeGgufVariant,
activeNativePathToken,
- ggufContextLength,
+ loadedIsGguf,
+ checkpoint,
]);
const keylessBase =
diff --git a/studio/frontend/tests/context-pin-survives-load.test.ts b/studio/frontend/tests/context-pin-survives-load.test.ts
index e923d377989..568fcb3303a 100644
--- a/studio/frontend/tests/context-pin-survives-load.test.ts
+++ b/studio/frontend/tests/context-pin-survives-load.test.ts
@@ -117,10 +117,11 @@ function sentNCtx(
ggufVariant: VARIANT,
isGguf: true,
customContextLength,
- ggufContextLength: residentCtx,
+ loadedContextLength: residentCtx,
currentCheckpoint,
activeGgufVariant: VARIANT,
- maxSeqLength: 4096,
+ pinnedMaxSeqLength: null,
+ defaultMaxSeqLength: 4096,
presetSource,
}),
);
@@ -240,9 +241,11 @@ test("a model change does not carry the old pin across", () => {
assert.match(RUNTIME, /customContextLength: null,\s*\n\s*\}\);/);
// The applier reads the saved value through the same resolver the batch sizes
// use, so "remembered" is this model's record and not the store's leftovers.
+ // savedContextPin, not the raw field: a record written before the MLX pin moved
+ // still carries it in maxSeqLength.
assert.match(
APPLIER,
- /remembered: remembered\?\.remembered\s*\n\s*\? \(remembered\.config\.customContextLength \?\? null\)\s*\n\s*: null,/,
+ /remembered: remembered\?\.remembered \? savedContextPin\(remembered\.config\) : null,/,
);
});
@@ -336,8 +339,8 @@ test("the clamp that stops a manual reload resizing is not a user pin", () => {
// on the same model, or the reload would send 0 and llama.cpp's --fit-off
// branch would take that as the NATIVE context. That is the app protecting the
// load, not the user choosing a length, so the pin is captured BEFORE it.
- const capture = RUNTIME.indexOf("const explicitCtxPin = loadCustomContextLength;");
- const clamp = RUNTIME.indexOf("loadCustomContextLength = loadGgufContextLength;");
+ const capture = RUNTIME.indexOf("const explicitCtxPin = loadRequestContextPin(");
+ const clamp = RUNTIME.indexOf("loadCustomContextLength = loadContextLength;");
assert.notEqual(capture, -1, "the load no longer captures the user's setting");
assert.notEqual(clamp, -1);
assert.ok(
@@ -352,7 +355,12 @@ test("the three in-app writers pin what the user asked for, not what they sent",
// only when there is one, and the current context otherwise.
assert.match(
RUNTIME,
- /const keepCustomCtx = resolveExplicitCtxPin\(\s*\n\s*loadResponse\.is_gguf \? explicitCtxPin : null,\s*\n\s*\);/,
+ /const keepCustomCtx = resolveExplicitCtxPin\(\s*\n\s*loadResponse\.is_gguf \|\| targetIsMlx \? explicitCtxPin : null,\s*\n\s*\);/,
+ );
+ // And the captured pin is the one the request was built from, pre-move field included.
+ assert.match(
+ RUNTIME,
+ /const explicitCtxPin = loadRequestContextPin\(\s*\n\s*loadCustomContextLength,\s*\n\s*targetIsMlx,\s*\n\s*pinnedMaxSeqLength,\s*\n\s*\);/,
);
assert.match(
RUNTIME,
@@ -366,7 +374,7 @@ test("the three in-app writers pin what the user asked for, not what they sent",
assert.match(ADAPTER, /loadedCustomContextLength: keepCustomCtx,/);
assert.match(
COMPOSER,
- /const keepCustomCtx = targetIsGguf\s*\n\s*\? resolveExplicitCtxPin\(effectiveCustomContextLength\)\s*\n\s*: null;/,
+ /const keepCustomCtx = targetIsGguf\s*\n\s*\? resolveExplicitCtxPin\(effectiveCustomContextLength\)\s*\n\s*: retainedContextPin\(\{/,
);
assert.match(COMPOSER, /customContextLength: keepCustomCtx,/);
assert.match(COMPOSER, /loadedCustomContextLength: keepCustomCtx,/);
@@ -375,7 +383,7 @@ test("the three in-app writers pin what the user asked for, not what they sent",
assert.match(COMPOSER, /const effectiveCustomContextLength = ownConfig\.customContextLength;/);
assert.match(
ADAPTER,
- /customContextLength: config\.customContextLength,\s*\n\s*ggufContextLength: null,/,
+ /customContextLength: config\.customContextLength,\s*\n\s*loadedContextLength: null,/,
);
});
@@ -487,3 +495,58 @@ test("a positive echo under manual memory with auto layers is an explicit pin",
/loadedPin: prevState\.loadedCustomContextLength \?\? null,/,
);
});
+
+test("a resident MLX pin from another tab is adopted, not read as Auto", () => {
+ // An unpinned MLX load sends 0, so a positive echo can only be an explicit pin.
+ // Model changed underneath this tab and there is no saved config to corroborate it.
+ const seeded = resolveCtxPinSeed({
+ incoming: 32768,
+ isGguf: true,
+ isMlx: true,
+ seedLoadParams: true,
+ modelChanged: true,
+ remembered: null,
+ gpuMemoryMode: null,
+ gpuLayers: null,
+ loadedPin: null,
+ });
+ assert.equal(seeded.customContextLength, 32768);
+ assert.equal(seeded.loadedCustomContextLength, 32768);
+
+ // Auto still clears: 0 is the wire form and proves its own meaning.
+ const auto = resolveCtxPinSeed({
+ incoming: 0,
+ isGguf: true,
+ isMlx: true,
+ seedLoadParams: true,
+ modelChanged: true,
+ remembered: null,
+ gpuMemoryMode: null,
+ gpuLayers: null,
+ loadedPin: null,
+ });
+ assert.equal(auto.customContextLength, null);
+
+ // GGUF keeps the old rule: its positive echo is the ambiguous resolved n_ctx.
+ const gguf = resolveCtxPinSeed({
+ incoming: 32768,
+ isGguf: true,
+ isMlx: false,
+ seedLoadParams: true,
+ modelChanged: true,
+ remembered: null,
+ gpuMemoryMode: null,
+ gpuLayers: null,
+ loadedPin: null,
+ });
+ assert.equal(gguf.customContextLength, null);
+});
+
+test("a failed switch rolls back on the backend that served the outgoing model", () => {
+ // The platform alone would call a native-audio checkpoint MLX on a Mac and roll it
+ // back at the auto-size sentinel, losing the context it was actually serving.
+ assert.match(
+ RUNTIME,
+ /const previousIsMlx = residentIsServedByMlx\(\s*\n\s*previousIsGguf,\s*\n\s*platform\.deviceType,\s*\n\s*platform\.chatOnlyReason,\s*\n\s*stateBeforeUnload\.loadedIsMlx,\s*\n\s*\);/,
+ );
+});
diff --git a/studio/frontend/tests/context-window-visible.test.ts b/studio/frontend/tests/context-window-visible.test.ts
index fd6795d4532..36fef62ab6e 100644
--- a/studio/frontend/tests/context-window-visible.test.ts
+++ b/studio/frontend/tests/context-window-visible.test.ts
@@ -15,7 +15,7 @@ import { hasKnownContextWindow } from "../src/features/chat/lib/context-window-k
const RESIDENT = "unsloth/Qwen3.6-35B-A3B-MTP-GGUF";
const base = {
- ggufContextLength: 32768,
+ loadedContextLength: 32768,
modelLoading: false,
isExternalModel: false,
residentCheckpoint: RESIDENT as string | null | undefined,
@@ -30,14 +30,14 @@ test("a load in flight has no window to name", () => {
assert.equal(hasKnownContextWindow({ ...base, modelLoading: true }), false);
});
-// selecting an API model nulls ggufContextLength, so a stale length must be refused on its own
+// selecting an API model nulls loadedContextLength, so a stale length must be refused on its own
test("an API model shows no window even with a stale length in the store", () => {
assert.equal(hasKnownContextWindow({ ...base, isExternalModel: true }), false);
});
test("a non-GGUF local model has no window either", () => {
assert.equal(
- hasKnownContextWindow({ ...base, ggufContextLength: null }),
+ hasKnownContextWindow({ ...base, loadedContextLength: null }),
false,
);
});
@@ -97,6 +97,31 @@ test("usage past the window clamps to 100 percent", () => {
assert.equal(deriveContextUsageBar({ used: 40000, total: 32768 })?.percent, 100);
});
+// llama.cpp stops at the window; MLX runs straight past it, so the advice differs, and
+// which side of the limit a chat is on cannot be read from the clamped percent
+test("the limit advice follows the backend and the unclamped ratio", () => {
+ const at = { used: 40000, total: 32768 };
+ assert.equal(deriveContextUsageBar(at)?.advice, "stops-at-limit");
+ // The MLX branches are about the ratio, so they state the bound they assume: an
+ // unconfirmed window advises on its own terms (see mlx-context-helpers).
+ assert.equal(
+ deriveContextUsageBar({ ...at, isMlx: true, contextEnforced: true })?.advice,
+ "mlx-past-limit",
+ );
+ assert.equal(
+ deriveContextUsageBar({
+ used: 30000,
+ total: 32768,
+ isMlx: true,
+ contextEnforced: true,
+ })?.advice,
+ "mlx-near-limit",
+ );
+ assert.equal(deriveContextUsageBar({ used: 4096, total: 32768 })?.advice, "none");
+ // no window and no count: nothing to advise against
+ assert.equal(deriveContextUsageBar({ used: 40000, total: null })?.advice, "none");
+});
+
// external providers: usage is known, the window is not
test("an unknown window shows a bare token count and no ratio", () => {
const state = deriveContextUsageBar({ used: 4096, total: null });
diff --git a/studio/frontend/tests/current-date-context-usage.test.ts b/studio/frontend/tests/current-date-context-usage.test.ts
index fdc46e2d36b..e1f6e93c679 100644
--- a/studio/frontend/tests/current-date-context-usage.test.ts
+++ b/studio/frontend/tests/current-date-context-usage.test.ts
@@ -15,7 +15,7 @@ test("a prompt setting change clears local usage even during a run", async () =>
const state = {
activeThreadId: "thread-1",
contextUsage: { totalTokens: 42 },
- ggufContextLength: 4096,
+ loadedContextLength: 4096,
modelLoading: false,
models: [],
params: { checkpoint: "local-model" },
@@ -50,7 +50,7 @@ test("a prompt setting change leaves external usage intact", async () => {
const state = {
activeThreadId: "thread-1",
contextUsage: { totalTokens: 42 },
- ggufContextLength: 4096,
+ loadedContextLength: 4096,
modelLoading: false,
models: [],
params: { checkpoint: "external:model" },
diff --git a/studio/frontend/tests/generation-length-cap-attribution.test.ts b/studio/frontend/tests/generation-length-cap-attribution.test.ts
index 46ff9352803..38a21d05a10 100644
--- a/studio/frontend/tests/generation-length-cap-attribution.test.ts
+++ b/studio/frontend/tests/generation-length-cap-attribution.test.ts
@@ -11,7 +11,7 @@ import { maxTokensIsTheLimit } from "../src/features/chat/api/generation-length.
// Hoisted: biome's useTopLevelRegex flags a literal recompiled per call.
const LOCAL_WINDOW_ARGUMENT =
- /isExternalRequest\s*\n\s*\? null\s*\n\s*: \(runtime\.loadedCustomContextLength \?\?\s*\n\s*runtime\.ggufContextLength \?\?\s*\n\s*\(params\.maxSeqLength \|\| null\)\)/;
+ /isExternalRequest\s*\n\s*\? null\s*\n\s*: \(runtime\.loadedCustomContextLength \?\?\s*\n\s*runtime\.loadedContextLength \?\?\s*\n\s*\(params\.maxSeqLength \|\| null\)\)/;
// The EDITABLE field must not be what a stop is judged against: the store defines a
// pending context edit as exactly `customContextLength !== loadedCustomContextLength`.
const PENDING_FIELD = /: \(runtime\.customContextLength \?\?/;
@@ -83,7 +83,7 @@ test("an unknown context length cannot make a cap the limit", () => {
test("a local model with no GGUF window still reports one", () => {
// A safetensors or MLX request on the legacy stream path has neither
- // customContextLength nor ggufContextLength, while params.maxSeqLength IS its
+ // customContextLength nor loadedContextLength, while params.maxSeqLength IS its
// effective window and is also where the default Max Tokens comes from. Passing
// null there makes the window infinite below, so every context-length stop is
// reported as a Max Tokens stop and the user is told to raise a setting that is
diff --git a/studio/frontend/tests/hydration-clears-stale-local-record.test.ts b/studio/frontend/tests/hydration-clears-stale-local-record.test.ts
index c3d369d12e0..229eabcb6cc 100644
--- a/studio/frontend/tests/hydration-clears-stale-local-record.test.ts
+++ b/studio/frontend/tests/hydration-clears-stale-local-record.test.ts
@@ -167,3 +167,24 @@ test("hydration propagates what its own write evicted", () => {
/for \(const dropped of hydrationEvicted\) \{ syncModelOverride\(dropped\.modelId, dropped\.ggufVariant, null, \{ keepLaunchFlags: true, \}\); \}/,
);
});
+
+test("hydration keeps a moved context pin in one field", () => {
+ // The picker reads customContextLength first and the auto-switch load max_seq_length
+ // first, so a record holding both loads the same model at two lengths.
+ const legacy = { maxSeqLength: 8192, customContextLength: null };
+ const moved = fromApiOverride({ custom_context_length: 32768 }, legacy as any);
+ assert.equal(moved.customContextLength, 32768);
+ assert.equal(moved.maxSeqLength, null, "the stale legacy field must not survive");
+
+ // The other direction: a row pinning in the pre-move field owns both too.
+ const back = fromApiOverride(
+ { max_seq_length: 8192 },
+ { customContextLength: 32768, maxSeqLength: null } as any,
+ );
+ assert.equal(back.customContextLength, null);
+ assert.equal(back.maxSeqLength, 8192);
+
+ // A row stating no pin falls back to this browser's, or opening the panel deletes it.
+ const kept = fromApiOverride({}, legacy as any);
+ assert.equal(kept.maxSeqLength, 8192);
+});
diff --git a/studio/frontend/tests/mlx-context-helpers.test.ts b/studio/frontend/tests/mlx-context-helpers.test.ts
new file mode 100644
index 00000000000..ff379ebb384
--- /dev/null
+++ b/studio/frontend/tests/mlx-context-helpers.test.ts
@@ -0,0 +1,283 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Behaviour of the pure helpers the MLX context work introduced. The rest of their
+// coverage regexes the source, which passes with the body deleted; these call them.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ installLocalStorageFake,
+ registerBundlerResolver,
+} from "./helpers/kit.ts";
+
+registerBundlerResolver();
+installLocalStorageFake();
+
+const {
+ DEFAULT_MAX_SEQ_LENGTH,
+ isServedByLlamaCpp,
+ isServedByMlx,
+ loadedContextFields,
+ residentIsServedByMlx,
+} = await import(
+ "../src/features/model-picker/model-config/per-model-config.ts"
+);
+const {
+ capturedContextLength,
+ loadedContextForParams,
+ resolveLoadMaxSeqLength,
+ loadRequestContextPin,
+ localMaxTokensCeiling,
+ replayMaxTokensCap,
+ resolveExplicitCtxPin,
+ resolveFitMaxSeqLength,
+ retainedContextPin,
+ unpinnedDefaultRequest,
+ unpinnedLoadContext,
+ unreportedWindowMaxTokens,
+} = await import("../src/features/chat/presets/preset-policy.ts");
+const { deriveContextUsageBar } = await import(
+ "../src/features/chat/lib/context-usage-bar-state.ts"
+);
+
+const GGUF = { is_gguf: true, context_length: 32768, max_context_length: 32768 };
+const MLX = {
+ is_gguf: false,
+ is_mlx: true,
+ context_length: 32768,
+ native_context_length: 262144,
+ max_context_length: 262144,
+};
+
+test("an MLX response carries a window without a native one", () => {
+ // The point of the field split: a non-GGUF response with no native_context_length used
+ // to be discarded, which is every MLX model declaring no trained window.
+ assert.deepEqual(loadedContextFields({ is_gguf: false, is_mlx: true, context_length: 8192 }), {
+ loadedContextLength: 8192,
+ maxContextLength: 8192,
+ nativeContextLength: null,
+ loadedIsGguf: false,
+ loadedIsMlx: true,
+ loadedContextEnforced: null,
+ });
+ // Transformers, which sizes nothing, still contributes no window.
+ assert.deepEqual(loadedContextFields({ is_gguf: false, context_length: 2048 }), {
+ loadedContextLength: null,
+ maxContextLength: null,
+ nativeContextLength: null,
+ loadedIsGguf: false,
+ loadedIsMlx: null,
+ loadedContextEnforced: null,
+ });
+ assert.equal(loadedContextFields(null).loadedIsGguf, null);
+});
+
+test("the enforcement verdict is a tri-state, and GGUF is true by construction", () => {
+ assert.equal(loadedContextFields(GGUF).loadedContextEnforced, true);
+ assert.equal(loadedContextFields(MLX).loadedContextEnforced, null);
+ assert.equal(
+ loadedContextFields({ ...MLX, context_length_enforced: true }).loadedContextEnforced,
+ true,
+ );
+ assert.equal(
+ loadedContextFields({ ...MLX, context_length_enforced: false }).loadedContextEnforced,
+ false,
+ );
+});
+
+test("a load that reported a non-GGUF backend outranks a stale variant", () => {
+ assert.equal(isServedByLlamaCpp({ loadedIsGguf: true }), true);
+ assert.equal(isServedByLlamaCpp({ activeGgufVariant: "Q4_K_M" }), true);
+ // The variant and the path token outlive the pick that set them.
+ assert.equal(
+ isServedByLlamaCpp({ loadedIsGguf: false, activeGgufVariant: "Q4_K_M" }),
+ false,
+ );
+ assert.equal(
+ isServedByLlamaCpp({ loadedIsGguf: false, activeNativePathToken: "tok" }),
+ false,
+ );
+ // A .gguf checkpoint before any load still reads as llama.cpp.
+ assert.equal(isServedByLlamaCpp({ checkpoint: "/m/model.gguf" }), true);
+ assert.equal(isServedByLlamaCpp({ checkpoint: "external::openai/gpt-4" }), false);
+});
+
+test("MLX is a Mac non-GGUF load, and the reasons that rule it out", () => {
+ assert.equal(isServedByMlx(false, "mac", null), true);
+ assert.equal(isServedByMlx(true, "mac", null), false);
+ assert.equal(isServedByMlx(false, "cuda", null), false);
+ for (const reason of ["mlx_unavailable", "intel_mac", "detection_failed"]) {
+ assert.equal(isServedByMlx(false, "mac", reason), false, reason);
+ }
+});
+
+test("an unpinned load asks a self-sizing backend for nothing", () => {
+ assert.equal(unpinnedLoadContext(true, false, 4096), 0);
+ assert.equal(unpinnedLoadContext(false, true, 4096), 0);
+ assert.equal(unpinnedLoadContext(false, false, 4096), 4096);
+ assert.equal(unpinnedLoadContext(false, null, DEFAULT_MAX_SEQ_LENGTH), 4096);
+});
+
+test("only MLX keeps its request as a pin after a load", () => {
+ assert.equal(retainedContextPin({ isMlx: true, requestedContextLength: 32768 }), 32768);
+ // Auto sends the sentinel, which is not a pin.
+ assert.equal(retainedContextPin({ isMlx: true, requestedContextLength: 0 }), null);
+ assert.equal(retainedContextPin({ isMlx: false, requestedContextLength: 32768 }), null);
+ assert.equal(retainedContextPin({ requestedContextLength: 32768 }), null);
+});
+
+test("a preset records a window only where replaying it needs one", () => {
+ assert.equal(capturedContextLength({ isGguf: true, controlPin: null, loadedContextLength: 32768 }), 32768);
+ // Non-GGUF: an unpinned window is arrived at again on its own.
+ assert.equal(capturedContextLength({ isGguf: false, controlPin: null, loadedContextLength: 32768 }), null);
+ assert.equal(capturedContextLength({ isGguf: false, controlPin: 8192, loadedContextLength: 32768 }), 8192);
+});
+
+test("the reported window outranks the request it answered", () => {
+ assert.equal(loadedContextForParams(32768, 0, 4096), 32768);
+ assert.equal(loadedContextForParams(null, 8192, 4096), 8192);
+ // The sentinel is below the control's minimum, so the previous value stands.
+ assert.equal(loadedContextForParams(null, 0, 4096), 4096);
+});
+
+test("Max Tokens is bounded by the window, and never below its own minimum", () => {
+ assert.equal(localMaxTokensCeiling(32768, 4096), 32768);
+ assert.equal(localMaxTokensCeiling(null, 4096), 4096);
+ // Reachable on MLX, which honours a tiny request verbatim; the control's minimum wins,
+ // since a slider whose maximum is below it cannot be operated.
+ assert.equal(localMaxTokensCeiling(16, 4096), 64);
+ assert.equal(unreportedWindowMaxTokens(true, 9000), 9000);
+ assert.equal(unreportedWindowMaxTokens(false, 9000), DEFAULT_MAX_SEQ_LENGTH);
+});
+
+test("--fit owns sizing only for an unpinned GGUF on manual auto-layers", () => {
+ assert.equal(resolveFitMaxSeqLength(true, "manual", -1, null, 4096), 0);
+ assert.equal(resolveFitMaxSeqLength(true, "manual", -1, 8192, 4096), 8192);
+ assert.equal(resolveFitMaxSeqLength(true, "manual", 20, null, 4096), 4096);
+ assert.equal(resolveFitMaxSeqLength(true, "auto", -1, null, 4096), 4096);
+ assert.equal(resolveFitMaxSeqLength(false, "manual", -1, null, 4096), 4096);
+ assert.equal(resolveExplicitCtxPin(8192), 8192);
+ assert.equal(resolveExplicitCtxPin(0), null);
+ assert.equal(resolveExplicitCtxPin(null), null);
+});
+
+test("the usage bar names the three ways a window can end", () => {
+ // Bounded unless a case says otherwise: an unconfirmed window is its own answer below.
+ const at = (used: number, extra: Record<string, unknown> = {}) =>
+ deriveContextUsageBar({
+ used,
+ total: 32768,
+ isMlx: true,
+ contextEnforced: true,
+ ...extra,
+ })?.advice;
+ assert.equal(at(1000), "none");
+ assert.equal(at(30000), "mlx-near-limit");
+ assert.equal(at(40000), "mlx-past-limit");
+ assert.equal(at(30000, { isMlx: false }), "stops-at-limit");
+ // A window the backend confirmed does not bound the cache is not a limit at all.
+ assert.equal(at(30000, { contextEnforced: false }), "unenforced-limit");
+ assert.equal(at(40000, { contextEnforced: false }), "unenforced-limit");
+ assert.equal(at(30000, { contextEnforced: true }), "mlx-near-limit");
+ // Unjudged says the same thing operationally: a probe that could not build a cache
+ // installed no window, so it grows exactly as a confirmed unenforced one does, and
+ // rotating-cache advice would be the opposite of true.
+ assert.equal(at(30000, { contextEnforced: null }), "unenforced-limit");
+ assert.equal(at(30000, { contextEnforced: undefined }), "unenforced-limit");
+ // Only for MLX: nothing else installs a window whose bound could go unjudged.
+ assert.equal(at(30000, { isMlx: false, contextEnforced: null }), "stops-at-limit");
+});
+
+test("an outgoing self-sizing window does not become the next model's request", () => {
+ // An unpinned MLX load writes its RESOLVED window into params.maxSeqLength.
+ const afterMlx = loadedContextForParams(131072, 0, 4096);
+ assert.equal(afterMlx, 131072);
+ // An unconfigured transformers model still asks for the app default: 131072 there is
+ // an allocation nobody requested.
+ assert.equal(unpinnedDefaultRequest(true, afterMlx, DEFAULT_MAX_SEQ_LENGTH), 4096);
+ // A backend that does not size its own window leaves the session request intact.
+ assert.equal(unpinnedDefaultRequest(false, 8192, DEFAULT_MAX_SEQ_LENGTH), 8192);
+ assert.equal(unpinnedDefaultRequest(false, 0, DEFAULT_MAX_SEQ_LENGTH), 4096);
+ assert.equal(unpinnedDefaultRequest(null, null, DEFAULT_MAX_SEQ_LENGTH), 4096);
+ // End to end: the resolver must not hand the outgoing window to the new load.
+ assert.equal(
+ resolveLoadMaxSeqLength({
+ modelId: "org/plain-transformers",
+ ggufVariant: null,
+ isGguf: false,
+ customContextLength: null,
+ loadedContextLength: null,
+ currentCheckpoint: "mlx-community/Some-MLX",
+ activeGgufVariant: null,
+ isMlx: false,
+ pinnedMaxSeqLength: null,
+ defaultMaxSeqLength: unpinnedDefaultRequest(true, afterMlx, DEFAULT_MAX_SEQ_LENGTH),
+ presetSource: "builtin-default",
+ }),
+ 4096,
+ );
+});
+
+test("the backend's own is_mlx vetoes the platform for a resident model", () => {
+ const MAC = ["mac", null] as const;
+ // A native-audio checkpoint loads on Apple Silicon through NativeAudioBackend, which
+ // the worker picks before the MLX fast-path, so its settings are not MLX's to clear.
+ assert.equal(residentIsServedByMlx(false, ...MAC, false), false);
+ assert.equal(residentIsServedByMlx(false, ...MAC, true), true);
+ // Nothing loaded yet: the platform is still the best answer available.
+ assert.equal(residentIsServedByMlx(false, ...MAC, null), true);
+ assert.equal(residentIsServedByMlx(false, ...MAC, undefined), true);
+ // The veto adds to the platform rule rather than replacing it.
+ assert.equal(residentIsServedByMlx(true, ...MAC, true), false);
+ assert.equal(residentIsServedByMlx(false, "linux", null, true), false);
+ // And the response carries that answer, so the store never has to infer it.
+ assert.equal(loadedContextFields({ is_gguf: false, is_mlx: true, context_length: 8192 }).loadedIsMlx, true);
+ assert.equal(
+ loadedContextFields({ is_gguf: false, is_mlx: false, context_length: 2048 }).loadedIsMlx,
+ false,
+ );
+ // Omitted is unknown, not a denial: an older backend answers nothing here.
+ assert.equal(loadedContextFields({ is_gguf: false, context_length: 2048 }).loadedIsMlx, null);
+ assert.equal(loadedContextFields({ is_gguf: true, context_length: 4096 }).loadedIsMlx, null);
+ assert.equal(loadedContextFields(null).loadedIsMlx, null);
+});
+
+test("a cap never lands below the Max Tokens control's own minimum", () => {
+ // MLX honours a tiny positive request verbatim, and the cap only lowers Max Tokens, so
+ // a raw window here would clamp the value outside its slider.
+ assert.equal(replayMaxTokensCap(32), 64);
+ assert.equal(replayMaxTokensCap(64), 64);
+ assert.equal(replayMaxTokensCap(32768), 32768);
+ // Nothing sized a window: no cap at all, which is not a cap of zero.
+ assert.equal(replayMaxTokensCap(null), undefined);
+ assert.equal(replayMaxTokensCap(undefined), undefined);
+ // The same floor the displayed ceiling already used, so the pair cannot disagree.
+ assert.equal(replayMaxTokensCap(32), localMaxTokensCeiling(32, 32));
+});
+
+test("a load keeps the pin it was built from, wherever the record held it", () => {
+ // resolveLoadMaxSeqLength takes the pre-move field for an unpinned MLX target, so the
+ // load must pin the same number or the UI shows Auto for a pinned runtime.
+ assert.equal(loadRequestContextPin(null, true, 8192), 8192);
+ assert.equal(loadRequestContextPin(32768, true, 8192), 32768, "the live field leads");
+ // llama.cpp's maxSeqLength is not a context pin, so only MLX admits it.
+ assert.equal(loadRequestContextPin(null, false, 8192), null);
+ assert.equal(loadRequestContextPin(null, true, null), null);
+ // The request the two agree on: same input, same number.
+ assert.equal(
+ loadRequestContextPin(null, true, 8192),
+ resolveLoadMaxSeqLength({
+ modelId: "org/mlx-model",
+ isGguf: false,
+ customContextLength: null,
+ loadedContextLength: null,
+ currentCheckpoint: "",
+ isMlx: true,
+ pinnedMaxSeqLength: 8192,
+ defaultMaxSeqLength: DEFAULT_MAX_SEQ_LENGTH,
+ presetSource: "custom",
+ }),
+ );
+});
diff --git a/studio/frontend/tests/mlx-context-pin-record-compat.test.ts b/studio/frontend/tests/mlx-context-pin-record-compat.test.ts
new file mode 100644
index 00000000000..ca0cef527f1
--- /dev/null
+++ b/studio/frontend/tests/mlx-context-pin-record-compat.test.ts
@@ -0,0 +1,470 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Compatibility of the stored MLX context pin, which moved from `maxSeqLength` into
+// `customContextLength` without a schema bump: `toStoredConfig` stamps both shapes
+// version 1, so neither direction can tell them apart.
+//
+// Backwards works: `savedContextPin` reads either field.
+//
+// Forwards does not, and the last section demonstrates it rather than asserting it away.
+// An old client's model-config page resolves a non-GGUF context from `config.maxSeqLength`
+// alone (model-config-page.tsx on main, ~2711), so a new record reads as 4096 and as "at
+// default settings". Only that page: main's `resolveLoadMaxSeqLength` and its compare-pane
+// rule both read `customContextLength` first, so auto-load and compare still honour it.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import type { PerModelConfig } from "../src/features/model-picker/model-config/per-model-config.ts";
+
+import {
+ installLocalStorageFake,
+ registerBundlerResolver,
+} from "./helpers/kit.ts";
+
+registerBundlerResolver();
+const { store } = installLocalStorageFake();
+
+const {
+ CONTEXT_LENGTH_MIN,
+ DEFAULT_MAX_SEQ_LENGTH,
+ DEFAULT_PER_MODEL_CONFIG,
+ MAX_SEQ_LENGTH_MIN,
+ contextPinPatch,
+ isDefaultConfig,
+ normalizeMaxSeqLength,
+ normalizePerModelConfig,
+ resolveInitialConfig,
+ savePerModelConfig,
+ savedContextPin,
+} = await import(
+ "../src/features/model-picker/model-config/per-model-config.ts"
+);
+const { resolveLoadMaxSeqLength } = await import(
+ "../src/features/chat/presets/preset-policy.ts"
+);
+
+const STORAGE_KEY = "unsloth_model_configs";
+const MODEL = "mlx-community/Qwen3-8B-4bit";
+/** The window an MLX model of this size reports; only used as the "native" input. */
+const NATIVE = 262144;
+
+
+/** The storage key `savePerModelConfig` uses for MODEL, discovered rather than guessed. */
+function storageKeyForModel(): string {
+ store.clear();
+ assert.ok(
+ savePerModelConfig(MODEL, null, {
+ ...DEFAULT_PER_MODEL_CONFIG,
+ customContextLength: 4096,
+ }),
+ );
+ const map = JSON.parse(store.get(STORAGE_KEY) ?? "{}") as Record<
+ string,
+ unknown
+ >;
+ const keys = Object.keys(map);
+ assert.equal(
+ keys.length,
+ 1,
+ `expected one stored key, got ${JSON.stringify(keys)}`,
+ );
+ return keys[0];
+}
+
+const MODEL_KEY = storageKeyForModel();
+
+/** Put `raw` in storage verbatim, bypassing normalization, and read it back the way the app does. */
+function stage(raw: Record<string, unknown>) {
+ store.clear();
+ // The legacy migration runs on the first read and would merge an unrelated blob in.
+ store.set("unsloth_model_configs_migrated", "1");
+ store.set(STORAGE_KEY, JSON.stringify({ [MODEL_KEY]: raw }));
+ return resolveInitialConfig(MODEL, null);
+}
+
+/** The version `toStoredConfig` stamps on a record carrying this pin and nothing else. */
+function stampedVersion(patch: Record<string, unknown>): number {
+ store.clear();
+ assert.ok(
+ savePerModelConfig(MODEL, null, { ...DEFAULT_PER_MODEL_CONFIG, ...patch }),
+ );
+ const map = JSON.parse(store.get(STORAGE_KEY) ?? "{}") as Record<
+ string,
+ { version: number }
+ >;
+ return map[MODEL_KEY].version;
+}
+
+
+type Row = {
+ name: string;
+ raw: Record<string, unknown>;
+ /** After `normalize`, which is what every reader outside a raw preset sees. */
+ normalizedPin: number | null;
+ /** `savedContextPin` applied to the RAW record, which preset code does reach. */
+ rawPin: number | null;
+ isDefault: boolean;
+ /** `readable: false` means the future-schema guard refuses the record entirely. */
+ readable: boolean;
+ /** What /load is asked for on each backend, with the control untouched. */
+ mlxRequest: number;
+ transformersRequest: number;
+ note?: string;
+};
+
+const ROWS: Row[] = [
+ {
+ name: "old record: pin only in maxSeqLength",
+ raw: { version: 1, maxSeqLength: 8192 },
+ normalizedPin: 8192,
+ rawPin: 8192,
+ isDefault: false,
+ readable: true,
+ mlxRequest: 8192,
+ transformersRequest: 8192,
+ note: "backwards compatibility: the pre-move field still pins, on either backend.",
+ },
+ {
+ name: "new record: pin only in customContextLength",
+ raw: { version: 1, customContextLength: 32768 },
+ normalizedPin: 32768,
+ rawPin: 32768,
+ isDefault: false,
+ readable: true,
+ mlxRequest: 32768,
+ transformersRequest: 32768,
+ },
+ {
+ name: "both fields set",
+ raw: { version: 1, customContextLength: 32768, maxSeqLength: 8192 },
+ normalizedPin: 32768,
+ rawPin: 32768,
+ isDefault: false,
+ readable: true,
+ mlxRequest: 32768,
+ transformersRequest: 32768,
+ note:
+ "customContextLength wins in both the pin reader and the load resolver, so the " +
+ "two agree. No edit can author this state -- contextPinPatch clears the other " +
+ "field -- but a hand-edited or merged store can hold it.",
+ },
+ {
+ name: "neither field set",
+ raw: { version: 1 },
+ normalizedPin: null,
+ rawPin: null,
+ isDefault: true,
+ readable: true,
+ // MLX sizes its own window (0 asks for nothing); transformers gets the app default.
+ mlxRequest: 0,
+ transformersRequest: DEFAULT_MAX_SEQ_LENGTH,
+ },
+ {
+ name: "zero in both fields",
+ raw: { version: 1, customContextLength: 0, maxSeqLength: 0 },
+ normalizedPin: null,
+ // 0 is neither null nor undefined, so `??` keeps it: an unnormalized record yields a
+ // falsy 0 "pin". Reachable because preset code calls savedContextPin on raw shapes.
+ rawPin: 0,
+ isDefault: true,
+ readable: true,
+ mlxRequest: 0,
+ transformersRequest: DEFAULT_MAX_SEQ_LENGTH,
+ },
+ {
+ name: "negative in both fields",
+ raw: { version: 1, customContextLength: -1, maxSeqLength: -4096 },
+ normalizedPin: null,
+ rawPin: -1,
+ isDefault: true,
+ readable: true,
+ mlxRequest: 0,
+ transformersRequest: DEFAULT_MAX_SEQ_LENGTH,
+ },
+ {
+ name: "non-integer in both fields",
+ raw: { version: 1, customContextLength: 8192.7, maxSeqLength: 8192.7 },
+ // Floors vs snaps to 128: both land on 8192 by different arithmetic.
+ normalizedPin: 8192,
+ rawPin: 8192.7,
+ isDefault: false,
+ readable: true,
+ mlxRequest: 8192,
+ transformersRequest: 8192,
+ },
+ {
+ name: "version 4 (below the current schema version)",
+ raw: { version: 4, customContextLength: 32768 },
+ normalizedPin: 32768,
+ rawPin: 32768,
+ isDefault: false,
+ readable: true,
+ mlxRequest: 32768,
+ transformersRequest: 32768,
+ note:
+ "The task called v4 the 'future' record. It is not: STORAGE_SCHEMA_VERSION is 5 " +
+ "in this tree and in main, not 3, so v4 is a v4-client record and reads normally.",
+ },
+ {
+ name: "version 6 (genuinely future)",
+ raw: { version: 6, customContextLength: 32768 },
+ normalizedPin: null,
+ rawPin: 32768,
+ isDefault: true,
+ // Above STORAGE_SCHEMA_VERSION: loadPerModelConfig refuses it, so the pin is unread
+ // and the record is safe from being overwritten.
+ readable: false,
+ mlxRequest: 0,
+ transformersRequest: DEFAULT_MAX_SEQ_LENGTH,
+ },
+];
+
+/** The n_ctx `/load` is asked for, through the shipped resolver, control untouched. */
+function loadRequest(
+ config: { customContextLength: number | null; maxSeqLength: number | null },
+ isMlx: boolean,
+): number {
+ return resolveLoadMaxSeqLength({
+ modelId: MODEL,
+ ggufVariant: null,
+ isGguf: false,
+ customContextLength: config.customContextLength,
+ loadedContextLength: null,
+ currentCheckpoint: "",
+ activeGgufVariant: null,
+ isMlx,
+ pinnedMaxSeqLength: normalizeMaxSeqLength(config.maxSeqLength),
+ defaultMaxSeqLength: DEFAULT_MAX_SEQ_LENGTH,
+ presetSource: "builtin-default",
+ });
+}
+
+for (const row of ROWS) {
+ test(`record matrix — ${row.name}`, () => {
+ const { config, remembered } = stage(row.raw);
+ assert.equal(remembered, row.readable, "remembered");
+ assert.equal(
+ savedContextPin(config),
+ row.normalizedPin,
+ "savedContextPin(normalized)",
+ );
+ assert.equal(
+ savedContextPin(
+ row.raw as { customContextLength?: number; maxSeqLength?: number },
+ ),
+ row.rawPin,
+ "savedContextPin(raw)",
+ );
+ assert.equal(isDefaultConfig(config), row.isDefault, "isDefaultConfig");
+ assert.equal(loadRequest(config, true), row.mlxRequest, "MLX /load n_ctx");
+ assert.equal(
+ loadRequest(config, false),
+ row.transformersRequest,
+ "transformers /load n_ctx",
+ );
+ });
+}
+
+
+test("contextPinPatch writes the pin in exactly one field and clears the other", () => {
+ assert.deepEqual(contextPinPatch(32768, true), {
+ customContextLength: 32768,
+ maxSeqLength: null,
+ });
+ assert.deepEqual(contextPinPatch(32768, false), {
+ customContextLength: null,
+ maxSeqLength: 32768,
+ });
+});
+
+test("contextPinPatch bounds without snapping, and never writes a blank", () => {
+ // Bounded to what /load accepts, not snapped to the control's 128 step.
+ assert.equal(contextPinPatch(8193, true).customContextLength, 8193);
+ assert.equal(contextPinPatch(8192.7, true).customContextLength, 8192);
+ assert.equal(
+ contextPinPatch(1, true).customContextLength,
+ MAX_SEQ_LENGTH_MIN,
+ );
+ // 0 and negatives become the floor, not a cleared pin: "unpin" must not route here.
+ assert.equal(
+ contextPinPatch(0, true).customContextLength,
+ MAX_SEQ_LENGTH_MIN,
+ );
+ assert.equal(contextPinPatch(-1, false).maxSeqLength, MAX_SEQ_LENGTH_MIN);
+ assert.equal(
+ contextPinPatch(Number.NaN, true).customContextLength,
+ MAX_SEQ_LENGTH_MIN,
+ );
+ assert.equal(
+ contextPinPatch(Number.POSITIVE_INFINITY, true).customContextLength,
+ MAX_SEQ_LENGTH_MIN,
+ );
+ assert.equal(MAX_SEQ_LENGTH_MIN, CONTEXT_LENGTH_MIN);
+});
+
+test("a patched pin round-trips through storage on both backends", () => {
+ for (const isMlx of [true, false]) {
+ store.clear();
+ const patched = {
+ ...DEFAULT_PER_MODEL_CONFIG,
+ ...contextPinPatch(32768, isMlx),
+ };
+ assert.equal(isDefaultConfig(normalizePerModelConfig(patched)), false);
+ assert.ok(savePerModelConfig(MODEL, null, patched));
+ const { config, remembered } = resolveInitialConfig(MODEL, null);
+ assert.ok(remembered);
+ assert.equal(savedContextPin(config), 32768, `isMlx=${isMlx}`);
+ assert.equal(loadRequest(config, isMlx), 32768, `isMlx=${isMlx}`);
+ // And the cross-backend read: the same record on a host serving the OTHER backend.
+ assert.equal(
+ loadRequest(config, !isMlx),
+ 32768,
+ `cross-read isMlx=${!isMlx}`,
+ );
+ }
+});
+
+
+test("both pin shapes are stamped version 1, so neither is distinguishable by version", () => {
+ assert.equal(stampedVersion({ customContextLength: 32768 }), 1);
+ assert.equal(stampedVersion({ maxSeqLength: 32768 }), 1);
+ // The old client's only forwards guard is `version > 5`, and v1 invites any client
+ // back to v1 to rewrite the record.
+ assert.equal(
+ stage({ version: 1, customContextLength: 32768 }).remembered,
+ true,
+ );
+ assert.equal(
+ stage({ version: 5, customContextLength: 32768 }).remembered,
+ true,
+ );
+ assert.equal(
+ stage({ version: 6, customContextLength: 32768 }).remembered,
+ false,
+ );
+});
+
+
+/**
+ * The old model-config page's read rule for a NON-GGUF target, transcribed from
+ * `studio/frontend/src/features/model-picker/components/model-config-page.tsx` on main:
+ *
+ * ~2699 const contextAtDefault = !target.isGguf || config.customContextLength == null;
+ * ~2700 const atDefault = contextAtDefault && perModelConfigsEqual(
+ * { ...config, customContextLength: null }, DEFAULT_PER_MODEL_CONFIG);
+ * ~2711 const maxSeqLengthValue =
+ * normalizeMaxSeqLength(config.maxSeqLength) ??
+ * clampMaxSeqLength(DEFAULT_MAX_SEQ_LENGTH, nativeMaxSeqLength);
+ * ~3126 const effectiveLoadConfig = target.isGguf
+ * ? effectiveRuntimeConfig
+ * : { ...effectiveRuntimeConfig, maxSeqLength: effectiveMaxSeqLengthValue };
+ *
+ * `customContextLength` appears in none of the three that decide the number, and the one
+ * place it does appear deletes it before comparing.
+ */
+function oldClientConfigPage(
+ config: PerModelConfig,
+ native: number,
+): { shownContext: number; loadRequests: number; showsAsDefault: boolean } {
+ const clamp = (value: number, max: number) => Math.min(value, max);
+ const shown =
+ normalizeMaxSeqLength(config.maxSeqLength) ??
+ clamp(DEFAULT_MAX_SEQ_LENGTH, native);
+ // contextAtDefault is unconditional for non-GGUF and nulls customContextLength out.
+ const showsAsDefault = isDefaultConfig({
+ ...config,
+ customContextLength: null,
+ });
+ return { shownContext: shown, loadRequests: shown, showsAsDefault };
+}
+
+test("FORWARDS-COMPAT GAP: an old client's config page silently drops a new record's pin", () => {
+ store.clear();
+ const patched = {
+ ...DEFAULT_PER_MODEL_CONFIG,
+ ...contextPinPatch(32768, true),
+ };
+ assert.ok(savePerModelConfig(MODEL, null, patched));
+ const stored = JSON.parse(store.get(STORAGE_KEY) ?? "{}") as Record<
+ string,
+ Record<string, unknown>
+ >;
+ const record = stored[MODEL_KEY];
+
+ assert.equal(record.customContextLength, 32768);
+ assert.equal(record.maxSeqLength, null);
+ assert.equal(record.version, 1);
+
+ const { config } = resolveInitialConfig(MODEL, null);
+
+ assert.equal(savedContextPin(config), 32768);
+ assert.equal(loadRequest(config, true), 32768);
+
+ const old = oldClientConfigPage(config, NATIVE);
+ assert.equal(old.shownContext, DEFAULT_MAX_SEQ_LENGTH);
+ assert.equal(old.loadRequests, DEFAULT_MAX_SEQ_LENGTH);
+ assert.equal(old.showsAsDefault, true);
+
+ // Nothing in the record could warn it: the stamp is 1 and its guard is `version > 5`.
+ assert.ok((record.version as number) <= 5);
+
+ const table = [
+ "| reader | context requested | shows as |",
+ "| ---------------------------------------- | ----------------- | -------- |",
+ `| new code (savedContextPin) | ${loadRequest(config, true)} | pinned |`,
+ `| old client, model-config page (non-GGUF) | ${old.loadRequests} | default |`,
+ ].join("\n");
+ assert.ok(table.includes("32768") && table.includes("4096"));
+ console.log(
+ [
+ "",
+ "Record on disk (written by the new code):",
+ ` ${JSON.stringify({
+ version: record.version,
+ customContextLength: record.customContextLength,
+ maxSeqLength: record.maxSeqLength,
+ })}`,
+ "",
+ table,
+ "",
+ ].join("\n"),
+ );
+});
+
+test("the gap is the config page's, not resolveLoadMaxSeqLength's", () => {
+ // main's resolveLoadMaxSeqLength reads customContextLength first, unconditionally, for
+ // every backend -- the signature changed in this PR but that first branch did not. So
+ // the auto-load path in chat-adapter still honours a new record on an old client, and
+ // "the old client loses the pin" would be too strong a claim to make unqualified.
+ store.clear();
+ assert.ok(
+ savePerModelConfig(MODEL, null, {
+ ...DEFAULT_PER_MODEL_CONFIG,
+ ...contextPinPatch(32768, true),
+ }),
+ );
+ const { config } = resolveInitialConfig(MODEL, null);
+ // The old signature, with the old argument names, on the same record.
+ const oldResolverAnswer =
+ config.customContextLength != null
+ ? config.customContextLength
+ : (normalizeMaxSeqLength(config.maxSeqLength) ?? DEFAULT_MAX_SEQ_LENGTH);
+ assert.equal(oldResolverAnswer, 32768);
+ // And main's compare-pane rule (shared-composer.tsx ~1404), likewise.
+ const oldComparePaneAnswer =
+ config.customContextLength ??
+ normalizeMaxSeqLength(config.maxSeqLength) ??
+ DEFAULT_MAX_SEQ_LENGTH;
+ assert.equal(oldComparePaneAnswer, 32768);
+});
+
+test("BACKWARDS COMPAT: an old record still pins under the new code, on either backend", () => {
+ const { config } = stage({ version: 1, maxSeqLength: 8192 });
+ assert.equal(savedContextPin(config), 8192);
+ assert.equal(loadRequest(config, true), 8192);
+ assert.equal(loadRequest(config, false), 8192);
+ // And it is not reported as default, so it survives savePerModelConfig's delete-if-default.
+ assert.equal(isDefaultConfig(config), false);
+});
diff --git a/studio/frontend/tests/per-model-params-hydration-races.test.ts b/studio/frontend/tests/per-model-params-hydration-races.test.ts
index 8fd3eb2f289..11c64673530 100644
--- a/studio/frontend/tests/per-model-params-hydration-races.test.ts
+++ b/studio/frontend/tests/per-model-params-hydration-races.test.ts
@@ -25,10 +25,11 @@ const { mergeBackendRecommendedInference } = await import(
const A = "unsloth/model-a";
const B = "unsloth/model-b";
+const STATUS_CONTEXT_LENGTH = 131072;
const STATUS = {
inference: { temperature: 0.9 },
is_gguf: true,
- context_length: 131072,
+ context_length: STATUS_CONTEXT_LENGTH,
} as never;
/** Every field this file varies is set explicitly: the store is a module
@@ -66,6 +67,7 @@ test("with the memory off, the saved shared settings still reach a new model", a
response: STATUS,
modelId: B,
presetSource: s.activePresetSource,
+ loadedContextLength: STATUS_CONTEXT_LENGTH,
}),
{ fromModelDefaults: true },
);
@@ -127,6 +129,7 @@ test("a pre-hydration edit survives on an install that has no model map", async
response: STATUS,
modelId: A,
presetSource: s2.activePresetSource,
+ loadedContextLength: STATUS_CONTEXT_LENGTH,
}),
{ fromModelDefaults: true },
);
diff --git a/studio/frontend/tests/per-model-params-hydration.test.ts b/studio/frontend/tests/per-model-params-hydration.test.ts
index 419bb798eb6..fab48a3c29f 100644
--- a/studio/frontend/tests/per-model-params-hydration.test.ts
+++ b/studio/frontend/tests/per-model-params-hydration.test.ts
@@ -34,11 +34,12 @@ const LLAMA = "unsloth/Llama-4-8B";
const EXTERNAL = "external::anthropic::claude-opus-5";
const TUNED = { temperature: 0.2, maxTokens: 4096, systemPrompt: "Be terse." };
+const STATUS_CONTEXT_LENGTH = 131072;
/** A status response for a resident GGUF, recommending its own sampling. */
const STATUS = {
inference: { temperature: 0.9, top_p: 0.5 },
is_gguf: true,
- context_length: 131072,
+ context_length: STATUS_CONTEXT_LENGTH,
} as never;
/** applyActiveModelStatusToStore's update, which the last test pins. */
@@ -50,6 +51,7 @@ function applyStatus(modelId: string) {
response: STATUS,
modelId,
presetSource: store.activePresetSource,
+ loadedContextLength: STATUS_CONTEXT_LENGTH,
}),
{ fromModelDefaults: true },
);
@@ -408,7 +410,7 @@ test("the replay at hydration fits the context already published", async () => {
},
paramsByModel: {},
// What the status published for the reduced context it loaded with.
- ggufContextLength: 8192,
+ loadedContextLength: 8192,
settingsHydrated: false,
});
const hydrating = useChatRuntimeStore.getState().hydratePersistedSettings();
@@ -487,14 +489,16 @@ test("a remembered budget is clamped to the context just loaded", () => {
// values without changing the checkpoint, so each has to ask for the replay;
// they pull in the chat UI, so this reads them rather than importing them.
test("every site that re-applies model defaults asks for the replay", () => {
+ // Wide enough for the window each call now records alongside the merge, and
+ // still far short of the next fromModelDefaults site in either file.
const sites: [string, RegExp][] = [
[
"../src/features/chat/lib/apply-inference-status-to-store.ts",
- /mergeBackendRecommendedInference\([\s\S]{0,500}?fromModelDefaults: true/,
+ /mergeBackendRecommendedInference\([\s\S]{0,1200}?fromModelDefaults: true/,
],
[
"../src/features/chat/hooks/use-chat-model-runtime.ts",
- /mergeBackendRecommendedInference\([\s\S]{0,500}?fromModelDefaults: true/,
+ /mergeBackendRecommendedInference\([\s\S]{0,1200}?fromModelDefaults: true/,
],
[
// The Qwen3 thinking-mode params applied after a load.
@@ -561,9 +565,12 @@ test("a remembered budget is capped by a non-GGUF load", () => {
"utf8",
);
// One cap for both sites: the load response and the Qwen3 thinking defaults.
+ // The reported window leads, and the request stands in only for a backend that
+ // sizes nothing -- a self-sizing one is sent the auto-size sentinel. Through the
+ // floor, so a window below the control's own minimum cannot become the cap.
assert.match(
runtime,
- /const loadedContextCap = loadResponse\.is_gguf\s*\?\s*\(loadResponse\.context_length \?\? undefined\)\s*:\s*effectiveMaxSeqLength;/,
+ /const loadedContextCap = replayMaxTokensCap\(\s*loadedFields\.loadedContextLength \?\?\s*\(!loadResponse\.is_gguf && effectiveMaxSeqLength > 0\s*\? effectiveMaxSeqLength\s*: null\),\s*\);/,
);
assert.equal(
runtime.match(/maxTokensCap: loadedContextCap/g)?.length,
@@ -577,7 +584,18 @@ test("a remembered budget is capped by a non-GGUF load", () => {
);
assert.match(
adapter,
- /\? \(loadResp\.context_length \?\? undefined\)\s*: effectiveMaxSeqLength,/,
+ /maxTokensCap: replayMaxTokensCap\(\s*candidate\.kind === "gguf"\s*\? loadedContextFields\(loadResp\)\.loadedContextLength\s*: loadedWindow,\s*\),/,
+ );
+
+ // Compare loads the same way: a pane with no context pin sends the sentinel, and
+ // capping its budget at 0 would leave the pane asking for no output at all.
+ const composer = readFileSync(
+ new URL("../src/features/chat/shared-composer.tsx", import.meta.url),
+ "utf8",
+ );
+ assert.match(
+ composer,
+ /maxTokensCap: replayMaxTokensCap\(\s*loadedContextFields\(resp\)\.loadedContextLength \?\?\s*\(!resp\.is_gguf && effectiveMaxSeqLength > 0/,
);
const status = readFileSync(
@@ -587,8 +605,10 @@ test("a remembered budget is capped by a non-GGUF load", () => {
),
"utf8",
);
- // Reported for a safetensors load too, so the cap is not narrowed to GGUF.
- assert.match(status, /maxTokensCap: status\.context_length \?\? undefined,/);
+ // Reported for a safetensors load too, so the cap is not narrowed to GGUF, and
+ // through the same floor the load paths use: hydration must not clamp Max Tokens
+ // below its own slider either.
+ assert.match(status, /maxTokensCap: replayMaxTokensCap\(status\.context_length\),/);
});
// The clamp itself, through the store: the memory holds a budget from a larger
@@ -645,12 +665,12 @@ test("turning the memory off is persisted and hydrated back", async () => {
});
// A safetensors load publishes its context through the cap, not through
-// ggufContextLength, which is null for everything that is not a GGUF.
+// loadedContextLength, which a backend that sizes no window leaves null.
test("a safetensors context also caps the hydration replay", async () => {
useChatRuntimeStore.setState({
settingsHydrated: false,
rememberParamsPerModel: true,
- ggufContextLength: null,
+ loadedContextLength: null,
paramsByModel: {},
params: { ...useChatRuntimeStore.getState().params, checkpoint: LLAMA },
});
@@ -684,7 +704,7 @@ test("a kept context does not follow the next model", async () => {
useChatRuntimeStore.setState({
settingsHydrated: false,
rememberParamsPerModel: true,
- ggufContextLength: null,
+ loadedContextLength: null,
paramsByModel: {},
params: { ...useChatRuntimeStore.getState().params, checkpoint: LLAMA },
});
@@ -758,7 +778,7 @@ test("the loaded context caps a global budget with no entry to replay", async ()
useChatRuntimeStore.setState({
settingsHydrated: false,
rememberParamsPerModel: true,
- ggufContextLength: null,
+ loadedContextLength: null,
paramsByModel: {},
params: { ...useChatRuntimeStore.getState().params, checkpoint: LLAMA },
});
@@ -925,13 +945,13 @@ test("two edits to one model inside a debounce window both survive", async () =>
);
});
-// Picking an external model leaves the local one resident, so ggufContextLength
+// Picking an external model leaves the local one resident, so loadedContextLength
// goes on describing a model that has nothing to do with the pick.
test("a resident GGUF context does not cap an external model", async () => {
useChatRuntimeStore.setState({
settingsHydrated: false,
rememberParamsPerModel: true,
- ggufContextLength: 8192,
+ loadedContextLength: 8192,
paramsByModel: {},
params: {
...useChatRuntimeStore.getState().params,
@@ -945,7 +965,7 @@ test("a resident GGUF context does not cap an external model", async () => {
// A local checkpoint with the same resident context is still capped.
useChatRuntimeStore.setState({
settingsHydrated: false,
- ggufContextLength: 8192,
+ loadedContextLength: 8192,
paramsByModel: {},
params: { ...useChatRuntimeStore.getState().params, checkpoint: QWEN },
});
diff --git a/studio/frontend/tests/per-model-params.test.ts b/studio/frontend/tests/per-model-params.test.ts
index c3424b31632..78c562111a0 100644
--- a/studio/frontend/tests/per-model-params.test.ts
+++ b/studio/frontend/tests/per-model-params.test.ts
@@ -222,6 +222,7 @@ test("a model's defaults do not outrank what it is remembered with", async () =>
response: response as never,
modelId,
presetSource: "builtin-default",
+ loadedContextLength: response.context_length,
});
const memory = { [QWEN]: { temperature: 0.2, maxTokens: 4096 } };
diff --git a/studio/frontend/tests/resident-config-match.test.ts b/studio/frontend/tests/resident-config-match.test.ts
index 941d68f5a5c..7933afb79c4 100644
--- a/studio/frontend/tests/resident-config-match.test.ts
+++ b/studio/frontend/tests/resident-config-match.test.ts
@@ -499,7 +499,7 @@ test("an unset context length is resolved the way the load resolves it", () => {
assert.equal(
matches({ ...DEFAULTS, requested_context_length: 32768 }, BLANK, {
...STANDING,
- // The re-pick branch: ggufContextLength, not 0.
+ // The re-pick branch: loadedContextLength, not 0.
resolveContextLength: (pin) => pin ?? 32768,
}),
true,
diff --git a/studio/frontend/tests/thread-scoped-pairing-invariants.test.ts b/studio/frontend/tests/thread-scoped-pairing-invariants.test.ts
index bb6d6b9de5b..9ecf20f9d4d 100644
--- a/studio/frontend/tests/thread-scoped-pairing-invariants.test.ts
+++ b/studio/frontend/tests/thread-scoped-pairing-invariants.test.ts
@@ -653,7 +653,7 @@ test("only a user edit to a sampling param lands on the chat", () => {
for (const source of [runtime, status]) {
assert.match(
source,
- /mergeBackendRecommendedInference\([\s\S]{0,700}?fromModelDefaults: true/,
+ /mergeBackendRecommendedInference\([\s\S]{0,1200}?fromModelDefaults: true/,
);
}
});
diff --git a/tests/studio/test_backend_ci_parallel_isolation.py b/tests/studio/test_backend_ci_parallel_isolation.py
index bf3b521032b..3ebd546131b 100644
--- a/tests/studio/test_backend_ci_parallel_isolation.py
+++ b/tests/studio/test_backend_ci_parallel_isolation.py
@@ -36,6 +36,7 @@ ISOLATED = [
("tests/studio/test_hardware_dispatch_matrix.py", "mutates hardware.py globals"),
("tests/studio/test_is_mlx_dispatch_gate.py", "mutates hardware.py globals"),
("tests/studio/test_xpu_spoof_pipeline.py", "mutates hardware.py globals"),
+ ("tests/studio/test_mlx_context_platform_matrix.py", "mutates hardware.py globals"),
]
diff --git a/tests/studio/test_chat_autoload_failure_gate.py b/tests/studio/test_chat_autoload_failure_gate.py
index cc4244044b7..8cdde321677 100644
--- a/tests/studio/test_chat_autoload_failure_gate.py
+++ b/tests/studio/test_chat_autoload_failure_gate.py
@@ -68,6 +68,9 @@ export type Scenario = {
/** How the Hub download manager answers the default-model request:
* "complete" (default), "cancelled", "failed", "busy", or "conflict". */
download: (request: any) => string;
+ // Which backend the host serves with, and what the record holds: both decide the ask.
+ platform?: { deviceType: string; chatOnlyReason: string | null };
+ config?: Record<string, unknown>;
};
// The stored-arguments hydration the auto-load runs before it calls /load. Neutral
@@ -187,6 +190,48 @@ function resolveInferenceCheckpointId(status: any) {
function snapshotQueuedChatRunSettings(state: any) {
return { ...state, params: { ...state.params } };
}
+// Mirrored rather than stubbed to constants, so a scenario that pins is not auto-answered.
+function loadedContextFields(resp: any) {
+ if (!resp) {
+ return {
+ loadedContextLength: null, maxContextLength: null,
+ nativeContextLength: null, loadedIsGguf: null,
+ loadedContextEnforced: null,
+ };
+ }
+ const isGguf = resp.is_gguf ?? false;
+ const loaded = resp.context_length ?? null;
+ // !is_mlx as well: MLX sizes its own window, so it reports one without a native.
+ if (!isGguf && !resp.is_mlx && resp.native_context_length == null) {
+ return {
+ loadedContextLength: null, maxContextLength: null,
+ nativeContextLength: null, loadedIsGguf: false,
+ loadedContextEnforced: null,
+ };
+ }
+ return {
+ loadedContextLength: loaded,
+ maxContextLength: resp.max_context_length ?? loaded,
+ nativeContextLength: resp.native_context_length ?? null,
+ loadedIsGguf: isGguf,
+ loadedContextEnforced: isGguf ? true : (resp.context_length_enforced ?? null),
+ };
+}
+const NO_MLX_REASONS = new Set(["mlx_unavailable", "intel_mac", "detection_failed"]);
+function isServedByMlx(isGguf: boolean, deviceType: string, reason: unknown) {
+ return !isGguf && deviceType === "mac" && !NO_MLX_REASONS.has((reason ?? "") as string);
+}
+function retainedContextPin(args: any) {
+ if (args.isGguf) {
+ return args.gpuMemoryMode === "manual" && args.gpuLayers < 0
+ ? ((args.requestedContextLength ?? 0) > 0 ? args.requestedContextLength : null)
+ : null;
+ }
+ if (args.isMlx) {
+ return (args.requestedContextLength ?? 0) > 0 ? args.requestedContextLength : null;
+ }
+ return null;
+}
function makeStore(): any {
const state: any = {
@@ -304,7 +349,10 @@ function syncModelCapabilities(modelId: string, resp: any) {
}
const useChatRuntimeStore = {
getState: () => STORE,
- setState: (_p: any) => {},
+ // Recorded, not discarded: a scenario asserting on them has nowhere else to read them.
+ setState: (p: any) => {
+ Object.assign(STORE, typeof p === "function" ? p(STORE) : p);
+ },
};
function createLoadingToastIcon() { return null; }
@@ -341,22 +389,51 @@ function readLastLocalModelLoad() { return SCENARIO.lastLoaded; }
function recordLastLocalModelLoad(x: any) {
EVENTS.push({ kind: "recordLastLocal", id: x.id, modelKind: x.kind });
}
+function normalizeMaxSeqLength(value: any) {
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : null;
+}
function resolveInitialConfig(_id: string, _variant: any) {
return { config: {
customContextLength: null, maxSeqLength: null, gpuMemoryMode: null,
gpuLayers: null, nCpuMoe: null, selectedGpuIds: undefined,
speculativeType: null, specDraftNMax: null, chatTemplateOverride: null,
kvCacheDtype: null, tensorParallel: false,
+ ...(SCENARIO.config ?? {}),
} };
}
-function resolveLoadMaxSeqLength(args: any) { return args.maxSeqLength ?? 0; }
-function resolveFitMaxSeqLength(..._a: any[]) { return 0; }
// Mirrors the real predicate rather than returning a constant: the sliced region
// stores its result as the load's context pin, so a stub that always answered null
// would make every autoload scenario here agree with a bug in it. It takes the
// user's own Context Length (config.customContextLength above), never the n_ctx
// that went on the wire, which is Auto-resolved on a same-model reload.
function resolveExplicitCtxPin(n: any) { return n && n > 0 ? n : null; }
+// Mirrors the real resolution: the pin, else the sentinel for a self-sizing backend and
+// the app default for one that does not, which is what these off-Mac scenarios send.
+function resolveLoadMaxSeqLength(args: any) {
+ return (
+ args.customContextLength ??
+ args.pinnedMaxSeqLength ??
+ (args.isGguf || args.isMlx ? 0 : args.defaultMaxSeqLength)
+ );
+}
+// The window reported, never the request: the sentinel is below the control's minimum.
+function loadedContextForParams(reported: any, requested: number, previous: number) {
+ return reported ?? (requested > 0 ? requested : previous);
+}
+function resolveFitMaxSeqLength(
+ isGguf: any, gpuMemoryMode: string, gpuLayers: number, pin: number | null, fallback: number,
+) {
+ if (!isGguf || gpuMemoryMode !== "manual" || gpuLayers >= 0) return fallback;
+ return pin && pin > 0 ? pin : 0;
+}
+function localMaxTokensCeiling(loadedContextLength: number | null, fallback: number) {
+ return Math.max(64, loadedContextLength ?? fallback);
+}
+function replayMaxTokensCap(loadedContextLength: number | null | undefined) {
+ return loadedContextLength == null ? undefined : Math.max(64, loadedContextLength);
+}
+function unreportedWindowMaxTokens(g: boolean, held: number) { return g ? held : 4096; }
+function resolveManualAutoCtxPin(..._a: any[]) { return null; }
async function ensureGpuDeviceCache() {}
function reconcilePersistedGpuIds(ids: any) { return ids; }
function saveSpeculativeType(_x: any) {}
@@ -389,7 +466,8 @@ function isHiddenModelId(..._a: any[]) { return false; }
// picker hides every other local format there, so a background pick must too.
const usePlatformStore = {
getState: () => ({
- deviceType: SCENARIO.deviceType ?? "linux",
+ deviceType: SCENARIO.platform?.deviceType ?? SCENARIO.deviceType ?? "linux",
+ chatOnlyReason: SCENARIO.platform?.chatOnlyReason ?? null,
// Server-reported unless a scenario says the probe has not landed.
fetched: SCENARIO.platformFetched !== false,
isChatOnly: () => SCENARIO.chatOnly === true,
@@ -523,8 +601,8 @@ async function loadModel(payload: any) {
kind: "loadModel",
model_path: payload.model_path,
gguf_variant: payload.gguf_variant ?? null,
- // GGUF sources send 0; a Transformers source sends the safetensors length.
- max_seq_length: payload.max_seq_length,
+ // GGUF and self-sizing sources send 0; a Transformers one the safetensors length.
+ max_seq_length: payload.max_seq_length ?? null,
rejected: result instanceof Error,
});
if (result instanceof Error) throw result;
@@ -585,6 +663,22 @@ SCENARIO_HELPERS = """
size_bytes: 1_100_000_000,
capabilities: { can_chat: true, requires_variant: false },
};
+ // A safetensors repo, which MLX serves on a Mac and transformers everywhere else.
+ const QWEN = {
+ repo_id: "unsloth/Qwen3.5-4B",
+ load_id: "unsloth/Qwen3.5-4B",
+ cache_path: "/home/john-doe/.cache/huggingface/hub/models--unsloth--Qwen3.5-4B",
+ size_bytes: 8000000000,
+ };
+ const MAC = { deviceType: "mac", chatOnlyReason: null };
+ // What a self-sizing backend answers: the window it resolved, not the request.
+ const SERVED = (n) => (payload) => ({
+ model: payload.model_path,
+ is_gguf: false,
+ context_length: n,
+ native_context_length: 262144,
+ max_context_length: 262144,
+ });
const scenario = (over) => ({
ggufRepos: [],
modelRepos: [],
@@ -696,7 +790,11 @@ def _build_harness(run_dir: Path):
"wrong-model assertions rather than saying what is actually missing."
)
(run_dir / "harness.ts").write_text(
- "// @ts-nocheck\n" + PREAMBLE + "\n" + body + "\nexport { autoLoadSmallestModel };\n",
+ "// @ts-nocheck\n"
+ + PREAMBLE
+ + "\n"
+ + body
+ + "\nexport { autoLoadSmallestModel };\nexport function storeState() { return STORE; }\n",
encoding = "utf-8",
)
@@ -711,7 +809,7 @@ def _run(scenario_expr: str) -> dict:
textwrap.dedent(
"""
// @ts-nocheck
- import { autoLoadSmallestModel, setScenario, EVENTS } from "./harness.ts";
+ import { autoLoadSmallestModel, setScenario, EVENTS, storeState } from "./harness.ts";
"""
)
+ SCENARIO_HELPERS
@@ -723,7 +821,18 @@ def _run(scenario_expr: str) -> dict:
const result = await autoLoadSmallestModel({{
abortSignal: new AbortController().signal,
}});
- console.log(JSON.stringify({{ result, events: EVENTS }}));
+ const s = storeState();
+ console.log(JSON.stringify({{
+ result,
+ events: EVENTS,
+ store: {{
+ maxSeqLength: s.params?.maxSeqLength ?? null,
+ maxTokens: s.params?.maxTokens ?? null,
+ customContextLength: s.customContextLength ?? null,
+ loadedCustomContextLength: s.loadedCustomContextLength ?? null,
+ loadedContextLength: s.loadedContextLength ?? null,
+ }},
+ }}));
"""
)
)
@@ -1572,3 +1681,41 @@ def test_an_unclassified_local_row_is_never_auto_loaded(fmt):
assert "/models/x" not in _loaded_paths(out)
assert _loaded_paths(out) == [DEFAULT_MODEL]
+
+
+def test_an_unpinned_mlx_candidate_is_loaded_at_the_window_the_backend_resolved():
+ """The auto-load runs unwatched, so its request is what an MLX model is left serving;
+ the app default there loaded every model at 4096."""
+ out = _run("scenario({ modelRepos: [QWEN], platform: MAC, load: SERVED(262144) })")
+ [load] = [e for e in out["events"] if e["kind"] == "loadModel"]
+ assert load["model_path"] == "unsloth/Qwen3.5-4B"
+ # The sentinel that hands sizing to the backend, not a length chosen here.
+ assert load["max_seq_length"] == 0
+ # And what comes back describes the model rather than the request.
+ assert out["store"]["maxSeqLength"] == 262144
+ assert out["store"]["maxTokens"] == 262144
+ # Nothing was pinned, so nothing is remembered as pinned.
+ assert out["store"]["customContextLength"] is None
+ assert out["store"]["loadedCustomContextLength"] is None
+
+
+def test_a_pinned_mlx_candidate_is_loaded_at_its_pin_and_keeps_it():
+ """The rules are proved apart; this is the only proof the auto-load threads them: the
+ record's pin into the request, and the retained pin back. Dropping either leaves a
+ pinned model asking for 0, or forgetting its pin on reload."""
+ out = _run(
+ "scenario({ modelRepos: [QWEN], platform: MAC,"
+ " config: { customContextLength: 8192 }, load: SERVED(8192) })"
+ )
+ [load] = [e for e in out["events"] if e["kind"] == "loadModel"]
+ assert load["max_seq_length"] == 8192
+ assert out["store"]["customContextLength"] == 8192
+ assert out["store"]["loadedCustomContextLength"] == 8192
+ assert out["store"]["maxSeqLength"] == 8192
+ # A pre-move record holds the pin in the other field; the write-back moves it.
+ legacy = _run(
+ "scenario({ modelRepos: [QWEN], platform: MAC,"
+ " config: { maxSeqLength: 8192 }, load: SERVED(8192) })"
+ )
+ assert [e for e in legacy["events"] if e["kind"] == "loadModel"][0]["max_seq_length"] == 8192
+ assert legacy["store"]["customContextLength"] == 8192
diff --git a/tests/studio/test_chat_preset_load_config.py b/tests/studio/test_chat_preset_load_config.py
index 6234ab395ce..42e5955511c 100644
--- a/tests/studio/test_chat_preset_load_config.py
+++ b/tests/studio/test_chat_preset_load_config.py
@@ -3,6 +3,7 @@
"""Contract coverage for preset load settings (#7347)."""
+import re
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
@@ -41,7 +42,7 @@ def test_persisted_preset_serializes_load_config():
def test_capture_reads_gguf_loaded_context():
source = _read("studio/frontend/src/features/chat/presets/preset-load-config.ts")
- assert "store.ggufContextLength" in source
+ assert "store.loadedContextLength" in source
assert "effectiveContextLength" in source
@@ -83,3 +84,31 @@ def test_preset_load_config_carries_parallel_slots():
"nParallel: Optional[int] = Field(default = None, ge = PARALLEL_MIN, le = PARALLEL_MAX)"
in routes
)
+
+
+def test_a_preset_records_a_self_sizing_load_s_pin_and_not_its_window():
+ """A preset must reproduce the setup that ran. A window nobody pinned is reached again
+ on replay, so only the pin is stored -- in the one field that means "pinned"."""
+ source = _read("studio/frontend/src/features/chat/presets/preset-load-config.ts")
+ body = source[source.index("export function capturePresetLoadConfig") :]
+ body = body[: body.index("\n}\n")]
+ # Here: capture asks the rule, off classifiers rather than constants, and bounds it.
+ assert "requestableContextLength(\n capturedContextLength(" in body, body
+ assert "isServedByLlamaCpp({\n loadedIsGguf: store.loadedIsGguf," in body, body
+ assert not re.search(r"LlamaCpp\(\{[^}]*?(\w+): (?!store\.[\w.]*\1,)", body), body
+ assert "isServedByMlx(isGguf, platform.deviceType, platform.chatOnlyReason)" in body, body
+ # Compared as a pin, not as a field: another backend holds it in the other field.
+ compare = source[source.index("function toComparablePerModelConfig(") :]
+ compare = compare[: compare.index("\n}\n")]
+ assert "const pin = savedContextPin(config);" in compare, compare
+ assert "customContextLength: pin,\n maxSeqLength: null," in compare, compare
+ # Both bounds, in the one rule capture and storage share, else the replays disagree.
+ rule = source[source.index("function requestableContextLength(") :]
+ rule = rule[: rule.index("\n}\n")]
+ assert "Math.min(MAX_SEQ_LENGTH_MAX, Math.max(CONTEXT_LENGTH_MIN," in rule, rule
+ assert source.count("requestableContextLength(") == 3, source
+ assert "loadedContextLength: store.loadedContextLength," in body, body
+ assert "controlPin: snapshot.customContextLength," in body, body
+ # A self-sized window is never captured: bounded, it replays a wider one narrower.
+ assert re.search(r"capturedContextLength\(\{\n\s*isGguf,\n\s*controlPin:", body), body
+ assert "maxSeqLength: isMlx ? null : normalizeMaxSeqLength(" in body, body
diff --git a/tests/studio/test_mlx_context_platform_matrix.py b/tests/studio/test_mlx_context_platform_matrix.py
new file mode 100644
index 00000000000..9d22c91327e
--- /dev/null
+++ b/tests/studio/test_mlx_context_platform_matrix.py
@@ -0,0 +1,628 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""[Windows, Linux, WSL, macOS] x [NVIDIA, AMD/ROCm, CPU-only] for the MLX context report.
+
+Per cell: the ``DeviceType`` ``detect_hardware()`` returns, whether ``worker.py`` would
+construct ``MLXInferenceBackend`` (the selection is ``_hw.DEVICE == _hw.DeviceType.MLX``
+and nothing else, asserted against the source too), and whether the context triple reaches
+the API. Only an MLX load resolves ``native_context_length`` / ``max_context_length``, so
+the other eleven cells withhold them through ``_mirrored_model_entry`` and ``/v1/models``.
+
+Every cell is presented with a HEALTHY MLX stack, including the absurd ones: the gate, not
+the missing package, is what must keep MLX off the other eleven. If the ordering in
+``_detect_hardware_locked`` changed, only a matrix that installs mlx everywhere would see it.
+
+What this CANNOT prove, recorded rather than skipped (tests at the bottom):
+
+ * WSL is indistinguishable from Linux in ``utils/hardware/**``, so its row is asserted
+ byte-identical to linux and the absence of any WSL discriminator is asserted structurally.
+ * macOS x NVIDIA and macOS x AMD are not bootable cells; the rows describe the detector's
+ ordering, not a machine.
+ * Windows x MLX is impossible by construction: ``is_apple_silicon()`` ANDs Darwin with
+ arm64, so Windows-on-ARM with a full MLX stack still lands on CPU.
+ * No Apple Silicon, ROCm or AMD GPU exists on this host, so every non-CPU answer comes
+ from the mocked torch shapes ``test_gpu_arch_gate_os_matrix_7624`` documents.
+
+Machinery is reused from ``test_gpu_arch_gate_os_matrix_7624.py`` and
+``test_hardware_dispatch_matrix.py``. It mutates ``hardware.py`` globals, so it is
+registered in ``test_backend_ci_parallel_isolation.py::ISOLATED`` and in both halves of the
+Backend CI pairing. Written without the workflow directory's literal path, which
+``test_workflow_guards_run_unfiltered`` scans for.
+"""
+
+from __future__ import annotations
+
+import ast
+import importlib.util
+import io
+import platform
+import sys
+import tokenize
+from dataclasses import dataclass
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+STUDIO_BACKEND = REPO_ROOT / "studio" / "backend"
+if str(STUDIO_BACKEND) not in sys.path:
+ sys.path.insert(0, str(STUDIO_BACKEND))
+
+# The studio backend pulls in torch. A runner without it cannot answer any question this
+# file asks, so skip the module rather than fail collection on it.
+pytest.importorskip("torch", reason = "the studio backend imports torch at module scope")
+
+# Imported eagerly, before any fake torch can be in place: these modules are the subject
+# of the test, and importing them under a spoof would measure the spoof.
+from core.inference.inference import runtime_context_length # noqa: E402
+from core.inference.mlx_inference import MLXInferenceBackend # noqa: E402
+from core.inference.orchestrator import _mirrored_model_entry # noqa: E402
+import routes.inference as routes_inference # noqa: E402
+
+WORKER_SOURCE = (STUDIO_BACKEND / "core" / "inference" / "worker.py").read_text(encoding = "utf-8")
+HARDWARE_PACKAGE = STUDIO_BACKEND / "utils" / "hardware"
+# The real torch, before anything here shadows it. Re-seated at the top of every spoof so
+# a second cell in one test does not build its profile against the previous fake.
+_REAL_TORCH = sys.modules.get("torch")
+
+
+def _code_without_comments(path: Path) -> str:
+ """Source with comments removed and string literals kept.
+
+ Both halves matter for the WSL claim below: `WSL` appears in this package only in
+ prose (two comments explaining that WSL is deliberately NOT special-cased), while a
+ real discriminator would be a string -- ``os.environ.get("WSL_DISTRO_NAME")``,
+ ``open("/proc/version")`` -- so stripping strings instead would hide exactly the thing
+ being looked for.
+ """
+ text = path.read_text(encoding = "utf-8")
+ return "".join(
+ token.string if token.type != tokenize.COMMENT else ""
+ for token in tokenize.generate_tokens(io.StringIO(text).readline)
+ )
+
+
+def _load_sibling(name: str, path: Path):
+ """Load a test module by path so its helpers can be reused verbatim.
+
+ By path rather than by name: ``tests/studio`` and ``studio/backend/tests`` are both
+ unpackaged, so neither is importable as ``tests.studio.x`` from the other.
+ """
+ spec = importlib.util.spec_from_file_location(name, path)
+ module = importlib.util.module_from_spec(spec)
+ # Registered before execution: @dataclass resolves annotations through
+ # sys.modules[cls.__module__], which is None for a module that is only half loaded.
+ sys.modules[name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+_OS_MATRIX = _load_sibling(
+ "_mlx_ctx_os_matrix_7624",
+ STUDIO_BACKEND / "tests" / "test_gpu_arch_gate_os_matrix_7624.py",
+)
+_DISPATCH = _load_sibling(
+ "_mlx_ctx_hardware_dispatch",
+ REPO_ROOT / "tests" / "studio" / "test_hardware_dispatch_matrix.py",
+)
+
+# The four simulated hosts, exactly as #7624 spells them.
+OS_KEYS = _OS_MATRIX.OS_KEYS
+# The three GPU vendors. "amd" is the ROCm wheel shape (torch.version.hip set); the AMD
+# SDK / Radeon wheel shape that leaves it unset is covered as an extra row below, because
+# it is the one that reaches IS_ROCM through torch.__version__ instead.
+VENDORS = ("nvidia", "amd", "cpu")
+CELLS = [(os_key, vendor) for os_key in OS_KEYS for vendor in VENDORS]
+CELL_IDS = [f"{os_key}-{vendor}" for os_key, vendor in CELLS]
+
+
+@dataclass(frozen = True)
+class Expectation:
+ """What one cell must produce. ``real`` records whether the cell can be booted."""
+
+ device: str
+ is_rocm: bool
+ mlx_selected: bool
+ reports_triple: bool
+ chat_only_reason: str | None
+ real: bool
+ note: str = ""
+
+
+# The machine a cell runs on. Darwin cells are arm64 (the only Apple Silicon shape);
+# everything else is x86_64. Windows-on-ARM and Intel Mac get their own rows below.
+_MACHINE = {"windows": "x86_64", "linux": "x86_64", "wsl": "x86_64", "macos": "arm64"}
+
+_NOT_A_REAL_CELL = (
+ "Not a bootable host: macOS has shipped no CUDA driver since 10.13 and ROCm has no "
+ "macOS build. Kept as an expectation about the detector's ordering, not a machine."
+)
+
+# The reasons hardware.py groups as "no GPU this torch can use" (see its own tuple in
+# _chat_only_reason): a CPU-only wheel and an unusable CUDA build are not "no_gpu".
+_CPU_ONLY_REASONS = ("no_gpu", "torch_cpu_build", "torch_cuda_unavailable")
+
+EXPECTED: dict[tuple[str, str], Expectation] = {
+ # --- Windows -----------------------------------------------------------------
+ ("windows", "nvidia"): Expectation(
+ "CUDA",
+ False,
+ False,
+ False,
+ None,
+ real = True,
+ ),
+ ("windows", "amd"): Expectation(
+ "CUDA",
+ True,
+ False,
+ False,
+ None,
+ real = True,
+ note = "ROCm reuses torch.cuda over HIP; DeviceType stays CUDA, IS_ROCM flips.",
+ ),
+ ("windows", "cpu"): Expectation(
+ "CPU",
+ False,
+ False,
+ False,
+ "no_gpu",
+ real = True,
+ note = "MLX stack present and healthy, and still CPU: the gate requires Darwin.",
+ ),
+ # --- Linux -------------------------------------------------------------------
+ ("linux", "nvidia"): Expectation("CUDA", False, False, False, None, real = True),
+ ("linux", "amd"): Expectation("CUDA", True, False, False, None, real = True),
+ ("linux", "cpu"): Expectation("CPU", False, False, False, "no_gpu", real = True),
+ # --- WSL (indistinguishable from Linux; see the dedicated tests) --------------
+ ("wsl", "nvidia"): Expectation(
+ "CUDA",
+ False,
+ False,
+ False,
+ None,
+ real = True,
+ note = "sys.platform is 'linux'; nothing in utils/hardware reads a WSL marker.",
+ ),
+ ("wsl", "amd"): Expectation("CUDA", True, False, False, None, real = True),
+ ("wsl", "cpu"): Expectation("CPU", False, False, False, "no_gpu", real = True),
+ # --- macOS -------------------------------------------------------------------
+ ("macos", "nvidia"): Expectation(
+ "CUDA",
+ False,
+ False,
+ False,
+ None,
+ real = False,
+ note = _NOT_A_REAL_CELL,
+ ),
+ ("macos", "amd"): Expectation(
+ "CUDA",
+ True,
+ False,
+ False,
+ None,
+ real = False,
+ note = _NOT_A_REAL_CELL,
+ ),
+ ("macos", "cpu"): Expectation(
+ "MLX",
+ False,
+ True,
+ True,
+ None,
+ real = True,
+ note = "The one cell that serves MLX: Darwin + arm64, no CUDA/XPU, healthy stack.",
+ ),
+}
+
+
+def _devices_for(vendor: str) -> list:
+ """The enumerated device list a vendor's torch reports."""
+ if vendor == "cpu":
+ return []
+ if vendor == "nvidia":
+ return [_OS_MATRIX._device(name = "NVIDIA GeForce RTX 4090", arch = "")]
+ return [_OS_MATRIX._device(arch = "gfx1100", name = "AMD Radeon RX 7900 XTX")]
+
+
+def spoof_cell(monkeypatch, spoof_hardware):
+ """Present one (OS, vendor, machine, mlx) host to ``detect_hardware()``.
+
+ Layered rather than rewritten. ``spoof_hardware`` owns the MLX side (the fake
+ ``mlx``/``mlx.core`` modules, the ``utils.mlx_repair`` stubs, and the meta-path finder
+ that makes ``import mlx.core`` raise), ``_apply_os`` owns ``sys.platform`` /
+ ``platform.system()``, and the fake torch is installed last so it shadows the real one
+ for the ``import torch`` inside the detector.
+ """
+
+ def _apply(
+ os_key: str,
+ vendor: str,
+ *,
+ machine: str | None = None,
+ mlx: bool = True,
+ ):
+ machine = machine or _MACHINE[os_key]
+ _, system_name = _OS_MATRIX._OS_CELLS[os_key]
+ # A test that presents two cells (the linux/wsl comparison) would otherwise build
+ # the second profile against the first cell's fake torch, which has no .backends.
+ if _REAL_TORCH is not None:
+ monkeypatch.setitem(sys.modules, "torch", _REAL_TORCH)
+ spoof_hardware(
+ _DISPATCH.HardwareProfile(
+ name = f"{os_key}-{vendor}",
+ system = system_name,
+ machine = machine,
+ cuda_available = vendor != "cpu",
+ hip_version = "6.4" if vendor == "amd" else None,
+ xpu_available = False,
+ has_mlx = mlx,
+ mps_available = system_name == "Darwin",
+ expect_is_mlx = False,
+ expect_device_type = "CPU",
+ expect_is_rocm = vendor == "amd",
+ expect_apple_silicon = system_name == "Darwin" and machine == "arm64",
+ )
+ )
+ _OS_MATRIX._apply_os(monkeypatch, os_key, is_rocm = vendor == "amd")
+ monkeypatch.setattr(platform, "machine", lambda: machine)
+ monkeypatch.setitem(
+ sys.modules,
+ "torch",
+ _OS_MATRIX._fake_torch(_devices_for(vendor), vendor = vendor),
+ )
+ # Neither hint may leak in from the host running this: an inherited
+ # ZE_AFFINITY_MASK plus a CPU-only torch would route the cell to XPU.
+ for var in ("ZE_AFFINITY_MASK", "UNSLOTH_FORCE_XPU", "CUDA_VISIBLE_DEVICES"):
+ monkeypatch.delenv(var, raising = False)
+ return _DISPATCH._import_studio_hardware_module()
+
+ return _apply
+
+
+def spoof_hardware(monkeypatch):
+ """``test_hardware_dispatch_matrix``'s fixture, bound to this module's monkeypatch."""
+ return _DISPATCH.spoof_hardware.__wrapped__(monkeypatch)
+
+
+# ======================================================================================
+# 1. Detection
+# ======================================================================================
+
+
[email protected](("os_key", "vendor"), CELLS, ids = CELL_IDS)
+def test_detected_device_per_cell(os_key, vendor, spoof_cell):
+ """Each cell resolves to the DeviceType recorded above, with a healthy MLX stack."""
+ expected = EXPECTED[(os_key, vendor)]
+ hw = spoof_cell(os_key, vendor)
+ device = hw.detect_hardware()
+ assert device == getattr(
+ hw.DeviceType, expected.device
+ ), f"{os_key}/{vendor}: expected {expected.device}, got {device!r}. {expected.note}"
+ assert hw.IS_ROCM is expected.is_rocm, f"{os_key}/{vendor}: IS_ROCM"
+ # A CPU cell names one of the three reasons hardware.py itself groups: which one
+ # depends on whether the HOST has GPUs this torch cannot use, so pinning a single
+ # spelling would pass on a GPU-less runner and fail on a GPU box, and vice versa.
+ if expected.chat_only_reason == "no_gpu":
+ assert hw.CHAT_ONLY_REASON in _CPU_ONLY_REASONS, f"{os_key}/{vendor}: chat-only reason"
+ else:
+ assert hw.CHAT_ONLY_REASON == expected.chat_only_reason, (
+ f"{os_key}/{vendor}: chat-only reason"
+ )
+
+
+# ======================================================================================
+# 2. Backend selection
+# ======================================================================================
+
+
[email protected](("os_key", "vendor"), CELLS, ids = CELL_IDS)
+def test_mlx_backend_selection_per_cell(os_key, vendor, spoof_cell):
+ """``MLXInferenceBackend`` is constructed on exactly one cell.
+
+ The predicate is the worker's own: ``_hw.DEVICE == _hw.DeviceType.MLX``. The test
+ below pins that this really is the whole condition, so evaluating it here is
+ evaluating the selection rather than a paraphrase of it.
+ """
+ expected = EXPECTED[(os_key, vendor)]
+ hw = spoof_cell(os_key, vendor)
+ hw.detect_hardware()
+ selected = hw.DEVICE == hw.DeviceType.MLX
+ assert selected is expected.mlx_selected, (
+ f"{os_key}/{vendor}: MLXInferenceBackend selected={selected}, "
+ f"expected {expected.mlx_selected}. {expected.note}"
+ )
+
+
+def test_worker_selects_mlx_on_device_type_alone():
+ """The construction site is guarded by the DEVICE comparison and nothing platform-ish.
+
+ Read with ast, not a regex: the guard also carries the native-audio exclusion, and a
+ grep for "DeviceType.MLX" would match the import line and the comment above it.
+ """
+ tree = ast.parse(WORKER_SOURCE)
+ guards = []
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.If):
+ continue
+ constructed = any(
+ isinstance(inner, ast.Call) and getattr(inner.func, "id", None) == "MLXInferenceBackend"
+ for inner in ast.walk(node)
+ )
+ if constructed:
+ guards.append(ast.unparse(node.test))
+ assert guards, "no if-statement in worker.py constructs MLXInferenceBackend"
+ for guard in guards:
+ assert "_hw.DEVICE == _hw.DeviceType.MLX" in guard, guard
+ # A guard that also consulted the platform would make the DEVICE comparison a
+ # partial answer, and every cell above would be measuring the wrong thing.
+ for forbidden in ("platform", "sys.platform", "is_apple_silicon", "machine"):
+ assert forbidden not in guard, f"{forbidden!r} in the MLX guard: {guard}"
+
+
+# ======================================================================================
+# 3. The context triple
+# ======================================================================================
+
+# A model config carrying a trained window, in the shape mlx-lm attaches it.
+_MLX_MODEL = SimpleNamespace(args = SimpleNamespace(max_position_embeddings = 131072))
+# What a transformers load attaches: Unsloth writes the served length onto the model and
+# nothing else, so there is no native window to read back.
+_TORCH_MODEL = SimpleNamespace(max_seq_length = 4096)
+
+
+def _model_info_for(mlx_selected: bool, requested: int) -> dict:
+ """The ``model_info`` the serving backend publishes for a load of ``requested``.
+
+ Both branches call the shipped resolver rather than restating its answer: the MLX one
+ is ``MLXInferenceBackend._resolve_context_lengths`` (which reads nothing off ``self``),
+ the other is ``runtime_context_length``, which is the only context field
+ ``core/inference/inference.py`` sets.
+ """
+ if mlx_selected:
+ served, native, ceiling = MLXInferenceBackend._resolve_context_lengths(
+ None, _MLX_MODEL, requested
+ )
+ return {
+ "is_mlx": True,
+ "context_length": served,
+ "native_context_length": native,
+ "max_context_length": ceiling,
+ "requested_context_length": requested or 0,
+ }
+ return {
+ "is_mlx": False,
+ "context_length": runtime_context_length(_TORCH_MODEL, requested),
+ }
+
+
+class _FakeOrchestrator:
+ def __init__(self, name, entry):
+ self.active_model_name = name
+ self.models = {name: entry}
+ self.context_length = None
+ self.max_seq_length = None
+
+
[email protected](("os_key", "vendor"), CELLS, ids = CELL_IDS)
[email protected]("requested", [0, 8192], ids = ["auto", "pinned"])
+def test_context_triple_reported_per_cell(os_key, vendor, requested, spoof_cell, monkeypatch):
+ """The triple survives to ``/v1/models`` on the MLX cell and is withheld on the rest.
+
+ Three seams, because a field can be lost at any of them and each loss looks identical
+ from the last one: what the backend resolves, what the parent mirrors out of the
+ subprocess (``_mirrored_model_entry``), and what the OpenAI listing publishes.
+ """
+ expected = EXPECTED[(os_key, vendor)]
+ hw = spoof_cell(os_key, vendor)
+ hw.detect_hardware()
+ mlx_selected = hw.DEVICE == hw.DeviceType.MLX
+ assert mlx_selected is expected.mlx_selected
+
+ model_info = _model_info_for(mlx_selected, requested)
+ mirrored = _mirrored_model_entry(model_info, "some/model")
+
+ if expected.reports_triple:
+ assert mirrored["context_length"] == (requested or 131072)
+ assert mirrored["native_context_length"] == 131072
+ assert mirrored["max_context_length"] == 131072
+ assert mirrored["requested_context_length"] == requested
+ else:
+ # A window is still reported -- transformers serves one -- but the model's own
+ # length and the ceiling are unknown, and reporting a guess is what the PR's
+ # frontend rule (loadedContextFields) reads as "this backend sized a window".
+ #
+ # 4096 under BOTH requests, and that is not a rounding of the pin: the request is
+ # only runtime_context_length's FALLBACK, so whatever Unsloth attached to the
+ # model wins and an 8192 pin does not show up in the report at all. The MLX rows
+ # above are the contrast -- there the request is the served window.
+ assert mirrored["context_length"] == 4096
+ assert mirrored["native_context_length"] is None
+ assert mirrored["max_context_length"] is None
+
+ # /v1/models, through the real projection.
+ monkeypatch.setattr(
+ routes_inference,
+ "get_llama_cpp_backend",
+ lambda: SimpleNamespace(is_loaded = False),
+ )
+ monkeypatch.setattr(
+ routes_inference,
+ "get_inference_backend",
+ lambda: _FakeOrchestrator("some/model", mirrored),
+ )
+ monkeypatch.setattr(routes_inference, "_orchestrator_public_model_id", lambda _b: "some/model")
+ (entry,) = routes_inference._openai_model_objects()
+ assert entry["context_length"] == mirrored["context_length"]
+ if expected.reports_triple:
+ assert entry["native_context_length"] == 131072
+ assert entry["max_context_length"] == 131072
+ else:
+ assert "native_context_length" not in entry
+ assert "max_context_length" not in entry
+
+
+def test_only_the_mlx_backend_resolves_a_native_window():
+ """The asymmetry the matrix above turns on, stated once and directly.
+
+ Only the MLX load resolves a triple. ``core/inference/inference.py`` publishes
+ ``context_length`` and nothing else, whatever ``runtime_context_length`` itself can
+ read, so "withheld on eleven cells" is a property of the serving path rather than of
+ the eleven fixtures. Asserted on the published entry, not on the helper's own answer,
+ which reads a declared window as well as the attached one.
+ """
+ assert runtime_context_length(_MLX_MODEL, 8192) == 8192
+ served, native, ceiling = MLXInferenceBackend._resolve_context_lengths(None, _MLX_MODEL, 0)
+ assert (served, native, ceiling) == (131072, 131072, 131072)
+ assert set(_model_info_for(False, 0)) == {"is_mlx", "context_length"}
+
+
+# ======================================================================================
+# 4. The cells that are not measurements
+# ======================================================================================
+
+
+def test_wsl_is_indistinguishable_from_linux_in_the_detector():
+ """No file under ``utils/hardware`` can tell WSL from Linux.
+
+ So the three wsl rows above are not independent evidence, and this is what says so.
+ ``llama_cpp.py`` does discriminate (``_wsl_system_rocm_lib_dirs``, and the #8403
+ Windows free-VRAM cap deliberately does NOT engage under WSL) -- that is the point:
+ the discrimination lives in the llama.cpp probe, not in device detection.
+ """
+ # Every way a Python process can learn it is under WSL. Not the bare token "WSL":
+ # hardware.py carries two comments saying WSL is deliberately left alone, and a
+ # comment is the opposite of a discriminator.
+ markers = (
+ "WSL_DISTRO_NAME",
+ "WSLENV",
+ "WSL_INTEROP",
+ "/proc/version",
+ "/proc/sys/kernel/osrelease",
+ "microsoft-standard",
+ "uname",
+ "is_wsl",
+ )
+ for path in sorted(HARDWARE_PACKAGE.rglob("*.py")):
+ code = _code_without_comments(path)
+ for marker in markers:
+ assert marker not in code, (
+ f"{path.relative_to(REPO_ROOT)} names {marker!r}: WSL is no longer "
+ "indistinguishable from Linux here, so the wsl rows in this file became "
+ "real cells and their expectations must be re-derived."
+ )
+ # And the one string that IS a Windows-only lookup, named so this test cannot be read
+ # as claiming the package never mentions Microsoft.
+ assert "Microsoft" in _code_without_comments(HARDWARE_PACKAGE / "hardware.py")
+ assert "_WINDOWS_DIRECTX_KEY" in (HARDWARE_PACKAGE / "hardware.py").read_text(encoding = "utf-8")
+ # And the llama.cpp side, which does, so this stays an accurate statement of scope.
+ llama_cpp = (STUDIO_BACKEND / "core" / "inference" / "llama_cpp.py").read_text(encoding = "utf-8")
+ assert "_wsl_system_rocm_lib_dirs" in llama_cpp
+
+
[email protected]("vendor", VENDORS)
+def test_wsl_row_equals_the_linux_row(vendor, spoof_cell):
+ """Measured, not merely argued: the two rows produce the same verdict."""
+ hw = spoof_cell("linux", vendor)
+ hw.detect_hardware()
+ linux = (hw.DEVICE, hw.IS_ROCM, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON)
+ hw = spoof_cell("wsl", vendor)
+ hw.detect_hardware()
+ assert (hw.DEVICE, hw.IS_ROCM, hw.CHAT_ONLY, hw.CHAT_ONLY_REASON) == linux
+
+
+def test_windows_on_arm_with_a_healthy_mlx_stack_is_still_cpu(spoof_cell):
+ """Windows x MLX is impossible by construction, not by the package being absent.
+
+ arm64 alone is not enough, and this is the half of ``is_apple_silicon`` the ordinary
+ Windows row cannot exercise (it is x86_64, so either conjunct would explain it).
+ """
+ hw = spoof_cell("windows", "cpu", machine = "arm64", mlx = True)
+ assert hw.detect_hardware() == hw.DeviceType.CPU
+ assert hw.is_apple_silicon() is False
+ assert hw.CHAT_ONLY_REASON == "no_gpu"
+
+
+def test_the_apple_silicon_gate_is_a_conjunction():
+ """Source-level, because the runtime answer cannot distinguish AND from OR here."""
+ source = (HARDWARE_PACKAGE / "hardware.py").read_text(encoding = "utf-8")
+ tree = ast.parse(source)
+ (gate,) = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.FunctionDef) and node.name == "is_apple_silicon"
+ ]
+ (returned,) = [node for node in ast.walk(gate) if isinstance(node, ast.Return)]
+ expression = ast.unparse(returned.value)
+ assert isinstance(returned.value, ast.BoolOp)
+ assert isinstance(returned.value.op, ast.And), expression
+ assert "'Darwin'" in expression and "'arm64'" in expression, expression
+
+
+def test_apple_silicon_without_the_mlx_stack_falls_to_chat_only(spoof_cell):
+ """The macos/cpu cell's other half: Darwin + arm64 with no usable stack is CPU."""
+ hw = spoof_cell("macos", "cpu", mlx = False)
+ assert hw.detect_hardware() == hw.DeviceType.CPU
+ assert hw.is_apple_silicon() is True
+ assert hw.CHAT_ONLY_REASON == "mlx_unavailable"
+
+
+def test_intel_mac_is_not_an_mlx_host(spoof_cell):
+ """x86_64 Darwin: the second impossible-on-macOS shape, and a real machine."""
+ hw = spoof_cell("macos", "cpu", machine = "x86_64", mlx = True)
+ assert hw.detect_hardware() == hw.DeviceType.CPU
+ assert hw.is_apple_silicon() is False
+ assert hw.CHAT_ONLY_REASON == "intel_mac"
+
+
+def test_amd_sdk_wheel_reaches_is_rocm_without_version_hip(monkeypatch, spoof_hardware):
+ """The AMD row's other wheel shape, which the vendor axis alone cannot carry.
+
+ An AMD SDK / Radeon wheel leaves ``torch.version.hip`` unset, so IS_ROCM is reached
+ through ``torch.__version__`` instead. Same verdict, different evidence.
+ """
+ spoof_hardware(
+ _DISPATCH.HardwareProfile(
+ name = "windows-amd-sdk",
+ system = "Windows",
+ machine = "x86_64",
+ cuda_available = True,
+ hip_version = None,
+ xpu_available = False,
+ has_mlx = True,
+ mps_available = False,
+ expect_is_mlx = False,
+ expect_device_type = "CUDA",
+ expect_is_rocm = True,
+ expect_apple_silicon = False,
+ )
+ )
+ _OS_MATRIX._apply_os(monkeypatch, "windows", is_rocm = True)
+ monkeypatch.setattr(platform, "machine", lambda: "x86_64")
+ monkeypatch.setitem(
+ sys.modules,
+ "torch",
+ _OS_MATRIX._fake_torch(_devices_for("amd"), vendor = "amd_sdk"),
+ )
+ for var in ("ZE_AFFINITY_MASK", "UNSLOTH_FORCE_XPU", "CUDA_VISIBLE_DEVICES"):
+ monkeypatch.delenv(var, raising = False)
+ hw = _DISPATCH._import_studio_hardware_module()
+ assert hw.detect_hardware() == hw.DeviceType.CUDA
+ assert hw.IS_ROCM is True
+
+
+def test_every_cell_in_the_product_has_an_expectation():
+ """No cell may be quietly dropped, and every impossible one must say so."""
+ assert set(EXPECTED) == set(CELLS)
+ unreal = {cell for cell, exp in EXPECTED.items() if not exp.real}
+ assert unreal == {("macos", "nvidia"), ("macos", "amd")}
+ for cell in unreal:
+ assert EXPECTED[cell].note == _NOT_A_REAL_CELL
+ # Exactly one cell serves MLX, and it is the only one that reports the triple.
+ assert {cell for cell, exp in EXPECTED.items() if exp.mlx_selected} == {("macos", "cpu")}
+ assert {cell for cell, exp in EXPECTED.items() if exp.reports_triple} == {("macos", "cpu")}
diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.py
index 9749a5b7aca..1d38a68d511 100644
--- a/tests/studio/test_model_picker_contracts.py
+++ b/tests/studio/test_model_picker_contracts.py
@@ -380,6 +380,17 @@ def test_chat_autoload_toast_is_persistent_and_dismissible():
assert "duration: Infinity" in explicit_load
+def test_a_recipe_restores_the_previous_model_at_the_context_it_asked_for():
+ """A recipe pins nothing, so restoring the model it displaced replays what it asked for."""
+ src = _read("features/recipe-studio/hooks/use-recipe-executions.ts")
+ assert src.count("requestedContextLength: status.requested_context_length ?? null,") == 2, src
+ assert (
+ " max_seq_length:\n"
+ " requestedContextLength ??\n"
+ " unpinnedLoadContext(" in src
+ ), src
+
+
def test_recipe_model_load_toast_is_persistent_and_dismissible():
"""Recipe model loading uses the same dismissible persistent lifecycle as
chat loading because both call the non-abortable loadModel API."""
@@ -981,6 +992,9 @@ def test_reset_persists_null_max_length_and_substitutes_only_for_load():
# Load-only substitution of the resolved value (recomputed from any committed
# same-click Max Seq Length draft, so it is never dropped).
assert "maxSeqLength: effectiveMaxSeqLengthValue" in src
+ # MLX pins via customContextLength, so substituting the shown default would turn
+ # "Auto" into a request for that number.
+ assert " : targetIsMlx\n ? effectiveRuntimeConfig" in src
assert "const effectiveLoadConfig" in src
# The persisted record is saved from effectiveRuntimeConfig; the load request
# carries effectiveLoadConfig (with any committed context input).
@@ -1001,8 +1015,7 @@ def test_initial_load_uses_staged_config_payload():
numeric = _read("features/model-picker/components/numeric-value-input.tsx")
assert "export type NumericValueInputHandle" in numeric
assert "commit:" in numeric
- # P1: commit returns null unless the user actually edited the field,
- # so Load/Save with untouched Auto does not pin native context.
+ # Commit returns null unless the field was edited, so an untouched control pins nothing.
assert "dirtyRef.current" in numeric
assert "return null;" in numeric
# P2: blur clears dirtyRef after commit so Reset/slider cannot be
@@ -1011,7 +1024,7 @@ def test_initial_load_uses_staged_config_payload():
assert "draftRef.current = String(final);" in numeric
# Same-click Load after blur still sees the committed draft.
assert "lastBlurCommittedRef" in numeric
- # Invalid drafts must not turn Auto into an explicit pin.
+ # Invalid drafts must not become an explicit pin.
assert "const commitDraft = (raw: string): number | null" in numeric
assert re.search(r"if \(!Number\.isFinite\(parsed\)\) \{\s*return null;", numeric)
assert re.search(
@@ -1048,6 +1061,10 @@ def test_same_click_commit_covers_all_numeric_inputs():
# The non-GGUF load path substitutes the committed Max Seq Length draft.
assert "const effectiveMaxSeqLengthValue =" in page
assert "maxSeqLength: effectiveMaxSeqLengthValue" in page
+ # The committed draft lands in this target's pin field.
+ assert (
+ "Object.assign(pendingPatch, contextPinPatch(committedMaxSeqLength, targetIsMlx));" in page
+ )
def test_context_commit_rechecks_persistence_only_shortcut():
@@ -1063,7 +1080,12 @@ def test_reset_enabled_for_explicit_context_pin_at_native():
"""An explicit customContextLength that equals the native ceiling is still a user
override, so contextAtDefault must require customContextLength == null."""
src = " ".join(_read("features/model-picker/components/model-config-page.tsx").split())
- assert "const contextAtDefault = !target.isGguf || config.customContextLength == null;" in src
+ # An MLX pin is an override too, so Reset stays enabled, whichever field held it.
+ assert (
+ "const contextAtDefault = !target.isGguf "
+ "? savedContextPin(config) == null "
+ ": config.customContextLength == null;" in src
+ )
# The old form that ignored an explicit pin equal to native must not return.
assert (
"(nativeContextLength == null ? config.customContextLength == null : "
@@ -1084,16 +1106,100 @@ def test_compare_pane_non_gguf_falls_back_to_app_default():
assert "DEFAULT_MAX_SEQ_LENGTH," in barrel
src = " ".join(_read("features/chat/shared-composer.tsx").split())
assert "DEFAULT_MAX_SEQ_LENGTH," in src
+ # Same helper as the single-view load, so a pane cannot load at a different size.
assert (
- "const effectiveMaxSeqLength = ownConfig.customContextLength ?? "
- "normalizeMaxSeqLength(ownConfig.maxSeqLength) ?? "
- "(targetIsGguf ? 0 : DEFAULT_MAX_SEQ_LENGTH);" in src
+ "const effectiveMaxSeqLength = savedContextPin(ownConfig) ?? "
+ "unpinnedLoadContext( targetIsGguf, "
+ "isServedByMlx(targetIsGguf, platform.deviceType, platform.chatOnlyReason), "
+ "DEFAULT_MAX_SEQ_LENGTH, );" in src
)
# The buggy fallback to the active model's shared runtime value must not return.
assert "(isGgufLoad ? 0 : maxSeqLength)" not in src
assert "const maxSeqLength = store.params.maxSeqLength;" not in src
+def test_every_load_path_asks_the_backend_before_it_asks_for_a_window():
+ """Which backend serves and what window it reported decide the request and the Max
+ Tokens ceiling. A literal for the first makes an interactive MLX load ask for the app
+ default again; a raw context field for the second raises Max Tokens to meet a length
+ nobody measured."""
+ load_paths = ("chat/hooks/use-chat-model-runtime.ts", "chat/api/chat-adapter.ts")
+ derived_backend = r"isMlx: isServedByMlx\(\s*[\w.=\" ]+,\s*platform\.deviceType,\s*platform\.chatOnlyReason,?\s*\)"
+ # A name bound to that same call counts, so hoisting one is not a literal creeping
+ # in; the binding itself is checked below.
+ hoisted = r"isMlx: (\w+),"
+ hoist_source = r"const {name} = isServedByMlx\(\s*\w+,\s*platform\.deviceType,\s*platform\.chatOnlyReason,?\s*\);"
+ for name in load_paths:
+ src = _read(f"features/{name}")
+ calls = src.count("resolveLoadMaxSeqLength({") + src.count("retainedContextPin({")
+ derived = len(re.findall(derived_backend, src))
+ for bound in set(re.findall(hoisted, src)):
+ if re.search(hoist_source.format(name = re.escape(bound)), src):
+ derived += src.count(f"isMlx: {bound},")
+ assert derived >= calls, (name, derived, calls)
+ for name in (*load_paths, "chat/lib/apply-inference-status-to-store.ts"):
+ src = _read(f"features/{name}")
+ # maxTokensCap is exempt: it only lowers a budget, and a transformers load
+ # reports there the max_seq_length it was configured with.
+ windows = re.sub(r"maxTokensCap:[^,]*,", "", src)
+ assert not re.search(r"\w+\.context_length\b", windows), name
+ # Including the fallback: on a model change the session length is the outgoing one's.
+ policy = _read("features/chat/presets/preset-policy.ts")
+ assert (
+ "localMaxTokensCeiling(\n loadedContextLength,\n"
+ " unreportedWindowMaxTokens(response.is_gguf ?? false, current.maxTokens)," in policy
+ )
+ # No window reported falls back to what this load asked for, not the app default,
+ # which halved Max Tokens for a transformers model carrying more.
+ adapter = _read("features/chat/api/chat-adapter.ts")
+ assert re.search(r"MaxTokensCeiling\(\s+loadedContextFields[^;]+loadedWindow,", adapter)
+ assert re.search(r"ContextForParams\(\s+loadedContext[^,]+,\s+effectiveMaxSeqLength,", adapter)
+
+
+def test_an_mlx_target_is_offered_a_context_length_not_a_sequence_length():
+ """MLX sizes its own window, so the control is GGUF's Context Length and states what a
+ load would serve. Max Seq Length at 4096 would describe a pin never sent."""
+ page = _read("features/model-picker/components/model-config-page.tsx")
+ assert 'const label = isMlx ? "Context Length" : "Max Seq Length";' in page
+ # A number, not a word: the placeholder is only for a window nobody has read.
+ assert 'displayValue={isMlx && windowUnknown ? "—" : undefined}' in page
+ assert "savedContextPin(config) == null && mlxServedWindow == null\n" in page
+ # The resident model's window, else this model's; request bounds would shorten it.
+ assert "(targetIsMlx && isActiveModel ? servedWindow(loadedContextLength) : null) ??" in page
+ assert "? servedWindow(modelMaxPosition.maxPositionEmbeddings)" in page
+ assert re.search(r"const servedWindow = [^;]*Math\.floor\(value\)\n\s*: null;", page), page
+ numeric = _read("features/model-picker/components/numeric-value-input.tsx")
+ # Typing the shown number is a choice even where it equals the value beneath it.
+ assert "derived={isMlx && !pinned}" in page
+ assert "pinned={savedContextPin(config) != null}" in page
+ # Committing pins that exact number; one outside the control's range is no commit,
+ # which is why the slider stays inside it too.
+ assert "const shown = parsed === value;" in numeric
+ assert re.search(r"shown && \(\(max[^{]+parsed < min\)+ \{\n\s+return null;", numeric)
+ assert "const final = commitDraft(draftRef.current);\n dirtyRef" in numeric
+ assert "value={maxSeqLengthValue}\n max={maxSeqLengthMax}" in page
+ assert "value={[Math.min(Math.max(value, MAX_SEQ_LENGTH_MIN), max)]}" in page
+ assert "const final = shown ? parsed : snapToStep(parsed, step, min, max);" in numeric
+ assert re.search(
+ r"MAX_SEQ_LENGTH_MAX,\s+Math\.max\(native\w+, maxSeqLengthValue\),\s+\);", page
+ )
+ # A record written before the pin moved fields carries it in maxSeqLength, and wins.
+ assert "servedWindow(savedContextPin(config)) ??\n mlxServedWindow ??" in page
+ # A hidden value and a value nobody chose both still count, through one predicate.
+ assert "final !== value || displayValue != null || derived;" in numeric
+ assert "if (isEdit(final)) {\n onChange(final);\n }\n return final;" in numeric
+ assert "lastBlurCommittedRef.current = isEdit(final) ? final : null;" in numeric
+ assert "update(contextPinPatch(value, targetIsMlx))" in page
+ # The platform answers which backend serves: "anything not GGUF" relabels CUDA.
+ assert (
+ "isServedByMlx(\n target.isGguf,\n platform.deviceType,\n platform.chatOnlyReason,\n )"
+ in page
+ )
+ # Both props are optional, so dropping either typechecks and mislabels the control.
+ assert "isMlx={targetIsMlx}" in page
+ assert "windowUnknown={" in page
+
+
def test_default_gpu_mode_clears_manual_knobs():
"""Switching GPU Memory back to Default must clear the Manual-only knobs
(gpuLayers/nCpuMoe/selectedGpuIds); otherwise a remembered config keeps stale
@@ -2128,9 +2234,13 @@ def test_adopting_a_resident_model_reseeds_the_slot_and_batch_controls():
assert "loadedNParallel: status.requested_parallel_slots," in status
# The batch pair is told the same thing, from the same local, so the two cannot drift.
assert "modelChanged: slotsModelChanged," in status
- # And the reseed re-reads this model's remembered config rather than blanking.
+ # The reseed re-reads this model's remembered config rather than blanking. Slot
+ # conditions are GGUF's alone; without slot fields it goes by whether the poll is
+ # hydrating a model already on screen.
assert (
- "status.is_gguf && (slotsUnseeded || batchesUnseeded || slotsModelChanged) "
+ "const remembered = (status.is_gguf "
+ "? slotsUnseeded || batchesUnseeded || slotsModelChanged "
+ ": hydratingExistingModel) "
"? resolveResidentInitialConfig(checkpointId, status.gguf_variant ?? null)" in status
), "the model-change reseed must feed the remembered lookup, or it discards the saved config"
@@ -2182,8 +2292,12 @@ def test_hydration_restores_a_remembered_slot_override():
"prevState.nParallel === null;" in status
)
assert (
- "status.is_gguf && (slotsUnseeded || batchesUnseeded || slotsModelChanged)" in status
+ "(status.is_gguf ? slotsUnseeded || batchesUnseeded || slotsModelChanged "
+ ": hydratingExistingModel)" in status
), "storage is read on a fresh store or a model change, never on a steady poll"
+ assert (
+ "const rememberedNParallel = status.is_gguf && remembered?.remembered" in status
+ ), "slots are a llama.cpp knob; reading MLX's record must not seed one"
assert (
"...(seedLoadParams && (slotsUnseeded || slotsModelChanged) &&" in status
), "the seed fires in both cases the clear leaves the control blank"
@@ -2868,7 +2982,7 @@ def test_the_hub_settings_page_matches_a_resident_path_loaded_model():
in hub
)
assert "loadedConfig={settingsTargetIsResident ? activeModelConfig : null}" in hub
- assert "settingsTargetIsResident ? activeGgufContextLength : null" in hub
+ assert "settingsTargetIsResident ? activeLoadedContextLength : null" in hub
# The loadable identifier, as every other status reader records it -- except for a
# speech model, which chat cannot adopt at all. speechOnly rides beside the null so
# the helper can tell it from the empty slot the idle-unload rule is about.
diff --git a/tests/studio/test_multi_chat_prompt_queue_contract.py b/tests/studio/test_multi_chat_prompt_queue_contract.py
index a73e9c64686..929a56ab4ec 100644
--- a/tests/studio/test_multi_chat_prompt_queue_contract.py
+++ b/tests/studio/test_multi_chat_prompt_queue_contract.py
@@ -476,15 +476,15 @@ def test_queued_settings_are_thread_scoped_without_cross_chat_fallback():
assert "liveRuntime.params.checkpoint" in auto_load_merge
assert "liveRuntime.supportsTools" in auto_load_merge
assert "liveRuntime.supportsReasoning" in auto_load_merge
- assert "liveRuntime.ggufContextLength" in auto_load_merge
+ assert "liveRuntime.loadedContextLength" in auto_load_merge
assert "isExternalModelId(visibleState.params.checkpoint)" in CHAT_ADAPTER
assert "resolveInferenceCheckpointId(status)" in CHAT_ADAPTER
assert "skipAdoptServerModel: true" in CHAT_ADAPTER
assert "snapshotVisibleModelState(" in CHAT_ADAPTER
assert "restoreVisibleModelState(visibleExternalState)" in CHAT_ADAPTER
- assert '"ggufContextLength"' in CHAT_ADAPTER
- assert '"ggufMaxContextLength"' in CHAT_ADAPTER
- assert '"ggufNativeContextLength"' in CHAT_ADAPTER
+ assert '"loadedContextLength"' in CHAT_ADAPTER
+ assert '"maxContextLength"' in CHAT_ADAPTER
+ assert '"nativeContextLength"' in CHAT_ADAPTER
assert '"loadedIsMultimodal"' in CHAT_ADAPTER
assert '"loadedIsDiffusion"' in CHAT_ADAPTER
assert (
diff --git a/tests/studio/test_new_chat_context_recount.py b/tests/studio/test_new_chat_context_recount.py
index 84008c391f7..d729bf3b65d 100644
--- a/tests/studio/test_new_chat_context_recount.py
+++ b/tests/studio/test_new_chat_context_recount.py
@@ -46,7 +46,7 @@ BOUND_NAMES = {
"aui",
"checkpoint",
"enabled",
- "ggufContextLength",
+ "loadedContextLength",
"isLoading",
"mainThreadId",
"runActive",
@@ -165,7 +165,7 @@ const state: any = {
contextUsageByThreadId: {},
params: { checkpoint: "", systemPrompt: "", systemVariables: "", maxTokens: 4096 },
activeGgufVariant: null,
- ggufContextLength: null,
+ loadedContextLength: null,
modelLoading: false,
runningByThreadId: {},
// The subset decoding on the local llama-server: the recount must not share it with a decode.
@@ -404,14 +404,14 @@ export function renderThreadContextUsageRecount(props: any = {}): void {
// Read through the store the way the component's selectors do.
const activeThreadId = state.activeThreadId;
const checkpoint = state.params.checkpoint;
- const ggufContextLength = state.ggufContextLength;
+ const loadedContextLength = state.loadedContextLength;
const modelLoading = state.modelLoading;
const runActive = Object.values(state.runningByThreadId ?? {}).some(Boolean);
const scope: any = {
activeThreadId,
checkpoint,
enabled,
- ggufContextLength,
+ loadedContextLength,
modelLoading,
runActive,
};
@@ -452,7 +452,7 @@ export function renderNewChatSwitch(props: any): void {
// The component reads these through useChatRuntimeStore selectors, so a
// re-render sees whatever the store holds right now.
const checkpoint = state.params.checkpoint;
- const ggufContextLength = state.ggufContextLength;
+ const loadedContextLength = state.loadedContextLength;
const modelLoading = state.modelLoading;
const runActive = Object.values(state.runningByThreadId ?? {}).some(Boolean);
const scope: any = {
@@ -463,7 +463,7 @@ export function renderNewChatSwitch(props: any): void {
nonce,
paused,
checkpoint,
- ggufContextLength,
+ loadedContextLength,
modelLoading,
runActive,
};
@@ -500,7 +500,7 @@ export async function adoptResidentModel(props: any): Promise<void> {
// The real hydration writes the whole status; the recount only reads the window.
const applyActiveModelStatusToStore = (status: any, _options: any): void => {
set({
- ggufContextLength: status.is_gguf ? (status.context_length ?? null) : null,
+ loadedContextLength: status.is_gguf ? (status.context_length ?? null) : null,
});
};
const syncModelCapabilities = (_id: string, _status: any): void => {};
@@ -577,7 +577,7 @@ def _run(script: str) -> dict:
LOADED_MODEL = """
seed({
params: { checkpoint: "unsloth/gguf-model", systemPrompt: "", systemVariables: "" },
- ggufContextLength: 8192,
+ loadedContextLength: 8192,
modelLoading: false,
});
"""
@@ -892,7 +892,7 @@ def test_a_count_that_is_not_a_finite_number_never_reaches_the_bar(reply):
NO_LOCAL_MODEL = """
seed({
params: { checkpoint: "", systemPrompt: "", systemVariables: "" },
- ggufContextLength: null,
+ loadedContextLength: null,
});
"""
@@ -1676,7 +1676,7 @@ def test_adopting_the_resident_gguf_reprices_the_open_thread():
// On an external provider, showing the usage that provider's last turn wrote.
seed({
params: { checkpoint: "openai:gpt-4o", systemPrompt: "", systemVariables: "" },
- ggufContextLength: null,
+ loadedContextLength: null,
activeThreadId: "thread-a",
contextUsage: { promptTokens: 900, completionTokens: 30, totalTokens: 930, cachedTokens: 0 },
});
@@ -1739,7 +1739,7 @@ DEEP_LINK_HYDRATING_AFTER_THE_LOADER = """
// /api/inference/status answers while the thread is still not active.
seed({
params: { checkpoint: "unsloth/gguf-model", systemPrompt: "", systemVariables: "" },
- ggufContextLength: 8192,
+ loadedContextLength: 8192,
modelLoading: false,
});
renderThreadContextUsageRecount();
diff --git a/tests/studio/test_project_chat_view_switch.py b/tests/studio/test_project_chat_view_switch.py
index b25d03cc695..0d19a7044d4 100644
--- a/tests/studio/test_project_chat_view_switch.py
+++ b/tests/studio/test_project_chat_view_switch.py
@@ -53,7 +53,7 @@ SOURCES = (PROVIDER, STORE, QUEUE)
BOUND_NAMES = {
"aui",
"checkpoint",
- "ggufContextLength",
+ "loadedContextLength",
"initialThreadId",
"isLoading",
"mainThreadId",
@@ -212,7 +212,7 @@ const state: any = {
contextUsage: null,
contextUsageByThreadId: {},
params: { checkpoint: "", systemPrompt: "", systemVariables: "" },
- ggufContextLength: null,
+ loadedContextLength: null,
modelLoading: false,
runningByThreadId: {},
};
@@ -465,7 +465,7 @@ function renderThreadNewChatSwitch(props: any): void {
const isLoading = props.isLoading ?? false;
// Read through useChatRuntimeStore selectors, so a re-render sees the store as it stands.
const checkpoint = state.params.checkpoint;
- const ggufContextLength = state.ggufContextLength;
+ const loadedContextLength = state.loadedContextLength;
const modelLoading = state.modelLoading;
const runActive = Object.values(state.runningByThreadId ?? {}).some(Boolean);
// The stale-switch correction subscribes to it, exactly as ThreadAutoSwitch does.
@@ -478,7 +478,7 @@ function renderThreadNewChatSwitch(props: any): void {
nonce,
paused,
checkpoint,
- ggufContextLength,
+ loadedContextLength,
modelLoading,
runActive,
};
@@ -610,7 +610,7 @@ def _run(imports: str, body: str) -> dict:
# A resident GGUF, so the second effect has something it could price. Only the tests about
# the pause gate need it; everywhere else the bar has nothing to count and stands down.
LOADED_MODEL = """
- seed({ params: { checkpoint: "unsloth/gguf-model" }, ggufContextLength: 8192 });
+ seed({ params: { checkpoint: "unsloth/gguf-model" }, loadedContextLength: 8192 });
"""
diff --git a/tests/studio/test_recipe_context_intent.py b/tests/studio/test_recipe_context_intent.py
new file mode 100644
index 00000000000..b15957e5856
--- /dev/null
+++ b/tests/studio/test_recipe_context_intent.py
@@ -0,0 +1,83 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The context intent the recipe load gates compare, executed rather than restated.
+
+`contextIntent` lives inside a React hook module that cannot be imported on its own, so
+it is sliced out of the real source and run. Restating the predicate here would pass
+just as happily with the source deleted.
+
+The rule it encodes: an unpinned MLX load sends 0, so a positive `requested_context_length`
+from MLX is an explicit pin. llama.cpp is ambiguous, because a same-model reload echoes the
+resolved n_ctx while the control is still Auto (see `resolve-ctx-pin-seed.ts`). Reading a
+GGUF echo as a pin makes an unpinned recipe reload the resident model on every run, and the
+restoration snapshot then replays that value as a pin the user never set.
+"""
+
+from __future__ import annotations
+
+import textwrap
+
+from _node_harness import (
+ WORKDIR,
+ read,
+ require_node,
+ run_harness,
+ slice_between,
+ source_path,
+)
+
+RECIPES = source_path("studio/frontend/src/features/recipe-studio/hooks/use-recipe-executions.ts")
+
+TEMP = WORKDIR / "temp" / "recipe_context_intent"
+
+SOURCES = (RECIPES,)
+
+
+def _harness_source() -> str:
+ return "// @ts-nocheck\nexport " + slice_between(
+ read(RECIPES),
+ "function contextIntent(",
+ "\nasync function isLocalModelAlreadyLoaded(",
+ )
+
+
+def _run(script: str) -> dict:
+ require_node(SOURCES)
+ return run_harness(TEMP, _harness_source(), script, sources = SOURCES)
+
+
+def test_only_mlx_reads_a_positive_context_echo_as_a_pin():
+ out = _run(
+ textwrap.dedent(
+ """
+ // @ts-nocheck
+ import { contextIntent } from "./harness.ts";
+ console.log(JSON.stringify({
+ mlxPinned: contextIntent(32768, true),
+ mlxAuto: contextIntent(0, true),
+ mlxUnset: contextIntent(null, true),
+ ggufEcho: contextIntent(32768, false),
+ ggufAuto: contextIntent(0, false),
+ }));
+ """
+ )
+ )
+ # MLX: a pinned resident and an unpinned recipe are different loads.
+ assert out["mlxPinned"] == 32768
+ assert out["mlxAuto"] is None
+ assert out["mlxUnset"] is None
+ # GGUF: the echo says nothing, so an unpinned recipe must not force a reload.
+ assert (
+ out["ggufEcho"] is None
+ ), "a positive GGUF echo is the resolved n_ctx of an Auto load, not a pin"
+ assert out["ggufAuto"] is None
+
+
+def test_both_load_gates_ask_the_backend_before_comparing_intent():
+ """The predicate is only correct if both callers pass the flag; neither may drop it."""
+ source = read(RECIPES)
+ assert "contextIntent(requestedContextLength, residentIsMlx)" in source
+ assert "contextIntent(status.requested_context_length, residentIsMlx)" in source
+ assert "contextIntent(left.requestedContextLength, left.isMlx)" in source
+ assert "contextIntent(right.requestedContextLength, right.isMlx)" in source
diff --git a/tests/studio/test_token_count_prompt_parity.py b/tests/studio/test_token_count_prompt_parity.py
index 5611039d332..5d6a6e4293d 100644
--- a/tests/studio/test_token_count_prompt_parity.py
+++ b/tests/studio/test_token_count_prompt_parity.py
@@ -32,10 +32,11 @@ from _node_harness import (
ADAPTER = source_path("studio/frontend/src/features/chat/api/chat-adapter.ts")
CAPABILITIES = source_path("studio/frontend/src/features/chat/provider-capabilities.ts")
+MODEL_SIZE = source_path("studio/frontend/src/lib/model-size.ts")
TEMP = WORKDIR / "temp" / "token_count_prompt_parity"
-SOURCES = (ADAPTER, CAPABILITIES)
+SOURCES = (ADAPTER, CAPABILITIES, MODEL_SIZE)
def _canvas_constants() -> str:
@@ -64,12 +65,32 @@ def _outbound_builder() -> str:
def _extras_builder() -> str:
- """buildLocalTokenCountExtras, the tool flags the count sends."""
- return slice_between(
- read(ADAPTER),
- "export async function buildLocalTokenCountExtras(",
- "\n\nasync function resolveUseAdapter(",
- )
+ """buildLocalTokenCountExtras, the tool flags the count sends, and the Auto-inject
+ resolution it shares with the request build.
+
+ Joined on blank lines, not concatenated: a slice that starts on the previous slice's
+ closing brace is not a declaration _harness_bindings can see, so resolve_dependencies
+ pulls its own copy and node refuses the duplicate.
+ """
+ parts = [
+ read(MODEL_SIZE).split("\n", 2)[2],
+ slice_between(
+ read(ADAPTER),
+ "const AUTOINJECT_AUTO_MAX_SIZE_B =",
+ "\n\ntype ThreadRecordReader",
+ ),
+ slice_between(
+ read(ADAPTER),
+ "function resolveAutoInject(",
+ "\n\n/** Server-side usage data",
+ ),
+ slice_between(
+ read(ADAPTER),
+ "export async function buildLocalTokenCountExtras(",
+ "\n\nasync function resolveUseAdapter(",
+ ),
+ ]
+ return "\n\n".join(part.strip("\n") for part in parts) + "\n"
def _reasoning_builder() -> str:
@@ -358,3 +379,80 @@ def test_the_rag_scope_a_count_sends_is_never_empty(thread_id, expected_thread_i
"keys"
), "an empty rag_scope is falsy server-side and drops the tool and the nudge"
assert (out.get("scope") or {}).get("thread_id") == expected_thread_id
+
+
+def test_the_count_sends_every_setting_that_changes_the_rendered_prompt():
+ """The backend prices the tool loop the settings describe: its gate, its call budget,
+ and whether it retrieves. Omitting one priced the server's defaults."""
+ settings = RAG_ON.rstrip(" }") + ', permissionMode: "ask", maxToolCallsPerMessage: 0 }'
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{ buildLocalTokenCountExtras, seed }} from "./harness.ts";
+ seed({settings});
+ const on = await buildLocalTokenCountExtras("thread-a");
+ seed({{ residentCheckpoint: "org/Model-70B" }});
+ const large = await buildLocalTokenCountExtras("thread-a");
+ seed({{ ragAutoInject: "off", residentCheckpoint: "org/Model-4B" }});
+ const injectOff = await buildLocalTokenCountExtras("thread-a");
+ seed({{ supportsTools: false }});
+ const off = await buildLocalTokenCountExtras("thread-a");
+ console.log(JSON.stringify({{ on, large, injectOff, off }}));
+ """
+ )
+ )
+ on, off = out["on"], out["off"]
+ assert on.get("permission_mode") == "ask", "the gate that holds the loop's retrieval"
+ assert on.get("max_tool_calls_per_message") == 0, "Off suppresses the loop entirely"
+ assert (on.get("rag_scope") or {}).get("autoinject") is True
+ # The values, not the keys: unknown size on, Auto off above the threshold.
+ assert (out["large"].get("rag_scope") or {}).get("autoinject") is False
+ off_scope = out["injectOff"].get("rag_scope") or {}
+ assert (off_scope.get("autoinject"), off_scope.get("whole_doc")) == (False, False)
+ # Explicit, and with no budget beside it, as the send is: an omitted flag would let
+ # `unsloth studio run --enable-tools` answer for the count.
+ assert off.get("enable_tools") is False
+ assert "max_tool_calls_per_message" not in off
+
+
+# Tools on, RAG deliberately off: the archive tool is gated on the thread id alone, so a
+# scope-only id would leave it unpriced exactly when RAG is not in play.
+TOOLS_ON_RAG_OFF = (
+ "{ supportsTools: true, toolsEnabled: true, codeToolsEnabled: false, "
+ "artifactsEnabled: false, mcpEnabledForChat: false, ragEnabled: false, "
+ 'ragSource: { type: "thread" }, ragMode: "hybrid", ragTopK: 5, '
+ "autoHealToolCalls: true }"
+)
+
+
+ ("thread_id", "expected"),
+ [("undefined", None), ('"thread-a"', "thread-a")],
+ ids = ["unpersisted_new_chat", "persisted_thread"],
+)
+def test_the_count_sends_the_thread_id_at_top_level_even_with_rag_off(thread_id, expected):
+ """`_select_request_tools` reads `payload.thread_id`, not the one inside `rag_scope`.
+
+ An archived thread puts `search_conversation` and its compaction nudge in the prompt,
+ so a count that only ever nests the id under a RAG scope under-reports every archived
+ conversation whose Docs pill is off, and the bar claims room the completion lacks.
+ """
+ out = _run(
+ textwrap.dedent(
+ f"""
+ // @ts-nocheck
+ import {{ buildLocalTokenCountExtras, seed }} from "./harness.ts";
+ seed({TOOLS_ON_RAG_OFF});
+ const extras = await buildLocalTokenCountExtras({thread_id});
+ console.log(JSON.stringify({{
+ threadId: extras.thread_id ?? null,
+ ragScope: extras.rag_scope ?? null,
+ }}));
+ """
+ )
+ )
+ assert out.get("ragScope") is None, "RAG is off, so there is no scope to hide the id in"
+ assert (
+ out.get("threadId") == expected
+ ), "the archive tool and its nudge are gated on the top-level thread id"
diff --git a/tests/studio/test_workflow_guards_run_unfiltered.py b/tests/studio/test_workflow_guards_run_unfiltered.py
index 6423eb26fe2..8351c9fe3ea 100644
--- a/tests/studio/test_workflow_guards_run_unfiltered.py
+++ b/tests/studio/test_workflow_guards_run_unfiltered.py
@@ -41,6 +41,9 @@ EXEMPT = {
"test_tauri_branding_contract.py",
# Imports a local `utils` helper that resolves only under the full test environment.
"test_update_release_notes.py",
+ # Spoofs the hardware stack, so it imports numpy/torch through the studio backend.
+ # It runs in the Studio backend job, which installs them; this one deliberately does not.
+ "test_mlx_context_platform_matrix.py",
}