Skip to content

The agent that grows with you

fix(agent): retain delivered partial output on retry-exhausted 429/network errors

finn763e947f60689b7
diff --git a/agent/turn_recovery.py b/agent/turn_recovery.py
index 1e2eff9b506..36effa52c9c 100644
--- a/agent/turn_recovery.py
+++ b/agent/turn_recovery.py
@@ -773,6 +773,50 @@ def _failed_turn_result(final_response: str, messages: Any, api_call_count: int,
}
+def _recover_delivered_partial_text(agent: Any, messages: Any) -> str:
+ """Visible assistant text already delivered this turn ("" when none).
+
+ ``build_api_request`` resets ``_current_streamed_assistant_text`` on every
+ attempt, so after a mid-stream death + continuation + pre-stream 429 the
+ live accumulator is empty and the only record is the
+ ``_length_continuation_fragment`` rows the truncation path appended (#119001).
+ """
+ try:
+ _live = getattr(agent, "_current_streamed_assistant_text", "") or ""
+ except Exception:
+ _live = ""
+ if isinstance(_live, str) and _live.strip():
+ return _live.strip()
+ _parts = [
+ m["content"].strip() for m in messages or ()
+ if isinstance(m, dict) and m.get("_length_continuation_fragment")
+ and isinstance(m.get("content"), str) and m["content"].strip()
+ ]
+ if not _parts:
+ return ""
+ # Same glue as _join_truncated_parts: newline where two parts would stick.
+ _joined = ""
+ for _part in _parts:
+ if _joined and not _joined[-1].isspace() and not _part[0].isspace():
+ _joined += "\n"
+ _joined += _part
+ return _joined.strip()
+
+
+def _with_delivered_partial(final_response: str, error_summary: str, agent: Any, messages: Any) -> tuple:
+ """Prepend delivered partial text to a terminal error body ("" unchanged).
+
+ Returns ``(final_response, keep_partial)``; callers set ``result["partial"]``
+ when ``keep_partial`` so the gateway emits ``payload.partial`` and surfaces
+ retain the bubble instead of clearing it. ``final_response`` must stay
+ distinct from ``error`` — that inequality is the retention contract.
+ """
+ _delivered = _recover_delivered_partial_text(agent, messages)
+ if not _delivered or _delivered.strip() == (error_summary or "").strip():
+ return final_response, False
+ return f"{_delivered}\n\n{final_response}", True
+
+
def limit_reset_epoch(agent: Any, api_error: Exception) -> Optional[float]:
"""Epoch seconds when the provider says its limit lifts (Retry-After header, ``resets_at`` /
``retry_after`` body fields, "try again in N" text) — the same datum the backoff honours."""
@@ -1043,14 +1087,19 @@ def nonretryable_client_error_result(
classified, provider=provider, model=model, summary=_nonretryable_summary,
prefix_suggestion=_prefix_suggestion,
)
- result = _failed_turn_result(_final_response, messages, api_call_count, _nonretryable_summary)
# Same verdict fields as the max-retries path: without them the UI descriptor
# (agent/error_surface.py) reads a rejected OAuth token as a retryable
# "Provider error" and offers Retry instead of a re-login.
+ _final_response, _keep_partial = _with_delivered_partial(
+ _final_response, _nonretryable_summary, agent, messages,
+ )
+ result = _failed_turn_result(_final_response, messages, api_call_count, _nonretryable_summary)
result.update({
"failure_reason": classified.reason.value,
"failure_retryable": bool(classified.retryable),
})
+ if _keep_partial:
+ result["partial"] = True
_stamp_limit_reset(result, agent, api_error)
if _welcome_hint and (_kind := _welcome_surface_kind(classified)):
# The card form: the desktop renders the sign-in as a button, so no "To sign in" tail.
@@ -1190,6 +1239,15 @@ def max_retries_exhausted_result(
# Present only for billing walls: (provider, billing_url, is_nous, message).
"billing_block": _billing_block,
})
+ # Retry-exhaustion after partial delivery (#119001): the text was already
+ # shown, so keep it as the reply (marked failed) instead of an error-only
+ # turn — the gateway flags ``partial`` and surfaces retain the bubble.
+ _final_response, _keep_partial = _with_delivered_partial(
+ _final_response, _final_summary, agent, messages,
+ )
+ if _keep_partial:
+ result["final_response"] = _final_response
+ result["partial"] = True
_stamp_limit_reset(result, agent, api_error)
if _free_tier_kind:
_stamp_free_tier(result, _free_tier_kind, (
diff --git a/tests/agent/test_retry_exhaustion_partial_retention.py b/tests/agent/test_retry_exhaustion_partial_retention.py
new file mode 100644
index 00000000000..759f6b9b29d
--- /dev/null
+++ b/tests/agent/test_retry_exhaustion_partial_retention.py
@@ -0,0 +1,123 @@
+"""#119001: a 429 / network error that exhausts retries AFTER partial output was
+delivered must retain that output instead of ending the turn error-only.
+
+Repro: attempt 1 streams text then dies mid-stream (partial-stub path appends a
+``_length_continuation_fragment`` + nudge to ``messages``); the continuation
+attempt 429s before the stream starts and every retry re-hits the limit.
+``build_api_request`` resets ``_current_streamed_assistant_text`` per attempt,
+so the only record of the delivered text is the fragment rows — the terminal
+builders below must recover it, flag ``partial``, and keep ``final_response``
+distinct from ``error`` (the gateway/desktop retention contract).
+"""
+from __future__ import annotations
+
+from agent.error_classifier import classify_api_error
+from agent.turn_recovery import (
+ max_retries_exhausted_result,
+ nonretryable_client_error_result,
+)
+
+
+class _Agent:
+ log_prefix = ""
+ verbose = False
+ verbose_logging = False
+ provider = "openrouter"
+ model = "m"
+ base_url = "https://openrouter.ai/api/v1"
+ _current_streamed_assistant_text = ""
+
+ def _summarize_api_error(self, error):
+ return str(error)
+
+ def _has_pending_fallback(self):
+ return False
+
+ def _try_activate_fallback(self, **_kw):
+ return False
+
+ def __getattr__(self, name):
+ return lambda *args, **kwargs: None
+
+
+class _Http(Exception):
+ def __init__(self, status_code, message):
+ super().__init__(message)
+ self.status_code = status_code
+
+
+PARTIAL = "Here is the first half of the report, already shown to the user."
+
+
+def _messages_with_fragment():
+ return [
+ {"role": "user", "content": "write a long report"},
+ {
+ "role": "assistant",
+ "content": PARTIAL,
+ "_length_continuation_fragment": True,
+ },
+ {
+ "role": "user",
+ "content": "continue where you left off",
+ "_length_continuation_nudge": True,
+ },
+ ]
+
+
+def _exhausted(messages, agent=None):
+ error = _Http(429, "HTTP 429: RequestBurstTooFast — slow down traffic growth")
+ classified = classify_api_error(error, provider="openrouter", model="m")
+ assert classified.reason.value == "rate_limit"
+ return max_retries_exhausted_result(
+ agent or _Agent(), error, classified, max_retries=3, is_rate_limited=True,
+ error_msg=str(error).lower(), api_kwargs=None, api_messages=[], messages=messages,
+ conversation_history=None, api_call_count=3, approx_tokens=10, provider="openrouter",
+ base_url="https://openrouter.ai/api/v1", model="m",
+ )
+
+
+def test_exhausted_429_keeps_delivered_partial():
+ result = _exhausted(_messages_with_fragment())
+ assert result.get("partial") is True
+ assert PARTIAL in result["final_response"]
+ # Gateway retention contract: final must differ from the error string.
+ assert result["final_response"].strip() != str(result["error"]).strip()
+ assert result["failure_reason"] == "rate_limit"
+ assert result["failed"] is True
+
+
+def test_exhausted_429_without_partial_is_unchanged():
+ result = _exhausted([])
+ assert "partial" not in result
+ assert "/retry" in result["final_response"]
+ assert result["failure_reason"] == "rate_limit"
+
+
+def test_exhausted_429_live_accumulator_counts_as_delivered():
+ agent = _Agent()
+ agent._current_streamed_assistant_text = "fresh streamed text"
+ result = _exhausted([], agent=agent)
+ assert result.get("partial") is True
+ assert "fresh streamed text" in result["final_response"]
+
+
+def test_whitespace_only_fragment_is_not_partial():
+ messages = _messages_with_fragment()
+ messages[1] = dict(messages[1], content=" ")
+ result = _exhausted(messages)
+ assert "partial" not in result
+
+
+def test_nonretryable_terminal_keeps_delivered_partial():
+ error = _Http(400, "HTTP 400: Bad request")
+ classified = classify_api_error(error, provider="openrouter", model="m")
+ result = nonretryable_client_error_result(
+ _Agent(), error, classified, status_code=400, api_kwargs=None, api_messages=[],
+ messages=_messages_with_fragment(), conversation_history=None, api_call_count=1,
+ approx_tokens=10, provider="openrouter",
+ base_url="https://openrouter.ai/api/v1", model="m",
+ )
+ assert result.get("partial") is True
+ assert PARTIAL in result["final_response"]
+ assert result["final_response"].strip() != str(result["error"]).strip()