Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(agent): make Stop responsive mid-stream and between tools (#229) (#235)

Haozhe Wuf0ba648b1f63
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.py
index fd4d7e3a0..15fda95a4 100644
--- a/agent/src/agent/loop.py
+++ b/agent/src/agent/loop.py
@@ -453,7 +453,7 @@ class AgentLoop:
self._event_callback = event_callback
self.max_iterations = max_iterations
self._called_ok: set[str] = set()
- self._cancelled: bool = False
+ self._cancel_event = threading.Event()
self._previous_summary: str = ""
self._persistent_memory = persistent_memory
self._run_iteration: int = 0
@@ -461,9 +461,11 @@ class AgentLoop:
def cancel(self) -> None:
"""Cancel the current loop.
- The main loop exits on the next iteration check.
+ Sets a thread-safe flag polled at every iteration boundary, per LLM
+ stream chunk, and between tool batches, so a running turn stops at the
+ next cooperative checkpoint instead of only at the next iteration.
"""
- self._cancelled = True
+ self._cancel_event.set()
def run(self, user_message: str, history: Optional[List[Dict[str, Any]]] = None, session_id: str = "") -> Dict[str, Any]:
"""Run the ReAct loop synchronously.
@@ -477,7 +479,7 @@ class AgentLoop:
Execution result dict.
"""
# Reset per-run state (safe for reuse across multiple run() calls)
- self._cancelled = False
+ self._cancel_event.clear()
self._called_ok = set()
self._previous_summary = ""
@@ -537,7 +539,7 @@ class AgentLoop:
try:
while iteration < self.max_iterations:
- if self._cancelled:
+ if self._cancel_event.is_set():
trace.write({"type": "cancelled", "iter": self._run_iteration + 1})
logger.info("AgentLoop cancelled by user")
break
@@ -628,6 +630,7 @@ class AgentLoop:
tools=tool_defs,
on_text_chunk=_on_text_chunk,
on_reasoning_chunk=_on_reasoning_chunk,
+ should_cancel=self._cancel_event.is_set,
)
except ProviderStreamError as exc:
# One retry for transient mid-stream failures (connection
@@ -660,7 +663,14 @@ class AgentLoop:
tools=tool_defs,
on_text_chunk=_on_text_chunk,
on_reasoning_chunk=_on_reasoning_chunk,
+ should_cancel=self._cancel_event.is_set,
)
+
+ # Cancelled mid-stream: discard this turn's partial response and
+ # end the run now, without executing any of its tool calls.
+ if self._cancel_event.is_set():
+ break
+
usage = getattr(response, "usage_metadata", None)
usage_delta = _record_llm_usage(
run_dir,
@@ -853,7 +863,7 @@ class AgentLoop:
# returned dict so SessionService can surface a meaningful UI
# message instead of "Execution failed: unknown" (issue #114).
final_reason: str | None = None
- if self._cancelled:
+ if self._cancel_event.is_set():
final_reason = "cancelled by user"
state_store.mark_failure(run_dir, final_reason)
final_status = "cancelled"
@@ -929,6 +939,10 @@ class AgentLoop:
focus_topic = ""
to_execute = []
+ # Cancelled before this turn's tools ran — skip execution entirely.
+ if self._cancel_event.is_set():
+ return compact_requested, focus_topic
+
for tc in tool_calls:
# Layer 4: compact tool — mark then defer execution
if tc.name == "compact":
@@ -1000,6 +1014,10 @@ class AgentLoop:
batches.append(("parallel", current_ro))
for mode, batch in batches:
+ # Stop launching further tool batches once cancelled — the current
+ # batch (if any) finishes, but no new work starts.
+ if self._cancel_event.is_set():
+ break
if mode == "parallel" and len(batch) > 1:
self._execute_parallel(batch, context, messages, trace, react_trace, iteration)
else:
diff --git a/agent/src/providers/chat.py b/agent/src/providers/chat.py
index 682f1c162..9bc8d27e8 100644
--- a/agent/src/providers/chat.py
+++ b/agent/src/providers/chat.py
@@ -7,7 +7,7 @@ from __future__ import annotations
import os
from dataclasses import dataclass, field
-from typing import Any, Dict, List, Optional
+from typing import Any, Callable, Dict, List, Optional
from src.providers.llm import build_llm
@@ -159,6 +159,7 @@ class ChatLLM:
on_text_chunk: Optional[Any] = None,
on_reasoning_chunk: Optional[Any] = None,
timeout: Optional[int] = None,
+ should_cancel: Optional[Callable[[], bool]] = None,
) -> LLMResponse:
"""Stream the LLM and optionally forward text deltas (e.g. thinking).
@@ -172,6 +173,9 @@ class ChatLLM:
on_text_chunk: Optional callback ``(delta: str) -> None``.
on_reasoning_chunk: Optional callback ``(delta: str) -> None``.
timeout: Optional per-call timeout in seconds.
+ should_cancel: Optional predicate polled per chunk; when it returns
+ True the stream stops early and the partial response is returned.
+ Lets a caller abort a live stream promptly (cooperative cancel).
Returns:
Parsed ``LLMResponse``.
@@ -181,6 +185,8 @@ class ChatLLM:
config = {"timeout": timeout} if timeout else {}
accumulated = None
for chunk in llm.stream(messages, config=config):
+ if should_cancel and should_cancel():
+ break
if chunk.content and on_text_chunk:
on_text_chunk(chunk.content)
reasoning = getattr(chunk, "additional_kwargs", {}).get("reasoning_content")
diff --git a/agent/tests/test_agent_goal_context.py b/agent/tests/test_agent_goal_context.py
index 8a274ffc9..ce7c56074 100644
--- a/agent/tests/test_agent_goal_context.py
+++ b/agent/tests/test_agent_goal_context.py
@@ -30,6 +30,7 @@ class _CapturingLLM:
tools: list[Any] | None = None,
on_text_chunk: Callable[[str], None] | None = None,
on_reasoning_chunk: Callable[[str], None] | None = None,
+ should_cancel: Callable[[], bool] | None = None,
) -> _AnswerResponse:
del tools, on_text_chunk, on_reasoning_chunk
self.messages = messages
diff --git a/agent/tests/test_agent_loop_stream_retry.py b/agent/tests/test_agent_loop_stream_retry.py
index d4bab78ad..79cb781f2 100644
--- a/agent/tests/test_agent_loop_stream_retry.py
+++ b/agent/tests/test_agent_loop_stream_retry.py
@@ -40,6 +40,7 @@ class _FlakyLoopLLM:
tools: list[Any] | None = None,
on_text_chunk: Callable[[str], None] | None = None,
on_reasoning_chunk: Callable[[str], None] | None = None,
+ should_cancel: Callable[[], bool] | None = 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.py
index d65e6740b..5ec5615de 100644
--- a/agent/tests/test_agent_loop_terminal_state.py
+++ b/agent/tests/test_agent_loop_terminal_state.py
@@ -13,6 +13,7 @@ from __future__ import annotations
import json
from pathlib import Path
+from types import SimpleNamespace
from typing import Any, Callable
import pytest
@@ -44,6 +45,7 @@ class _StubLLMNoFinal:
tools: list[Any] | None = None,
on_text_chunk: Callable[[str], None] | None = None,
on_reasoning_chunk: Callable[[str], None] | None = None,
+ should_cancel: Callable[[], bool] | None = None,
) -> _StubLLMResponse:
return _StubLLMResponse()
@@ -60,6 +62,7 @@ class _StubLLMWithUsage:
tools: list[Any] | None = None,
on_text_chunk: Callable[[str], None] | None = None,
on_reasoning_chunk: Callable[[str], None] | None = None,
+ should_cancel: Callable[[], bool] | None = None,
) -> _StubLLMResponse:
response = _StubLLMResponse()
response.content = "done"
@@ -86,11 +89,12 @@ class _StubLLMCancelMidStream:
tools: list[Any] | None = None,
on_text_chunk: Callable[[str], None] | None = None,
on_reasoning_chunk: Callable[[str], None] | None = None,
+ should_cancel: Callable[[], bool] | None = 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
# iteration completes cleanly.
- self._agent_ref[0]._cancelled = True
+ self._agent_ref[0]._cancel_event.set()
return _StubLLMResponse()
def chat(self, messages: list[dict[str, Any]], **_: Any) -> _StubLLMResponse:
@@ -148,6 +152,60 @@ def test_cancelled_terminal_returns_reason(tmp_path: Path) -> None:
assert result["max_iterations"] == 3
+class _StubLLMCancelWithToolCalls:
+ """LLM stub that cancels mid-stream while returning a tool-calling response.
+
+ Mimics the user pressing Stop during the model's turn. The loop must end
+ the run as cancelled WITHOUT executing the turn's tool calls (#229).
+ """
+
+ def __init__(self, agent_ref: "list[AgentLoop]") -> None:
+ self._agent_ref = agent_ref
+
+ def stream_chat(
+ self,
+ messages: list[dict[str, Any]],
+ tools: list[Any] | None = None,
+ on_text_chunk: Callable[[str], None] | None = None,
+ on_reasoning_chunk: Callable[[str], None] | None = None,
+ should_cancel: Callable[[], bool] | None = None,
+ ) -> _StubLLMResponse:
+ self._agent_ref[0]._cancel_event.set()
+ resp = _StubLLMResponse()
+ resp.has_tool_calls = True
+ resp.tool_calls = [SimpleNamespace(id="c1", name="get_market_data", arguments={})]
+ return resp
+
+ def chat(self, messages: list[dict[str, Any]], **_: Any) -> _StubLLMResponse:
+ return _StubLLMResponse()
+
+
+def test_cancel_mid_stream_skips_tool_execution(tmp_path: Path) -> None:
+ """Cancelling during the stream ends the run before any tool runs (#229)."""
+ agent_ref: list[AgentLoop] = []
+ agent = _build_agent(
+ _StubLLMCancelWithToolCalls(agent_ref),
+ max_iter=3,
+ tmp_run_dir=tmp_path / "run",
+ )
+ agent_ref.append(agent)
+
+ processed = {"tools": False}
+ original = agent._process_tool_calls
+
+ def _spy(*args: Any, **kwargs: Any):
+ processed["tools"] = True
+ return original(*args, **kwargs)
+
+ agent._process_tool_calls = _spy # type: ignore[method-assign]
+
+ result = agent.run(user_message="anything")
+
+ assert result["status"] == "cancelled"
+ assert result["reason"] == "cancelled by user"
+ assert processed["tools"] is False
+
+
def test_session_service_renders_meaningful_error_from_result(tmp_path: Path) -> None:
"""End-to-end guard for the original UI symptom in #114: with the new
`reason` field populated, `result.get('reason', 'unknown')` returns the
@@ -198,6 +256,7 @@ class _StubLLMAlwaysToolCalls:
tools: list[Any] | None = None,
on_text_chunk: Callable[[str], None] | None = None,
on_reasoning_chunk: Callable[[str], None] | None = None,
+ should_cancel: Callable[[], bool] | None = None,
) -> _StubLLMResponse:
resp = _StubLLMResponse()
if tools is not None:
@@ -224,6 +283,7 @@ class _StubLLMIgnoresForcedTextOnly:
tools: list[Any] | None = None,
on_text_chunk: Callable[[str], None] | None = None,
on_reasoning_chunk: Callable[[str], None] | None = None,
+ should_cancel: Callable[[], bool] | None = None,
) -> _StubLLMResponse:
resp = _StubLLMResponse()
resp.has_tool_calls = True
@@ -243,6 +303,7 @@ class _StubLLMStreamFailure:
tools: list[Any] | None = None,
on_text_chunk: Callable[[str], None] | None = None,
on_reasoning_chunk: Callable[[str], None] | None = None,
+ should_cancel: Callable[[], bool] | None = None,
) -> _StubLLMResponse:
raise ProviderStreamError(
provider="deepseek",
diff --git a/agent/tests/test_agent_loop_trace.py b/agent/tests/test_agent_loop_trace.py
index 1422a1acf..7e291de53 100644
--- a/agent/tests/test_agent_loop_trace.py
+++ b/agent/tests/test_agent_loop_trace.py
@@ -97,6 +97,7 @@ class _LongAnswerLLM:
tools: list[Any] | None = None,
on_text_chunk: Callable[[str], None] | None = None,
on_reasoning_chunk: Callable[[str], None] | None = None,
+ should_cancel: Callable[[], bool] | None = None,
) -> _LongAnswerResponse:
del messages, tools, on_reasoning_chunk
if on_text_chunk:
diff --git a/agent/tests/test_chat_llm_streaming.py b/agent/tests/test_chat_llm_streaming.py
index df91554f9..a6a1e0c58 100644
--- a/agent/tests/test_chat_llm_streaming.py
+++ b/agent/tests/test_chat_llm_streaming.py
@@ -84,6 +84,46 @@ def test_reasoning_only_chunks_emit_progress_without_final_answer_text() -> None
assert response.reasoning_content == "thinking more"
+def test_should_cancel_stops_stream_early() -> None:
+ """A should_cancel predicate breaks the chunk loop; later chunks are dropped."""
+ fake = _FakeStreamingLLM([
+ _FakeChunk(content="a"),
+ _FakeChunk(content="b"),
+ _FakeChunk(content="c"),
+ ])
+ seen: list[str] = []
+ calls = {"n": 0}
+
+ def should_cancel() -> bool:
+ # Polled at the top of each chunk: let the first through, cancel after.
+ n = calls["n"]
+ calls["n"] += 1
+ return n >= 1
+
+ response = _client(fake).stream_chat(
+ [{"role": "user", "content": "hi"}],
+ on_text_chunk=seen.append,
+ should_cancel=should_cancel,
+ )
+
+ assert seen == ["a"]
+ assert response.content == "a"
+
+
+def test_should_cancel_absent_consumes_full_stream() -> None:
+ """Without should_cancel the stream is consumed in full (no behavior change)."""
+ fake = _FakeStreamingLLM([_FakeChunk(content="x"), _FakeChunk(content="y")])
+ seen: list[str] = []
+
+ response = _client(fake).stream_chat(
+ [{"role": "user", "content": "hi"}],
+ on_text_chunk=seen.append,
+ )
+
+ assert seen == ["x", "y"]
+ assert response.content == "xy"
+
+
def test_stream_failure_raises_provider_error_without_silent_fallback() -> None:
fake = _FakeStreamingLLM(exc=RuntimeError("stream exploded"))
diff --git a/agent/tests/test_reasoning_delta_throttle.py b/agent/tests/test_reasoning_delta_throttle.py
index b6dbd52bf..c18d518b0 100644
--- a/agent/tests/test_reasoning_delta_throttle.py
+++ b/agent/tests/test_reasoning_delta_throttle.py
@@ -36,6 +36,7 @@ class _ReasoningBurstLLM:
tools: list[Any] | None = None,
on_text_chunk: Callable[[str], None] | None = None,
on_reasoning_chunk: Callable[[str], None] | None = None,
+ should_cancel: Callable[[], bool] | None = None,
) -> _StubLLMResponse:
assert on_reasoning_chunk is not None
for _ in range(CHUNK_COUNT):