Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(agent): preserve queued cancellation signals

xkam7arb51b9413ce15
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.py
index 8eef047de..8be770c19 100644
--- a/agent/src/agent/loop.py
+++ b/agent/src/agent/loop.py
@@ -550,6 +550,7 @@ class AgentLoop:
self._previous_summary: str = ""
self._persistent_memory = persistent_memory
self._run_iteration: int = 0
+ self._has_run = False
def cancel(self) -> None:
"""Cancel the current loop.
@@ -571,8 +572,13 @@ class AgentLoop:
Returns:
Execution result dict.
"""
- # Reset per-run state (safe for reuse across multiple run() calls)
- self._cancel_event.clear()
+ # Preserve cancellation accepted while the first run is queued. A
+ # completed loop may still be reused deliberately, so clear terminal
+ # state only after the first run has begun.
+ if self._has_run:
+ self._cancel_event.clear()
+ else:
+ self._has_run = True
self._called_ok = set()
self._previous_summary = ""
diff --git a/agent/tests/test_agent_loop_terminal_state.py b/agent/tests/test_agent_loop_terminal_state.py
index 5ec5615de..2a47e945b 100644
--- a/agent/tests/test_agent_loop_terminal_state.py
+++ b/agent/tests/test_agent_loop_terminal_state.py
@@ -73,6 +73,29 @@ class _StubLLMWithUsage:
return _StubLLMResponse()
+class _StubLLMSuccess:
+ """LLM stub that records calls and returns a final answer."""
+
+ def __init__(self) -> None:
+ self.calls = 0
+
+ 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.calls += 1
+ response = _StubLLMResponse()
+ response.content = "done"
+ return response
+
+ def chat(self, messages: list[dict[str, Any]], **_: Any) -> _StubLLMResponse:
+ return _StubLLMResponse()
+
+
class _StubLLMCancelMidStream:
"""LLM stub that cancels the loop from inside the LLM call.
@@ -152,6 +175,24 @@ def test_cancelled_terminal_returns_reason(tmp_path: Path) -> None:
assert result["max_iterations"] == 3
+def test_cancel_before_first_run_is_not_cleared(tmp_path: Path) -> None:
+ """A cancellation accepted while queued must stop before the LLM call."""
+ llm = _StubLLMSuccess()
+ agent = _build_agent(llm, max_iter=1, tmp_run_dir=tmp_path / "run")
+
+ agent.cancel()
+ cancelled = agent.run(user_message="stale request")
+
+ assert cancelled["status"] == "cancelled"
+ assert cancelled["reason"] == "cancelled by user"
+ assert llm.calls == 0
+
+ reused = agent.run(user_message="new request")
+
+ assert reused["status"] == "success"
+ assert llm.calls == 1
+
+
class _StubLLMCancelWithToolCalls:
"""LLM stub that cancels mid-stream while returning a tool-calling response.