Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(web): clear partial stream text on provider retry

Haozhe Wu4c4565a50f25
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.py
index 9d3f6ff24..4f8b5885a 100644
--- a/agent/src/agent/loop.py
+++ b/agent/src/agent/loop.py
@@ -516,6 +516,15 @@ class AgentLoop:
iteration,
exc,
)
+ self._emit(
+ "stream_reset",
+ {
+ "iter": iteration,
+ "reason": "provider_stream_retry",
+ "provider": exc.provider,
+ "model": exc.model,
+ },
+ )
thinking_chunks.clear()
reasoning_chars = 0
last_reasoning_emit = None
diff --git a/agent/tests/test_agent_loop_stream_retry.py b/agent/tests/test_agent_loop_stream_retry.py
index f45e68796..d4bab78ad 100644
--- a/agent/tests/test_agent_loop_stream_retry.py
+++ b/agent/tests/test_agent_loop_stream_retry.py
@@ -61,6 +61,8 @@ class _FlakyLoopLLM:
if on_text_chunk:
on_text_chunk("partial-from-failed-attempt ")
raise self._errors.pop(0)
+ if on_text_chunk:
+ on_text_chunk(self._final_content)
return LLMResponse(content=self._final_content)
def chat(self, messages: list[dict[str, Any]], **_: Any) -> LLMResponse:
@@ -101,13 +103,19 @@ def _bad_request_error() -> ProviderStreamError:
)
-def _run(monkeypatch, tmp_path: Path, llm: _FlakyLoopLLM) -> dict[str, Any]:
+def _run(
+ monkeypatch,
+ tmp_path: Path,
+ llm: _FlakyLoopLLM,
+ events: list[tuple[str, dict[str, Any]]] | None = None,
+) -> dict[str, Any]:
"""Run an AgentLoop turn against the given scripted LLM.
Args:
monkeypatch: pytest monkeypatch fixture (zeroes the retry sleep).
tmp_path: Scratch run directory.
llm: The scripted LLM stub.
+ events: Optional event sink collecting ``(event_type, data)`` tuples.
Returns:
The AgentLoop result dict.
@@ -121,6 +129,11 @@ def _run(monkeypatch, tmp_path: Path, llm: _FlakyLoopLLM) -> dict[str, Any]:
agent = AgentLoop(
registry=build_registry(persistent_memory=pm, include_shell_tools=False),
llm=llm,
+ event_callback=(
+ (lambda event_type, data: events.append((event_type, data)))
+ if events is not None
+ else None
+ ),
max_iterations=3,
persistent_memory=pm,
)
@@ -135,13 +148,27 @@ def test_transient_stream_failure_is_retried_and_run_succeeds(
) -> None:
"""One transient ProviderStreamError then success → run completes (2 calls)."""
llm = _FlakyLoopLLM([_transient_error()], "Final answer.")
+ events: list[tuple[str, dict[str, Any]]] = []
- result = _run(monkeypatch, tmp_path, llm)
+ result = _run(monkeypatch, tmp_path, llm, events)
assert result["status"] == "success"
assert result["content"] == "Final answer."
assert llm.calls == 2
+ event_types = [event_type for event_type, _ in events]
+ assert "stream_reset" in event_types
+ text_positions = [
+ index for index, event_type in enumerate(event_types) if event_type == "text_delta"
+ ]
+ reset_position = event_types.index("stream_reset")
+ assert text_positions[0] < reset_position < text_positions[-1]
+ reset = next(data for event_type, data in events if event_type == "stream_reset")
+ assert reset["reason"] == "provider_stream_retry"
+ assert reset["iter"] == 1
+ assert reset["provider"] == "deepseek"
+ assert reset["model"] == "deepseek-v4-pro"
+
def test_double_stream_failure_fails_run(monkeypatch, tmp_path: Path) -> None:
"""Two consecutive transient failures → failed run, no third attempt."""
diff --git a/frontend/src/hooks/__tests__/useSSE.test.ts b/frontend/src/hooks/__tests__/useSSE.test.ts
index 5ac3e6102..725b9ce4e 100644
--- a/frontend/src/hooks/__tests__/useSSE.test.ts
+++ b/frontend/src/hooks/__tests__/useSSE.test.ts
@@ -136,6 +136,26 @@ describe("useSSE — event handling", () => {
expect(reasoningEvents).toEqual([{ chars: 8 }]);
});
+ it("dispatches stream reset events", () => {
+ const resetEvents: unknown[] = [];
+ const { result } = renderHook(() => useSSE());
+
+ act(() =>
+ result.current.connect("http://test/events", {
+ stream_reset: (data) => resetEvents.push(data),
+ }),
+ );
+
+ act(() =>
+ MockEventSource.latest.emit(
+ "stream_reset",
+ { reason: "provider_stream_retry" },
+ "evt-reset",
+ ),
+ );
+ expect(resetEvents).toEqual([{ reason: "provider_stream_retry" }]);
+ });
+
it("falls back to message handler for known event types without specific handler", () => {
const messages: unknown[] = [];
const { result } = renderHook(() => useSSE());
diff --git a/frontend/src/hooks/useSSE.ts b/frontend/src/hooks/useSSE.ts
index 5d1b322c8..8147acdc6 100644
--- a/frontend/src/hooks/useSSE.ts
+++ b/frontend/src/hooks/useSSE.ts
@@ -80,7 +80,7 @@ export function useSSE(config?: SSEConfig) {
// Only subscribe to event types the backend actually emits
const knownTypes = [
- "text_delta", "reasoning_delta", "thinking_done", "tool_call", "tool_result", "compact",
+ "text_delta", "reasoning_delta", "stream_reset", "thinking_done", "tool_call", "tool_result", "compact",
"tool_heartbeat", "tool_progress", "llm_usage",
"swarm.started", "swarm.event",
"attempt.created", "attempt.started", "attempt.completed", "attempt.failed",
diff --git a/frontend/src/pages/Agent.tsx b/frontend/src/pages/Agent.tsx
index 6682e7727..ac075eab0 100644
--- a/frontend/src/pages/Agent.tsx
+++ b/frontend/src/pages/Agent.tsx
@@ -422,6 +422,13 @@ export function Agent() {
if (act().status !== "streaming") act().setStatus("streaming");
scrollToBottom();
},
+ stream_reset: () => {
+ touch();
+ setReasoningActive(false);
+ act().clearStreaming();
+ if (act().status !== "streaming") act().setStatus("streaming");
+ scrollToBottom();
+ },
thinking_done: () => { touch(); /* don't flush — keep streaming text visible */ },
tool_call: (d) => {