Skip to content

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

Studio: close the MLX context compaction gaps left after #9399 (#12823)

Long Yixing72c55d620343
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.py
index 3975189b513..391d7e98e2d 100644
--- a/studio/backend/core/inference/orchestrator.py
+++ b/studio/backend/core/inference/orchestrator.py
@@ -2753,6 +2753,7 @@ class InferenceOrchestrator:
preserve_thinking: Optional[bool] = None,
continue_final_message: bool = False,
tool_loop: bool = False,
+ recall_reachable: bool = False,
anchor_ids = None,
replay_boundary: bool = True,
recall_done: bool = False,
@@ -2761,8 +2762,8 @@ class InferenceOrchestrator:
) -> dict:
"""Fit one MLX prompt into the served window under the policy GGUF uses.
- Only a ``tool_loop`` turn that carries tools may reset the epoch: no other MLX turn
- is offered ``search_conversation``. ``request_branch`` is the client's transcript and
+ A ``tool_loop`` turn carrying tools may reset the epoch; a plain turn only when a later
+ one can search (``recall_reachable``). ``request_branch`` is the client's transcript and
``live_branch`` that plus the loop's replies and tool results; both default to the prompt.
Never raises: a failed fit returns the request unchanged.
"""
@@ -2838,8 +2839,9 @@ class InferenceOrchestrator:
can_reset = _can_reset_epoch(
thread_id,
- calls_tools,
- tools_withheld = _memory_tool_withheld(thread_id, tools),
+ calls_tools if tool_loop else recall_reachable,
+ # A plain turn carries no catalogue to read; the route answered for it.
+ tools_withheld = tool_loop and _memory_tool_withheld(thread_id, tools),
)
sticky, sticky_is_checkpoint = (
_sticky_compaction_state(
@@ -2867,7 +2869,7 @@ class InferenceOrchestrator:
**_compaction_fit_kwargs(context_policy, compaction_headroom_ratio),
)
if not truncation:
- return unchanged
+ return {**unchanged, "boundary_applied": True}
recall = _archive_and_recall(
fitted,
@@ -2901,6 +2903,7 @@ class InferenceOrchestrator:
"events": [*recall["events"], {"type": "context_truncated", **truncation}],
"recalled": bool(recall["recalled"]),
"anchored": list(recall["anchored"]),
+ "boundary_applied": True,
}
except Exception as exc:
logger.warning("Could not preflight the MLX context window: %s", exc)
@@ -3233,8 +3236,9 @@ class InferenceOrchestrator:
request_branch = _request_branch,
live_branch = live_branch,
)
- # The saved boundary describes the original transcript, so it applies once.
- _sticky_boundary_applied = True
+ # The saved boundary applies once, in the first fit that runs (not resumed or failed).
+ if result.get("boundary_applied"):
+ _sticky_boundary_applied = True
if result.get("recalled"):
_conversation_recall_done = True
for message in result.get("anchored") or ():
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index ac28f1abcc8..3ad90b4fc25 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -32580,6 +32580,21 @@ async def produce_openai_chat_completions(
_sf_mcp_allowed = (
payload.tool_choice != "none" and bool(payload.mcp_enabled) and _sf_cli_policy is not False
)
+ # tool_choice asked directly: _tool_loop_unusable weighs it against GGUF's tools.
+ _sf_recall_loop_usable = (
+ payload.tool_choice != "none"
+ and not _tool_loop_unusable
+ and not _has_client_tool_contract
+ and not _response_format_constrains_decoding(payload)
+ and (_ui_events or not _confirm_gate_would_prompt(payload, ("search_conversation",)))
+ )
+ # GGUF parity: a checkpointed thread reopens the loop with search_conversation alone.
+ _sf_recall_reopens_loop = (
+ _sf_fit_overflow is not None
+ and not (_sf_tools_on or _sf_mcp_allowed)
+ and _sf_recall_loop_usable
+ and _checkpoint_recall_may_enable_tools(payload)
+ )
# Named templates may expose native reasoning only in their ``tool_use``
# branch. Use a truthy placeholder for Unsloth-managed tools, whose concrete
@@ -32587,7 +32602,7 @@ async def produce_openai_chat_completions(
# A withdrawn catalogue renders plain here too, so the probe and the completion agree on
# which branch the conversation is in.
_sf_server_tool_intent = payload.tool_choice != "none" and bool(
- _sf_tools_on or _explicit_studio_tool_loop_requested(payload)
+ _sf_tools_on or _sf_recall_reopens_loop or _explicit_studio_tool_loop_requested(payload)
)
# Detection only: this picks which branch of a named template is READ, never what is
# rendered (the catalogue is withdrawn above and in _sf_tools_to_use), so it must not
@@ -32749,7 +32764,7 @@ async def produce_openai_chat_completions(
# _sf_cli_policy / _sf_tools_on / _sf_mcp_allowed are resolved above, before
# the response protocol is classified, so both use the same decision.
_sf_use_tools = (
- (_sf_tools_on or _sf_mcp_allowed)
+ (_sf_tools_on or _sf_mcp_allowed or _sf_recall_reopens_loop)
and _sf_features.get("supports_tools", False)
# An attachment used to withdraw the tools: the loop had no way to carry
# a picture. It has one now, so only a model that cannot read images does.
@@ -33644,44 +33659,71 @@ async def produce_openai_chat_completions(
**kw,
)
- def generate(messages_override = None, choice_index = 0):
- base_kwargs = (
- gen_kwargs
- if messages_override is None
- else {**gen_kwargs, "messages": messages_override}
+ # A plain reset needs the next turn to reopen the loop, which renders the tool branch.
+ # A vision model renders text turns through its processor body too (Qwen2.5-VL drops tools, #7066).
+ _sf_recall_tpl = (_sf_model_info.get("chat_template_info") or {}).get("processor_template")
+ _sf_recall_reachable = (
+ _sf_fit_overflow is not None
+ and _sf_recall_loop_usable
+ and not _sf_is_gptoss
+ and bool(
+ (
+ _sf_rendered_features(backend, _sf_model_info, ({},))[0]
+ if _sf_recall_tpl is None
+ else _detect_safetensors_features(
+ backend, _sf_recall_tpl, tools = ({},), prefer_tool_use = False
+ )
+ ).get("supports_tools")
)
+ )
- if choice_index:
- base_kwargs = {**base_kwargs, "seed": _choice_seed(payload.seed, choice_index)}
+ _sf_fit_cache: dict = {}
+ def _sf_fit_request():
+ # On the generation thread, once: every choice and retry starts from this prompt.
+ if "kwargs" in _sf_fit_cache:
+ return _sf_fit_cache["kwargs"], ()
+ fitted_kwargs, events = gen_kwargs, ()
+ # The count cannot price pictures or video, so those prompts are left alone.
+ if _sf_fit_overflow and all(
+ gen_kwargs.get(key) is None for key in ("image", "images", "video")
+ ):
+ fitted = backend.compact_chat_context(
+ gen_kwargs.get("messages") or [],
+ system_prompt = gen_kwargs.get("system_prompt") or "",
+ tools = gen_kwargs.get("tools"),
+ context_overflow = _sf_fit_overflow,
+ context_policy = _request_context_policy(payload),
+ compaction_headroom_ratio = _request_compaction_headroom_ratio(payload),
+ max_tokens = effective_max_tokens,
+ thread_id = payload.thread_id,
+ cancel_event = cancel_event,
+ enable_thinking = gen_kwargs.get("enable_thinking"),
+ reasoning_effort = gen_kwargs.get("reasoning_effort"),
+ preserve_thinking = gen_kwargs.get("preserve_thinking"),
+ continue_final_message = bool(gen_kwargs.get("continue_final_message", False)),
+ recall_reachable = _sf_recall_reachable,
+ )
+ fitted_kwargs = {
+ **gen_kwargs,
+ "messages": fitted["messages"],
+ "system_prompt": fitted["system_prompt"],
+ }
+ events = fitted.get("events") or ()
+ _sf_fit_cache["kwargs"] = fitted_kwargs
+ return fitted_kwargs, events
+
+ def generate(messages_override = None, choice_index = 0):
def _run():
- generation_kwargs = base_kwargs
- # The count cannot price pictures or video, so those prompts are left alone.
- if _sf_fit_overflow and all(
- base_kwargs.get(key) is None for key in ("image", "images", "video")
- ):
- fitted = backend.compact_chat_context(
- base_kwargs.get("messages") or [],
- system_prompt = base_kwargs.get("system_prompt") or "",
- tools = base_kwargs.get("tools"),
- context_overflow = _sf_fit_overflow,
- context_policy = _request_context_policy(payload),
- compaction_headroom_ratio = _request_compaction_headroom_ratio(payload),
- max_tokens = effective_max_tokens,
- thread_id = payload.thread_id,
- cancel_event = cancel_event,
- enable_thinking = base_kwargs.get("enable_thinking"),
- reasoning_effort = base_kwargs.get("reasoning_effort"),
- preserve_thinking = base_kwargs.get("preserve_thinking"),
- continue_final_message = bool(base_kwargs.get("continue_final_message", False)),
- )
+ generation_kwargs, events = _sf_fit_request()
+ yield from events
+ if messages_override is not None:
+ generation_kwargs = {**generation_kwargs, "messages": messages_override}
+ if choice_index:
generation_kwargs = {
- **base_kwargs,
- "messages": fitted["messages"],
- "system_prompt": fitted["system_prompt"],
+ **generation_kwargs,
+ "seed": _choice_seed(payload.seed, choice_index),
}
- for event in fitted.get("events") or ():
- yield event
yield from _sf_raw_generate(generation_kwargs)
return _run()
@@ -33961,15 +34003,17 @@ async def produce_openai_chat_completions(
_prompt_details = None
_last_stats = None
+ def _note_fit(event):
+ if event.get("type") == "context_truncated":
+ _sf_context_truncation_holder["value"] = _accumulate_context_truncation(
+ None, event
+ )
+
def _drain_generate(messages_override = None, choice_index = 0):
final = ""
for token in generate(messages_override, choice_index = choice_index):
if isinstance(token, dict):
- if token.get("type") == "context_truncated":
- # Choices and retries refit one prompt: report a fit, not their sum.
- _sf_context_truncation_holder["value"] = _accumulate_context_truncation(
- None, token
- )
+ _note_fit(token)
continue
if isinstance(token, GenStreamError):
return token
@@ -33989,11 +34033,14 @@ async def produce_openai_chat_completions(
_finished = set()
def _drain_batch():
+ fitted_kwargs, fit_events = _sf_fit_request()
+ for event in fit_events:
+ _note_fit(event)
for event in backend.generate_chat_batch(
rows = rows,
cancel_event = cancel_event,
stats_holder = batch_stats,
- **gen_kwargs,
+ **fitted_kwargs,
):
if isinstance(event, GenStreamError):
return event
@@ -34113,7 +34160,8 @@ async def produce_openai_chat_completions(
try:
# Mark the owning turn before the correction is appended,
# or the reverse scan attaches the picture to it (#10092).
- _nudge_base = gen_kwargs["messages"]
+ # The fitted prompt: the retry extends it and is not refitted.
+ _nudge_base = _sf_fit_request()[0]["messages"]
if _sf_renders_image or _video_clip is not None:
from core.inference.chat_template_helpers import (
messages_with_attached_image as _nudge_attach,
diff --git a/studio/backend/tests/test_mlx_context_compaction.py b/studio/backend/tests/test_mlx_context_compaction.py
index 68e09bde400..1162ec08e2e 100644
--- a/studio/backend/tests/test_mlx_context_compaction.py
+++ b/studio/backend/tests/test_mlx_context_compaction.py
@@ -110,10 +110,12 @@ def test_a_prompt_the_fit_must_not_touch_is_returned_unchanged(case):
assert result["messages"] == messages
assert result["system_prompt"] == "you are helpful"
- assert result["events"] == []
+ assert result["events"] == [] and "boundary_applied" not in result
-def test_only_a_tool_loop_request_resets_and_only_an_offered_search_is_named(archive_calls):
+def test_a_request_resets_only_where_search_can_follow_and_names_only_an_offered_tool(
+ archive_calls, monkeypatch
+):
def fit(messages = None, **kwargs):
result = _fit(
_backend(),
@@ -129,6 +131,14 @@ def test_only_a_tool_loop_request_resets_and_only_an_offered_search_is_named(arc
assert not truncation.get("checkpoint") and "carried_forward" not in system
assert archived["style"] == "inline"
+ # A plain request has no catalogue to miss the tool from: the route's answer alone decides.
+ with monkeypatch.context() as patch:
+ patch.setattr(llama_cpp, "_memory_tool_withheld", lambda thread_id, tools: True)
+ truncation, system, archived = fit(recall_reachable = True)
+ assert truncation["checkpoint_started"] is True and "carried_forward" in system
+ assert "search_conversation tool" not in system and archived["style"] == "inline"
+ assert not fit(tool_loop = True, tools = [WEB])[0].get("checkpoint")
+
truncation, system, archived = fit(tool_loop = True, tools = [WEB])
assert truncation["checkpoint_started"] is True and "carried_forward" in system
assert "search_conversation tool" not in system
@@ -144,7 +154,7 @@ def test_only_a_tool_loop_request_resets_and_only_an_offered_search_is_named(arc
# The loop's final answer carries no tools: no reset, and its reply never comes back,
# so recall gets all the room the fit left.
turns = [{"role": "user", "content": "x" * size} for size in (3200, 800, 8)]
- truncation, _, archived = fit(messages = turns, tool_loop = True)
+ truncation, _, archived = fit(messages = turns, tool_loop = True, recall_reachable = True)
after = truncation["prompt_tokens_after"]
whole = retrieval_budget(1200, 200, after)
assert not truncation.get("checkpoint") and archived["recall_budget_tokens"] == whole
@@ -225,6 +235,34 @@ def test_the_tool_loop_refits_every_turn_and_keeps_the_question_past_a_reprompt(
assert last_fit["thread_id"] == "thread-1"
+# A result overflowing by less than one old turn, against a boundary two turns deep; or neither.
[email protected]("result_chars, saved", [(3300, 4), (8, 0)])
+def test_a_turn_that_is_not_fitted_leaves_the_saved_boundary_to_the_next(
+ monkeypatch, archive_calls, result_chars, saved
+):
+ asked = []
+
+ def _saved_boundary(*_args, **_kwargs):
+ asked.append(1)
+ return saved, False
+
+ monkeypatch.setattr(llama_cpp, "_sticky_compaction_state", _saved_boundary)
+ first, second = ({"role": "user", "content": letter * 400} for letter in "ab")
+ resumed = {"role": "assistant", "content": "Let me"}
+ _, prompts, _ = _run_loop(
+ monkeypatch,
+ [first, ANSWERED, second, ANSWERED, QUESTION, resumed],
+ [CALL % 1, CALL % 2, "done"],
+ result_chars,
+ continue_final_message = True,
+ context_policy = "rolling",
+ )
+
+ assert any(m is first for m in prompts[0])
+ assert any(m is second for m in prompts[1]) == (not saved)
+ assert len(asked) == 1
+
+
# The cap's budget notice; then the no-op notice a repeated call earns, once, twice, and
# twice with the model's own words in between.
@pytest.mark.parametrize(
diff --git a/studio/backend/tests/test_sf_client_tools_passthrough.py b/studio/backend/tests/test_sf_client_tools_passthrough.py
index 0ab6bdeba6a..01eac85a6db 100644
--- a/studio/backend/tests/test_sf_client_tools_passthrough.py
+++ b/studio/backend/tests/test_sf_client_tools_passthrough.py
@@ -1536,6 +1536,234 @@ def test_the_contract_reaches_the_backend_and_its_reply_comes_back_whole(monkeyp
assert not message.get("reasoning_content")
+class _FittedToolLoopBackend(_ToolLoopBackend):
+ def __init__(self, responder, **kwargs):
+ super().__init__(responder, **kwargs)
+ self.fits: list = []
+
+ def compact_chat_context(
+ self,
+ messages,
+ *,
+ system_prompt = "",
+ **kwargs,
+ ):
+ self.fits.append(kwargs)
+ return {"messages": messages, "system_prompt": system_prompt}
+
+
+def _serve(
+ monkeypatch,
+ *,
+ frames = True,
+ **fields,
+):
+ """Send to an installed backend; ``frames`` off drops the control-frame header."""
+ if fields.get("response_format"):
+ pytest.importorskip("llguidance.mlx")
+ if not frames:
+ monkeypatch.setattr(_Request, "headers", {})
+ payload = _request(**fields)
+ response = asyncio.run(
+ openai_chat_completions(payload, request = _Request(), current_subject = "u")
+ )
+ return _collect_sse(response) if payload.stream else response
+
+
+ "is_mlx, checkpointed, extra, offered",
+ [
+ (True, True, {}, ["search_conversation"]),
+ (False, True, {}, None),
+ (True, False, {}, None),
+ (True, True, {"context_policy": "rolling"}, None),
+ (True, True, {"context_overflow": None}, None),
+ (True, True, {"tool_choice": "none"}, None),
+ (True, True, {"max_tool_calls_per_message": 0}, None),
+ (True, True, {"n": 2}, None),
+ (True, True, {"permission_mode": "ask"}, None),
+ (True, True, {"stream": True, "frames": False, "permission_mode": "ask"}, None),
+ (True, True, {"response_format": _RF_FORMAT}, None),
+ (True, True, {"tools": [LOOKUP_TOOL]}, ["lookup"]),
+ ],
+)
+def test_a_compacted_mlx_thread_keeps_archive_search_with_tools_off(
+ monkeypatch, is_mlx, checkpointed, extra, offered
+):
+ import routes.inference as inf
+
+ monkeypatch.setattr(inf, "_thread_has_conversation_archive", lambda thread_id: True)
+ monkeypatch.setattr(
+ inf, "_thread_has_checkpoint", lambda thread_id, messages = None: checkpointed
+ )
+ backend = _FittedToolLoopBackend(_fixed("done"))
+ backend.models["sf-model"]["is_mlx"] = is_mlx
+ fields = {
+ "stream": False,
+ "enable_tools": False,
+ "thread_id": "saved",
+ "context_overflow": "truncate_oldest",
+ "context_policy": "checkpoint",
+ **extra,
+ }
+ probed = []
+
+ def _features(*_args, **kwargs):
+ probed.append(bool(kwargs.get("tools")))
+ return {"supports_tools": True, "supports_reasoning": False}
+
+ _install(monkeypatch, backend)
+ monkeypatch.setattr(inf, "_detect_safetensors_features", _features)
+ _serve(monkeypatch, **fields)
+ tools = backend.calls[0]["tools"]
+ assert (tools and [tool["function"]["name"] for tool in tools]) == offered
+ # The template branch that is classified is the one the request renders.
+ assert probed[0] is bool(offered)
+
+
[email protected]("asked", [{"enable_tools": True}, {"mcp_enabled": True}])
+def test_tool_choice_none_keeps_a_compacted_mlx_thread_tool_free(monkeypatch, asked):
+ import routes.inference as inf
+
+ monkeypatch.setattr(inf, "_thread_has_conversation_archive", lambda thread_id: True)
+ monkeypatch.setattr(inf, "_thread_has_checkpoint", lambda thread_id, messages = None: True)
+ backend = _FittedToolLoopBackend(_fixed("done"))
+ backend.models["sf-model"]["is_mlx"] = True
+ _install(monkeypatch, backend)
+ # A GGUF model that is still loading already reports its tool support.
+ loading = SimpleNamespace(**{**vars(_llama_stub()), "supports_tools": True})
+ monkeypatch.setattr(inf, "get_llama_cpp_backend", lambda: loading)
+ fields = {"thread_id": "saved", "context_overflow": "truncate_oldest", "tool_choice": "none"}
+ _serve(monkeypatch, stream = False, context_policy = "checkpoint", **fields, **asked)
+
+ assert backend.calls[0]["tools"] is None
+ assert [fit["recall_reachable"] for fit in backend.fits] == [False]
+
+
+_TURNS = "{% for m in messages %}<|im_start|>{{ m.role }}\n{{ m.content }}<|im_end|>\n{% endfor %}"
+_WITH_TOOLS = "{% if tools %}<tool_call>{{ tools }}</tool_call>{% endif %}" + _TURNS
+# Named templates: only the branch a turn carrying tools renders decides, either way round.
+_TOOL_BRANCH = {"default": _TURNS, "tool_use": _WITH_TOOLS}
+_DEFAULT_BRANCH = {"default": _WITH_TOOLS, "tool_use": _TURNS}
+
+
+ "extra, supports_tools, gpt_oss, reachable",
+ [
+ ({}, True, False, True),
+ ({}, False, False, False),
+ ({}, _TOOL_BRANCH, False, True),
+ ({}, _DEFAULT_BRANCH, False, False),
+ ({}, True, True, False),
+ ({"tool_choice": "none"}, True, False, False),
+ ({"stream": True, "permission_mode": "ask"}, True, False, True),
+ ({"stream": True, "frames": False}, True, False, True),
+ ({"stream": True, "frames": False, "permission_mode": "ask"}, True, False, False),
+ ({"response_format": _RF_FORMAT}, True, False, False),
+ ({"tools": [LOOKUP_TOOL]}, True, False, False),
+ ],
+)
+def test_a_plain_mlx_fit_may_reset_only_where_the_loop_can_reopen(
+ monkeypatch, extra, supports_tools, gpt_oss, reachable
+):
+ backend = _FittedToolLoopBackend(_fixed("done"))
+ backend.models["sf-model"]["is_mlx"] = True
+ backend._is_gpt_oss_model = lambda: gpt_oss
+ import routes.inference as inf
+
+ classify = inf._detect_safetensors_features
+ _install(monkeypatch, backend, supports_tools = supports_tools is True)
+ if isinstance(supports_tools, dict):
+ # The real classifier, so the branch it selects is the one under test.
+ backend.models["sf-model"]["chat_template_info"] = {"template": supports_tools}
+ monkeypatch.setattr(inf, "_detect_safetensors_features", classify)
+ base = {"stream": False, "enable_tools": False, "context_overflow": "truncate_oldest"}
+ _serve(monkeypatch, **{**base, **extra})
+ assert [fit["recall_reachable"] for fit in backend.fits] == [reachable]
+
+
+ "tokenizer_body, processor_body, reachable",
+ [(_WITH_TOOLS, _TURNS, False), (_TURNS, _WITH_TOOLS, True)],
+ ids = ["processor_drops_tools", "processor_renders_tools"],
+)
+def test_a_vision_model_is_asked_about_the_body_its_text_turn_renders(
+ monkeypatch, tokenizer_body, processor_body, reachable
+):
+ import routes.inference as inf
+
+ backend = _FittedToolLoopBackend(_fixed("done"))
+ backend.models["sf-model"]["is_mlx"] = True
+ classify = inf._detect_safetensors_features
+ _install(monkeypatch, backend)
+ backend.models["sf-model"]["chat_template_info"] = {
+ "template": tokenizer_body,
+ "processor_template": processor_body,
+ }
+ monkeypatch.setattr(inf, "_detect_safetensors_features", classify)
+ _serve(monkeypatch, stream = False, enable_tools = False, context_overflow = "truncate_oldest")
+ assert [fit["recall_reachable"] for fit in backend.fits] == [reachable]
+
+
+class _TrimmingBackend(_FittedToolLoopBackend):
+ """Fits by keeping only the newest message."""
+
+ def compact_chat_context(self, messages, **kwargs):
+ self.fits.append(kwargs)
+ event = {"type": "context_truncated", "dropped_messages": len(messages) - 1, "fits": True}
+ return {"messages": messages[-1:], "system_prompt": "fitted", "events": [event]}
+
+
+def _texts(messages):
+ return [message["content"] for message in messages]
+
+
+def _overflowing(**kwargs):
+ turns = [("user", "old"), ("assistant", "ok"), ("user", "new")]
+ return _request(
+ messages = [ChatMessage(role = role, content = text) for role, text in turns],
+ stream = False,
+ context_overflow = "truncate_oldest",
+ **kwargs,
+ )
+
+
[email protected]("slots", [4, 1], ids = ["batched", "one_by_one"])
+def test_every_choice_of_an_mlx_request_starts_from_one_fit(monkeypatch, slots):
+ from routes.inference import _choice_seed
+
+ backend = _TrimmingBackend(_fixed("done"))
+ backend.models["sf-model"]["is_mlx"] = True
+ backend.effective_parallel_slots = slots
+ body = _json_body(_call(_overflowing(n = 3, seed = 11), monkeypatch, backend))
+
+ assert len(backend.fits) == 1
+ assert len(backend.batch_calls) == (slots > 1)
+ sent = [(_texts(c["messages"]), c["system_prompt"], c["seed"]) for c in backend.calls]
+ seeds = (11, _choice_seed(11, 1), _choice_seed(11, 2))
+ assert sent == [(["new"], "fitted", seed) for seed in seeds]
+ assert body["context_truncated"]["dropped_messages"] == 2
+
+
+def test_an_mlx_prompt_carrying_a_picture_is_sent_unfitted(monkeypatch):
+ backend = _TrimmingBackend(_fixed("done"))
+ backend.models["sf-model"].update(is_mlx = True, is_vision = True)
+ _call(_overflowing(image_base64 = _PNG_1x1), monkeypatch, backend)
+
+ assert backend.fits == [] and len(backend.calls[0]["messages"]) == 3
+
+
+def test_a_nudge_retry_extends_the_fitted_prompt_and_is_not_refitted(monkeypatch):
+ backend = _TrimmingBackend(_fixed('<tool_call>{"name": "lookup"'))
+ backend.models["sf-model"]["is_mlx"] = True
+ payload = _overflowing(tools = [LOOKUP_TOOL], nudge_tool_calls = True)
+ _call(payload, monkeypatch, backend)
+
+ first, retry = (_texts(call["messages"]) for call in backend.calls)
+ assert len(backend.fits) == 1 and first == ["new"]
+ assert retry[:1] == first and len(retry) > 1
+
+
class _VisionToolLoopBackend(_ToolLoopBackend):
def __init__(self, responder, **kwargs):
super().__init__(responder, **kwargs)