Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(swarm): persist a cancelled worker as a cancelled task, and test the worker half of cancellation

Haozhe Wuaf8d297edfaa
diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.py
index e90a2b889..15dfc69c4 100644
--- a/agent/cli/_legacy.py
+++ b/agent/cli/_legacy.py
@@ -2160,6 +2160,11 @@ class _SwarmDashboard:
agent["elapsed"] = (time.monotonic() - agent["started_at"]) if agent["started_at"] else 0
error = data.get("error", "")[:80]
self.completed_summaries.append((agent["name"], f"[red]FAILED: {error}[/red]"))
+ elif etype == "task_cancelled":
+ agent["status"] = "cancelled"
+ agent["elapsed"] = (time.monotonic() - agent["started_at"]) if agent["started_at"] else 0
+ agent["iters"] = data.get("iterations", agent["iters"])
+ self.completed_summaries.append((agent["name"], "[yellow]CANCELLED[/yellow]"))
elif etype == "task_blocked":
agent["status"] = "blocked"
blocked_by = ", ".join(data.get("blocked_by", []))
@@ -2224,6 +2229,9 @@ class _SwarmDashboard:
elif status == "retry":
status_str = "[yellow][\u21bb retry ][/yellow]"
elapsed = time.monotonic() - agent["started_at"] if agent["started_at"] else 0
+ elif status == "cancelled":
+ status_str = "[yellow][\u2298 cancel][/yellow]"
+ elapsed = agent["elapsed"]
else:
status_str = "[dim][\u25cb waiting][/dim]"
elapsed = 0
@@ -2235,7 +2243,7 @@ class _SwarmDashboard:
table.add_row(styled_name, status_str, agent["tool"], time_str, iter_str, last_text)
# Progress bar row
- done_count = sum(1 for a in self.agents.values() if a["status"] in ("done", "failed"))
+ done_count = sum(1 for a in self.agents.values() if a["status"] in ("done", "failed", "cancelled"))
total_count = len(self.agents) or 1
pct = int(done_count / total_count * 100)
bar_width = 40
diff --git a/agent/src/swarm/runtime.py b/agent/src/swarm/runtime.py
index 123d369a9..e90fc2942 100644
--- a/agent/src/swarm/runtime.py
+++ b/agent/src/swarm/runtime.py
@@ -508,6 +508,37 @@ class SwarmRuntime:
},
),
)
+ elif result.status == "cancelled":
+ # The worker stopped because cancel_run() was
+ # signalled mid-flight; that is a user stop, not a
+ # worker error. Persist it as cancelled — the same
+ # terminal state _cancel_remaining_tasks gives tasks
+ # that never started — so the dashboard, the run
+ # summary and a later resume all see one consistent
+ # story instead of a spurious "worker did not
+ # complete" failure.
+ all_succeeded = False
+ task_store.update_status(
+ tid,
+ TaskStatus.cancelled,
+ summary=result.summary,
+ completed_at=datetime.now(timezone.utc).isoformat(),
+ artifacts=result.artifact_paths,
+ worker_iterations=result.iterations,
+ )
+ self._emit_event(
+ run_id,
+ self._make_event(
+ "task_cancelled",
+ task_id=tid,
+ data={
+ "status": result.status,
+ "iterations": result.iterations,
+ "input_tokens": result.input_tokens,
+ "output_tokens": result.output_tokens,
+ },
+ ),
+ )
else:
all_succeeded = False
task_store.update_status(
diff --git a/agent/tests/test_swarm_cancel_mid_flight_worker.py b/agent/tests/test_swarm_cancel_mid_flight_worker.py
index 23cb9a106..06e932a91 100644
--- a/agent/tests/test_swarm_cancel_mid_flight_worker.py
+++ b/agent/tests/test_swarm_cancel_mid_flight_worker.py
@@ -87,3 +87,32 @@ def test_run_worker_receives_cancel_event_kwarg(tmp_path, monkeypatch):
runtime._execute_run(run, cancel_event)
assert received["cancel_event"] is cancel_event
+
+
+def test_cancelled_worker_result_persists_as_cancelled_task(tmp_path, monkeypatch):
+ """A worker that stopped because cancel_run() fired must land as a
+ *cancelled* task with a task_cancelled event — the generic "worker did
+ not complete" branch would otherwise relabel a user stop as a failure."""
+ from src.swarm.models import RunStatus, TaskStatus
+ from src.swarm.task_store import TaskStore
+
+ def cancelling_worker(agent_spec, task, **kwargs):
+ kwargs["cancel_event"].set()
+ return WorkerResult(status="cancelled", summary="stopped on request", iterations=2)
+
+ monkeypatch.setattr(rt, "run_worker", cancelling_worker)
+ store, runtime, run = _make_run(tmp_path)
+ cancel_event = threading.Event()
+
+ runtime._execute_run(run, cancel_event)
+
+ task = TaskStore(store.run_dir(run.id)).load_task("t1")
+ assert task.status == TaskStatus.cancelled, task.status
+ assert not task.error, f"a cancelled task must carry no failure error, got {task.error!r}"
+ assert task.worker_iterations == 2
+
+ event_types = [e.type for e in store.read_events(run.id)]
+ assert "task_cancelled" in event_types, event_types
+ assert "task_failed" not in event_types, event_types
+
+ assert store.load_run(run.id).status == RunStatus.cancelled
diff --git a/agent/tests/test_swarm_worker_cancel.py b/agent/tests/test_swarm_worker_cancel.py
new file mode 100644
index 000000000..3ccbb6407
--- /dev/null
+++ b/agent/tests/test_swarm_worker_cancel.py
@@ -0,0 +1,197 @@
+"""Worker-side half of cooperative swarm cancellation.
+
+``test_swarm_cancel_mid_flight_worker.py`` proves the runtime threads
+``cancel_event`` from ``cancel_run()`` into ``run_worker``; this file proves
+what ``run_worker`` does with it once it arrives:
+
+* set before an iteration starts → no LLM call is made, status ``cancelled``;
+* set while the stream is in flight → that turn's tool calls are never
+ dispatched, status ``cancelled`` (a control run shows the same response
+ *does* dispatch its tool when nothing is cancelled);
+* the event is handed to ``ChatLLM.stream_chat`` as ``should_cancel`` — the
+ same predicate ``AgentLoop`` passes — so the provider stream itself stops
+ early instead of running to its natural end.
+"""
+
+from __future__ import annotations
+
+import threading
+from pathlib import Path
+from unittest.mock import patch
+
+from src.providers.chat import LLMResponse, ToolCallRequest
+from src.swarm.models import SwarmAgentSpec, SwarmTask, WorkerResult
+import src.swarm.worker as worker_mod
+from src.swarm.worker import run_worker
+
+_TOOL_DEF = {
+ "type": "function",
+ "function": {"name": "noop_tool", "description": "no-op", "parameters": {"type": "object", "properties": {}}},
+}
+
+
+class _Registry:
+ """Registry stand-in exposing one tool and recording every dispatch."""
+
+ def __init__(self) -> None:
+ self.executed: list[str] = []
+
+ def get_definitions(self) -> list[dict]:
+ """Return the single scripted tool definition."""
+ return [_TOOL_DEF]
+
+ def get(self, name: str):
+ """Local-only registry: no MCPRemoteTool, so no remote metadata."""
+ return None
+
+ def execute(self, name: str, args: dict) -> str:
+ """Record the dispatch and return a benign JSON envelope."""
+ self.executed.append(name)
+ return '{"ok": true, "data": {}}'
+
+
+class _ScriptedLLM:
+ """``stream_chat`` stub that records its kwargs and can flip the cancel
+ flag while "streaming", the way ``should_cancel`` would fire mid-stream."""
+
+ def __init__(
+ self,
+ response: LLMResponse,
+ cancel_event: threading.Event | None = None,
+ set_on_stream: bool = False,
+ ) -> None:
+ self._response = response
+ self._cancel_event = cancel_event
+ self._set_on_stream = set_on_stream
+ self.calls = 0
+ self.should_cancel_seen: list[object] = []
+
+ def __call__(self, *args, **kwargs) -> "_ScriptedLLM":
+ """Support ``ChatLLM(model_name=...)`` constructor-style patching."""
+ return self
+
+ def close(self) -> None:
+ """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):
+ """Return the scripted response, optionally cancelling "mid-stream"."""
+ self.calls += 1
+ self.should_cancel_seen.append(should_cancel)
+ if self._set_on_stream and self._cancel_event is not None:
+ self._cancel_event.set()
+ return self._response
+
+
+def _tool_call_response() -> LLMResponse:
+ return LLMResponse(
+ content="",
+ tool_calls=[ToolCallRequest(id="c1", name="noop_tool", arguments={})],
+ finish_reason="tool_calls",
+ )
+
+
+def _run(tmp_path: Path, llm: _ScriptedLLM, registry: _Registry, cancel_event: threading.Event | None):
+ """Run one tool-enabled worker against the scripted LLM and registry."""
+ agent = SwarmAgentSpec(
+ id="analyst",
+ role="Analyst",
+ system_prompt="You analyse.",
+ tools=["noop_tool"],
+ skills=[],
+ max_iterations=2,
+ timeout_seconds=60,
+ )
+ task = SwarmTask(id="t1", agent_id="analyst", prompt_template="Do the thing.")
+ events: list[str] = []
+ with (
+ patch.object(worker_mod, "build_swarm_registry", lambda *a, **k: registry),
+ patch.object(worker_mod, "ChatLLM", llm),
+ ):
+ result = run_worker(
+ agent_spec=agent,
+ task=task,
+ upstream_summaries={},
+ user_vars={},
+ run_dir=tmp_path,
+ event_callback=lambda ev: events.append(ev.type),
+ cancel_event=cancel_event,
+ )
+ return result, events
+
+
+def test_cancel_set_before_first_iteration_makes_no_llm_call(tmp_path):
+ cancel_event = threading.Event()
+ cancel_event.set()
+ llm = _ScriptedLLM(_tool_call_response())
+ registry = _Registry()
+
+ result, events = _run(tmp_path, llm, registry, cancel_event)
+
+ assert isinstance(result, WorkerResult)
+ assert result.status == "cancelled"
+ assert llm.calls == 0, "a cancel signalled before the iteration must not start an LLM call"
+ assert registry.executed == []
+ assert "worker_cancelled" in events
+ assert "Cancelled" in result.summary
+
+
+def test_cancel_during_stream_skips_that_turns_tool_calls(tmp_path):
+ cancel_event = threading.Event()
+ llm = _ScriptedLLM(_tool_call_response(), cancel_event=cancel_event, set_on_stream=True)
+ registry = _Registry()
+
+ result, events = _run(tmp_path, llm, registry, cancel_event)
+
+ assert result.status == "cancelled"
+ assert llm.calls == 1
+ assert registry.executed == [], (
+ "tool calls from a turn whose stream was cancelled must not be dispatched, "
+ f"got {registry.executed}"
+ )
+ assert "worker_cancelled" in events
+ assert "tool_call" not in events
+
+
+def test_same_response_dispatches_its_tool_when_nothing_is_cancelled(tmp_path):
+ """Control for the test above: the scripted tool-call response really does
+ reach the registry when no cancellation fires, so the empty ``executed``
+ list there is the cancel check at work, not a stub that never dispatches."""
+ llm = _ScriptedLLM(_tool_call_response())
+ registry = _Registry()
+
+ result, events = _run(tmp_path, llm, registry, cancel_event=None)
+
+ assert result.status != "cancelled"
+ assert registry.executed == ["noop_tool", "noop_tool"], registry.executed
+ assert "tool_call" in events
+ assert "worker_cancelled" not in events
+
+
+def test_cancel_event_is_forwarded_to_stream_chat_as_should_cancel(tmp_path):
+ cancel_event = threading.Event()
+ llm = _ScriptedLLM(_tool_call_response())
+ registry = _Registry()
+
+ _run(tmp_path, llm, registry, cancel_event)
+
+ assert llm.should_cancel_seen, "stream_chat was never called"
+ predicate = llm.should_cancel_seen[0]
+ assert predicate == cancel_event.is_set, (
+ "the worker must hand cancel_event.is_set to stream_chat as should_cancel, "
+ "the same cooperative predicate AgentLoop uses"
+ )
+ assert predicate() is False
+ cancel_event.set()
+ assert predicate() is True
+
+
+def test_no_cancel_event_leaves_stream_chat_signature_untouched(tmp_path):
+ """Callers that never pass cancel_event (older call sites, tests with stubs
+ whose stream_chat has no should_cancel parameter) must see no new kwarg."""
+ llm = _ScriptedLLM(_tool_call_response())
+ registry = _Registry()
+
+ _run(tmp_path, llm, registry, cancel_event=None)
+
+ assert llm.should_cancel_seen and all(p is None for p in llm.should_cancel_seen)
diff --git a/frontend/src/lib/__tests__/swarmStatus.test.ts b/frontend/src/lib/__tests__/swarmStatus.test.ts
index 3c0c66efd..2037be092 100644
--- a/frontend/src/lib/__tests__/swarmStatus.test.ts
+++ b/frontend/src/lib/__tests__/swarmStatus.test.ts
@@ -74,3 +74,47 @@ describe("swarmStatus server timestamps", () => {
expect(truncated.completedAt).toBe(Date.parse("2026-07-29T12:00:09Z"));
});
});
+
+describe("swarmStatus cancellation events", () => {
+ it("marks a mid-flight worker cancelled, not failed, on task_cancelled", () => {
+ const initial = buildSwarmStatusFromStarted({
+ run_id: "run-cancel",
+ status: "running",
+ agents: [{ id: "analyst" }],
+ tasks: [{ id: "task-1", agent_id: "analyst", status: "pending" }],
+ })!;
+ const started = applySwarmEvent(initial, {
+ type: "task_started",
+ agent_id: "analyst",
+ task_id: "task-1",
+ timestamp: "2026-08-22T09:00:00Z",
+ });
+ const cancelled = applySwarmEvent(started, {
+ type: "task_cancelled",
+ task_id: "task-1",
+ timestamp: "2026-08-22T09:00:07Z",
+ data: { iterations: 2 },
+ });
+
+ expect(cancelled.agents[0].status).toBe("cancelled");
+ expect(cancelled.agents[0].iterations).toBe(2);
+ expect(cancelled.agents[0].elapsed_s).toBe(7);
+ expect(cancelled.agents[0].error).toBeUndefined();
+ });
+
+ it("maps the worker-side worker_cancelled event the same way", () => {
+ const initial = buildSwarmStatusFromStarted({
+ run_id: "run-cancel-2",
+ status: "running",
+ agents: [{ id: "analyst" }],
+ tasks: [{ id: "task-1", agent_id: "analyst", status: "in_progress" }],
+ })!;
+ const cancelled = applySwarmEvent(initial, {
+ type: "worker_cancelled",
+ agent_id: "analyst",
+ task_id: "task-1",
+ data: { iterations: 1 },
+ });
+ expect(cancelled.agents[0].status).toBe("cancelled");
+ });
+});
diff --git a/frontend/src/lib/swarmStatus.ts b/frontend/src/lib/swarmStatus.ts
index 8eadafdd9..158f041e4 100644
--- a/frontend/src/lib/swarmStatus.ts
+++ b/frontend/src/lib/swarmStatus.ts
@@ -265,6 +265,18 @@ export function applySwarmEvent(current: SwarmRunStatus, rawEvent: unknown): Swa
}));
}
+ if (type === "task_cancelled" || type === "worker_cancelled") {
+ // cancel_run() reached this worker mid-flight: a user stop, not a failure.
+ return updateAgent(current, { agentId, taskId }, (agent) => ({
+ ...agent,
+ status: "cancelled",
+ elapsed_s: agent.startedAt && eventTime
+ ? Math.max(0, (eventTime - agent.startedAt) / 1000)
+ : agent.elapsed_s,
+ iterations: asNumber(data.iterations) ?? agent.iterations,
+ }));
+ }
+
if (type === "task_blocked") {
const blockedBy = Array.isArray(data.blocked_by) ? data.blocked_by.join(", ") : asString(data.reason);
return updateAgent(current, { agentId, taskId }, (agent) => ({