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: stop edit_file writing a compacted-argument placeholder into files (#11950)

oobabooga4489b5fabb92
diff --git a/studio/backend/core/inference/context_window.py b/studio/backend/core/inference/context_window.py
index de15047f953..c7b77a93cc1 100644
--- a/studio/backend/core/inference/context_window.py
+++ b/studio/backend/core/inference/context_window.py
@@ -433,6 +433,39 @@ _COMPLETED_NEUTRAL_PHRASE = (
)
_FILE_WRITING_TOOLS = frozenset({"edit_file"})
+# Bracketed = leaf receipt, bare = `_unsloth_compacted` receipt for unparseable arguments.
+_RECEIPT_PHRASES = "|".join(
+ re.escape(phrase).replace(r"\{where\}", rf"(?: to [^\n]{{1,{_RECEIPT_PATH_MAX_CHARS}}})?")
+ for phrase in (_REFUSED_PHRASE, _COMPLETED_PHRASE, _COMPLETED_NEUTRAL_PHRASE)
+)
+_RECEIPT_LEAF = re.compile(rf"<\d+ chars (?:{_RECEIPT_PHRASES})>|\d+ chars (?:{_RECEIPT_PHRASES})")
+
+
+def compaction_receipt_field(
+ value: Any,
+ where: str = "",
+ match_only: "frozenset[str]" = frozenset(),
+) -> Optional[str]:
+ """First field holding only a receipt, or None; `match_only` keys (e.g. `old_string`) may, to repair files."""
+ if isinstance(value, str):
+ return (where or "arguments") if _RECEIPT_LEAF.fullmatch(value.strip()) else None
+ if isinstance(value, dict):
+ items = (
+ (f"{where}.{key}" if where else str(key), item)
+ for key, item in value.items()
+ if key not in match_only
+ )
+ elif isinstance(value, list):
+ items = ((f"{where}[{index}]", item) for index, item in enumerate(value))
+ else:
+ return None
+ for inner, item in items:
+ found = compaction_receipt_field(item, inner, match_only)
+ if found is not None:
+ return found
+ return None
+
+
# A reply opening like this reports a call that ran and did NOT do what was asked, so the file wording would describe
# a write that never landed.
_FAILED_REPLY_MARKERS = ("error", "failed", "not found", "no such file", "traceback")
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 5292e17cdcd..93a63aad08a 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -35,7 +35,7 @@ import threading
from contextvars import ContextVar
# What a truncated result costs besides its body, charged where the cut is decided rather than held back in advance.
-from .context_window import _RESULT_NOTICE_RESERVE
+from .context_window import _RESULT_NOTICE_RESERVE, compaction_receipt_field
# The window of the model THIS request is served by, set by execute_tool for the call's duration. Left unset it falls
# back to the process-global probe, which is wrong for an external-provider request: that runs Unsloth's tool loop
@@ -13060,6 +13060,17 @@ def execute_tool(
f"Error: {name} arguments {cause}, so nothing ran. Resend as complete JSON, "
"split across smaller calls if the content is long."
)
+ # Block placeholders copied from compacted history before any tool can write them (#11839).
+ receipt_field = compaction_receipt_field(
+ arguments,
+ match_only = frozenset({"old_string"}) if name == "edit_file" else frozenset(),
+ )
+ if receipt_field is not None:
+ return (
+ f"Error: {name} '{receipt_field}' is a placeholder that stood in for earlier "
+ "arguments to save room, not content, so nothing ran. Write the actual content "
+ "out in full."
+ )
effective_timeout = _EXEC_TIMEOUT if timeout is _TIMEOUT_UNSET else timeout
if name == "create_skill":
from .skills import SkillError, create_skill
diff --git a/studio/backend/tests/test_edit_file_tool.py b/studio/backend/tests/test_edit_file_tool.py
index cc811814bcf..488e84be1f2 100644
--- a/studio/backend/tests/test_edit_file_tool.py
+++ b/studio/backend/tests/test_edit_file_tool.py
@@ -7,6 +7,7 @@ Pinned here: a miss or an ambiguous match fails loudly and writes nothing, and
the file's encoding, line endings and mode survive an edit.
"""
+import json
import os
import stat
import sys
@@ -885,3 +886,125 @@ class TestEmptyPatternSafety:
)
assert "empty 'old_string'" in error
+
+
+class TestReplayedReceipt:
+ """Prevent copied compaction receipts from overwriting file content (#11839)."""
+
+ @staticmethod
+ def _replayed(path: str, old: str, new: str) -> dict:
+ from core.inference.context_window import compact_completed_tool_arguments
+
+ arguments = {"path": path, "edits": [{"old_string": old, "new_string": new}]}
+ messages = [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {
+ "id": "c1",
+ "type": "function",
+ "function": {"name": "edit_file", "arguments": json.dumps(arguments)},
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "c1", "content": f"Edited {path} (1 replacement)"},
+ ]
+ fitted, compacted = compact_completed_tool_arguments(messages)
+ assert compacted == 1
+ return json.loads(fitted[0]["tool_calls"][0]["function"]["arguments"])
+
+ def test_a_replayed_call_sent_back_writes_nothing(self, workdir):
+ target = workdir / "PortalManager.java"
+ original = "class A {\n private static final int PARTNER_TRIES = 8;\n}\n"
+ target.write_text(original)
+ replayed = self._replayed(
+ "PortalManager.java", " private static final int PARTNER_TRIES = 8;", "x" * 1100
+ )
+ assert "chars of arguments you sent" in replayed["edits"][0]["new_string"]
+
+ result = execute_tool("edit_file", replayed, session_id = "t")
+
+ assert result.startswith("Error:")
+ assert "edits[0].new_string" in result
+ assert target.read_text() == original
+
+ def test_one_receipt_in_a_batch_of_real_edits_stops_the_whole_batch(self, workdir):
+ target = workdir / "a.py"
+ target.write_text("a = 1\nb = 2\n")
+
+ result = _edit(
+ path = "a.py",
+ edits = [
+ {"old_string": "a = 1", "new_string": "a = 10"},
+ {
+ "old_string": "b = 2",
+ "new_string": "<410 chars of arguments you sent, elided to save room; "
+ "the call already ran. Not tool output>",
+ },
+ ],
+ )
+
+ assert result.startswith("Error:")
+ assert "edits[1].new_string" in result
+ assert target.read_text() == "a = 1\nb = 2\n"
+
+ def test_text_that_only_quotes_a_receipt_is_still_written(self, workdir):
+ target = workdir / "t.py"
+ target.write_text("RECEIPT = None\n")
+ quoted = (
+ 'RECEIPT = "<12 chars of arguments you sent, elided to save room; '
+ 'the call already ran. Not tool output>"'
+ )
+
+ result = _edit(path = "t.py", old_string = "RECEIPT = None", new_string = quoted)
+
+ assert "1 replacement" in result
+ assert target.read_text() == quoted + "\n"
+
+ def test_a_file_the_receipt_already_damaged_can_be_repaired(self, workdir):
+ receipt = (
+ "<1081 chars of arguments you sent, already written to PortalManager.java; "
+ "elided to save room. Not tool output; the file on disk holds it.>"
+ )
+ target = workdir / "PortalManager.java"
+ target.write_text(f"class A {{\n{receipt}\n}}\n")
+
+ result = _edit(
+ path = "PortalManager.java",
+ old_string = receipt,
+ new_string = " private static final int PARTNER_TRIES = 32;",
+ )
+
+ assert "1 replacement" in result
+ assert (
+ target.read_text() == "class A {\n private static final int PARTNER_TRIES = 32;\n}\n"
+ )
+
+ def test_a_receipt_copied_into_old_string_still_writes_nothing(self, workdir):
+ target = workdir / "a.py"
+ target.write_text("a = 1\n")
+
+ result = _edit(
+ path = "a.py",
+ old_string = "<410 chars of arguments you sent, elided to save room; "
+ "the call already ran. Not tool output>",
+ new_string = "a = 2",
+ )
+
+ assert "was not found" in result
+ assert target.read_text() == "a = 1\n"
+
+ def test_other_tools_refuse_it_before_running(self, workdir):
+ result = execute_tool(
+ "python",
+ {
+ "code": "<1500 chars of arguments you sent, elided to save room; "
+ "the call already ran. Not tool output>"
+ },
+ session_id = "t",
+ )
+
+ assert result.startswith("Error:")
+ assert "'code'" in result
+ assert "nothing ran" in result
diff --git a/studio/backend/tests/test_tool_call_arg_compaction.py b/studio/backend/tests/test_tool_call_arg_compaction.py
index b94c151e31c..ab1b7a61640 100644
--- a/studio/backend/tests/test_tool_call_arg_compaction.py
+++ b/studio/backend/tests/test_tool_call_arg_compaction.py
@@ -22,6 +22,7 @@ from core.inference.context_window import (
compact_completed_tool_arguments,
compact_executed_call_arguments,
compact_refused_tool_arguments,
+ compaction_receipt_field,
turn_is_servable,
)
@@ -946,3 +947,62 @@ def test_a_tool_reply_with_no_call_behind_it_is_still_blamed_on_itself():
]
assert _blamed_role_for_turn(messages) == "tool"
+
+
+ "compact, reply",
+ [
+ (lambda m: compact_completed_tool_arguments(m)[0], "Edited flappy-bird.html"),
+ (lambda m: compact_completed_tool_arguments(m)[0], "Error: 'old_string' was not found"),
+ (lambda m: compact_executed_call_arguments(m, "c1"), "Edited flappy-bird.html"),
+ (lambda m: compact_refused_tool_arguments(m, "c1"), "Not enough context"),
+ ],
+)
+def test_every_receipt_is_recognised_if_the_model_sends_it_back(compact, reply):
+ """Keep detection in sync with generated receipts."""
+ messages = _thread("<!DOCTYPE html>" + "x" * 8000)
+ messages[-1]["content"] = reply
+
+ replayed = json.loads(_replayed_arguments(compact(messages)))
+
+ assert compaction_receipt_field(replayed) == "new_string"
+
+
+def test_the_unparseable_receipt_is_recognised_too():
+ messages = [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {
+ "id": "c1",
+ "type": "function",
+ "function": {"name": "edit_file", "arguments": "{not json" + "x" * 8000},
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "c1", "name": "edit_file", "content": "ok"},
+ ]
+
+ fitted, _ = compact_completed_tool_arguments(messages)
+
+ replayed = json.loads(fitted[0]["tool_calls"][0]["function"]["arguments"])
+ assert compaction_receipt_field(replayed) == "_unsloth_compacted"
+
+
+ "arguments",
+ [
+ {"path": "a.py", "edits": [{"old_string": "a", "new_string": "b"}]},
+ {"code": "print('<3 chars of arguments you sent, quoted>')"},
+ {"note": "12 chars of arguments you sent,\nacross lines"},
+ {
+ "new_string": "<410 chars of arguments you sent, elided to save room; the call already "
+ "ran. Not tool output> return value"
+ },
+ {"new_string": "<12 chars of arguments you sent, see the notes>"},
+ {"count": 3, "flags": [True, None]},
+ ],
+)
+def test_ordinary_arguments_are_not_taken_for_a_receipt(arguments):
+ assert compaction_receipt_field(arguments) is None