The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: show the long-wait status once per silence, neutrally worded, naming its watchdog
teknium1eee53835b89b
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex f4a250afb73..c700f02c6bd 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -518,27 +518,6 @@ def _estimate_chunk_bytes(chunk: Any) -> int:return size-def _codex_wait_notice_recovery(*, stale_timeout: float, ttfb_enabled: bool, ttfb_timeout: float,- last_event_ts: Optional[float], last_progress_ts: Optional[float],- retry_started_ts: Optional[float], call_start: float, idle_enabled: bool,- idle_timeout: float, idle_requires_progress: bool, elapsed: float) -> str:- """Describe the earliest enabled Codex watchdog on the call timeline."""- deadlines: list[float] = []- if math.isfinite(stale_timeout):- deadlines.append(stale_timeout)- if retry_started_ts is not None:- if ttfb_enabled and math.isfinite(ttfb_timeout):- deadlines.append(max(0.0, retry_started_ts - call_start) + ttfb_timeout)- elif last_event_ts is None:- if ttfb_enabled and math.isfinite(ttfb_timeout):- deadlines.append(ttfb_timeout)- elif (not idle_requires_progress or last_progress_ts is not None) and idle_enabled and math.isfinite(idle_timeout):- deadlines.append(max(0.0, last_event_ts - call_start) + idle_timeout)- if not deadlines or min(deadlines) <= elapsed:- return ""- return f"; auto-reconnect at {int(min(deadlines))}s"--# ── Cross-turn stale-call circuit breaker (#58962) ─────────────────────# A session wedged against an unresponsive provider would otherwise hit the# stale detector on every call forever. ``agent._consecutive_stale_streams``diff --git a/agent/chat_completion_nonstream.py b/agent/chat_completion_nonstream.pyindex 17127b41157..96d3c4a1d34 100644--- a/agent/chat_completion_nonstream.py+++ b/agent/chat_completion_nonstream.py@@ -1,6 +1,7 @@"""Request-local worker lifecycle, watchdog polling, and wait status."""from agent import chat_completion_helpers as h+from agent import chat_completion_wait_notice as wnclass _NonStreamRequest:@@ -40,6 +41,7 @@ class _NonStreamRequest:)self.call_start = h.time.time()self.wait_notice_started_ts = None+ self.wait_notice = wn.WaitNoticeState()self.thread = Nonedef _install_codex_request_token(self) -> None:@@ -134,6 +136,7 @@ class _NonStreamRequest:and activity_ts > self.wait_notice_started_ts):self.agent._emit_wait_notice("")self.wait_notice_started_ts = None+ self.wait_notice.reset()if not heartbeat:returnsilence = self.call_start + elapsed - (@@ -143,23 +146,26 @@ class _NonStreamRequest:"waiting for first stream event after reconnect"if retry_started_ts is not None else "waiting for provider response")return- status = "no response yet"+ phase = "first_event"if retry_started_ts is not None:- status = "no response after reconnect"+ phase = "reconnect"elif last_event_ts is not None:- status = "no stream events"- recovery = h._codex_wait_notice_recovery(stale_timeout=wd.stale_timeout,+ phase = "post_event"+ watchdog = wn.codex_watchdog_deadline(stale_timeout=wd.stale_timeout,ttfb_enabled=wd.ttfb_enabled, ttfb_timeout=wd.ttfb_timeout,last_event_ts=last_event_ts, last_progress_ts=last_progress_ts,retry_started_ts=retry_started_ts,call_start=self.call_start, idle_enabled=wd.idle_enabled, idle_timeout=wd.idle_timeout,idle_requires_progress=wd.idle_requires_progress,elapsed=elapsed)- if recovery and activity_ts is not None:- recovery += " total elapsed"- self.agent._emit_wait_notice(- f"⏳ waiting on {self.api_kwargs.get('model', 'the provider')} — "- f"{int(silence)}s with {status} (provider may be slow or overloaded{recovery})")+ # One neutral notice per silence; repeating it every heartbeat made+ # healthy long calls read as provider trouble (#92550).+ near = watchdog is not None and watchdog[1] <= wn.NEAR_DEADLINE_SECS+ if not self.wait_notice.should_emit(phase, watchdog):+ self.agent._touch_activity(f"waiting for provider response ({int(silence)}s, {phase})")+ return+ self.agent._emit_wait_notice(wn.wait_notice_text(+ self.api_kwargs.get('model', 'the provider'), silence, phase, watchdog, near=near))self.wait_notice_started_ts = self.call_start + elapsedexcept Exception:h.logger.debug("wait-notice construction failed", exc_info=True)diff --git a/agent/chat_completion_stream_monitor.py b/agent/chat_completion_stream_monitor.pyindex e0c669a7806..145e412bcd4 100644--- a/agent/chat_completion_stream_monitor.py+++ b/agent/chat_completion_stream_monitor.py@@ -3,6 +3,7 @@import timefrom types import SimpleNamespace+from agent import chat_completion_wait_notice as wnfrom agent.model_metadata import is_local_endpoint@@ -22,6 +23,7 @@ class StreamingWaitMonitor:_load_notice = _managed_local_load_notice(self.agent, self.api_kwargs)if _load_notice is not None:m.wait_notice_started_ts = None # The local loader now owns the display.+ m.wait_notice.reset()self.agent._emit_wait_notice(_load_notice)self.agent._touch_activity("local model loading")m.load_notice_shown, m.load_notice_misses, m.last_heartbeat = True, 0, now # loading IS liveness@@ -38,13 +40,19 @@ class StreamingWaitMonitor:"""Gateway inactivity heartbeat: the start-to-first-chunk gap (thinking,local prefill) can exceed the gateway timeout."""if waiting_secs >= 60.0:- # No chunks for 60s+: say WHAT the wait is and WHEN recovery kicks in.+ # No chunks for 60s+: say WHAT the wait is and WHEN recovery kicks in —+ # once per silence, not every heartbeat (#92550).stale = self._stream_stale_timeout- _recovery = f"; auto-reconnect at {int(stale)}s" if stale is not None and stale != float("inf") else ""+ watchdog = ("stream stale", stale - waiting_secs) if stale is not None and stale != float("inf") else None+ diag = getattr(getattr(self, "clients", None), "diag", None)+ phase = "post_chunk" if isinstance(diag, dict) and diag.get("first_chunk_at") else "first_chunk"+ near = watchdog is not None and watchdog[1] <= wn.NEAR_DEADLINE_SECS+ if not self._mon.wait_notice.should_emit(phase, watchdog):+ self.agent._touch_activity(f"waiting for stream response ({waiting_secs}s, {phase})")+ returnself._mon.wait_notice_started_ts = self._mon.last_heartbeat- self.agent._emit_wait_notice(- f"⏳ waiting on {self.api_kwargs.get('model', 'the provider')} — no stream output for {waiting_secs}s "- f"(provider may be slow or overloaded, or the model is thinking{_recovery})")+ self.agent._emit_wait_notice(wn.wait_notice_text(+ self.api_kwargs.get('model', 'the provider'), waiting_secs, phase, watchdog, near=near))else:# Chunks are flowing — keep the tracker fresh, leave the display alone.self.agent._touch_activity(f"waiting for stream response ({waiting_secs}s, no chunks yet)")@@ -54,6 +62,7 @@ class StreamingWaitMonitor:self._mon = SimpleNamespace(last_heartbeat=time.time(), last_load_poll=0.0,load_notice_shown=False, load_notice_misses=0, wait_notice_started_ts=None,+ wait_notice=wn.WaitNoticeState(),)_is_local_base = bool(self.agent.base_url) and is_local_endpoint(self.agent.base_url)while not self._call_done.is_set():@@ -67,12 +76,14 @@ class StreamingWaitMonitor:and self.last_chunk_time["t"] > self._mon.wait_notice_started_ts):self.agent._emit_wait_notice("")self._mon.wait_notice_started_ts = None+ self._mon.wait_notice.reset()if _hb_now - self._mon.last_heartbeat >= _HEARTBEAT_INTERVAL:self._mon.last_heartbeat = _hb_nowself._heartbeat(int(_hb_now - self.last_chunk_time["t"]))_stale_elapsed = time.time() - self.last_chunk_time["t"]if _stale_elapsed > self._stream_stale_timeout:self._mon.wait_notice_started_ts = None # Reconnect status has its own owner.+ self._mon.wait_notice.reset()self._kill_stale_stream(_stale_elapsed)if self.agent._interrupt_requested:self._abort_for_interrupt(_stale_elapsed)diff --git a/agent/chat_completion_wait_notice.py b/agent/chat_completion_wait_notice.pynew file mode 100644index 00000000000..3c51ffefcc9--- /dev/null+++ b/agent/chat_completion_wait_notice.py@@ -0,0 +1,87 @@+"""Operator-facing wait notice for long provider silences (#92550).++The 30s heartbeat is gateway liveness, not a warning. Once a request has been+silent past the notice threshold this module decides WHAT the status line says+(neutral: which phase of the wait we are in, which watchdog would reconnect and+when) and WHETHER to rewrite it: once when the silence starts, again only when+the wait phase changes or a watchdog deadline is near. Watchdog thresholds and+retry policy live with the watchdogs; this is presentation only.+"""++import math+from typing import Optional++NEAR_DEADLINE_SECS = 15.0++_PHASE_TEXT = {+ # Codex Responses (non-stream request path)+ "first_event": "{n}s waiting for the first provider event",+ "reconnect": "{n}s waiting for the first provider event after reconnect",+ "post_event": "provider stream active; {n}s without stream events",+ # Chat-completions streaming path+ "first_chunk": "{n}s waiting for the first stream chunk",+ "post_chunk": "stream open; {n}s without stream output",+}+++def wait_notice_text(model: str, silence_secs: float, phase: str,+ watchdog: Optional[tuple[str, float]] = None, *, near: bool = False) -> str:+ """One neutral status line. ``watchdog`` is ``(label, seconds_until_it_fires)``."""+ lead = "still waiting on" if near else "waiting on"+ text = f"⏳ {lead} {model} — " + _PHASE_TEXT[phase].format(n=int(silence_secs))+ if watchdog is not None:+ label, remaining = watchdog+ text += f" (auto-reconnect: {label} watchdog in {max(0, int(remaining))}s)"+ return text+++def codex_watchdog_deadline(*, stale_timeout: float, ttfb_enabled: bool, ttfb_timeout: float,+ last_event_ts: Optional[float], last_progress_ts: Optional[float],+ retry_started_ts: Optional[float], call_start: float, idle_enabled: bool,+ idle_timeout: float, idle_requires_progress: bool, elapsed: float) -> Optional[tuple[str, float]]:+ """Earliest enabled Codex watchdog as ``(label, seconds_until_it_fires)``; None when+ none applies (disabled/infinite, or its deadline already passed)."""+ deadlines: list[tuple[str, float]] = []+ if math.isfinite(stale_timeout):+ deadlines.append(("wall-clock stale", stale_timeout))+ if retry_started_ts is not None:+ if ttfb_enabled and math.isfinite(ttfb_timeout):+ deadlines.append(("TTFB", max(0.0, retry_started_ts - call_start) + ttfb_timeout))+ elif last_event_ts is None:+ if ttfb_enabled and math.isfinite(ttfb_timeout):+ deadlines.append(("TTFB", ttfb_timeout))+ elif (not idle_requires_progress or last_progress_ts is not None) and idle_enabled and math.isfinite(idle_timeout):+ deadlines.append(("stream idle", max(0.0, last_event_ts - call_start) + idle_timeout))+ if not deadlines:+ return None+ label, deadline = min(deadlines, key=lambda d: d[1])+ if deadline <= elapsed:+ return None+ return label, deadline - elapsed+++class WaitNoticeState:+ """Per-request memory of what the status line currently shows.++ ``should_emit`` is True for the first notice of a silence, for a phase or+ watchdog change, and once when the applicable deadline comes within+ ``NEAR_DEADLINE_SECS``; every other heartbeat only touches liveness.+ ``reset`` when activity resumes so the next silence gets a fresh notice.+ """++ def __init__(self) -> None:+ self.reset()++ def reset(self) -> None:+ self.phase: Optional[str] = None+ self.watchdog_label: Optional[str] = None+ self.near_shown = False++ def should_emit(self, phase: str, watchdog: Optional[tuple[str, float]]) -> bool:+ label = watchdog[0] if watchdog is not None else None+ near = watchdog is not None and watchdog[1] <= NEAR_DEADLINE_SECS+ emit = self.phase != phase or self.watchdog_label != label or (near and not self.near_shown)+ self.phase, self.watchdog_label = phase, label+ if near:+ self.near_shown = True+ return emitdiff --git a/tests/agent/test_codex_ttfb_watchdog.py b/tests/agent/test_codex_ttfb_watchdog.pyindex 62b2c50ae73..1609a0ff4d5 100644--- a/tests/agent/test_codex_ttfb_watchdog.py+++ b/tests/agent/test_codex_ttfb_watchdog.py@@ -406,9 +406,9 @@ def test_wait_notice_omits_reconnect_when_all_deadlines_are_non_finite(stale_timeout,):"""A disabled watchdog must not be advertised as a future reconnect."""- from agent import chat_completion_helpers as h+ from agent import chat_completion_wait_notice as wn- recovery = h._codex_wait_notice_recovery(+ recovery = wn.codex_watchdog_deadline(stale_timeout=stale_timeout,ttfb_enabled=False,ttfb_timeout=float("nan"),@@ -422,7 +422,7 @@ def test_wait_notice_omits_reconnect_when_all_deadlines_are_non_finite(elapsed=30.0,)- assert recovery == ""+ assert recovery is None@@ -527,9 +527,11 @@ def test_wait_notice_formatting_error_does_not_abort_request(monkeypatch):"_dispatch_nonstreaming_api_request",lambda *_args, **_kwargs: response,)+ from agent import chat_completion_wait_notice as wn+monkeypatch.setattr(- h,- "_codex_wait_notice_recovery",+ wn,+ "codex_watchdog_deadline",lambda **_kwargs: (_ for _ in ()).throw(ValueError("bad display state")),)diff --git a/tests/agent/test_nonstream_wait_notice.py b/tests/agent/test_nonstream_wait_notice.pyindex a27e6b4549a..2de95bdc544 100644--- a/tests/agent/test_nonstream_wait_notice.py+++ b/tests/agent/test_nonstream_wait_notice.py@@ -7,6 +7,7 @@ import pytestfrom agent import chat_completion_helpers as hfrom agent.chat_completion_nonstream import _NonStreamRequest+from agent.chat_completion_wait_notice import WaitNoticeStatedef _request():@@ -29,6 +30,7 @@ def _request():retry_started_ts=None,)request.wait_notice_started_ts = None+ request.wait_notice = WaitNoticeState()request.result = {"error": None, "response": None}return request, notices, touches@@ -38,12 +40,12 @@ def _request():[(59.0, 59.0, None, None), # Reasoning/text/tool arguments still arriving.(59.0, None, None, None), # Lifecycle traffic is not transport silence either.- (0.0, 0.0, None, "60s with no stream events"),- (0.0, None, None, "60s with no stream events"),+ (0.0, 0.0, None, "provider stream active; 60s without stream events"),+ (0.0, None, None, "provider stream active; 60s without stream events"),(1.0, None, None, None), # 59 seconds of silence is still quiet.- (None, None, None, "60s with no response yet"),+ (None, None, None, "60s waiting for the first provider event"),(10.0, 10.0, 59.0, None), # Internal reconnect gets a fresh first-event wait.- (0.0, 0.0, 0.0, "60s with no response after reconnect"),+ (0.0, 0.0, 0.0, "60s waiting for the first provider event after reconnect"),(0.0, 0.0, 1.0, None),],)@@ -66,7 +68,7 @@ def test_wait_notice_tracks_current_attempt_silence(event, progress, retry, expeelse:assert len(notices) == 1assert expected in notices[0]- assert "auto-reconnect at" in notices[0]+ assert "auto-reconnect:" in notices[0]def test_resumed_events_clear_only_this_requests_wait_notice(monkeypatch):@@ -95,6 +97,6 @@ def test_resumed_events_clear_only_this_requests_wait_notice(monkeypatch):monkeypatch.setattr(h.time, "time", lambda: 1000.0 + ticks[0] * 0.3)assert request.run() is sentinelassert len(notices) == 2- assert "no response yet" in notices[0]+ assert "waiting for the first provider event" in notices[0]# Nonempty thinking.delta payloads enter TUI reasoning history.assert notices[1] == ""diff --git a/tests/agent/test_wait_notice_cadence.py b/tests/agent/test_wait_notice_cadence.pynew file mode 100644index 00000000000..89b6020dc98--- /dev/null+++ b/tests/agent/test_wait_notice_cadence.py@@ -0,0 +1,81 @@+"""The long-wait status line is one neutral notice per silence, not a 30s warning drumbeat (#92550).++Both builders (Codex non-stream request, chat-completions stream monitor) name the wait+phase and the watchdog that would reconnect; they rewrite the line only on a phase change+or when that deadline is near.+"""+import threading+from types import SimpleNamespace++from agent import chat_completion_helpers as h+from agent.chat_completion_nonstream import _NonStreamRequest+from agent.chat_completion_wait_notice import WaitNoticeState++WARNING_COPY = ("provider may be slow", "no response yet")+++def _nonstream_request(ttfb_timeout=300.0):+ request = _NonStreamRequest.__new__(_NonStreamRequest)+ notices, touches = [], []+ request.agent = SimpleNamespace(_emit_wait_notice=notices.append, _touch_activity=touches.append,+ _interrupt_requested=False)+ request.api_kwargs = {"model": "test-model"}+ request.call_start = 1000.0+ request.wd = SimpleNamespace(codex=True, stale_timeout=600.0, ttfb_enabled=True, ttfb_timeout=ttfb_timeout,+ idle_enabled=True, idle_timeout=180.0, idle_requires_progress=False)+ request.codex_watchdog_state = SimpleNamespace(lock=threading.Lock(), last_event_ts=None,+ last_progress_ts=None, retry_started_ts=None)+ request.wait_notice_started_ts = None+ request.wait_notice = WaitNoticeState()+ request.result = {"error": None, "response": None}+ return request, notices, touches+++def test_nonstream_notice_once_per_phase_then_near_deadline_only():+ request, notices, touches = _nonstream_request(ttfb_timeout=300.0)+ for heartbeat in range(1, 10): # 30s .. 270s of silence, no event ever+ request._emit_wait_notice(30.0 * heartbeat)+ # 60s: first notice; 90..270s: liveness touches only, until the TTFB deadline is within 15s.+ assert [n for n in notices if n] == [+ "⏳ waiting on test-model — 60s waiting for the first provider event (auto-reconnect: TTFB watchdog in 240s)",+ ]+ assert touches, "gateway liveness heartbeat survives the quiet heartbeats"+ request._emit_wait_notice(290.0)+ assert notices[-1].startswith("⏳ still waiting on test-model — 290s waiting for the first provider event")+ assert "TTFB watchdog in 10s" in notices[-1]+ # A first event moves the wait into a new phase: clear, then one post-event notice naming stream idle.+ request.codex_watchdog_state.last_event_ts = 1295.0+ request._emit_wait_notice(300.0, heartbeat=False)+ assert notices[-1] == ""+ request._emit_wait_notice(360.0)+ request._emit_wait_notice(390.0)+ assert [n for n in notices[notices.index("") + 1:]] == [+ "⏳ waiting on test-model — provider stream active; 65s without stream events "+ "(auto-reconnect: stream idle watchdog in 115s)",+ ]+ assert not any(copy in n for n in notices for copy in WARNING_COPY)+++def test_stream_monitor_notice_does_not_repeat_every_heartbeat():+ call = h._StreamingCall.__new__(h._StreamingCall)+ notices, touches = [], []+ call.agent = SimpleNamespace(_emit_wait_notice=notices.append, _touch_activity=touches.append)+ call.api_kwargs = {"model": "test-model"}+ call._stream_stale_timeout = 180.0+ call.clients = SimpleNamespace(diag={"first_chunk_at": None})+ call._mon = SimpleNamespace(last_heartbeat=1000.0, wait_notice_started_ts=None, wait_notice=WaitNoticeState())+ for secs in (30, 60, 90, 120, 150):+ call._mon.last_heartbeat = 1000.0 + secs+ call._heartbeat(secs)+ assert notices == [+ "⏳ waiting on test-model — 60s waiting for the first stream chunk (auto-reconnect: stream stale watchdog in 120s)",+ ]+ assert len(touches) >= 3 # 30s (pre-threshold) + the suppressed 90/120/150s heartbeats+ call._heartbeat(170) # within 15s of the stale kill: one "still waiting" update+ assert notices[-1].startswith("⏳ still waiting on test-model — 170s waiting for the first stream chunk")+ # Output that stopped after chunks arrived is a different phase, worded as such.+ call._mon.wait_notice.reset()+ call.clients.diag["first_chunk_at"] = 1005.0+ call._heartbeat(60)+ assert notices[-1].startswith("⏳ waiting on test-model — stream open; 60s without stream output")+ assert not any(copy in n for n in notices for copy in WARNING_COPY)diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex 1679ee838c4..e4dd3a48a4c 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -1276,7 +1276,7 @@ The **stale non-stream detection** kills non-streaming calls that produce no resThis budget bounds every non-streaming call. A provider that accepts a request and then goes silent — connection held open, no bytes, no error — is aborted at the stale timeout and retried, rather than hanging until the much longer socket read timeout (or, for an unattended cron run, until something external kills the process).-The periodic provider-wait notice appears only after at least **60 seconds of silence**. The Codex Responses **waiting status** describes silence, not total generation time: active stream events (including reasoning) keep it quiet. If events stop, it reports time without stream events instead of claiming no response has arrived; the notice clears when events resume. When a reconnect starts a fresh first-event watchdog phase, the waiting status follows that phase. This display behavior does not extend the separate wall-clock stale-call budget or change watchdog timeouts. Chat-completion streams likewise clear their silence warning promptly when chunks resume, without replacing a local model-loading status.+The periodic provider-wait notice appears only after at least **60 seconds of silence**. The Codex Responses **waiting status** describes silence, not total generation time: active stream events (including reasoning) keep it quiet. If events stop, it reports time without stream events instead of claiming no response has arrived; the notice clears when events resume. When a reconnect starts a fresh first-event watchdog phase, the waiting status follows that phase. This display behavior does not extend the separate wall-clock stale-call budget or change watchdog timeouts. The status is shown once per silence (after 60s), in neutral wording that names the wait phase (`waiting for the first provider event` vs `provider stream active; Ns without stream events`) and the watchdog that would reconnect (`TTFB`, `stream idle`, or `wall-clock stale`) with the seconds left before it fires; it is rewritten only when the phase changes or that deadline is near, not on every 30s liveness heartbeat. Chat-completion streams follow the same rule (`waiting for the first stream chunk` / `stream open; Ns without stream output`, `stream stale` watchdog) and likewise clear their silence notice promptly when chunks resume, without replacing a local model-loading status.Cron jobs and delegated subagents stream too. They run the request inline on their own thread (the interrupt worker other sessions use wedges inside the gateway's nested thread pools), but the wire request is still `stream: true`, so the **stale stream detection** budget above governs them — every token counts as liveness, so a reasoning model that thinks for minutes is not mistaken for a hung provider, and edge proxies that kill silent connections keep seeing bytes.