The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): count restarts since the last response toward the redirect cap
FroRaut40aa83919e99
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex b88367a7963..d88600832e5 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -1417,10 +1417,10 @@ class _LoopState:failed: bool = Falsecodex_ack_continuations: int = 0length_continue_retries: int = 0- # Per-turn backstop for the refunding restarts (redirect / rebuilt-for-fallback).- # Unlike ``retry_count`` (rebound to 0 each iteration) this accumulates for the whole- # turn so a runaway interrupt/redirect that keeps re-arming a restart flag cannot- # refund the iteration budget forever and hold the turn lease indefinitely.+ # Backstop for the refunding restarts (redirect / rebuilt-for-fallback). Unlike+ # ``retry_count`` (rebound to 0 each iteration) this survives across iterations until a+ # response arrives, so a runaway interrupt/redirect that keeps re-arming a restart flag+ # cannot refund the iteration budget forever and hold the turn lease indefinitely.restart_count: int = 0_outer_error_count: int = 0 # outer-loop exceptions this turn (#92450), see _MAX_OUTER_LOOP_ERRORStruncated_tool_call_retries: int = 0diff --git a/agent/turn_iteration_prep.py b/agent/turn_iteration_prep.pyindex 2ee6cfa30fe..1dbc05282f8 100644--- a/agent/turn_iteration_prep.py+++ b/agent/turn_iteration_prep.py@@ -539,4 +539,9 @@ def apply_retry_restarts(agent._emit_diagnostic_status("❌ The model provider didn't answer after all retries. Send /retry, or switch models with /model.")agent._persist_session(messages, conversation_history)return _verdict("break")+ # A response arrived, so the turn is not stuck re-issuing a cancelled request: start+ # the refunding-restart bound over (restart_count = restarts since the last response).+ # Counting every mid-turn correction for the whole turn ended healthy interactive+ # turns on the (max_retries + 1)th message (#128000).+ restart_count = 0return _verdict("fallthrough")diff --git a/tests/agent/test_run_agent.py b/tests/agent/test_run_agent.pyindex 76c2e4b305b..c9951f58bf2 100644--- a/tests/agent/test_run_agent.py+++ b/tests/agent/test_run_agent.py@@ -3989,6 +3989,52 @@ class TestRunConversation:for message in result["messages"])+ def test_corrections_between_completed_requests_do_not_end_the_turn(self, agent):+ """#128000: follow-ups sent while the model works redirect one request each, with+ tool rounds completing in between. Only back-to-back cancelled requests count+ toward the restart cap, so the fourth message no longer ends the turn."""+ self._setup_agent(agent)+ agent._api_max_retries = 3+ tool_round = _mock_response(+ content="", finish_reason="tool_calls",+ tool_calls=[_mock_tool_call(name="web_search", arguments="{}", call_id="c1")],+ )+ final = _mock_response(content="Launching the audit.", finish_reason="stop")+ # A string is a correction the user sends while that request is in flight.+ script = [+ "why 4 minutes only", tool_round,+ "why only 12 tools limit", tool_round,+ "if it finishes faster then just collect info",+ "also check if any of them are stuck",+ final,+ ]+ calls = 0++ def _fake_api_call(_api_kwargs):+ nonlocal calls+ step = script[calls]+ calls += 1+ if isinstance(step, str):+ assert agent.redirect(step) is True+ raise InterruptedError("request cancelled by redirect")+ return step++ with (+ patch.object(agent, "_interruptible_api_call", side_effect=_fake_api_call),+ patch("model_tools.handle_function_call", return_value="ok"),+ patch.object(agent, "_persist_session"),+ patch.object(agent, "_save_trajectory"),+ patch.object(agent, "_cleanup_task_resources"),+ ):+ result = agent.run_conversation("Run the audit with 50 workers.")++ assert calls == len(script)+ assert result["completed"] is True+ assert result["final_response"] == "Launching the audit."+ assert not result.get("pending_steer")+ corrections = [m["content"] for m in result["messages"] if m["role"] == "user"][1:]+ assert corrections == [step for step in script if isinstance(step, str)]+def test_redirect_from_input_thread_cancels_live_model_request(self, agent):"""Exercise the real cross-thread path used by CLI and gateways."""self._setup_agent(agent)diff --git a/tests/agent/test_turn_iteration_prep.py b/tests/agent/test_turn_iteration_prep.pyindex 39cb320ea83..456bbb96055 100644--- a/tests/agent/test_turn_iteration_prep.py+++ b/tests/agent/test_turn_iteration_prep.py@@ -90,3 +90,38 @@ def test_interrupt_exit_reason_names_the_system_issuer(tool_interrupt_reason, ex"""A watchdog abort must not be recorded as a user stop: the exit reason carries the issuer."""verdict = _interrupted_agent(tool_interrupt_reason)assert (verdict.action, verdict.interrupted, verdict._turn_exit_reason) == ("break", True, expected)+++def _respond(agent, restart_count: int):+ """No restart flag and a response in hand: the iteration proceeds to process it."""+ return apply_retry_restarts(+ agent, _retry=TurnRetryState(), response=SimpleNamespace(), interrupted=False, messages=[],+ conversation_history=[], user_message="hi", api_kwargs={}, current_turn_user_idx=0,+ final_response=None, retry_count=0, max_retries=MAX_RETRIES, api_call_count=1,+ restart_count=restart_count, length_continue_retries=0,+ _preflight_compression_blocked=True, _turn_exit_reason="unknown",+ )++[email protected]("flag", RESTART_FLAGS)+def test_response_between_restarts_resets_the_bound(flag):+ """#128000: the user answering clarify cards / sending follow-ups while the model works+ redirects once per request, with a response in between. The bound is for requests that+ are cancelled over and over, so a response starts it over instead of the whole turn+ sharing ``max_retries`` restarts."""+ agent = _agent()+ restart_count, actions = 0, []+ for _ in range(3): # three rounds of max_retries restarts, each followed by a response+ for _ in range(MAX_RETRIES):+ verdict = _apply(agent, flag, restart_count)+ actions.append(verdict.action)+ restart_count = verdict.restart_count+ verdict = _respond(agent, restart_count)+ assert (verdict.action, verdict.restart_count) == ("fallthrough", 0)+ restart_count = verdict.restart_count+ assert actions == ["continue"] * (3 * MAX_RETRIES)+ assert agent.steered == []+ # Back-to-back restarts with no response in between still hit the cap.+ for _ in range(MAX_RETRIES):+ restart_count = _apply(agent, flag, restart_count).restart_count+ assert _apply(agent, flag, restart_count).action == "break"