"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(progress): carry provider waits and real reasoning events through all consumers
Haozhe Wua9e556053185
diff --git a/README.md b/README.mdindex f16c0f1e7..d3b8083db 100644--- a/README.md+++ b/README.md@@ -1082,7 +1082,7 @@ LANGCHAIN_MODEL_NAME=claude-opus-5-5> **Warning:** Both settings are convenience filters, not a security boundary. `python -c` can still run arbitrary code, and external MCP tools (`mcp_<server>_<tool>`) are not covered by the default prefixes. Live orders stay bound by the mandate gate and kill switch whatever these settings allow.-> **Note:** When Settings shows this provider, it loads the models your Claude Code login can run (cached for 5 minutes; **Load models** refreshes), and the reasoning effort menu offers only the levels the selected model accepts. The chosen level is passed to each `claude -p` call as `--effort`; it does not read or change `~/.claude/settings.json`, and "Provider default" means the model's own default. Base URL, temperature and `MAX_RETRIES` have no effect with this provider, and `TIMEOUT_SECONDS` is raised to at least 600 seconds per decision. Image input is not supported. The CLI returns each decision in one piece, so a decision longer than `VIBE_TRADING_SSE_TIMEOUT` (default 90 seconds) makes the Web UI report a timeout while the run continues; raise that value if you use high effort levels.+> **Note:** When Settings shows this provider, it loads the models your Claude Code login can run (cached for 5 minutes; **Load models** refreshes), and the reasoning effort menu offers only the levels the selected model accepts. The chosen level is passed to each `claude -p` call as `--effort`; it does not read or change `~/.claude/settings.json`, and "Provider default" means the model's own default. Base URL, temperature and `MAX_RETRIES` have no effect with this provider, and `TIMEOUT_SECONDS` is raised to at least 600 seconds per decision. Image input is not supported. The CLI returns each decision in one piece; while it runs, provider waiting events keep the Web UI active. Transport keepalives alone do not suppress `VIBE_TRADING_SSE_TIMEOUT` (default 90 seconds), and cancellation and the per-decision deadline remain enforced.### Path A: Docker (zero setup)diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex ae9f65a25..b1aad634d 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -627,6 +627,15 @@ class AgentLoop:)streamed_chars = safe+ last_waiting_emit: float | None = None++ def _on_waiting_chunk() -> None:+ nonlocal last_waiting_emit+ now = _time.monotonic()+ if last_waiting_emit is None or now - last_waiting_emit >= _heartbeat_interval_s():+ last_waiting_emit = now+ self._emit("llm_waiting", {"iter": current_iter})+def _on_reasoning_chunk(delta: str) -> None:# Throttled: long reasoning streams produce hundreds of# chunks; emitting each one floods the SSE replay buffer@@ -684,6 +693,7 @@ class AgentLoop:tools=tool_defs,on_text_chunk=_on_text_chunk,on_reasoning_chunk=_on_reasoning_chunk,+ on_waiting_chunk=_on_waiting_chunk,timeout=llm_timeout,idle_timeout_s=llm_timeout,should_cancel=self._cancel_event.is_set,@@ -750,6 +760,7 @@ class AgentLoop:tools=tool_defs,on_text_chunk=_on_text_chunk,on_reasoning_chunk=_on_reasoning_chunk,+ on_waiting_chunk=_on_waiting_chunk,timeout=llm_timeout,idle_timeout_s=llm_timeout,should_cancel=self._cancel_event.is_set,diff --git a/agent/src/channels/attempt_progress.py b/agent/src/channels/attempt_progress.pyindex dc9daf2c0..4e218839a 100644--- a/agent/src/channels/attempt_progress.py+++ b/agent/src/channels/attempt_progress.py@@ -21,6 +21,7 @@ class AttemptProgress:self.stream_started = Falseself.reasoning_started = Falseself.last_status = ""+ self.reasoning_chars: dict[int, int] = {}async def _send(self, content: str, **flags: Any) -> None:await self.bus.publish_outbound(OutboundMessage(@@ -39,16 +40,27 @@ class AttemptProgress:continuekind = event.event_typeif kind == "reasoning_delta":- delta = data.get("delta", "")- if delta:+ iteration = int(data.get("iter", 0))+ chars = int(data.get("chars", 0))+ seen = self.reasoning_chars.get(iteration, 0)+ self.reasoning_chars[iteration] = max(seen, chars)+ # AgentLoop emits a bounded cumulative tail, not a delta.+ # A missing tail is deliberate grounding redaction: show only+ # a status, never reconstruct text from any other payload.+ tail = data.get("tail")+ if isinstance(tail, str) and chars > seen and tail:self.reasoning_started = True- await self._send(str(delta), _reasoning_delta=True)- continue+ await self._send(tail[-min(chars - seen, len(tail)):], _reasoning_delta=True)+ continue+ if tail is not None or chars <= seen:+ continueif kind in {"tool_call", "grounding_status", "attempt.completed", "attempt.failed"}:await self._end_reasoning()tool = str(data.get("tool") or "tool")status = {"attempt.created": "Working on your request…",+ "reasoning_delta": "Reasoning…",+ "llm_waiting": "Waiting for the model…","tool_call": f"Using {tool}…","tool_heartbeat": f"Still running {tool}…","grounding_status": "Checking the figures…",diff --git a/agent/src/providers/chat.py b/agent/src/providers/chat.pyindex 243ef7fc2..1884fa5fa 100644--- a/agent/src/providers/chat.py+++ b/agent/src/providers/chat.py@@ -481,6 +481,7 @@ class ChatLLM:timeout: Optional[int] = None,idle_timeout_s: Optional[float] = None,should_cancel: Optional[Callable[[], bool]] = None,+ on_waiting_chunk: Optional[Callable[[], None]] = None,) -> LLMResponse:"""Stream the LLM and optionally forward text deltas (e.g. thinking).@@ -497,6 +498,8 @@ class ChatLLM:idle_timeout_s: Optional per-chunk idle timeout; when no streamdelta arrives for this long the call fails as a retryabletimeout instead of hanging the loop silently.+ on_waiting_chunk: Provider-confirmed waiting activity, carrying no text.+ Plain empty chunks and transport keepalives do not invoke it.should_cancel: Optional predicate polled per chunk; when it returnsTrue the stream stops early and the partial response is returned.Lets a caller abort a live stream promptly (cooperative cancel).@@ -526,6 +529,8 @@ class ChatLLM:if should_cancel and should_cancel():cancelled = Truebreak+ if getattr(chunk, "additional_kwargs", {}).get("provider_waiting") is True and on_waiting_chunk:+ on_waiting_chunk()chunk_text = _text_content(chunk.content)if chunk_text and on_text_chunk:if possible_dsml_text:diff --git a/agent/src/providers/claude_cli.py b/agent/src/providers/claude_cli.pyindex b4a71e4b4..012b28132 100644--- a/agent/src/providers/claude_cli.py+++ b/agent/src/providers/claude_cli.py@@ -597,7 +597,7 @@ class ClaudeCliLLM:# One decision is a single chunk that can take minutes. Without# empty chunks meanwhile, vibe's idle timeout discards an answer# that is still on its way and the stop button is never polled.- yield AIMessageChunk(content="")+ yield AIMessageChunk(content="", additional_kwargs={"provider_waiting": True})continueif chunk is sentinel:returndiff --git a/agent/tests/test_agent_goal_context.py b/agent/tests/test_agent_goal_context.pyindex e8111bcc0..66638edd9 100644--- a/agent/tests/test_agent_goal_context.py+++ b/agent/tests/test_agent_goal_context.py@@ -33,6 +33,7 @@ class _CapturingLLM:timeout: int | None = None,idle_timeout_s: float | None = None,should_cancel: Callable[[], bool] | None = None,+ on_waiting_chunk=None,) -> _AnswerResponse:del tools, on_text_chunk, on_reasoning_chunkself.messages = messagesdiff --git a/agent/tests/test_agent_grounding.py b/agent/tests/test_agent_grounding.pyindex 868b76c83..0e6fd9263 100644--- a/agent/tests/test_agent_grounding.py+++ b/agent/tests/test_agent_grounding.py@@ -1337,6 +1337,7 @@ class _CorrectingLLM:timeout: int | None = None,idle_timeout_s: float | None = None,should_cancel: Callable[[], bool] | None = None,+ on_waiting_chunk=None,) -> _Response:self.messages_history.append(list(messages))response = self.responses.pop(0)diff --git a/agent/tests/test_agent_loop_content_filter.py b/agent/tests/test_agent_loop_content_filter.pyindex 26eee1341..d31f7f4c8 100644--- a/agent/tests/test_agent_loop_content_filter.py+++ b/agent/tests/test_agent_loop_content_filter.py@@ -37,6 +37,7 @@ class _ContentFilterLoopLLM:timeout: int | None = None,idle_timeout_s: float | None = None,should_cancel: Callable[[], bool] | None = None,+ on_waiting_chunk=None,) -> LLMResponse:self.calls += 1self.messages_history.append(list(messages))@@ -69,6 +70,7 @@ class _EmptyResponseLoopLLM:timeout: int | None = None,idle_timeout_s: float | None = None,should_cancel: Callable[[], bool] | None = None,+ on_waiting_chunk=None,) -> LLMResponse:self.calls += 1return LLMResponse(content="", content_filter_triggered=False)@@ -213,6 +215,7 @@ def test_single_empty_response_recovers_with_nudge(timeout: int | None = None,idle_timeout_s: float | None = None,should_cancel: Callable[[], bool] | None = None,+ on_waiting_chunk=None,) -> LLMResponse:self.calls += 1self.messages_history.append(list(messages))@@ -322,6 +325,7 @@ class _RatioFilterLoopLLM:timeout: int | None = None,idle_timeout_s: float | None = None,should_cancel: Callable[[], bool] | None = None,+ on_waiting_chunk=None,) -> LLMResponse:self.calls += 1if self.calls <= self._filter_count:diff --git a/agent/tests/test_agent_loop_no_assistant_prefill.py b/agent/tests/test_agent_loop_no_assistant_prefill.pyindex 66f003e6a..74797b574 100644--- a/agent/tests/test_agent_loop_no_assistant_prefill.py+++ b/agent/tests/test_agent_loop_no_assistant_prefill.py@@ -47,6 +47,7 @@ class _StubLLM:timeout: Any = None,idle_timeout_s: Any = None,should_cancel: Any = None,+ on_waiting_chunk=None,) -> Any:messages = [m for m in messages]self.call_count += 1diff --git a/agent/tests/test_agent_loop_stream_retry.py b/agent/tests/test_agent_loop_stream_retry.pyindex 79318a95c..5bd3badac 100644--- a/agent/tests/test_agent_loop_stream_retry.py+++ b/agent/tests/test_agent_loop_stream_retry.py@@ -43,6 +43,7 @@ class _FlakyLoopLLM:timeout: int | None = None,idle_timeout_s: float | None = None,should_cancel: Callable[[], bool] | None = None,+ on_waiting_chunk=None,) -> LLMResponse:"""Raise the next queued error or return the final response.diff --git a/agent/tests/test_agent_loop_terminal_state.py b/agent/tests/test_agent_loop_terminal_state.pyindex 39d1244c0..96a6badfd 100644--- a/agent/tests/test_agent_loop_terminal_state.py+++ b/agent/tests/test_agent_loop_terminal_state.py@@ -48,6 +48,7 @@ class _StubLLMNoFinal:timeout: int | None = None,idle_timeout_s: float | None = None,should_cancel: Callable[[], bool] | None = None,+ on_waiting_chunk=None,) -> _StubLLMResponse:return _StubLLMResponse()@@ -67,6 +68,7 @@ class _StubLLMWithUsage:timeout: int | None = None,idle_timeout_s: float | None = None,should_cancel: Callable[[], bool] | None = None,+ on_waiting_chunk=None,) -> _StubLLMResponse:response = _StubLLMResponse()response.content = "done"@@ -92,6 +94,7 @@ class _StubLLMSuccess:timeout: int | None = None,idle_timeout_s: float | None = None,should_cancel: Callable[[], bool] | None = None,+ on_waiting_chunk=None,) -> _StubLLMResponse:self.calls += 1response = _StubLLMResponse()@@ -121,6 +124,7 @@ class _StubLLMCancelMidStream:timeout: int | None = None,idle_timeout_s: float | None = None,should_cancel: Callable[[], bool] | None = None,+ on_waiting_chunk=None,) -> _StubLLMResponse:# Set _cancelled on the bound agent so the next loop iteration check# picks it up. We still need a valid response so the current@@ -224,6 +228,7 @@ class _StubLLMCancelWithToolCalls:timeout: int | None = None,idle_timeout_s: float | None = None,should_cancel: Callable[[], bool] | None = None,+ on_waiting_chunk=None,) -> _StubLLMResponse:self._agent_ref[0]._cancel_event.set()resp = _StubLLMResponse()@@ -314,6 +319,7 @@ class _StubLLMAlwaysToolCalls:timeout: int | None = None,idle_timeout_s: float | None = None,should_cancel: Callable[[], bool] | None = None,+ on_waiting_chunk=None,) -> _StubLLMResponse:resp = _StubLLMResponse()if tools is not None:@@ -343,6 +349,7 @@ class _StubLLMIgnoresForcedTextOnly:timeout: int | None = None,idle_timeout_s: float | None = None,should_cancel: Callable[[], bool] | None = None,+ on_waiting_chunk=None,) -> _StubLLMResponse:resp = _StubLLMResponse()resp.has_tool_calls = True@@ -365,6 +372,7 @@ class _StubLLMStreamFailure:timeout: int | None = None,idle_timeout_s: float | None = None,should_cancel: Callable[[], bool] | None = None,+ on_waiting_chunk=None,) -> _StubLLMResponse:raise ProviderStreamError(provider="deepseek",diff --git a/agent/tests/test_agent_loop_trace.py b/agent/tests/test_agent_loop_trace.pyindex 8fb2e785d..8dffdf1fe 100644--- a/agent/tests/test_agent_loop_trace.py+++ b/agent/tests/test_agent_loop_trace.py@@ -100,6 +100,7 @@ class _LongAnswerLLM:timeout: int | None = None,idle_timeout_s: float | None = None,should_cancel: Callable[[], bool] | None = None,+ on_waiting_chunk=None,) -> _LongAnswerResponse:del messages, tools, on_reasoning_chunkif on_text_chunk:diff --git a/agent/tests/test_channels_attempt_progress.py b/agent/tests/test_channels_attempt_progress.pyindex ad77cf946..d74d229c4 100644--- a/agent/tests/test_channels_attempt_progress.py+++ b/agent/tests/test_channels_attempt_progress.py@@ -22,7 +22,7 @@ class _Service:for attempt, kind, data in [('old', 'tool_call', {'tool': 'stale_tool'}),('a', 'attempt.created', {}),- ('a', 'reasoning_delta', {'delta': 'Let me check the source.'}),+ ('a', 'reasoning_delta', {'iter': 1, 'chars': 24, 'tail': 'Let me check the source.'}),('a', 'tool_call', {'tool': 'get_market_data'}),('a', 'text_delta', {'delta': 'UNVALIDATED 987.65'}),('a', 'tool_result', {'result': 'RAW_PAYLOAD'}),@@ -88,3 +88,29 @@ def test_timeout_closes_transient_stream(tmp_path):assert any(m.metadata.get('_stream_end') for m in messages)assert messages[-1].metadata['error']asyncio.run(scenario())+++def test_real_reasoning_tails_are_incremental_and_redaction_stays_private():+ from src.channels.attempt_progress import AttemptProgress++ async def scenario():+ bus, events = MessageBus(), EventBus()+ message = InboundMessage(channel="feishu", chat_id="c", sender_id="u", content="q", metadata={"_wants_stream": True})+ progress = AttemptProgress(bus, events, message, "s", "a")+ for data in [+ {"iter": 1, "chars": 5, "tail": "Hello"},+ {"iter": 1, "chars": 11, "tail": "Hello world"},+ {"iter": 1, "chars": 11, "tail": "Hello world"},+ {"iter": 2, "chars": 20}, # grounding withheld the text+ ]:+ events.emit("s", "reasoning_delta", {**data, "attempt_id": "a"})+ events.emit("s", "llm_waiting", {"attempt_id": "a", "iter": 2})+ await progress.poll()+ sent = []+ while bus.outbound_size:+ sent.append(await bus.consume_outbound())+ reasoning = "".join(m.content for m in sent if m.metadata.get("_reasoning_delta"))+ assert reasoning == "Hello world"+ assert any(m.content == "Reasoning…\n" for m in sent)+ assert any(m.content == "Waiting for the model…\n" for m in sent)+ asyncio.run(scenario())diff --git a/agent/tests/test_chat_llm_streaming.py b/agent/tests/test_chat_llm_streaming.pyindex f43dc95c1..4ca23df97 100644--- a/agent/tests/test_chat_llm_streaming.py+++ b/agent/tests/test_chat_llm_streaming.py@@ -390,3 +390,16 @@ def test_stream_idle_timeout_allows_a_flowing_stream() -> None:)assert response.content == "ab"+++def test_only_explicit_provider_waiting_reaches_activity_callback():+ from langchain_core.messages import AIMessageChunk++ waiting = []+ response = _client(_FakeStreamingLLM([+ AIMessageChunk(content=""),+ AIMessageChunk(content="", additional_kwargs={"provider_waiting": True}),+ AIMessageChunk(content="final"),+ ])).stream_chat([{"role": "user", "content": "q"}], on_waiting_chunk=lambda: waiting.append(True))+ assert waiting == [True]+ assert response.content == "final"diff --git a/agent/tests/test_claude_cli_provider.py b/agent/tests/test_claude_cli_provider.pyindex 1f367d5c9..6bedc1493 100644--- a/agent/tests/test_claude_cli_provider.py+++ b/agent/tests/test_claude_cli_provider.py@@ -265,11 +265,14 @@ def test_slow_decision_outlives_the_stream_idle_timeout(fake_cli, monkeypatch) -monkeypatch.setattr(claude_cli, "_HEARTBEAT_S", 0.2)use_provider(monkeypatch)+ waiting = []response = ChatLLM().stream_chat(- [{"role": "user", "content": "x"}], idle_timeout_s=1+ [{"role": "user", "content": "x"}], idle_timeout_s=1,+ on_waiting_chunk=lambda: waiting.append(time.monotonic()),)assert response.content == "slow answer"+ assert waiting, "a real CLI child must emit waiting progress before its final response"def test_stop_button_ends_a_running_decision(fake_cli, monkeypatch) -> None:diff --git a/agent/tests/test_content_filter_e2e.py b/agent/tests/test_content_filter_e2e.pyindex 2ec909cce..a6eea972f 100644--- a/agent/tests/test_content_filter_e2e.py+++ b/agent/tests/test_content_filter_e2e.py@@ -52,6 +52,7 @@ class _InterleavedFilterLLM:timeout: int | None = None,idle_timeout_s: float | None = None,should_cancel: Callable[[], bool] | None = None,+ on_waiting_chunk=None,) -> LLMResponse:self.calls += 1# Calls 1 and 3: content filter triggered@@ -97,6 +98,7 @@ class _CleanRunLLM:timeout: int | None = None,idle_timeout_s: float | None = None,should_cancel: Callable[[], bool] | None = None,+ on_waiting_chunk=None,) -> LLMResponse:self.calls += 1if self.calls < 5:diff --git a/agent/tests/test_grounding_recovery.py b/agent/tests/test_grounding_recovery.pyindex 6b5298cb8..163e140ec 100644--- a/agent/tests/test_grounding_recovery.py+++ b/agent/tests/test_grounding_recovery.py@@ -338,6 +338,7 @@ class _FailingDraftLLM:timeout: int | None = None,idle_timeout_s: float | None = None,should_cancel: Callable[[], bool] | None = None,+ on_waiting_chunk=None,) -> LLMResponse:self.calls += 1self.messages_history.append(list(messages))diff --git a/agent/tests/test_grounding_release.py b/agent/tests/test_grounding_release.pyindex d536adfd7..4bfa3f35a 100644--- a/agent/tests/test_grounding_release.py+++ b/agent/tests/test_grounding_release.py@@ -633,6 +633,7 @@ class _ScriptedLLM:timeout: int | None = None,idle_timeout_s: float | None = None,should_cancel: Callable[[], bool] | None = None,+ on_waiting_chunk=None,) -> _Response:self.calls += 1self.messages_history.append(list(messages))@@ -2102,6 +2103,7 @@ class _ChunkedLLM:timeout: int | None = None,idle_timeout_s: float | None = None,should_cancel: Callable[[], bool] | None = None,+ on_waiting_chunk=None,) -> _Response:self.calls += 1if on_text_chunk:diff --git a/agent/tests/test_load_skill_allowlist.py b/agent/tests/test_load_skill_allowlist.pyindex 9de0a23be..a5d35d557 100644--- a/agent/tests/test_load_skill_allowlist.py+++ b/agent/tests/test_load_skill_allowlist.py@@ -129,7 +129,7 @@ def test_swarm_worker_passes_spec_skills_as_allowlist(tmp_path: Path) -> None:def close(self) -> None:pass- def stream_chat(self, messages, tools=None, on_text_chunk=None, timeout=None):+ def stream_chat(self, messages, tools=None, on_text_chunk=None, timeout=None, on_waiting_chunk=None):from src.providers.llm import LLMResponsereturn LLMResponse(content="done")@@ -184,7 +184,7 @@ def test_swarm_worker_empty_skills_stays_unrestricted(tmp_path: Path) -> None:def close(self) -> None:pass- def stream_chat(self, messages, tools=None, on_text_chunk=None, timeout=None):+ def stream_chat(self, messages, tools=None, on_text_chunk=None, timeout=None, on_waiting_chunk=None):from src.providers.llm import LLMResponsereturn LLMResponse(content="done")diff --git a/agent/tests/test_reasoning_delta_throttle.py b/agent/tests/test_reasoning_delta_throttle.pyindex df581b05a..1649774b1 100644--- a/agent/tests/test_reasoning_delta_throttle.py+++ b/agent/tests/test_reasoning_delta_throttle.py@@ -39,6 +39,7 @@ class _ReasoningBurstLLM:timeout: int | None = None,idle_timeout_s: float | None = None,should_cancel: Callable[[], bool] | None = None,+ on_waiting_chunk=None,) -> _StubLLMResponse:assert on_reasoning_chunk is not Nonefor _ in range(CHUNK_COUNT):@@ -98,3 +99,24 @@ def test_reasoning_delta_throttled_but_first_chunk_immediate(tmp_path: Path) -># Cumulative "chars" payload semantics preserved (monotonically increasing).chars = [d["chars"] for d in deltas]assert chars == sorted(chars)+++def test_provider_waiting_reaches_loop_without_answer_or_reasoning(tmp_path):+ from langchain_core.messages import AIMessageChunk+ from src.providers.chat import ChatLLM++ class Provider:+ def bind_tools(self, tools):+ return self+ def stream(self, *args, **kwargs):+ for _ in range(100):+ yield AIMessageChunk(content="", additional_kwargs={"provider_waiting": True})+ yield AIMessageChunk(content="Done.")+ llm = ChatLLM.__new__(ChatLLM)+ llm._llm, llm.model_name = Provider(), "test-waiting"+ events = []+ result = _build_agent(llm, events, tmp_path / "waiting").run(user_message="say done")+ assert result["status"] == "success"+ waiting = [data for kind, data in events if kind == "llm_waiting"]+ assert waiting == [{"iter": 1}]+ assert not any(kind == "reasoning_delta" for kind, _ in events)diff --git a/agent/tests/test_stream_retry_escalation.py b/agent/tests/test_stream_retry_escalation.pyindex 52ba33293..f6358a9b9 100644--- a/agent/tests/test_stream_retry_escalation.py+++ b/agent/tests/test_stream_retry_escalation.py@@ -72,7 +72,7 @@ class _ScriptedWorkerLLM:"""No-op: the stub owns no HTTP client."""return None- def stream_chat(self, messages, tools=None, on_text_chunk=None, timeout=None):+ def stream_chat(self, messages, tools=None, on_text_chunk=None, timeout=None, on_waiting_chunk=None):"""Play the next scripted entry, or repeat the final response."""self.calls += 1if self._script:@@ -325,6 +325,7 @@ class _FlakyLoopLLM:timeout: int | None = None,idle_timeout_s: float | None = None,should_cancel: Callable[[], bool] | None = None,+ on_waiting_chunk=None,) -> LLMResponse:"""Raise the next queued error or return the final response."""self.calls += 1diff --git a/agent/tests/test_swarm_m4_e2e.py b/agent/tests/test_swarm_m4_e2e.pyindex c0845cb8b..4b4782cd0 100644--- a/agent/tests/test_swarm_m4_e2e.py+++ b/agent/tests/test_swarm_m4_e2e.py@@ -134,7 +134,7 @@ class _StubChatLLM:def __call__(self, *args, **kwargs): # pragma: no cover — supports ChatLLM(model_name=...)return self- def stream_chat(self, messages, tools=None, on_text_chunk=None, timeout=None):+ def stream_chat(self, messages, tools=None, on_text_chunk=None, timeout=None, on_waiting_chunk=None):self.tool_defs_seen.append(tools)if not self._responses:return LLMResponse(content="(stub exhausted)", finish_reason="stop")diff --git a/agent/tests/test_swarm_m5_trust_model.py b/agent/tests/test_swarm_m5_trust_model.pyindex 382501002..5921c5b67 100644--- a/agent/tests/test_swarm_m5_trust_model.py+++ b/agent/tests/test_swarm_m5_trust_model.py@@ -288,7 +288,7 @@ class _StubChatLLM:def __call__(self, *args, **kwargs): # ChatLLM(model_name=...) constructor shimreturn self- def stream_chat(self, messages, tools=None, on_text_chunk=None, timeout=None):+ def stream_chat(self, messages, tools=None, on_text_chunk=None, timeout=None, on_waiting_chunk=None):self.tool_defs_seen.append(tools)if not self._responses:return LLMResponse(content="(stub exhausted)", finish_reason="stop")diff --git a/agent/tests/test_swarm_output_contract.py b/agent/tests/test_swarm_output_contract.pyindex dcab18843..98a27e850 100644--- a/agent/tests/test_swarm_output_contract.py+++ b/agent/tests/test_swarm_output_contract.py@@ -343,7 +343,7 @@ class _ScriptedLLM:),]- def stream_chat(self, messages, tools=None, timeout=None, on_text_chunk=None):+ def stream_chat(self, messages, tools=None, timeout=None, on_text_chunk=None, on_waiting_chunk=None):return self._responses.pop(0)def close(self) -> None:diff --git a/agent/tests/test_swarm_tool_run_dir.py b/agent/tests/test_swarm_tool_run_dir.pyindex 4b5146601..0c2698e7b 100644--- a/agent/tests/test_swarm_tool_run_dir.py+++ b/agent/tests/test_swarm_tool_run_dir.py@@ -131,7 +131,7 @@ class _ScriptedLLM:),]- def stream_chat(self, messages, tools=None, timeout=None, on_text_chunk=None):+ def stream_chat(self, messages, tools=None, timeout=None, on_text_chunk=None, on_waiting_chunk=None):return self._responses.pop(0)def close(self) -> None:diff --git a/agent/tests/test_swarm_worker_cancel.py b/agent/tests/test_swarm_worker_cancel.pyindex 3ccbb6407..57a5a5229 100644--- a/agent/tests/test_swarm_worker_cancel.py+++ b/agent/tests/test_swarm_worker_cancel.py@@ -74,7 +74,7 @@ class _ScriptedLLM:"""No-op: the stub owns no HTTP client."""return None- def stream_chat(self, messages, tools=None, on_text_chunk=None, timeout=None, should_cancel=None):+ def stream_chat(self, messages, tools=None, on_text_chunk=None, timeout=None, should_cancel=None, on_waiting_chunk=None):"""Return the scripted response, optionally cancelling "mid-stream"."""self.calls += 1self.should_cancel_seen.append(should_cancel)diff --git a/agent/tests/test_swarm_worker_content_filter.py b/agent/tests/test_swarm_worker_content_filter.pyindex fbbf93d71..73f0b0b0b 100644--- a/agent/tests/test_swarm_worker_content_filter.py+++ b/agent/tests/test_swarm_worker_content_filter.py@@ -52,7 +52,8 @@ class _ScriptedChatLLM:"""No-op: the scripted stub owns no HTTP client."""def stream_chat(- self, messages, tools=None, on_text_chunk=None, timeout=None+ self, messages, tools=None, on_text_chunk=None, timeout=None,+ on_waiting_chunk=None,) -> LLMResponse:self.calls += 1self.received_messages.append(list(messages))diff --git a/agent/tests/test_swarm_worker_message_log.py b/agent/tests/test_swarm_worker_message_log.pyindex c53607a16..4f63cab31 100644--- a/agent/tests/test_swarm_worker_message_log.py+++ b/agent/tests/test_swarm_worker_message_log.py@@ -57,7 +57,7 @@ class _ScriptedLLM:),]- def stream_chat(self, messages, tools=None, timeout=None, on_text_chunk=None):+ def stream_chat(self, messages, tools=None, timeout=None, on_text_chunk=None, on_waiting_chunk=None):return self._responses.pop(0)def close(self) -> None:@@ -70,7 +70,7 @@ class _ContentFilteredLLM:def __init__(self) -> None:self._remaining = 20- def stream_chat(self, messages, tools=None, timeout=None, on_text_chunk=None):+ def stream_chat(self, messages, tools=None, timeout=None, on_text_chunk=None, on_waiting_chunk=None):self._remaining -= 1if self._remaining >= 0:return LLMResponse(content="", content_filter_triggered=True)@@ -83,7 +83,7 @@ class _ContentFilteredLLM:class _AnswersWithoutToolCallsLLM:"""A final answer and nothing else, for a data agent that never probed."""- def stream_chat(self, messages, tools=None, timeout=None, on_text_chunk=None):+ def stream_chat(self, messages, tools=None, timeout=None, on_text_chunk=None, on_waiting_chunk=None):return LLMResponse(content="The market looks range-bound, so no further analysis is needed.",tool_calls=[],diff --git a/agent/tests/test_swarm_worker_stream_retry.py b/agent/tests/test_swarm_worker_stream_retry.pyindex 96250899a..442d3df83 100644--- a/agent/tests/test_swarm_worker_stream_retry.py+++ b/agent/tests/test_swarm_worker_stream_retry.py@@ -67,7 +67,7 @@ class _FlakyChatLLM:"""No-op: the stub owns no HTTP client."""return self- def stream_chat(self, messages, tools=None, on_text_chunk=None, timeout=None) -> LLMResponse:+ def stream_chat(self, messages, tools=None, on_text_chunk=None, timeout=None, on_waiting_chunk=None) -> LLMResponse:"""Raise the next queued error or return the final response.Args:diff --git a/agent/tests/test_swarm_worker_tool_result_truncation.py b/agent/tests/test_swarm_worker_tool_result_truncation.pyindex f883d95a9..5fa47033f 100644--- a/agent/tests/test_swarm_worker_tool_result_truncation.py+++ b/agent/tests/test_swarm_worker_tool_result_truncation.py@@ -64,7 +64,8 @@ class _ScriptedChatLLM:"""No-op: the scripted stub owns no HTTP client."""def stream_chat(- self, messages, tools=None, on_text_chunk=None, timeout=None+ self, messages, tools=None, on_text_chunk=None, timeout=None,+ on_waiting_chunk=None,) -> LLMResponse:self.received_messages.append(list(messages))if self._responses:diff --git a/frontend/src/hooks/__tests__/useSSE.test.ts b/frontend/src/hooks/__tests__/useSSE.test.tsindex 42960bd7a..1831f2669 100644--- a/frontend/src/hooks/__tests__/useSSE.test.ts+++ b/frontend/src/hooks/__tests__/useSSE.test.ts@@ -136,6 +136,21 @@ describe("useSSE — event handling", () => {expect(reasoningEvents).toEqual([{ chars: 8 }]);});+ it("dispatches provider waits separately from transport heartbeats", () => {+ const waiting = vi.fn();+ const heartbeat = vi.fn();+ const { result } = renderHook(() => useSSE());+ act(() => result.current.connect("http://test/events", { llm_waiting: waiting, heartbeat }));+ const payload = { attempt_id: "attempt-wait", iter: 1 };+ act(() => {+ MockEventSource.latest.emit("heartbeat", {}, "evt-heartbeat");+ MockEventSource.latest.emit("llm_waiting", payload, "evt-wait");+ MockEventSource.latest.emit("llm_waiting", payload, "evt-wait");+ });+ expect(waiting).toHaveBeenCalledExactlyOnceWith(payload);+ expect(heartbeat).toHaveBeenCalledExactlyOnceWith({});+ });+it("dispatches stream reset events", () => {const resetEvents: unknown[] = [];const { result } = renderHook(() => useSSE());diff --git a/frontend/src/hooks/useSSE.ts b/frontend/src/hooks/useSSE.tsindex 0979b2917..fdbfbd94e 100644--- a/frontend/src/hooks/useSSE.ts+++ b/frontend/src/hooks/useSSE.ts@@ -85,7 +85,7 @@ export function useSSE(config?: SSEConfig) {// Only subscribe to event types the backend actually emitsconst knownTypes = ["text_delta", "reasoning_delta", "stream_reset", "thinking_done", "tool_call", "tool_result", "compact",- "tool_heartbeat", "tool_progress", "llm_usage", "grounding_status",+ "tool_heartbeat", "tool_progress", "llm_usage", "llm_waiting", "grounding_status","swarm.started", "swarm.event","attempt.created", "attempt.started", "attempt.completed", "attempt.failed","attempt.cancelled",diff --git a/frontend/src/pages/Agent.tsx b/frontend/src/pages/Agent.tsxindex 5de535b31..4a19b1f50 100644--- a/frontend/src/pages/Agent.tsx+++ b/frontend/src/pages/Agent.tsx@@ -761,6 +761,12 @@ export function Agent() {if (act().status !== "streaming") act().setStatus("streaming");queueStreamUpdate(String(d.delta || ""), false);},+ llm_waiting: (d) => {+ touch();+ replayAttemptSeenRef.current = true;+ identifyActivity(d, "thinking");+ },+reasoning_delta: (d) => {touch();replayAttemptSeenRef.current = true;diff --git a/frontend/src/pages/__tests__/AgentActivityTimerPersistence.test.tsx b/frontend/src/pages/__tests__/AgentActivityTimerPersistence.test.tsxindex 0509bed93..4d68f173b 100644--- a/frontend/src/pages/__tests__/AgentActivityTimerPersistence.test.tsx+++ b/frontend/src/pages/__tests__/AgentActivityTimerPersistence.test.tsx@@ -351,4 +351,30 @@ describe("Agent completion trusts the backend's attempt start", () => {endedAt: endedSec * 1000,});});+ it("keeps explicit provider waiting active but still times out on transport keepalives alone", async () => {+ const router = createMemoryRouter([{ path: "/", element: <Agent /> }], { initialEntries: ["/?session=session-one"] });+ render(<RouterProvider router={router} />);+ await waitFor(() => expect(sseMock.connect).toHaveBeenCalled());+ await waitFor(() => expect(apiMock.getLLMSettings).toHaveBeenCalled());+ vi.useFakeTimers();+ try {+ act(() => {+ const store = useAgentStore.getState();+ store.startActivity("attempt-wait");+ store.setStatus("streaming");+ });+ for (let i = 0; i < 4; i++) {+ act(() => { vi.advanceTimersByTime(40_000); });+ act(() => { latestHandlers().llm_waiting({ attempt_id: "attempt-wait", iter: 1 }); });+ }+ expect(useAgentStore.getState().status).toBe("streaming");+ expect(useAgentStore.getState().streamingText).toBe("");+ for (let i = 0; i < 3; i++) {+ act(() => { vi.advanceTimersByTime(40_000); });+ act(() => { latestHandlers().heartbeat({}); });+ }+ expect(useAgentStore.getState().status).toBe("idle");+ } finally { vi.useRealTimers(); }+ });+});