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: Let the agent run a command again after it edits a file (#10810)

Nilay701ba22cb4c0
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 9017750bae7..cd9d4193129 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -439,6 +439,7 @@ from core.inference.tool_call_parser import (
from core.inference.passthrough_healing import nudge_enabled as _nudge_enabled
from core.inference.repetition_guard import is_repetition_dominated
from core.inference.tool_loop_controller import (
+ _WORKSPACE_TOOLS,
ToolLoopController,
append_deferred_nudges,
awaiting_approval_status,
@@ -32670,11 +32671,27 @@ class LlamaCppBackend:
# fallback (mirrors the safetensors loop; see _MAX_TOOL_CALLS_PER_TURN).
if tool_calls and not has_structured_tc and len(tool_calls) > 1:
_seen_keys: set = set()
+ _last_workspace_key = None
+ # One rerun per piece of new work: `test, edit A, test, edit B, test` keeps
+ # every test, while `read, edit, read, edit` stops replaying and cannot
+ # fill the cap.
+ _novel_kept = 0
+ _novel_at_last_keep: dict = {}
_deduped: list = []
for _tc in tool_calls:
_fn = _tc.get("function", {}) or {}
_key = (_fn.get("name", ""), str(_fn.get("arguments", "")))
- if _key in _seen_keys:
+ if _fn.get("name") in _WORKSPACE_TOOLS:
+ if _key == _last_workspace_key:
+ continue
+ if _key in _seen_keys:
+ if _novel_kept <= _novel_at_last_keep.get(_key, 0):
+ continue
+ else:
+ _novel_kept += 1
+ _novel_at_last_keep[_key] = _novel_kept
+ _last_workspace_key = _key
+ elif _key in _seen_keys:
continue
_seen_keys.add(_key)
_deduped.append(_tc)
diff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.py
index 49343e10ae9..219dd9b439b 100644
--- a/studio/backend/core/inference/safetensors_agentic.py
+++ b/studio/backend/core/inference/safetensors_agentic.py
@@ -54,6 +54,7 @@ from core.tool_healing import (
strip_outside_think,
)
from core.inference.tool_loop_controller import (
+ _WORKSPACE_TOOLS,
ToolLoopController,
append_deferred_nudges,
awaiting_approval_status,
@@ -1303,11 +1304,26 @@ def run_safetensors_tool_loop(
# Collapse exact-duplicate calls and cap the count (runaway-turn guard).
if tool_calls:
seen_keys: set = set()
+ last_workspace_key = None
+ # One rerun per piece of new work: `test, edit A, test, edit B, test` keeps every
+ # test, while `read, edit, read, edit` stops replaying and cannot fill the cap.
+ novel_kept = 0
+ novel_at_last_keep: dict = {}
deduped: list = []
for _tc in tool_calls:
_fn = _tc.get("function", {}) or {}
_key = (_fn.get("name", ""), str(_fn.get("arguments", "")))
- if _key in seen_keys:
+ if _fn.get("name") in _WORKSPACE_TOOLS:
+ if _key == last_workspace_key:
+ continue
+ if _key in seen_keys:
+ if novel_kept <= novel_at_last_keep.get(_key, 0):
+ continue
+ else:
+ novel_kept += 1
+ novel_at_last_keep[_key] = novel_kept
+ last_workspace_key = _key
+ elif _key in seen_keys:
continue
seen_keys.add(_key)
deduped.append(_tc)
diff --git a/studio/backend/core/inference/tool_loop_controller.py b/studio/backend/core/inference/tool_loop_controller.py
index 38ad1d76f61..9173071666b 100644
--- a/studio/backend/core/inference/tool_loop_controller.py
+++ b/studio/backend/core/inference/tool_loop_controller.py
@@ -935,6 +935,7 @@ _SANDBOX_TOOLS = frozenset({"python", "terminal"})
# than the card the user is looking at.
_IMAGE_SENTINEL_TOOLS = _SANDBOX_TOOLS | {"code_execution"}
_SOURCE_MAP_TOOLS = frozenset({"search_knowledge_base", "search_conversation"})
+_WORKSPACE_TOOLS = _SANDBOX_TOOLS | {"edit_file"}
def strip_result_for_model(result: str, tool_name: "str | None" = None) -> str:
@@ -1030,6 +1031,10 @@ class ToolLoopController:
self._one_shot_tools = one_shot_tools
self._completed_one_shot_tools: set[str] = set()
self._successful_keys: set[str] = set()
+ # `_workspace_novel_at[key]` is the distinct-call count when `key` last ran.
+ self._workspace_ran: set[str] = set()
+ self._workspace_novel = 0
+ self._workspace_novel_at: dict[str, int] = {}
self._duplicate_noop_counts: dict[str, int] = {}
self._duplicate_noop_limit = max(1, duplicate_noop_limit)
self._history: list[_ToolCallRecord] = []
@@ -1121,6 +1126,23 @@ class ToolLoopController:
action = decision.action,
)
)
+ # One rerun per piece of NEW work, not per call: `read, edit, read, edit` would
+ # otherwise apply the edit twice. Here as well as in the prefilters, which a
+ # structured batch skips. A failed command can still have written, so it counts too.
+ if decision.tool_name in _WORKSPACE_TOOLS:
+ if decision.key not in self._workspace_ran:
+ self._workspace_ran.add(decision.key)
+ self._workspace_novel += 1
+ stale = {
+ key
+ for key in self._successful_keys
+ if key.partition(":")[0] in _WORKSPACE_TOOLS
+ and self._workspace_novel_at.get(key, 0) < self._workspace_novel
+ }
+ self._successful_keys -= stale
+ for key in stale:
+ self._duplicate_noop_counts.pop(key, None)
+ self._workspace_novel_at[decision.key] = self._workspace_novel
if not failed:
self._successful_keys.add(decision.key)
if decision.tool_name in self._one_shot_tools:
diff --git a/studio/backend/tests/test_llama_cpp_tool_loop.py b/studio/backend/tests/test_llama_cpp_tool_loop.py
index bdc55a0850d..5ce59f06af4 100644
--- a/studio/backend/tests/test_llama_cpp_tool_loop.py
+++ b/studio/backend/tests/test_llama_cpp_tool_loop.py
@@ -6362,3 +6362,217 @@ def test_only_the_tool_loop_flushes_held_text_on_cancel():
), f"exactly one cancel arm may flush held text; flushing arms: {flushing}"
# The last arm is the synthesized final pass, which owns none of those buffers.
assert flushing[0] != len(arms) - 1, "the final pass must not flush the tool loop's buffers"
+
+
[email protected]("edit_result", ["Edited notes.txt", "Error: failed after writing"])
+def test_textual_workspace_read_edit_read_in_one_turn(monkeypatch, edit_result):
+ read = '<tool_call>{"name":"terminal","arguments":{"command":"cat notes.txt"}}</tool_call>'
+ edit = '<tool_call>{"name":"edit_file","arguments":{"path":"notes.txt","edits":[]}}</tool_call>'
+ backend, _ = _backend_and_payloads(
+ monkeypatch,
+ [
+ [_sse({"content": read + edit + read}), _done()],
+ [_sse({"content": "Done."}), _done()],
+ ],
+ )
+ calls = []
+ results = iter(["before", edit_result, "after"])
+
+ def execute(name, arguments, **kwargs):
+ calls.append(name)
+ return next(results)
+
+ monkeypatch.setattr("core.inference.tools.execute_tool", execute)
+ list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "Read, edit, and verify notes.txt"}],
+ tools = [
+ {"type": "function", "function": {"name": name}}
+ for name in ("terminal", "edit_file")
+ ],
+ max_tool_iterations = 3,
+ )
+ )
+ assert calls == ["terminal", "edit_file", "terminal"]
+
+
+def test_textual_repeated_workspace_reads_do_not_crowd_out_a_later_edit(monkeypatch):
+ read = '<tool_call>{"name":"terminal","arguments":{"command":"cat notes.txt"}}</tool_call>'
+ edit = '<tool_call>{"name":"edit_file","arguments":{"path":"notes.txt","edits":[]}}</tool_call>'
+ backend, _ = _backend_and_payloads(
+ monkeypatch,
+ [
+ [_sse({"content": read * 8 + edit + read}), _done()],
+ [_sse({"content": "Done."}), _done()],
+ ],
+ )
+ calls = []
+ results = iter(["before", "Edited notes.txt", "after"])
+
+ def execute(name, arguments, **kwargs):
+ calls.append(name)
+ return next(results)
+
+ monkeypatch.setattr("core.inference.tools.execute_tool", execute)
+ list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "Read, edit, and verify notes.txt"}],
+ tools = [
+ {"type": "function", "function": {"name": name}}
+ for name in ("terminal", "edit_file")
+ ],
+ max_tool_iterations = 3,
+ )
+ )
+ assert calls == ["terminal", "edit_file", "terminal"]
+
+
+def test_textual_alternating_workspace_block_does_not_replay_the_edit(monkeypatch):
+ """One re-run verifies an edit. A repeating block past that applied the edit twice."""
+ read = '<tool_call>{"name":"terminal","arguments":{"command":"cat notes.txt"}}</tool_call>'
+ edit = '<tool_call>{"name":"edit_file","arguments":{"path":"notes.txt","edits":[]}}</tool_call>'
+ backend, _ = _backend_and_payloads(
+ monkeypatch,
+ [
+ [_sse({"content": (read + edit) * 2}), _done()],
+ [_sse({"content": "Done."}), _done()],
+ ],
+ )
+ calls = []
+ results = iter(["before", "Edited notes.txt", "after", "Edited notes.txt"])
+
+ def execute(name, arguments, **kwargs):
+ calls.append(name)
+ return next(results)
+
+ monkeypatch.setattr("core.inference.tools.execute_tool", execute)
+ list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "Read, edit, and verify notes.txt"}],
+ tools = [
+ {"type": "function", "function": {"name": name}}
+ for name in ("terminal", "edit_file")
+ ],
+ max_tool_iterations = 3,
+ )
+ )
+ assert calls == ["terminal", "edit_file", "terminal"]
+
+
+def test_textual_alternating_workspace_block_does_not_crowd_out_a_later_tool(monkeypatch):
+ """The block used to fill the 8-call cap, so the search the model asked for never ran."""
+ read = '<tool_call>{"name":"terminal","arguments":{"command":"cat notes.txt"}}</tool_call>'
+ edit = '<tool_call>{"name":"edit_file","arguments":{"path":"notes.txt","edits":[]}}</tool_call>'
+ search = '<tool_call>{"name":"web_search","arguments":{"query":"gpu prices"}}</tool_call>'
+ backend, _ = _backend_and_payloads(
+ monkeypatch,
+ [
+ [_sse({"content": (read + edit) * 4 + search}), _done()],
+ [_sse({"content": "Done."}), _done()],
+ ],
+ )
+ calls = []
+ results = iter(["before", "Edited notes.txt", "after", "results"])
+
+ def execute(name, arguments, **kwargs):
+ calls.append(name)
+ return next(results)
+
+ monkeypatch.setattr("core.inference.tools.execute_tool", execute)
+ list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "Read, edit, verify, then search"}],
+ tools = [
+ {"type": "function", "function": {"name": name}}
+ for name in ("terminal", "edit_file", "web_search")
+ ],
+ max_tool_iterations = 3,
+ )
+ )
+ assert calls == ["terminal", "edit_file", "terminal", "web_search"]
+
+
+def test_textual_every_independent_edit_gets_its_own_verification_rerun(monkeypatch):
+ """Two edit-and-verify cycles in one turn: the test after the second edit must run."""
+ test = '<tool_call>{"name":"terminal","arguments":{"command":"pytest -q"}}</tool_call>'
+ edit_a = '<tool_call>{"name":"edit_file","arguments":{"path":"a.py","edits":[]}}</tool_call>'
+ edit_b = '<tool_call>{"name":"edit_file","arguments":{"path":"b.py","edits":[]}}</tool_call>'
+ backend, _ = _backend_and_payloads(
+ monkeypatch,
+ [
+ [_sse({"content": test + edit_a + test + edit_b + test}), _done()],
+ [_sse({"content": "Done."}), _done()],
+ ],
+ )
+ calls = []
+ results = iter(["1 failed", "Edited a.py", "1 failed", "Edited b.py", "1 passed"])
+
+ def execute(name, arguments, **kwargs):
+ calls.append(name)
+ return next(results)
+
+ monkeypatch.setattr("core.inference.tools.execute_tool", execute)
+ list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "Fix the test"}],
+ tools = [
+ {"type": "function", "function": {"name": name}}
+ for name in ("terminal", "edit_file")
+ ],
+ max_tool_iterations = 3,
+ )
+ )
+ assert calls == ["terminal", "edit_file", "terminal", "edit_file", "terminal"]
+
+
+def _structured_batch(spec: list) -> list:
+ """One assistant turn carrying `spec` as parallel structured tool_calls."""
+ frames = [
+ _tool_call_sse(name, args, f"call_{i}", index = i) for i, (name, args) in enumerate(spec)
+ ]
+ return [frames + [_done()], [_sse({"content": "Done."}), _done()]]
+
+
+def _drive_structured(monkeypatch, spec, results):
+ backend, _ = _backend_and_payloads(monkeypatch, _structured_batch(spec))
+ calls: list[str] = []
+ supply = iter(results)
+
+ def execute(name, arguments, **kwargs):
+ calls.append(name)
+ return next(supply, "OK")
+
+ monkeypatch.setattr("core.inference.tools.execute_tool", execute)
+ list(
+ backend.generate_chat_completion_with_tools(
+ messages = [{"role": "user", "content": "Read, edit, and verify notes.txt"}],
+ tools = [
+ {"type": "function", "function": {"name": name}}
+ for name in ("terminal", "edit_file")
+ ],
+ max_tool_iterations = 3,
+ )
+ )
+ return calls
+
+
+def test_structured_workspace_block_does_not_replay_the_edit(monkeypatch):
+ """Structured batches skip the textual prefilter, so the controller has to catch this."""
+ read = ("terminal", {"command": "cat notes.txt"})
+ edit = ("edit_file", {"path": "notes.txt", "edits": []})
+ calls = _drive_structured(
+ monkeypatch, [read, edit, read, edit], ["v1", "Edited notes.txt", "v2", "Edited"]
+ )
+ assert calls == ["terminal", "edit_file", "terminal"]
+
+
+def test_structured_every_independent_edit_keeps_its_verification(monkeypatch):
+ read = ("terminal", {"command": "cat notes.txt"})
+ edit_a = ("edit_file", {"path": "a.txt", "edits": []})
+ edit_b = ("edit_file", {"path": "b.txt", "edits": []})
+ calls = _drive_structured(
+ monkeypatch,
+ [read, edit_a, read, edit_b, read],
+ ["v1", "Edited a.txt", "v2", "Edited b.txt", "v3"],
+ )
+ assert calls == ["terminal", "edit_file", "terminal", "edit_file", "terminal"]
diff --git a/studio/backend/tests/test_safetensors_tool_loop.py b/studio/backend/tests/test_safetensors_tool_loop.py
index a694795a141..efbd70f1ab8 100644
--- a/studio/backend/tests/test_safetensors_tool_loop.py
+++ b/studio/backend/tests/test_safetensors_tool_loop.py
@@ -5229,3 +5229,145 @@ def test_call_single_turn_falls_back_to_legacy_signatures():
assert list(_call_single_turn(no_flag, [], [{"x": 1}], False)) == ["a"]
assert list(_call_single_turn(bare, [], [{"x": 1}], False)) == ["b"]
assert seen == [("no_flag", [{"x": 1}]), ("bare", None)]
+
+
[email protected]("edit_result", ["Edited notes.txt", "Error: failed after writing"])
+def test_workspace_read_edit_read_in_one_turn(edit_result):
+ read = '<tool_call>{"name":"terminal","arguments":{"command":"cat notes.txt"}}</tool_call>'
+ edit = '<tool_call>{"name":"edit_file","arguments":{"path":"notes.txt","edits":[]}}</tool_call>'
+ turns = iter([read + edit + read, "Done."])
+
+ def single_turn(messages, **kwargs):
+ yield next(turns)
+
+ executor = FakeExecuteTool(["before", edit_result, "after"])
+ events = _collect_events(
+ run_safetensors_tool_loop(
+ single_turn = single_turn,
+ messages = [{"role": "user", "content": "Read, edit, and verify notes.txt"}],
+ tools = [
+ {"type": "function", "function": {"name": name}}
+ for name in ("terminal", "edit_file")
+ ],
+ execute_tool = executor,
+ max_tool_iterations = 3,
+ )
+ )
+ assert [name for name, _ in executor.calls] == ["terminal", "edit_file", "terminal"]
+ assert [event["result"] for event in events if event["type"] == "tool_end"] == [
+ "before",
+ edit_result,
+ "after",
+ ]
+
+
+def test_repeated_workspace_reads_do_not_crowd_out_a_later_edit():
+ read = '<tool_call>{"name":"terminal","arguments":{"command":"cat notes.txt"}}</tool_call>'
+ edit = '<tool_call>{"name":"edit_file","arguments":{"path":"notes.txt","edits":[]}}</tool_call>'
+ turns = iter([read * 8 + edit + read, "Done."])
+
+ def single_turn(messages, **kwargs):
+ yield next(turns)
+
+ executor = FakeExecuteTool(["before", "Edited notes.txt", "after"])
+ _collect_events(
+ run_safetensors_tool_loop(
+ single_turn = single_turn,
+ messages = [{"role": "user", "content": "Read, edit, and verify notes.txt"}],
+ tools = [
+ {"type": "function", "function": {"name": name}}
+ for name in ("terminal", "edit_file")
+ ],
+ execute_tool = executor,
+ max_tool_iterations = 3,
+ )
+ )
+ assert [name for name, _ in executor.calls] == ["terminal", "edit_file", "terminal"]
+
+
+def test_an_alternating_workspace_block_does_not_replay_the_edit():
+ """One re-run verifies an edit. A repeating block past that applied the edit twice."""
+ read = '<tool_call>{"name":"terminal","arguments":{"command":"cat notes.txt"}}</tool_call>'
+ edit = '<tool_call>{"name":"edit_file","arguments":{"path":"notes.txt","edits":[]}}</tool_call>'
+ turns = iter([(read + edit) * 2, "Done."])
+
+ def single_turn(messages, **kwargs):
+ yield next(turns)
+
+ executor = FakeExecuteTool(["before", "Edited notes.txt", "after", "Edited notes.txt"])
+ _collect_events(
+ run_safetensors_tool_loop(
+ single_turn = single_turn,
+ messages = [{"role": "user", "content": "Read, edit, and verify notes.txt"}],
+ tools = [
+ {"type": "function", "function": {"name": name}}
+ for name in ("terminal", "edit_file")
+ ],
+ execute_tool = executor,
+ max_tool_iterations = 3,
+ )
+ )
+ assert [name for name, _ in executor.calls] == ["terminal", "edit_file", "terminal"]
+
+
+def test_an_alternating_workspace_block_does_not_crowd_out_a_later_tool():
+ """The block used to fill the 8-call cap, so the search the model asked for never ran."""
+ read = '<tool_call>{"name":"terminal","arguments":{"command":"cat notes.txt"}}</tool_call>'
+ edit = '<tool_call>{"name":"edit_file","arguments":{"path":"notes.txt","edits":[]}}</tool_call>'
+ search = '<tool_call>{"name":"web_search","arguments":{"query":"gpu prices"}}</tool_call>'
+ turns = iter([(read + edit) * 4 + search, "Done."])
+
+ def single_turn(messages, **kwargs):
+ yield next(turns)
+
+ executor = FakeExecuteTool(["before", "Edited notes.txt", "after", "results"])
+ _collect_events(
+ run_safetensors_tool_loop(
+ single_turn = single_turn,
+ messages = [{"role": "user", "content": "Read, edit, verify, then search"}],
+ tools = [
+ {"type": "function", "function": {"name": name}}
+ for name in ("terminal", "edit_file", "web_search")
+ ],
+ execute_tool = executor,
+ max_tool_iterations = 3,
+ )
+ )
+ assert [name for name, _ in executor.calls] == [
+ "terminal",
+ "edit_file",
+ "terminal",
+ "web_search",
+ ]
+
+
+def test_every_independent_edit_gets_its_own_verification_rerun():
+ """Two edit-and-verify cycles in one turn: the test after the second edit must run."""
+ test = '<tool_call>{"name":"terminal","arguments":{"command":"pytest -q"}}</tool_call>'
+ edit_a = '<tool_call>{"name":"edit_file","arguments":{"path":"a.py","edits":[]}}</tool_call>'
+ edit_b = '<tool_call>{"name":"edit_file","arguments":{"path":"b.py","edits":[]}}</tool_call>'
+ turns = iter([test + edit_a + test + edit_b + test, "Done."])
+
+ def single_turn(messages, **kwargs):
+ yield next(turns)
+
+ executor = FakeExecuteTool(["1 failed", "Edited a.py", "1 failed", "Edited b.py", "1 passed"])
+ _collect_events(
+ run_safetensors_tool_loop(
+ single_turn = single_turn,
+ messages = [{"role": "user", "content": "Fix the test"}],
+ tools = [
+ {"type": "function", "function": {"name": name}}
+ for name in ("terminal", "edit_file")
+ ],
+ execute_tool = executor,
+ max_tool_iterations = 3,
+ )
+ )
+ assert [name for name, _ in executor.calls] == [
+ "terminal",
+ "edit_file",
+ "terminal",
+ "edit_file",
+ "terminal",
+ ]
diff --git a/studio/backend/tests/test_tool_loop_controller.py b/studio/backend/tests/test_tool_loop_controller.py
index 6091f8f02f7..e020528b3ce 100644
--- a/studio/backend/tests/test_tool_loop_controller.py
+++ b/studio/backend/tests/test_tool_loop_controller.py
@@ -199,6 +199,69 @@ def test_repeated_successful_duplicate_becomes_terminal_after_one_recovery_nudge
assert controller.active_tools() == []
+def test_command_can_run_again_after_a_file_edit():
+ controller = ToolLoopController(
+ tools = [_tool("terminal"), _tool("edit_file"), _tool("web_search")]
+ )
+ run = _call("terminal", {"command": "python calc.py"})
+ edit = _call(
+ "edit_file", {"path": "calc.py", "edits": [{"old_string": "a", "new_string": "b"}]}
+ )
+ search = _call("web_search", {"query": "gpu prices"})
+
+ controller.record_result(controller.prepare_call(search), "ok")
+ controller.record_result(controller.prepare_call(run), "3")
+ assert controller.prepare_call(run).action == "duplicate"
+ controller.record_noop(controller.prepare_call(run))
+
+ controller.record_result(controller.prepare_call(edit), "Edited calc.py")
+ rerun = controller.prepare_call(run)
+ assert rerun.action == "execute"
+ controller.record_result(rerun, "-1")
+
+ controller.record_noop(controller.prepare_call(run))
+ assert not controller.force_final_answer
+ # The edit does NOT come back. Nothing new has run since it did -- only `run`, which was
+ # already spent -- so re-applying the identical edit is a repeating block replaying
+ # itself, and a non-idempotent one (an appending python/terminal call) would land twice.
+ assert controller.prepare_call(edit).action == "duplicate"
+ assert controller.prepare_call(search).action == "duplicate"
+
+
+def test_each_independent_edit_buys_back_its_own_verification():
+ """A rerun is worth one piece of new work, not one per call, so B's check is not lost."""
+ controller = ToolLoopController(tools = [_tool("terminal"), _tool("edit_file")])
+ test = _call("terminal", {"command": "pytest -q"})
+ edit_a = _call("edit_file", {"path": "a.py", "edits": [{"old_string": "a", "new_string": "b"}]})
+ edit_b = _call("edit_file", {"path": "b.py", "edits": [{"old_string": "c", "new_string": "d"}]})
+
+ controller.record_result(controller.prepare_call(test), "1 failed")
+ controller.record_result(controller.prepare_call(edit_a), "Edited a.py")
+ after_a = controller.prepare_call(test)
+ assert after_a.action == "execute"
+ controller.record_result(after_a, "1 failed")
+
+ controller.record_result(controller.prepare_call(edit_b), "Edited b.py")
+ after_b = controller.prepare_call(test)
+ assert after_b.action == "execute"
+
+
+def test_a_repeating_workspace_block_stops_replaying_itself():
+ """read, edit, read, edit: the second edit is the block repeating, not new work."""
+ controller = ToolLoopController(tools = [_tool("terminal"), _tool("edit_file")])
+ read = _call("terminal", {"command": "cat notes.txt"})
+ edit = _call(
+ "edit_file", {"path": "notes.txt", "edits": [{"old_string": "a", "new_string": "b"}]}
+ )
+
+ controller.record_result(controller.prepare_call(read), "version one")
+ controller.record_result(controller.prepare_call(edit), "Edited notes.txt")
+ reread = controller.prepare_call(read)
+ assert reread.action == "execute"
+ controller.record_result(reread, "version two")
+ assert controller.prepare_call(edit).action == "duplicate"
+
+
def test_failed_call_does_not_block_retry():
controller = ToolLoopController(tools = [_tool("web_search")])
first = controller.prepare_call(_call("web_search", {"query": "gpu prices"}))
@@ -594,3 +657,14 @@ def test_a_success_that_opens_with_error_is_not_nudged_as_a_failure():
assert not completion.is_error
assert TOOL_ERROR_NUDGE not in completion.model_message()["content"]
+
+
[email protected]("tool_name", ["python", "terminal", "edit_file"])
+def test_failed_workspace_execution_invalidates_previous_reads(tool_name):
+ controller = ToolLoopController(tools = [_tool("terminal"), _tool(tool_name)])
+ read = _call("terminal", {"command": "cat notes.txt"})
+ controller.record_result(controller.prepare_call(read), "before")
+ write = _call(tool_name, {"code": "write_then_fail", "command": "write_then_fail"})
+ controller.record_result(controller.prepare_call(write), "Error: failed after writing")
+ assert controller.prepare_call(read).action == "execute"
+ assert controller.prepare_call(write).action == "execute"