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: keep loop notes ahead of the MCP image envelope (#11367)

Jyotirmoy Roy60c86b9d1fb3
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 0abd775cd06..a76e5a24660 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -2348,6 +2348,16 @@ def _is_window_notice(result: str) -> bool:
return _WINDOW_NOTICE_MARKER in result or _ZERO_ROOM_MARKER in result
+def _note_before_envelopes(result: str, tool_name: str, add_note) -> str:
+ """Text after the __MCP_IMAGES__ array breaks its parse and ships the base64 as text (#11358)."""
+ if not isinstance(result, str):
+ return add_note(result)
+ from core.inference.tools import _split_frontend_suffix
+
+ body, suffix = _split_frontend_suffix(result, tool_name)
+ return add_note(body) + suffix
+
+
# How far back the classifier looks for llama.cpp's argument-parsing error. It
# prints one and exits, so it is always at the end; generous enough to survive a
# usage hint printed after it, small enough that a 10 MB unterminated line (which
@@ -40671,7 +40681,11 @@ class LlamaCppBackend:
decision.tool_name,
_MIN_USEFUL_RESULT_TOKENS,
)
- result = _starved_result_message(decision.tool_name, result)
+ result = _note_before_envelopes(
+ result,
+ decision.tool_name,
+ lambda body: _starved_result_message(decision.tool_name, body),
+ )
else:
# Cleared either way: it describes THIS call's budget, and leaving
# it set would hand the notice to the next call instead.
@@ -40720,8 +40734,12 @@ class LlamaCppBackend:
# Told, not silently stopped. The model can still finish the
# task another way, and hard-stopping a turn that is otherwise
# healthy would trade one dead end for a worse one.
- result = _repeated_result_message(
- decision.tool_name, _identical_result_runs[0], result
+ result = _note_before_envelopes(
+ result,
+ decision.tool_name,
+ lambda body: _repeated_result_message(
+ decision.tool_name, _identical_result_runs[0], body
+ ),
)
_identical_result_runs[0] = 0
_last_tool_result_key[0] = None
diff --git a/studio/backend/core/inference/mcp_images.py b/studio/backend/core/inference/mcp_images.py
index 09b630e5a4f..55277f2b4c4 100644
--- a/studio/backend/core/inference/mcp_images.py
+++ b/studio/backend/core/inference/mcp_images.py
@@ -48,8 +48,31 @@ def is_image_tool(name: str) -> bool:
return name == "view_image" or name.startswith(MCP_TOOL_PREFIX)
+# The tool loop's own notes, which results saved before #11367 carry after the array (#11358).
+_LOOP_NOTE = re.compile(
+ r"\[(?:No room in the window for this result, so "
+ r"|[^\n\]]+ returned exactly this \d+ times; it will not change)[^\n]*\]"
+)
+
+
def split_images(result: str) -> tuple[str, list[dict]]:
"""Validated, so tool text that merely mentions the marker is not truncated."""
+ end = len(result)
+ # At most the starved note and then the repeat note; peeled first so the array parses once.
+ for _ in range(2):
+ if not result.endswith("]", 0, end):
+ break
+ cut = result.rfind("\n\n[", max(0, end - 512), end)
+ if cut == -1 or not _LOOP_NOTE.fullmatch(result, cut + 2, end):
+ break
+ end = cut
+ if end == len(result):
+ return _split_images(result)
+ text, images = _split_images(result[:end])
+ return (text + result[end:], images) if images else (result, [])
+
+
+def _split_images(result: str) -> tuple[str, list[dict]]:
head, sep, payload = result.rpartition("\n" + SENTINEL)
if not sep:
return result, []
diff --git a/studio/backend/tests/test_llama_cpp_tool_loop.py b/studio/backend/tests/test_llama_cpp_tool_loop.py
index d01b66f4e47..507409266c3 100644
--- a/studio/backend/tests/test_llama_cpp_tool_loop.py
+++ b/studio/backend/tests/test_llama_cpp_tool_loop.py
@@ -6668,6 +6668,39 @@ def test_mcp_images_are_not_sent_to_a_text_only_model(monkeypatch):
assert "__MCP_IMAGES__" not in messages[-1]["content"]
+def test_repeated_note_on_an_mcp_image_keeps_the_base64_out_of_the_tool_text(monkeypatch):
+ """#11358: a note after the image array broke its parse and sent the base64 as text."""
+ tool = "mcp__browser__screenshot"
+ # A window-cut result: the repeat key ignores the arguments, so three distinct calls repeat.
+ fitted = (
+ "page\n\n... (truncated to 4 chars for the model; 99 chars total.)\n" + _mcp_image_result()
+ )
+ streams = [_structured_tool_call(tool, {"page": page}, f"call_{page}") for page in range(3)] + [
+ [_sse({"content": "done"}), _done()]
+ ]
+ payloads: list[dict] = []
+ backend = _vision_backend(monkeypatch, streams, payloads, vision = True)
+ monkeypatch.setattr(
+ "core.inference.tools.execute_tool", lambda name, arguments, **_kwargs: fitted
+ )
+
+ events = list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "screenshot each page"}],
+ tools = [{"type": "function", "function": {"name": tool}}],
+ max_tool_iterations = 4,
+ )
+ )
+
+ tool_texts = [m["content"] for m in payloads[-1]["messages"] if m["role"] == "tool"]
+ assert len(tool_texts) == 3
+ assert "returned exactly this 3 times" in tool_texts[-1]
+ assert not any(_MCP_PNG_B64 in text for text in tool_texts)
+ saved = [e["result"] for e in events if e.get("type") == "tool_end"][-1]
+ assert saved.endswith("}]")
+ assert saved.index("returned exactly this 3 times") < saved.index("__MCP_IMAGES__")
+
+
@pytest.mark.parametrize("wanted", [True, False])
def test_the_decode_slot_is_asked_for_and_read_only_when_a_caller_wants_it(monkeypatch, wanted):
"""Verbose alone would attach the whole prompt, so it travels with the narrowing."""
diff --git a/studio/backend/tests/test_mcp_envelope_appended_notes.py b/studio/backend/tests/test_mcp_envelope_appended_notes.py
new file mode 100644
index 00000000000..07e0edf230b
--- /dev/null
+++ b/studio/backend/tests/test_mcp_envelope_appended_notes.py
@@ -0,0 +1,114 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+import base64
+import io
+import json
+import os
+import sys
+from pathlib import Path
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+from core.inference import tools
+from core.inference.llama_cpp import _is_window_notice, _note_before_envelopes
+from core.inference.mcp_images import (
+ SENTINEL,
+ promote_history,
+ split_images,
+)
+from core.inference.tool_call_parser import (
+ repeated_result_message,
+ starved_result_message,
+)
+from core.inference.tool_loop_controller import strip_result_for_model
+
+TOOL = "mcp__a5d934d4713a4f20__screenshot"
+
+
+def _png() -> str:
+ from PIL import Image
+
+ out = io.BytesIO()
+ Image.frombytes("RGB", (128, 128), os.urandom(128 * 128 * 3)).save(out, "PNG")
+ return base64.b64encode(out.getvalue()).decode()
+
+
+BASE64 = _png()
+FITTED = (
+ "page text\n\n... (truncated to 10 chars for the model; 99 chars total.)\n[1 image returned]"
+ f"\n{SENTINEL}{json.dumps([{'data': BASE64, 'mimeType': 'image/png'}])}"
+)
+# The saved shape from #11358: the notice landed after the array.
+CORRUPTED = starved_result_message(TOOL, FITTED)
+
+
+def test_the_fitter_leaves_the_shape_the_starved_branch_fires_on(monkeypatch):
+ raw = "page text\n" + "x" * 50_000 + FITTED[FITTED.index("\n[1 image returned]") :]
+ monkeypatch.setattr(tools, "_loaded_context_tokens", lambda: 8192)
+ token = tools._REQUEST_RESULT_BUDGET.set(200)
+ try:
+ fitted = tools._fit_result_to_room(raw, TOOL)
+ finally:
+ tools._REQUEST_RESULT_BUDGET.reset(token)
+ assert _is_window_notice(fitted)
+ assert split_images(fitted)[1][0]["data"] == BASE64
+ assert not starved_result_message(TOOL, fitted).endswith("}]")
+ noted = _note_before_envelopes(fitted, TOOL, lambda body: starved_result_message(TOOL, body))
+ assert split_images(noted)[1][0]["data"] == BASE64
+ assert BASE64[:40] not in strip_result_for_model(noted, TOOL)
+
+
+def test_starved_and_repeated_notes_keep_the_envelope_parseable():
+ for add, note in (
+ (lambda body: starved_result_message(TOOL, body), "No room in the window"),
+ (lambda body: repeated_result_message(TOOL, 3, body), "returned exactly this 3 times"),
+ ):
+ result = _note_before_envelopes(FITTED, TOOL, add)
+ assert result.endswith("}]")
+ text, images = split_images(result)
+ assert images and images[0]["data"] == BASE64
+ assert text.startswith("page text") and note in text
+
+
+def test_saved_results_with_notes_after_the_array_are_repaired():
+ both = repeated_result_message(TOOL, 3, CORRUPTED)
+ for saved in (CORRUPTED, both):
+ text, images = split_images(saved)
+ assert images and images[0]["data"] == BASE64
+ assert text.startswith("page text") and "No room in the window" in text
+ model_text = strip_result_for_model(saved, TOOL)
+ assert BASE64[:40] not in model_text and "No room in the window" in model_text
+ assert "returned exactly this 3 times" in split_images(both)[0]
+
+
+def test_saved_result_is_repaired_on_replay():
+ messages = [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {"id": "c1", "type": "function", "function": {"name": TOOL, "arguments": "{}"}}
+ ],
+ },
+ {"role": "tool", "tool_call_id": "c1", "content": CORRUPTED},
+ ]
+ plain = promote_history(messages, vision = False)
+ assert BASE64[:40] not in json.dumps(plain)
+ assert "No room in the window" in plain[1]["content"]
+ promoted = []
+ promote_history(messages, vision = True, promoted_out = promoted)
+ assert len(promoted) == 1
+
+
+def test_other_text_after_an_envelope_is_left_alone():
+ # A file an MCP tool read may quote an envelope; only the loop's own notes are moved.
+ quoted = FITTED + "\n\nmore of the file\n[1] footnote"
+ assert split_images(quoted) == (quoted, [])
+ assert strip_result_for_model(quoted, TOOL) == quoted
+ prose = f"docs say\n{SENTINEL} is the marker\n\n[No room in the window for this result, so x]"
+ assert split_images(prose) == (prose, [])