Skip to content

The agent that grows with you

refactor(agent): isolate streaming wait monitor phase

Tekniumba395af50f68
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py
index 987bae36962..2b10036d90f 100644
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@ -27,6 +27,7 @@ from hermes_cli.timeouts import get_provider_request_timeout, get_provider_stale
from hermes_constants import PARTIAL_STREAM_STUB_ID, FINISH_REASON_LENGTH
from agent.error_classifier import (FailoverReason, PROVIDER_STREAM_NON_JSON_ERROR_CODE)
from agent.errors import EmptyStreamError
+from agent.chat_completion_stream_monitor import StreamingWaitMonitor
from agent.fast_mode import effective_request_overrides
from agent.turn_context import substitute_api_content
from agent.gemini_native_adapter import is_native_gemini_base_url
@@ -2549,7 +2550,7 @@ class _ToolCallAccumulator:
return None
-class _StreamingCall:
+class _StreamingCall(StreamingWaitMonitor):
"""One streaming request on the chat_completions / anthropic_messages wire.
State shared between the request worker and the poll-loop monitor (heartbeat,
stale kill, interrupt abort) lives on the instance, mutated from both threads."""
@@ -3224,44 +3225,6 @@ class _StreamingCall:
finally:
self._call_done.set()
- def _poll_local_load_notice(self, now: float) -> bool:
- """Managed local server: surface a cold model's weight-load progress
- instead of the 30s "provider may be slow" copy. Polled ~1s only while no
- REAL chunk arrived for 2s+ (never during healthy token flow); in-memory,
- no network. True while loading = heartbeat liveness, skip the rest of
- this iteration (the stale detector's local floor dwarfs any load)."""
- m = self._mon
- if now - self.last_chunk_time["t"] < 2.0 or now - m.last_load_poll < 1.0:
- return False
- m.last_load_poll = now
- _load_notice = _managed_local_load_notice(self.agent, self.api_kwargs)
- if _load_notice is not None:
- 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
- return True
- if m.load_notice_shown:
- # One missed sample is routine (probe timeout under load); clearing on it strobed the line.
- m.load_notice_misses += 1
- if m.load_notice_misses >= 3:
- m.load_notice_shown, m.load_notice_misses = False, 0
- self.agent._emit_wait_notice("")
- return False
-
- def _heartbeat(self, waiting_secs: int, interval: float) -> None:
- """Gateway inactivity heartbeat: the start-to-first-chunk gap (thinking,
- local prefill) can exceed the gateway timeout."""
- if waiting_secs >= interval:
- # No chunks for 30s+: say WHAT the wait is and WHEN recovery kicks in.
- stale = self._stream_stale_timeout
- _recovery = f"; auto-reconnect at {int(stale)}s" if stale is not None and stale != float("inf") else ""
- self.agent._emit_wait_notice(
- f"⏳ waiting on {self.api_kwargs.get('model', 'the provider')} — {waiting_secs}s with no output yet "
- f"(provider may be slow or overloaded, or the model is thinking{_recovery})")
- 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)")
-
def _kill_stale_stream(self, elapsed: float) -> None:
"""SSE pings but no chunks: cancel the attempt and abort the request-local
client so the retry loop opens a fresh one. The shared client is never
@@ -3305,25 +3268,6 @@ class _StreamingCall:
_join_worker_for_relay_teardown(self.worker, label="Streaming")
self._monitor_interrupted["yes"] = True
- def _monitor_loop(self) -> None:
- _HEARTBEAT_INTERVAL = 30.0 # seconds between gateway activity touches
- self._mon = SimpleNamespace(last_heartbeat=time.time(), last_load_poll=0.0, load_notice_shown=False, load_notice_misses=0)
- _is_local_base = bool(self.agent.base_url) and is_local_endpoint(self.agent.base_url)
- while not self._call_done.is_set():
- self._call_done.wait(timeout=0.3)
- _hb_now = time.time()
- if _is_local_base and self._poll_local_load_notice(_hb_now):
- continue
- if _hb_now - self._mon.last_heartbeat >= _HEARTBEAT_INTERVAL:
- self._mon.last_heartbeat = _hb_now
- self._heartbeat(int(_hb_now - self.last_chunk_time["t"]), _HEARTBEAT_INTERVAL)
- _stale_elapsed = time.time() - self.last_chunk_time["t"]
- if _stale_elapsed > self._stream_stale_timeout:
- self._kill_stale_stream(_stale_elapsed)
- if self.agent._interrupt_requested:
- self._abort_for_interrupt(_stale_elapsed)
- return
-
# ── orchestration ───────────────────────────────────────────────────
def _resolve_stale_timeout(self) -> None:
diff --git a/agent/chat_completion_stream_monitor.py b/agent/chat_completion_stream_monitor.py
new file mode 100644
index 00000000000..869cbed870d
--- /dev/null
+++ b/agent/chat_completion_stream_monitor.py
@@ -0,0 +1,68 @@
+"""Display and heartbeat phase of the request-local streaming monitor."""
+
+import time
+from types import SimpleNamespace
+
+from agent.model_metadata import is_local_endpoint
+
+
+class StreamingWaitMonitor:
+ def _poll_local_load_notice(self, now: float) -> bool:
+ """Managed local server: surface a cold model's weight-load progress
+ instead of the 30s "provider may be slow" copy. Polled ~1s only while no
+ REAL chunk arrived for 2s+ (never during healthy token flow); in-memory,
+ no network. True while loading = heartbeat liveness, skip the rest of
+ this iteration (the stale detector's local floor dwarfs any load)."""
+ from agent.chat_completion_helpers import _managed_local_load_notice
+
+ m = self._mon
+ if now - self.last_chunk_time["t"] < 2.0 or now - m.last_load_poll < 1.0:
+ return False
+ m.last_load_poll = now
+ _load_notice = _managed_local_load_notice(self.agent, self.api_kwargs)
+ if _load_notice is not None:
+ 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
+ return True
+ if m.load_notice_shown:
+ # One missed sample is routine (probe timeout under load); clearing on it strobed the line.
+ m.load_notice_misses += 1
+ if m.load_notice_misses >= 3:
+ m.load_notice_shown, m.load_notice_misses = False, 0
+ self.agent._emit_wait_notice("")
+ return False
+
+ def _heartbeat(self, waiting_secs: int, interval: float) -> None:
+ """Gateway inactivity heartbeat: the start-to-first-chunk gap (thinking,
+ local prefill) can exceed the gateway timeout."""
+ if waiting_secs >= interval:
+ # No chunks for 30s+: say WHAT the wait is and WHEN recovery kicks in.
+ stale = self._stream_stale_timeout
+ _recovery = f"; auto-reconnect at {int(stale)}s" if stale is not None and stale != float("inf") else ""
+ self.agent._emit_wait_notice(
+ f"⏳ waiting on {self.api_kwargs.get('model', 'the provider')} — {waiting_secs}s with no output yet "
+ f"(provider may be slow or overloaded, or the model is thinking{_recovery})")
+ 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)")
+
+ def _monitor_loop(self) -> None:
+ _HEARTBEAT_INTERVAL = 30.0 # seconds between gateway activity touches
+ self._mon = SimpleNamespace(last_heartbeat=time.time(), last_load_poll=0.0, load_notice_shown=False, load_notice_misses=0)
+ _is_local_base = bool(self.agent.base_url) and is_local_endpoint(self.agent.base_url)
+ while not self._call_done.is_set():
+ self._call_done.wait(timeout=0.3)
+ _hb_now = time.time()
+ if _is_local_base and self._poll_local_load_notice(_hb_now):
+ continue
+ if _hb_now - self._mon.last_heartbeat >= _HEARTBEAT_INTERVAL:
+ self._mon.last_heartbeat = _hb_now
+ self._heartbeat(int(_hb_now - self.last_chunk_time["t"]), _HEARTBEAT_INTERVAL)
+ _stale_elapsed = time.time() - self.last_chunk_time["t"]
+ if _stale_elapsed > self._stream_stale_timeout:
+ self._kill_stale_stream(_stale_elapsed)
+ if self.agent._interrupt_requested:
+ self._abort_for_interrupt(_stale_elapsed)
+ return
+