The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): keep interrupt scaffold off the tool-tail redirect placeholder
HexLab9868d1aea1ae1a
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex 01a256d5dce..bf2b306bc60 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -220,14 +220,13 @@ def _apply_active_turn_redirect(agent: Any, messages: List[Dict[str, Any]], text``[This response was interrupted by a user correction.]`` and its``Visible response before the interruption:`` header exist so the MODELunderstands its own reply was cut off. They are not prose the user wrote- or the agent said. Persisting them into ``content`` painted the raw- machinery as an assistant bubble on every reload (and merged it into the- preceding tool-call bubble), which is what made a steered transcript- unreadable. Carry the scaffolded form in the ``api_content`` sidecar --- the exact bytes replayed to the provider -- and keep ``content`` clean.- When nothing was on screen there is no clean form at all, so the row is- marked ``display_kind="hidden"``: still replayed to the model, dropped by- every transcript surface (desktop, TUI, CLI resume), exactly like the+ or the agent said. Persisting them into an assistant row's ``content`` or+ ``api_content`` made the model treat the scaffold as *its own previous+ reply*, echo it, and self-replicate ghost rows across turns (#81841).+ Carry the scaffolded form only in the *user correction's* ``api_content``+ sidecar — never on the placeholder assistant row. When nothing was on+ screen the placeholder is marked ``display_kind="hidden"`` (empty+ content) so every transcript surface drops it, exactly likecompaction-reference rows."""visible = agent._strip_think_blocks(@@ -240,34 +239,37 @@ def _apply_active_turn_redirect(agent: Any, messages: List[Dict[str, Any]], text["Visible response before the interruption:", visible])checkpoint = "\n\n".join(checkpoint_parts)+ correction = (+ "[Context from the interrupted assistant response]\n"+ f"{checkpoint}\n\n"+ f"{text}"+ )- # The normal live tail is user or tool, so an assistant checkpoint followed- # by the correction preserves strict alternation. If a transport already- # committed an assistant item, attribute the checkpoint inside the user- # correction instead of creating assistant→assistant.+ # The normal live tail is user or tool, so an assistant placeholder+ # followed by the correction preserves strict alternation. If a transport+ # already committed an assistant item, attribute the checkpoint inside the+ # user correction instead of creating assistant→assistant.if messages and messages[-1].get("role") == "assistant":- correction = (- "[Context from the interrupted assistant response]\n"- f"{checkpoint}\n\n"- f"{text}"- )# Transcript shows the user's own words; the provider replays the# scaffolded form so it still sees the interrupted context.messages.append({"role": "user", "content": text, "api_content": correction})else:- entry: Dict[str, Any] = {+ # Placeholder preserves role alternation only. Scaffold bytes must+ # never land here — the API replay path substitutes api_content back+ # into content, and a scaffold-as-assistant-reply is what the model+ # then echoes (#81841 / incomplete #73146 else branch).+ placeholder: Dict[str, Any] = {"role": "assistant",- "content": visible or checkpoint,- "api_content": checkpoint,+ "content": visible or "",}if not visible:- # Nothing reached the screen — this row carries no assistant prose- # at all, only the cut-off notice for the model.- entry["display_kind"] = "hidden"- messages.append(entry)- messages.append({"role": "user", "content": text})+ placeholder["display_kind"] = "hidden"+ messages.append(placeholder)+ messages.append(+ {"role": "user", "content": text, "api_content": correction}+ )agent._current_streamed_assistant_text = ""agent._stream_needs_break = Truediff --git a/tests/run_agent/test_run_agent.py b/tests/run_agent/test_run_agent.pyindex 222ba26ca6e..a997214c5bf 100644--- a/tests/run_agent/test_run_agent.py+++ b/tests/run_agent/test_run_agent.py@@ -3542,14 +3542,18 @@ class TestRunConversation:"assistant","user",]- checkpoint = replay[-2]["content"]- assert "interrupted by a user correction" in checkpoint+ # Scaffold rides on the user correction (api_content → content), never+ # as the assistant placeholder's own reply (#81841).+ placeholder = replay[-2]["content"]+ correction = replay[-1]["content"]+ assert "interrupted by a user correction" not in (placeholder or "")+ assert "interrupted by a user correction" in correction+ assert correction.endswith("No, use Postgres instead.")# Displayed chain-of-thought must NOT be replayed: an assistant turn# inlining its own reasoning trips Anthropic's output classifier and# bricks the session with deterministic empty responses (July 2026).- assert "I should implement this with SQLite." not in checkpoint- assert "Reasoning shown before the interruption" not in checkpoint- assert replay[-1]["content"] == "No, use Postgres instead."+ assert "I should implement this with SQLite." not in correction+ assert "Reasoning shown before the interruption" not in correctionassert agent._pending_redirect is Noneassert any(snapshot[-1].get("content") == "No, use Postgres instead."@@ -3629,14 +3633,21 @@ class TestRunConversation:assert calls == 2assert results["result"]["completed"] is Trueassert results["result"]["final_response"] == "Corrected answer."- checkpoint = results["result"]["messages"][-3]- assert "interrupted by a user correction" in checkpoint["content"]+ placeholder = results["result"]["messages"][-3]+ correction = results["result"]["messages"][-2]+ assert placeholder["role"] == "assistant"+ assert "interrupted by a user correction" not in (+ placeholder.get("content") or ""+ )+ assert "interrupted by a user correction" in (+ correction.get("api_content") or ""+ )# Displayed reasoning is display-only — replaying it as assistant# content trips Anthropic's output classifier (July 2026 brickings).- assert "Following the original approach." not in checkpoint["content"]- assert results["result"]["messages"][-2]["content"] == (- "Use the corrected approach."+ assert "Following the original approach." not in (+ correction.get("api_content") or "")+ assert correction["content"] == "Use the corrected approach."def test_nous_401_refreshes_after_remint_and_retries(self, agent):diff --git a/tests/run_agent/test_steer.py b/tests/run_agent/test_steer.pyindex 7b48eb4b1e7..d020d80eb87 100644--- a/tests/run_agent/test_steer.py+++ b/tests/run_agent/test_steer.py@@ -217,10 +217,10 @@ class TestActiveTurnRedirectCheckpoint:"""The checkpoint machinery is for the MODEL, not the transcript.Persisting ``[This response was interrupted by a user correction.]``- into ``content`` painted raw scaffolding as an assistant bubble on- every reload. It must ride in ``api_content`` (replayed to the- provider) while ``content`` stays clean, or be marked- ``display_kind="hidden"`` when there is no clean form at all.+ into an assistant row's ``content`` or ``api_content`` painted raw+ scaffolding as the model's own prior reply (#81841). Scaffold bytes+ ride only in the *user correction's* ``api_content``; assistant+ placeholders stay clean (or ``display_kind="hidden"`` when empty)."""from agent.conversation_loop import _apply_active_turn_redirect@@ -248,6 +248,20 @@ class TestActiveTurnRedirectCheckpoint:_apply_active_turn_redirect(agent, messages, "New direction.")for msg in messages:+ if msg.get("role") == "assistant":+ # Scaffold must never live on an assistant row at all+ # — content OR api_content (API replay substitutes the+ # sidecar back into content).+ blob = (+ str(msg.get("content") or "")+ + str(msg.get("api_content") or "")+ )+ for marker in scaffolding:+ assert marker not in blob, (+ f"scaffolding leaked into assistant row "+ f"(tail={tail_role}, streamed={bool(streamed)}): "+ f"{blob!r}"+ )if msg.get("display_kind") == "hidden":continue # dropped by every transcript surfacecontent = str(msg.get("content", ""))@@ -259,10 +273,9 @@ class TestActiveTurnRedirectCheckpoint:# The user's correction is always shown verbatim.assert messages[-1]["content"] == "New direction."- # ...and the model still receives the interrupted context.- replayed = "".join(- str(m.get("api_content") or m.get("content", "")) for m in messages- )+ # ...and the model still receives the interrupted context,+ # but only via the user correction's api_content sidecar.+ replayed = messages[-1].get("api_content") or ""assert "[This response was interrupted by a user correction.]" in replayedif streamed:assert streamed in replayed@@ -307,15 +320,46 @@ class TestActiveTurnRedirectCheckpoint:_apply_active_turn_redirect(agent, messages, "New direction.")- checkpoint_row = messages[-2]- # Nothing was on screen, so the row exists only for the model: hidden- # from every transcript surface, scaffolding replayed via the sidecar.- assert checkpoint_row["display_kind"] == "hidden"+ placeholder = messages[-2]+ correction = messages[-1]+ # Nothing was on screen: empty hidden placeholder for alternation;+ # scaffold rides only on the user correction's api_content.+ assert placeholder["role"] == "assistant"+ assert placeholder["display_kind"] == "hidden"+ assert placeholder.get("content") == ""+ assert not placeholder.get("api_content")+ assert correction["content"] == "New direction."assert (- checkpoint_row["api_content"]- == "[This response was interrupted by a user correction.]"+ "[This response was interrupted by a user correction.]"+ in correction["api_content"]+ )++ def test_tool_tail_scaffold_never_on_assistant_api_content(self):+ """#81841: mid-tool steer must not put the interrupt scaffold on the+ placeholder assistant row (that is what the model echoed)."""+ from agent.conversation_loop import _apply_active_turn_redirect++ agent = _bare_agent()+ messages = [+ {"role": "user", "content": "start"},+ {"role": "assistant", "tool_calls": [{"id": "a"}]},+ {"role": "tool", "content": "out", "tool_call_id": "a"},+ ]++ _apply_active_turn_redirect(agent, messages, "Stop and do X instead.")++ placeholder = messages[-2]+ correction = messages[-1]+ assert placeholder["role"] == "assistant"+ assert placeholder.get("display_kind") == "hidden"+ assert placeholder.get("content") == ""+ assert not placeholder.get("api_content")+ assert correction["role"] == "user"+ assert correction["content"] == "Stop and do X instead."+ assert correction["api_content"].startswith(+ "[Context from the interrupted assistant response]\n"+ "[This response was interrupted by a user correction.]")- assert messages[-1]["content"] == "New direction."class TestSteerInjection: