Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
studio: compact long chats with media attachments
Lee Jackson69514299cb7a
diff --git a/studio/backend/core/inference/checkpoint.py b/studio/backend/core/inference/checkpoint.pyindex 013acd71275..b2e614724c6 100644--- a/studio/backend/core/inference/checkpoint.py+++ b/studio/backend/core/inference/checkpoint.py@@ -516,6 +516,7 @@ def fit_checkpoint_context(keeps_boundary: bool = False,can_reset: bool = False,searchable: bool = True,+ estimate_message: Callable[[dict], int] = estimate_message_tokens,# Signature compatibility with `fit_rolling_context`. A checkpoint reset already# drops to the latest turn plus X; an extra bite of the window would only shrink# the standing-instruction block, which is the half worth keeping.@@ -603,6 +604,7 @@ def fit_checkpoint_context(1.0,protected_message_ids = protected_message_ids,min_dropped = sticky_dropped,+ estimate_message = estimate_message,)if replayed:fitted = candidate@@ -619,7 +621,10 @@ def fit_checkpoint_context(# user groups.if current_tokens > prompt_target and _resolved(can_reset):candidate, reset_dropped = truncate_oldest_messages(- messages, 0.0, protected_message_ids = protected_message_ids+ messages,+ 0.0,+ protected_message_ids = protected_message_ids,+ estimate_message = estimate_message,)if reset_dropped:fitted = candidatediff --git a/studio/backend/core/inference/context_window.py b/studio/backend/core/inference/context_window.pyindex 2a8b9e1bb07..ade0900a00e 100644--- a/studio/backend/core/inference/context_window.py+++ b/studio/backend/core/inference/context_window.py@@ -12,6 +12,9 @@ from collections.abc import Callablefrom typing import Any, Optional_OMITTED_TOOL_EXCHANGE = "[Earlier tool exchange omitted from the rolling context window.]"+_UNPRICED_MEDIA_TYPES = frozenset(+ ("image_url", "input_audio", "audio", "input_image", "input_video")+)# How far BELOW the prompt budget a compaction trims, as a fraction of that budget.# Trimming to exactly the budget puts the next turn over it again, so the boundary creeps@@ -23,6 +26,22 @@ _COMPACTION_HEADROOM_RATIO = max()+def _message_without_unpriced_media(message: dict) -> dict:+ content = message.get("content")+ if not isinstance(content, list):+ return message+ countable = [+ part+ for part in content+ if not (isinstance(part, dict) and part.get("type") in _UNPRICED_MEDIA_TYPES)+ ]+ if len(countable) == len(content):+ return message+ copy = dict(message)+ copy["content"] = countable or ""+ return copy++def estimate_message_tokens(message: dict) -> int:try:return max(1, len(json.dumps(message, ensure_ascii = False)) // 4)@@ -30,6 +49,14 @@ def estimate_message_tokens(message: dict) -> int:return 1+def estimate_message_tokens_without_unpriced_media(message: dict) -> int:+ return estimate_message_tokens(_message_without_unpriced_media(message))+++def estimate_messages_tokens_without_unpriced_media(messages: list[dict]) -> int:+ return sum(estimate_message_tokens_without_unpriced_media(message) for message in messages)++def estimate_messages_tokens(messages: list[dict]) -> int:return sum(estimate_message_tokens(message) for message in messages)@@ -163,6 +190,7 @@ def truncate_oldest_messages(*,protected_message_ids: Optional[set[int]] = None,min_dropped: int = 0,+ estimate_message: Callable[[dict], int] = estimate_message_tokens,) -> tuple[list[dict], int]:"""Drop complete oldest turns while preserving system messages and the latest turn.@@ -177,7 +205,7 @@ def truncate_oldest_messages(if len(groups) <= 1:return messages, 0- estimates = {id(message): estimate_message_tokens(message) for message in messages}+ estimates = {id(message): estimate_message(message) for message in messages}current_estimate = sum(estimates.values())target_estimate = int(current_estimate * max(0.0, keep_ratio))dropped = 0@@ -243,26 +271,19 @@ def truncate_oldest_messages(return kept, dropped-def messages_have_media(messages: list[dict]) -> bool:- for message in messages:- content = message.get("content")- if not isinstance(content, list):- continue- for part in content:- if not isinstance(part, dict):- continue- # `input_video` is llama.cpp's own part type (written by `_inject_video_part`);- # missing it here would let a video prompt take the rolling preflight, whose- # `/apply-template` count omits the sampled video tokens.- if part.get("type") in (- "image_url",- "input_audio",- "audio",- "input_image",- "input_video",- ):- return True- return False+def messages_without_unpriced_media(messages: list[dict]) -> list[dict]:+ """Return the text/template portion that llama-server can count reliably.++ ``/apply-template`` does not include tokens added later by the multimodal+ processor. Sending base64 there is therefore both expensive and misleading, but+ skipping the rolling fit entirely also sends an already-overlong text history to+ prefill. Count a media-free shallow copy as a lower bound instead. The original+ messages, including every media part, remain the request that is ultimately sent.+ """+ stripped = [_message_without_unpriced_media(message) for message in messages]+ return (+ messages if all(before is after for before, after in zip(messages, stripped)) else stripped+ )def prompt_budget(context_length: int, max_tokens: Optional[int]) -> int:@@ -1113,6 +1134,7 @@ def fit_rolling_context(sticky_dropped: int = 0,keeps_boundary: bool = False,headroom_ratio: Optional[float] = None,+ estimate_message: Callable[[dict], int] = estimate_message_tokens,) -> tuple[list[dict], Optional[dict[str, Any]]]:"""Fit a chat into its real context by dropping oldest complete turns.@@ -1152,6 +1174,7 @@ def fit_rolling_context(1.0,protected_message_ids = protected_message_ids,min_dropped = sticky_dropped,+ estimate_message = estimate_message,)if dropped:fitted = candidate@@ -1190,6 +1213,7 @@ def fit_rolling_context(fitted,keep_ratio,protected_message_ids = protected_message_ids,+ estimate_message = estimate_message,)if dropped == 0:breakdiff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 274b01a2136..1420fea8817 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -57,13 +57,14 @@ from core.inference.context_window import (compact_completed_tool_arguments,compact_executed_call_arguments,compact_refused_tool_arguments,- estimate_messages_tokens,+ estimate_message_tokens_without_unpriced_media,+ estimate_messages_tokens_without_unpriced_media,_reply_floor,estimate_messages_tokens_conservative,estimate_messages_tokens_dense,evicted_messages,fit_rolling_context,- messages_have_media,+ messages_without_unpriced_media,retrieval_budget,tool_result_budget,turn_is_servable,@@ -26682,11 +26683,7 @@ class LlamaCppBackend:if max_tokens is not Noneelse (self._effective_context_length or _DEFAULT_MAX_TOKENS_FLOOR))- if (- context_overflow == "truncate_oldest"- and self._effective_context_length- and not messages_have_media(openai_messages)- ):+ if context_overflow == "truncate_oldest" and self._effective_context_length:try:_before_fit = openai_messages# One value for both the boundary read and the fit: a boundary the fit@@ -26708,7 +26705,9 @@ class LlamaCppBackend:context_length = self._effective_context_length,max_tokens = payload["max_tokens"],count_tokens = lambda fitted: self.count_chat_tokens(- neutralize_control_markup_in_messages(fitted, None, self.markup_profile),+ neutralize_control_markup_in_messages(+ messages_without_unpriced_media(fitted), None, self.markup_profile+ ),None,None,strict = True,@@ -26716,6 +26715,7 @@ class LlamaCppBackend:continue_final_message = continue_final_message,should_abort = lambda: bool(cancel_event and cancel_event.is_set()),),+ estimate_message = estimate_message_tokens_without_unpriced_media,reserve_tokens = _conversation_recall_reserve(thread_id),sticky_dropped = _sticky,sticky_is_checkpoint = _sticky_is_checkpoint,@@ -26745,7 +26745,9 @@ class LlamaCppBackend:),count_tokens = lambda fitted: self.count_chat_tokens(neutralize_control_markup_in_messages(- fitted, None, self.markup_profile+ messages_without_unpriced_media(fitted),+ None,+ self.markup_profile,),None,None,@@ -27395,8 +27397,6 @@ class LlamaCppBackend:"""if context_overflow != "truncate_oldest" or not self._effective_context_length:return None- if messages_have_media(candidate):- return Nonetry:_fitted, _truncation = _fit_with_instruction_pins(list(candidate),@@ -27410,7 +27410,9 @@ class LlamaCppBackend:),count_tokens = lambda fitted: self.count_chat_tokens(neutralize_control_markup_in_messages(- fitted, _markup_cache, self.markup_profile+ messages_without_unpriced_media(fitted),+ _markup_cache,+ self.markup_profile,),None,tools,@@ -27418,6 +27420,7 @@ class LlamaCppBackend:chat_template_kwargs = reasoning_kw,continue_final_message = continue_flag,),+ estimate_message = estimate_message_tokens_without_unpriced_media,anchor_ids = _rolling_anchor_ids,)except Exception:@@ -27452,7 +27455,9 @@ class LlamaCppBackend:try:_tokens = self.count_chat_tokens(neutralize_control_markup_in_messages(- candidate, _markup_cache, self.markup_profile+ messages_without_unpriced_media(candidate),+ _markup_cache,+ self.markup_profile,),None,tools,@@ -27573,11 +27578,7 @@ class LlamaCppBackend:)_preflight_context_length = None_preflight_succeeded = False- if (- context_overflow == "truncate_oldest"- and self._effective_context_length- and not messages_have_media(conversation)- ):+ if context_overflow == "truncate_oldest" and self._effective_context_length:_preflight_context_length = self._effective_context_lengthtry:_before_fit = conversation@@ -27603,7 +27604,9 @@ class LlamaCppBackend:max_tokens = _iteration_max_tokens,count_tokens = lambda fitted: self.count_chat_tokens(neutralize_control_markup_in_messages(- fitted, _markup_cache, self.markup_profile+ messages_without_unpriced_media(fitted),+ _markup_cache,+ self.markup_profile,),None,safe_tools,@@ -27614,6 +27617,7 @@ class LlamaCppBackend:),should_abort = lambda: bool(cancel_event and cancel_event.is_set()),),+ estimate_message = estimate_message_tokens_without_unpriced_media,anchor_ids = _rolling_anchor_ids,keeps_boundary = _keeps_compaction_boundary(thread_id),can_reset = _iteration_can_reset,@@ -27629,7 +27633,7 @@ class LlamaCppBackend:# messages, priced by the fit with the catalogue and template._prompt_token_offset = int(truncation.get("prompt_tokens_after") or 0- ) - estimate_messages_tokens(conversation)+ ) - estimate_messages_tokens_without_unpriced_media(conversation)if truncation:_recalled = _archive_and_recall(conversation,@@ -27659,7 +27663,9 @@ class LlamaCppBackend:),count_tokens = lambda fitted: self.count_chat_tokens(neutralize_control_markup_in_messages(- fitted, _markup_cache, self.markup_profile+ messages_without_unpriced_media(fitted),+ _markup_cache,+ self.markup_profile,),None,safe_tools,@@ -27768,7 +27774,9 @@ class LlamaCppBackend:max_tokens = _iteration_max_tokens,count_tokens = lambda fitted: self.count_chat_tokens(neutralize_control_markup_in_messages(- fitted, _markup_cache, self.markup_profile+ messages_without_unpriced_media(fitted),+ _markup_cache,+ self.markup_profile,),None,safe_tools,@@ -27779,6 +27787,7 @@ class LlamaCppBackend:),should_abort = lambda: bool(cancel_event and cancel_event.is_set()),),+ estimate_message = estimate_message_tokens_without_unpriced_media,anchor_ids = _rolling_anchor_ids,keeps_boundary = _keeps_compaction_boundary(thread_id),can_reset = _can_reset_epoch(@@ -27896,11 +27905,18 @@ class LlamaCppBackend:_reply_target = prompt_budget(self._effective_context_length, _iteration_max_tokens)- if estimate_messages_tokens_dense(conversation) > 0.7 * _reply_target:+ if (+ estimate_messages_tokens_dense(+ messages_without_unpriced_media(conversation)+ )+ > 0.7 * _reply_target+ ):try:_prompt_now = self.count_chat_tokens(neutralize_control_markup_in_messages(- conversation, _markup_cache, self.markup_profile+ messages_without_unpriced_media(conversation),+ _markup_cache,+ self.markup_profile,),None,safe_tools,@@ -29248,7 +29264,12 @@ class LlamaCppBackend:# the write lands before the next request is rejected. Erring# high here only costs an extra count; erring low costs the# whole gate.- if estimate_messages_tokens_conservative(conversation) > 0.7 * _room_target:+ if (+ estimate_messages_tokens_conservative(+ messages_without_unpriced_media(conversation)+ )+ > 0.7 * _room_target+ ):# Priced with a STAND-IN tool message for the call about to# run, not on the conversation as it stands. A chat template# renders an assistant turn's `tool_calls` only once a `tool`@@ -29274,7 +29295,9 @@ class LlamaCppBackend:try:_turn_tokens = self.count_chat_tokens(neutralize_control_markup_in_messages(- [*conversation, _probe_message],+ messages_without_unpriced_media(+ [*conversation, _probe_message]+ ),_markup_cache,self.markup_profile,),@@ -29331,7 +29354,9 @@ class LlamaCppBackend:try:_after_tokens = self.count_chat_tokens(neutralize_control_markup_in_messages(- _as_if_run, _markup_cache, self.markup_profile+ messages_without_unpriced_media(_as_if_run),+ _markup_cache,+ self.markup_profile,),None,safe_tools,@@ -29530,7 +29555,9 @@ class LlamaCppBackend:try:_exact_prompt_tokens = self.count_chat_tokens(neutralize_control_markup_in_messages(- [*conversation, _size_probe],+ messages_without_unpriced_media(+ [*conversation, _size_probe]+ ),_markup_cache,self.markup_profile,),@@ -29560,7 +29587,9 @@ class LlamaCppBackend:if _compact_after_execution and _compacted_turn_tokenselse _exact_prompt_tokensif _exact_prompt_tokens is not None- else estimate_messages_tokens_dense(conversation)+ else estimate_messages_tokens_dense(+ messages_without_unpriced_media(conversation)+ )+ (_prompt_token_offsetif _prompt_token_offset is not None@@ -29647,7 +29676,9 @@ class LlamaCppBackend:# is handed to the result._spent_after = self.count_chat_tokens(neutralize_control_markup_in_messages(- [*conversation, _size_probe],+ messages_without_unpriced_media(+ [*conversation, _size_probe]+ ),_markup_cache,self.markup_profile,),@@ -30018,11 +30049,7 @@ class LlamaCppBackend:)_final_preflight_context_length = None_final_preflight_succeeded = False- if (- context_overflow == "truncate_oldest"- and self._effective_context_length- and not messages_have_media(conversation)- ):+ if context_overflow == "truncate_oldest" and self._effective_context_length:_final_preflight_context_length = self._effective_context_lengthtry:_before_final_fit = conversation@@ -30050,13 +30077,16 @@ class LlamaCppBackend:context_length = self._effective_context_length,max_tokens = _final_max_tokens,count_tokens = lambda fitted: self.count_chat_tokens(- neutralize_control_markup_in_messages(fitted, None, self.markup_profile),+ neutralize_control_markup_in_messages(+ messages_without_unpriced_media(fitted), None, self.markup_profile+ ),None,None,strict = True,chat_template_kwargs = _reasoning_kw,should_abort = lambda: bool(cancel_event and cancel_event.is_set()),),+ estimate_message = estimate_message_tokens_without_unpriced_media,anchor_ids = _rolling_anchor_ids,keeps_boundary = _keeps_compaction_boundary(thread_id),can_reset = _final_can_reset,@@ -30089,7 +30119,9 @@ class LlamaCppBackend:),count_tokens = lambda fitted: self.count_chat_tokens(neutralize_control_markup_in_messages(- fitted, None, self.markup_profile+ messages_without_unpriced_media(fitted),+ None,+ self.markup_profile,),None,None,@@ -30172,13 +30204,16 @@ class LlamaCppBackend:context_length = self._effective_context_length,max_tokens = max_tokens,count_tokens = lambda fitted: self.count_chat_tokens(- neutralize_control_markup_in_messages(fitted, None, self.markup_profile),+ neutralize_control_markup_in_messages(+ messages_without_unpriced_media(fitted), None, self.markup_profile+ ),None,None,strict = True,chat_template_kwargs = _reasoning_kw,should_abort = lambda: bool(cancel_event and cancel_event.is_set()),),+ estimate_message = estimate_message_tokens_without_unpriced_media,anchor_ids = _rolling_anchor_ids,keeps_boundary = _keeps_compaction_boundary(thread_id),can_reset = _can_reset_epoch(@@ -30290,7 +30325,7 @@ class LlamaCppBackend:return Truetry:_tokens = self.count_chat_tokens(- candidate_messages,+ messages_without_unpriced_media(candidate_messages),None,None,strict = True,diff --git a/studio/backend/tests/test_context_overflow_truncation.py b/studio/backend/tests/test_context_overflow_truncation.pyindex a9ec4c2eecf..658a0671b67 100644--- a/studio/backend/tests/test_context_overflow_truncation.py+++ b/studio/backend/tests/test_context_overflow_truncation.py@@ -39,10 +39,13 @@ from routes.inference import ()from core.inference import context_windowfrom core.inference.context_window import (+ estimate_message_tokens,+ estimate_message_tokens_without_unpriced_media,+ estimate_messages_tokens_dense,evicted_messages,fit_rolling_context,group_turns,- messages_have_media,+ messages_without_unpriced_media,)from models.inference import ChatCompletionimport routes.inference as routes_mod@@ -233,19 +236,96 @@ def test_rolling_truncation_keeps_task_when_a_synthetic_user_nudge_is_latest():assert new[-1] is nudge-def test_rolling_media_detection_covers_image_and_audio_parts():- assert messages_have_media(- [{"role": "user", "content": [{"type": "image_url", "image_url": {}}]}]- )- assert messages_have_media(- [{"role": "user", "content": [{"type": "input_audio", "input_audio": {}}]}]- )- # llama.cpp's own part type; missing it would send a video prompt through a- # preflight that does not count its tokens.- assert messages_have_media(- [{"role": "user", "content": [{"type": "input_video", "input_video": {"data": "AAAA"}}]}]- )- assert not messages_have_media([{"role": "user", "content": "text only"}])+ "media",+ [+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}},+ {"type": "input_audio", "input_audio": {"data": "AAAA", "format": "wav"}},+ {"type": "audio", "audio": {"data": "AAAA", "format": "wav"}},+ {"type": "input_image", "image_url": {"url": "data:image/png;base64,AAAA"}},+ {"type": "input_video", "input_video": {"data": "AAAA"}},+ ],+)+def test_rolling_token_count_strips_unpriced_media_without_mutating_the_request(media):+ text = {"type": "text", "text": "describe this"}+ messages = [{"role": "user", "content": [text, media]}]++ countable = messages_without_unpriced_media(messages)++ assert countable == [{"role": "user", "content": [text]}]+ assert messages == [{"role": "user", "content": [text, media]}]+ assert messages_without_unpriced_media([{"role": "user", "content": [media]}]) == [+ {"role": "user", "content": ""}+ ]+++def test_rolling_token_count_reuses_text_only_messages():+ messages = [{"role": "user", "content": "text only"}]++ assert messages_without_unpriced_media(messages) is messages+++def test_media_free_estimates_do_not_change_shared_admission_estimates():+ message = {+ "role": "user",+ "content": [+ {+ "type": "input_audio",+ "input_audio": {"data": "A" * 100_000, "format": "wav"},+ }+ ],+ }++ assert estimate_message_tokens(message) > 20_000+ assert estimate_messages_tokens_dense([message]) > 20_000+ assert estimate_message_tokens_without_unpriced_media(message) < 20+++def test_rolling_eviction_does_not_charge_protected_media_transport_bytes():+ history = [+ {"role": role, "content": marker * 10}+ for marker in "abcde"+ for role in ("user", "assistant")+ ]++ def count_text(candidate):+ total = 0+ for message in messages_without_unpriced_media(candidate):+ content = message.get("content", "")+ if isinstance(content, str):+ total += len(content)+ else:+ total += sum(len(part.get("text", "")) for part in content)+ return total++ results = []+ for payload_size in (4, 100_000):+ latest = {+ "role": "user",+ "content": [+ {"type": "text", "text": "final"},+ {+ "type": "input_audio",+ "input_audio": {"data": "A" * payload_size, "format": "wav"},+ },+ ],+ }+ messages = [*history, latest]++ fitted, truncation = fit_rolling_context(+ messages,+ context_length = 120,+ max_tokens = 20,+ count_tokens = count_text,+ estimate_message = estimate_message_tokens_without_unpriced_media,+ )++ assert truncation and truncation["fits"]+ assert fitted[-1] is latest+ assert fitted[-1]["content"][-1]["input_audio"]["data"] == "A" * payload_size+ results.append((truncation["dropped_messages"], len(fitted)))++ assert results == [(2, 9), (2, 9)]def test_rolling_truncation_preserves_nonleading_system_messages():diff --git a/studio/backend/tests/test_length_truncated_reasoning_continuation.py b/studio/backend/tests/test_length_truncated_reasoning_continuation.pyindex 70f3247e523..f31741873dc 100644--- a/studio/backend/tests/test_length_truncated_reasoning_continuation.py+++ b/studio/backend/tests/test_length_truncated_reasoning_continuation.py@@ -781,10 +781,20 @@ def test_a_continuation_one_eviction_short_is_not_abandoned(monkeypatch):for index in range(30):old_turns.append({"role": "user", "content": f"Question {index}. " + "x" * 600})old_turns.append({"role": "assistant", "content": f"Answer {index}. " + "y" * 600})+ latest = {+ "role": "user",+ "content": [+ {"type": "text", "text": "Create a Flappy Bird game"},+ {+ "type": "input_audio",+ "input_audio": {"data": "A" * 100_000, "format": "wav"},+ },+ ],+ }events = list(backend.generate_chat_completion_with_tools(- messages = [*old_turns, {"role": "user", "content": "Create a Flappy Bird game"}],+ messages = [*old_turns, latest],tools = [_WEB_SEARCH_TOOL],enable_thinking = True,max_tool_iterations = 3,@@ -794,9 +804,61 @@ def test_a_continuation_one_eviction_short_is_not_abandoned(monkeypatch):)assert len(payloads) == 2, "the continuation was abandoned instead of making room"+ assert payloads[1]["messages"][-3] == latest+ assert payloads[1]["messages"][-3]["content"][1]["input_audio"]["data"] == "A" * 100_000assert "Done." in "".join(_texts(events, "content"))+def test_final_pass_continuation_counts_strip_media_and_payloads_keep_it(monkeypatch):+ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ _truncated_thought_then([_sse({"content": "Done."}), _done()]),+ payloads,+ )+ counted: list[list[dict]] = []++ def fake_count(messages, *_args, **_kwargs):+ counted.append(copy.deepcopy(messages))+ return 100++ monkeypatch.setattr(backend, "count_chat_tokens", fake_count)+ audio_data = "A" * 100_000+ latest = {+ "role": "user",+ "content": [+ {"type": "text", "text": "Create a Flappy Bird game"},+ {+ "type": "input_audio",+ "input_audio": {"data": audio_data, "format": "wav"},+ },+ ],+ }++ list(+ backend.generate_chat_completion_with_tools(+ messages = [latest],+ tools = [],+ max_tool_iterations = 0,+ enable_thinking = True,+ context_overflow = "truncate_oldest",+ )+ )++ assert counted+ assert all(+ part.get("type") != "input_audio"+ for candidate in counted+ for message in candidate+ for part in message.get("content", [])+ if isinstance(part, dict)+ )+ assert len(payloads) == 2+ assert payloads[0]["messages"][0] == latest+ assert payloads[1]["messages"][0] == latest+ assert payloads[1]["messages"][0]["content"][1]["input_audio"]["data"] == audio_data++def test_a_continuation_is_sized_by_what_is_left_of_the_cap(monkeypatch):"""`prompt_budget` shrinks as `max_tokens` grows, so the two must agree.diff --git a/studio/backend/tests/test_llama_cpp_tool_loop.py b/studio/backend/tests/test_llama_cpp_tool_loop.pyindex aae6df8da6a..d5e602b148d 100644--- a/studio/backend/tests/test_llama_cpp_tool_loop.py+++ b/studio/backend/tests/test_llama_cpp_tool_loop.py@@ -3970,6 +3970,190 @@ def test_tool_loop_refits_each_preflight_path_after_context_shrinking_respawn(moassert len(payloads[1]["messages"]) == 1+def test_tool_loop_compacts_text_history_around_latest_audio(monkeypatch):+ """Unpriced media must not disable compaction that the text alone requires."""+ payloads: list[dict] = []+ backend = _make_backend(monkeypatch, [[_sse({"content": "OK"}), _done()]], payloads)+ backend._effective_context_length = 100+ counted: list[list[dict]] = []++ def count_tokens(candidate, *_args, **_kwargs):+ counted.append(copy.deepcopy(candidate))+ return sum(len(str(message.get("content", ""))) for message in candidate)++ monkeypatch.setattr(backend, "count_chat_tokens", count_tokens)+ audio_turn = {+ "role": "user",+ "content": [+ {"type": "text", "text": "latest"},+ {+ "type": "input_audio",+ "input_audio": {"data": "AAAA", "format": "wav"},+ },+ ],+ }+ events = list(+ backend.generate_chat_completion_with_tools(+ messages = [+ {"role": "user", "content": "u" * 40},+ {"role": "assistant", "content": "a" * 40},+ audio_turn,+ ],+ tools = [{"type": "function", "function": {"name": "python"}}],+ max_tokens = 20,+ max_tool_iterations = 1,+ context_overflow = "truncate_oldest",+ )+ )++ notices = [event for event in events if event.get("type") == "context_truncated"]+ assert counted+ assert all(+ part.get("type") != "input_audio"+ for candidate in counted+ for message in candidate+ for part in message.get("content", [])+ if isinstance(part, dict)+ )+ assert [notice["dropped_messages"] for notice in notices] == [2]+ assert payloads[0]["messages"] == [audio_turn]+++def test_tool_loop_secondary_counts_strip_media_but_payloads_keep_it(monkeypatch):+ payloads: list[dict] = []+ backend = _make_backend(+ monkeypatch,+ [+ _structured_tool_call("python", {"code": "print('ok')"}, "call_python"),+ [_sse({"content": "Done."}), _done()],+ ],+ payloads,+ )+ counted: list[list[dict]] = []++ def count_tokens(candidate, *_args, **_kwargs):+ counted.append(copy.deepcopy(candidate))+ return 1000++ monkeypatch.setattr(backend, "count_chat_tokens", count_tokens)+ monkeypatch.setattr(+ "core.inference.tools.execute_tool",+ lambda *_args, **_kwargs: "ok",+ )+ audio_data = "A" * 100_000+ audio_turn = {+ "role": "user",+ "content": [+ {"type": "text", "text": "x" * 12_000},+ {+ "type": "input_audio",+ "input_audio": {"data": audio_data, "format": "wav"},+ },+ ],+ }++ list(+ backend.generate_chat_completion_with_tools(+ messages = [audio_turn],+ tools = [{"type": "function", "function": {"name": "python"}}],+ max_tokens = 512,+ max_tool_iterations = 2,+ )+ )++ assert len(counted) >= 3+ assert all(+ part.get("type") != "input_audio"+ for candidate in counted+ for message in candidate+ for part in message.get("content", [])+ if isinstance(part, dict)+ )+ assert len(payloads) == 2+ assert payloads[0]["messages"][0] == audio_turn+ assert payloads[1]["messages"][0] == audio_turn+ assert payloads[1]["messages"][0]["content"][1]["input_audio"]["data"] == audio_data++[email protected]("with_tools", [False, True])+def test_media_compaction_recall_recount_uses_the_stripped_view(monkeypatch, with_tools):+ from core.inference import llama_cpp++ payloads: list[dict] = []+ backend = _make_backend(monkeypatch, [[_sse({"content": "OK"}), _done()]], payloads)+ backend._effective_context_length = 100+ counted: list[list[dict]] = []+ recall_recounts: list[list[dict]] = []++ def count_tokens(candidate, *_args, **_kwargs):+ counted.append(copy.deepcopy(candidate))+ total = 0+ for message in candidate:+ content = message.get("content", "")+ if isinstance(content, str):+ total += len(content)+ else:+ total += sum(len(part.get("text", "")) for part in content)+ return total++ def fake_archive(conversation, _before, **kwargs):+ before_count = len(counted)+ kwargs["count_tokens"](conversation)+ assert len(counted) == before_count + 1+ recall_recounts.append(counted[-1])+ return {+ "conversation": conversation,+ "events": [],+ "counts": {},+ "recalled": False,+ "anchored": [],+ }++ monkeypatch.setattr(backend, "count_chat_tokens", count_tokens)+ monkeypatch.setattr(llama_cpp, "_archive_and_recall", fake_archive)+ audio_turn = {+ "role": "user",+ "content": [+ {"type": "text", "text": "latest"},+ {+ "type": "input_audio",+ "input_audio": {"data": "A" * 100_000, "format": "wav"},+ },+ ],+ }+ kwargs = {+ "messages": [+ {"role": "user", "content": "u" * 40},+ {"role": "assistant", "content": "a" * 40},+ audio_turn,+ ],+ "max_tokens": 20,+ "context_overflow": "truncate_oldest",+ "thread_id": "media-recall",+ }++ if with_tools:+ list(+ backend.generate_chat_completion_with_tools(+ **kwargs,+ tools = [{"type": "function", "function": {"name": "python"}}],+ max_tool_iterations = 1,+ )+ )+ else:+ list(backend.generate_chat_completion(**kwargs))++ assert recall_recounts+ assert all(+ part.get("type") != "input_audio"+ for candidate in recall_recounts+ for message in candidate+ for part in message.get("content", [])+ if isinstance(part, dict)+ )+ assert payloads[0]["messages"][-1] == audio_turn++def test_a_respawn_refit_that_misses_its_target_still_archives_and_reports(monkeypatch):"""A rescued respawn refit archives its evictions and emits metadata."""import httpx