Skip to content

The agent that grows with you

fix: keep looped partials out of every interrupt checkpoint, tell the model why

teknium12f3c3cfbc004
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.py
index 1eb1725b31e..2ffef43db30 100644
--- a/agent/conversation_loop.py
+++ b/agent/conversation_loop.py
@@ -28,7 +28,7 @@ from agent.prompt_caching import (
strip_anthropic_cache_control,
strip_anthropic_tool_cache_control,
)
-from agent.repetition_guard import is_repetition_dominated
+from agent.repetition_guard import REPETITION_LOOP_INTERRUPTED, is_repetition_dominated
from agent.runtime_cwd import resolve_agent_cwd
from agent.surface_switch import (
identity_line_value, note_inert_pinned_tools, split_runtime_boundary, stage_surface_switch_note,
@@ -287,11 +287,14 @@ def _apply_active_turn_redirect(agent: Any, messages: List[Dict[str, Any]], text
empty-response storms); the interruption scaffold is replay text carried only in the user
correction's ``api_content``; an on-screen-empty placeholder is ``display_kind=hidden``."""
visible = agent._strip_think_blocks(getattr(agent, "_current_streamed_assistant_text", "") or "").strip()
- if is_repetition_dominated(visible):
- visible = ""
checkpoint_parts = [_INTERRUPT_SCAFFOLD_MARKER]
- if visible:
+ if is_repetition_dominated(visible):
+ # Same guard as the truncated-continuation path: the looped bytes must reach neither the
+ # replayed correction nor the placeholder below (empty ``visible`` takes the hidden shape).
+ checkpoint_parts.append(REPETITION_LOOP_INTERRUPTED)
+ visible = ""
+ elif visible:
checkpoint_parts += ["Visible response before the interruption:", visible]
checkpoint = "\n\n".join(checkpoint_parts)
correction = f"[Context from the interrupted assistant response]\n{checkpoint}\n\n{text}"
diff --git a/agent/repetition_guard.py b/agent/repetition_guard.py
index 6b536de629d..661ea4df602 100644
--- a/agent/repetition_guard.py
+++ b/agent/repetition_guard.py
@@ -22,6 +22,12 @@ _MIN_REPEAT_COUNT = 5
# "Repetition-dominated" = repeated windows cover at least this fraction.
_DOMINANCE_RATIO = 0.5
+# What an interrupt checkpoint says INSTEAD of a repetition-dominated partial. Replaying the
+# looped bytes (as the redirect's api_content or as the interrupted assistant row) re-seeds the
+# loop on the next request and the corruption survives restarts (#112764); the model only needs
+# to know the reply degenerated and was cut off.
+REPETITION_LOOP_INTERRUPTED = "[the reply degenerated into a repetition loop and was interrupted]"
+
def is_repetition_dominated(text: str) -> bool:
"""True when a single 60+ char substring recurs often enough to cover at least half
diff --git a/agent/turn_api_call.py b/agent/turn_api_call.py
index 024815d03bc..e8af62ffba8 100644
--- a/agent/turn_api_call.py
+++ b/agent/turn_api_call.py
@@ -15,7 +15,9 @@ import time
from typing import Any, Dict, Optional
from agent.error_classifier import FailoverReason
+from agent.agent_runtime_helpers import _INTERRUPTED_PLACEHOLDER
from agent.message_metadata import append_message
+from agent.repetition_guard import REPETITION_LOOP_INTERRUPTED, is_repetition_dominated
from agent.turn_failure_copy import site_copy, stamp_failure
logger = logging.getLogger("agent.conversation_loop")
@@ -185,7 +187,12 @@ def handle_api_interrupt(
_partial = agent._strip_think_blocks(
getattr(agent, "_current_streamed_assistant_text", "") or ""
).strip()
- if _partial:
+ if _partial and is_repetition_dominated(_partial):
+ # The interrupted row is replayed next turn; looped bytes there re-seed the loop
+ # (#112764). Keep the neutral placeholder the sanitizer would heal to anyway.
+ append_message(messages, {"role": "assistant", "content": _INTERRUPTED_PLACEHOLDER})
+ final_response = REPETITION_LOOP_INTERRUPTED
+ elif _partial:
append_message(messages, {"role": "assistant", "content": _partial})
final_response = _partial
else:
diff --git a/tests/agent/test_steer.py b/tests/agent/test_steer.py
index 636beea87a2..f5a05997d8e 100644
--- a/tests/agent/test_steer.py
+++ b/tests/agent/test_steer.py
@@ -191,8 +191,11 @@ class TestActiveTurnRedirect:
class TestActiveTurnRedirectCheckpoint:
def test_repetition_dominated_partial_is_not_replayed(self):
- """A looped partial must not seed the correction's next API request."""
+ """A looped partial must not seed the correction's next API request (#112764): neither
+ the replayed correction nor the alternation placeholder carries the bytes; the model
+ is told the reply degenerated instead."""
from agent.conversation_loop import _apply_active_turn_redirect
+ from agent.repetition_guard import REPETITION_LOOP_INTERRUPTED
repeated = ("The same degenerate partial response keeps repeating without progress.\n" * 10)
agent = _bare_agent()
@@ -201,9 +204,15 @@ class TestActiveTurnRedirectCheckpoint:
_apply_active_turn_redirect(agent, messages, "Change course.")
- replayed = messages[-1]["api_content"]
+ placeholder, correction = messages[-2], messages[-1]
+ replayed = correction["api_content"]
assert repeated not in replayed
assert "Visible response before the interruption:" not in replayed
+ assert REPETITION_LOOP_INTERRUPTED in replayed
+ assert placeholder["role"] == "assistant"
+ assert placeholder["display_kind"] == "hidden"
+ assert repeated not in (placeholder.get("content") or "")
+ assert repeated not in (placeholder.get("api_content") or "")
def test_ordinary_partial_remains_replayable(self):
"""Useful interrupted text remains available to the corrected request."""
diff --git a/tests/agent/test_turn_api_call_interrupt.py b/tests/agent/test_turn_api_call_interrupt.py
new file mode 100644
index 00000000000..e8163573c91
--- /dev/null
+++ b/tests/agent/test_turn_api_call_interrupt.py
@@ -0,0 +1,57 @@
+"""Tests for ``agent/turn_api_call.py::handle_api_interrupt`` — the plain (non-redirect)
+interrupt that lands mid provider call and records the streamed partial as the interrupted
+assistant row."""
+from __future__ import annotations
+
+import threading
+import time
+
+from agent.agent_runtime_helpers import _INTERRUPTED_PLACEHOLDER
+from agent.repetition_guard import REPETITION_LOOP_INTERRUPTED
+from agent.turn_api_call import handle_api_interrupt
+from agent.turn_retry_state import TurnRetryState
+from run_agent import AIAgent
+
+
+def _bare_agent(streamed: str) -> AIAgent:
+ agent = object.__new__(AIAgent)
+ agent._pending_redirect = None
+ agent._pending_redirect_lock = threading.Lock()
+ agent._interrupt_requested = False
+ agent._interrupt_message = None
+ agent._current_streamed_assistant_text = streamed
+ agent._strip_think_blocks = lambda content: content
+ agent.quiet_mode = True
+ agent.log_prefix = ""
+ agent.thinking_callback = None
+ agent._print_fn = lambda *args, **kwargs: None
+ agent._persist_session = lambda *args, **kwargs: None
+ return agent
+
+
+def _interrupt(streamed: str):
+ messages = [{"role": "user", "content": "start"}]
+ verdict = handle_api_interrupt(
+ _bare_agent(streamed), _retry=TurnRetryState(), thinking_spinner=None, messages=messages,
+ conversation_history=[], api_start_time=time.time(), interrupted=False, final_response=None,
+ )
+ return messages, verdict
+
+
+def test_repetition_dominated_partial_is_not_kept_as_the_interrupted_row():
+ """A looped partial replayed as the interrupted assistant row re-seeds the loop on the next
+ turn (#112764): the row keeps the neutral placeholder and the user is told what happened."""
+ looped = "I. " * 1941
+
+ messages, verdict = _interrupt(looped)
+
+ assert (messages[-1]["role"], messages[-1]["content"]) == ("assistant", _INTERRUPTED_PLACEHOLDER)
+ assert verdict.final_response == REPETITION_LOOP_INTERRUPTED
+ assert "I. I. I." not in verdict.final_response
+
+
+def test_ordinary_partial_is_kept_as_the_interrupted_row():
+ messages, verdict = _interrupt("Visible draft.")
+
+ assert (messages[-1]["role"], messages[-1]["content"]) == ("assistant", "Visible draft.")
+ assert verdict.final_response == "Visible draft."