"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(swarm): stop user-cancelled swarm runs
Zigen Haneb76f2d21de7
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex ca8bed1bd..dc4781aba 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -185,6 +185,7 @@ class AgentLoop(ToolCallLifecycle):event_callback: Optional[Callable[[str, Dict[str, Any]], None]] = None,max_iterations: int = 50,persistent_memory: Optional[Any] = None,+ cancel_event: Optional[threading.Event] = None,) -> None:"""Initialize AgentLoop.@@ -195,6 +196,10 @@ class AgentLoop(ToolCallLifecycle):event_callback: Event callback (event_type, data).max_iterations: Maximum number of loop iterations.persistent_memory: PersistentMemory for cross-session recall.+ cancel_event: Optional cancellation flag to share with long-running+ tools (e.g. ``run_swarm``). The host session owns the event so a+ user stop reaches both the loop and the tools it is blocked in;+ ``None`` keeps the loop self-contained (CLI and tests)."""self.registry = prepare_registry(registry)self.llm = llm@@ -232,7 +237,7 @@ class AgentLoop(ToolCallLifecycle):# Capture successful identities before context collapse can stub args.# Skipped/error call IDs never enter this ledger.self._successful_call_keys: dict[str, tuple[str, str]] = {}- self._cancel_event = threading.Event()+ self._cancel_event = cancel_event if cancel_event is not None else threading.Event()self._previous_summary: str = ""self._persistent_memory = persistent_memoryself._run_iteration: int = 0diff --git a/agent/src/api/swarm_routes.py b/agent/src/api/swarm_routes.pyindex 8cd4db22f..9c2ea17fc 100644--- a/agent/src/api/swarm_routes.py+++ b/agent/src/api/swarm_routes.py@@ -228,6 +228,12 @@ def register_swarm_routes(_host_validate_path_param(run_id, "run_id")runtime = _get_swarm_runtime()ok = runtime.cancel_run(run_id)+ if not ok:+ # Runs started by the agent are owned by a runtime created inside the+ # tool call; the module index is the only handle that reaches them.+ from src.swarm.runtime import cancel_indexed_run++ ok = cancel_indexed_run(run_id)if not ok:raise HTTPException(status_code=404, detail=f"No active run {run_id}")return {"status": "cancelled"}diff --git a/agent/src/session/service.py b/agent/src/session/service.pyindex 061856ffe..3a854e085 100644--- a/agent/src/session/service.py+++ b/agent/src/session/service.py@@ -43,6 +43,27 @@ _TERMINAL_EVENTS = {}+def _cancel_session_swarm_runs(session_id: str) -> int:+ """Signal every live swarm run started by this session.++ Imported lazily: ``src.swarm.runtime`` pulls in worker/tool modules that+ would create an import cycle at module load, and this helper is only needed+ on the cancel path.++ Args:+ session_id: Session whose swarm runs should stop.++ Returns:+ Number of runs that received a cancel signal.+ """+ try:+ from src.swarm.runtime import cancel_runs_for_session+ except Exception: # pragma: no cover - swarm extra missing in slim installs+ logger.debug("Swarm runtime unavailable; skipping swarm cancel", exc_info=True)+ return 0+ return cancel_runs_for_session(session_id)++class SessionBusyError(RuntimeError):"""Raised when a session already has an in-flight run.@@ -346,6 +367,9 @@ class SessionService:loop = self._active_loops.get(session_id)if loop is not None:loop.cancel()+ # The loop only stops the ReAct cycle; tools that spawned their own+ # background work (swarm) keep burning tokens unless told directly.+ _cancel_session_swarm_runs(session_id)return True# No loop yet: the run is still building its registry. Cancel the task# itself so the claim is released instead of stranding the session.@@ -353,6 +377,11 @@ class SessionService:if task is not None and not task.done():self._user_cancel_requests.add(session_id)task.cancel()+ _cancel_session_swarm_runs(session_id)+ return True+ # Loop already returned (budget exhausted, turn ended) but a swarm it+ # started may still be running in the background.+ if _cancel_session_swarm_runs(session_id):return Truereturn False@@ -552,6 +581,11 @@ class SessionService:"""Forward MCP server-name collision warnings to the operator event channel."""self.event_bus.emit(session_id, "mcp.warning", {"attempt_id": attempt_id, "message": msg})+ # One flag per turn, shared by the AgentLoop and the swarm tool. The+ # loop's own cancel() sets it, so a user stop reaches long-running tools+ # without a second cancellation channel that can drift out of sync.+ turn_cancel = threading.Event()+registry = await loop.run_in_executor(_AGENT_EXECUTOR,lambda: build_registry(@@ -561,6 +595,7 @@ class SessionService:session_id=session_id,event_callback=event_callback,warn_callback=_mcp_collision_warn,+ cancel_event=turn_cancel,),)@@ -572,6 +607,7 @@ class SessionService:event_callback=event_callback,max_iterations=get_env_config().agent_tuning.vibe_trading_agent_max_iterations,persistent_memory=pm,+ cancel_event=turn_cancel,)self._active_loops[session_id] = agentdiff --git a/agent/src/swarm/runtime.py b/agent/src/swarm/runtime.pyindex 9daad36de..eb17c6180 100644--- a/agent/src/swarm/runtime.py+++ b/agent/src/swarm/runtime.py@@ -54,6 +54,83 @@ from src.swarm.worker import agent_artifact_dir, clear_agent_artifacts, run_worklogger = logging.getLogger(__name__)+# Swarm runs that are still in flight, keyed by run id and owned by the session+# that started them. ``SwarmRuntime`` keeps its cancel events per instance, and+# ``run_swarm`` builds one instance per tool call — so an HTTP cancel handler+# holding a different runtime cannot reach a run started by the agent, and once+# the tool call returns (wait budget exhausted) nobody polls that instance at+# all. This module-level index is the only handle that outlives both: the owning+# session can still stop the run while its worker threads are burning tokens.+_ACTIVE_RUNS: dict[str, tuple[str, Callable[[], bool]]] = {}+_ACTIVE_RUNS_LOCK = threading.Lock()+++def register_active_run(run_id: str, session_id: str, cancel: Callable[[], bool]) -> None:+ """Index a freshly started run under the session that owns it."""+ with _ACTIVE_RUNS_LOCK:+ _ACTIVE_RUNS[run_id] = (session_id, cancel)+++def unregister_active_run(run_id: str) -> None:+ """Drop a run from the index once it is terminal or no longer ours."""+ with _ACTIVE_RUNS_LOCK:+ _ACTIVE_RUNS.pop(run_id, None)+++def cancel_indexed_run(run_id: str) -> bool:+ """Signal one indexed run regardless of which runtime started it.++ The HTTP cancel endpoint owns an app-level ``SwarmRuntime`` singleton, while+ agent-initiated runs live in the instance built inside the tool call. Without+ this fallback the endpoint answers 404 for exactly the runs a user is most+ likely to want stopped.+ """+ with _ACTIVE_RUNS_LOCK:+ entry = _ACTIVE_RUNS.pop(run_id, None)+ if entry is None:+ return False+ try:+ return bool(entry[1]())+ except Exception:+ logger.warning("Swarm cancel callback failed for run %s", run_id, exc_info=True)+ return False+++def active_run_ids(session_id: str) -> list[str]:+ """Return the run ids currently indexed for ``session_id``."""+ with _ACTIVE_RUNS_LOCK:+ return [rid for rid, (sid, _) in _ACTIVE_RUNS.items() if sid == session_id]+++def cancel_runs_for_session(session_id: str) -> int:+ """Signal every indexed run of ``session_id``; return how many were reached.++ Cancellation is requested for all of them before any is waited on, so a+ session with parallel runs stops them together instead of serially. Runs+ that accepted the signal leave the index: nothing else can be done for them,+ and keeping dead ids around would make ``cancel_current`` report success for+ a stop that changes nothing.+ """+ with _ACTIVE_RUNS_LOCK:+ targets = [+ (rid, cancel)+ for rid, (sid, cancel) in _ACTIVE_RUNS.items()+ if sid == session_id+ ]+ signalled: list[str] = []+ for run_id, cancel in targets:+ try:+ if cancel():+ signalled.append(run_id)+ except Exception:+ logger.warning("Swarm cancel callback failed for session %s", session_id, exc_info=True)+ if signalled:+ with _ACTIVE_RUNS_LOCK:+ for run_id in signalled:+ _ACTIVE_RUNS.pop(run_id, None)+ return len(signalled)++def _worker_retry_delay_ceiling_s(retry_number: int) -> float:"""Return the capped exponential ceiling for a one-based retry number."""if retry_number < 1:diff --git a/agent/src/tools/__init__.py b/agent/src/tools/__init__.pyindex ff06e2c20..e6e281cfc 100644--- a/agent/src/tools/__init__.py+++ b/agent/src/tools/__init__.py@@ -16,7 +16,7 @@ import pkgutilfrom collections.abc import Mappingfrom collections import dequefrom pathlib import Path-from typing import TYPE_CHECKING, Callable+from typing import TYPE_CHECKING, Any, Callablefrom src.agent.tools import BaseTool, ToolRegistry@@ -82,6 +82,7 @@ def build_registry(event_callback: Callable[[str, dict], None] | None = None,warn_callback: Callable[[str], None] | None = None,interactive: bool | None = None,+ cancel_event: Any | None = None,_mcp_server_tool_name_segments: Mapping[str, str] | None = None,) -> ToolRegistry:"""Build the tool registry via auto-discovery, optionally enriched with MCP tools.@@ -164,7 +165,14 @@ def build_registry(elif cls in session_injected_classes:registry.register(cls(default_session_id=session_id, event_callback=event_callback))elif cls is SwarmTool:- registry.register(cls(include_shell_tools=include_shell_tools, event_callback=event_callback))+ registry.register(+ cls(+ include_shell_tools=include_shell_tools,+ event_callback=event_callback,+ session_id=session_id,+ cancel_event=cancel_event,+ )+ )else:registry.register(cls())except Exception as exc:diff --git a/agent/src/tools/swarm_tool.py b/agent/src/tools/swarm_tool.pyindex 9def2c4f3..d08e2b6f7 100644--- a/agent/src/tools/swarm_tool.py+++ b/agent/src/tools/swarm_tool.py@@ -20,6 +20,11 @@ logger = logging.getLogger(__name__)_POLL_INTERVAL_SECONDS = 5+# How long a user-cancelled run gets to reach a terminal state before the tool+# reports "cancelling" instead of a settled result. Workers honour the cancel+# flag between iterations, so this only covers one in-flight LLM call.+_CANCEL_SETTLE_SECONDS = 20+def _max_wait_seconds() -> int:import sys as _sys@@ -499,6 +504,8 @@ class SwarmTool(BaseTool):*,include_shell_tools: bool = False,event_callback: Any | None = None,+ session_id: str | None = None,+ cancel_event: Any | None = None,) -> None:"""Initialize the swarm launcher.@@ -506,9 +513,16 @@ class SwarmTool(BaseTool):include_shell_tools: Whether worker registries may include shellexecution tools requested by presets.event_callback: Optional session event bridge used by the web chat.+ session_id: Session that owns this call. Used to index the run so a+ later user stop from the same session can still reach it.+ cancel_event: Cancellation flag shared with the hosting AgentLoop.+ Polled while waiting on the run so a user stop ends the wait+ instead of leaving the tool blocked for the whole budget."""self.include_shell_tools = include_shell_toolsself._event_callback = event_callback+ self._session_id = session_id+ self._cancel_event = cancel_eventdef _emit_session_event(self, event_type: str, data: dict[str, Any]) -> None:"""Forward swarm status to the hosting session SSE channel if present."""@@ -559,7 +573,7 @@ class SwarmTool(BaseTool):)from src.config import load_swarm_agent_config- from src.swarm.runtime import SwarmRuntime+ from src.swarm.runtime import SwarmRuntime, register_active_run, unregister_active_runfrom src.swarm.store import SwarmStore, swarm_runs_rootswarm_base_dir = swarm_runs_root()@@ -637,33 +651,113 @@ class SwarmTool(BaseTool):t0 = time.monotonic()max_wait = _max_wait_seconds()- while time.monotonic() - t0 < max_wait:- time.sleep(_POLL_INTERVAL_SECONDS)-+ # Index the run so a user stop arriving after this call returns (budget+ # exhausted, or from the HTTP cancel endpoint holding a different+ # runtime) can still reach it.+ if self._session_id is not None:+ register_active_run(run_id, self._session_id, lambda: runtime.cancel_run(run_id))+ # Only a terminal run leaves the index. On the timeout path the worker+ # threads are still alive, so dropping the entry there would make a+ # later user stop unable to reach them.+ settled = False+ try:+ while time.monotonic() - t0 < max_wait:+ if self._cancel_event is not None:+ # wait() returns as soon as the flag is set, so a stop does+ # not have to sit out the poll interval.+ if self._cancel_event.wait(_POLL_INTERVAL_SECONDS):+ settled = True+ return self._stop_cancelled_run(+ runtime, store, run_id, preset, variables+ )+ else:+ time.sleep(_POLL_INTERVAL_SECONDS)++ loaded = store.load_run(run_id)+ if loaded is None:+ settled = True+ return json.dumps(+ {"status": "error", "error": f"Run {run_id} disappeared"},+ ensure_ascii=False,+ )++ reconciled = store.reconcile_run(loaded, write=True)+ if reconciled.status.value in ("completed", "failed", "cancelled"):+ settled = True+ return _format_result(reconciled, preset, variables)++ # Wait budget elapsed but the run is still in flight. Do NOT cancel —+ # the daemon thread keeps working and the agent can decide to wait+ # more (re-invoke with the returned run_id) or hand off partial state+ # to the user. Cancelling here used to throw away minutes of LLM cost+ # whenever a preset legitimately ran past the budget.loaded = store.load_run(run_id)- if loaded is None:- return json.dumps(- {"status": "error", "error": f"Run {run_id} disappeared"},- ensure_ascii=False,+ if loaded is not None:+ return _format_result(+ store.reconcile_run(loaded, write=True), preset, variables, timed_out=True)- reconciled = store.reconcile_run(loaded, write=True)- if reconciled.status.value in ("completed", "failed", "cancelled"):- return _format_result(reconciled, preset, variables)+ return json.dumps(+ {"status": "timeout", "error": f"Swarm run {run_id} timed out after {max_wait}s"},+ ensure_ascii=False,+ )+ finally:+ if settled:+ unregister_active_run(run_id)++ def _stop_cancelled_run(+ self,+ runtime: Any,+ store: Any,+ run_id: str,+ preset: str,+ variables: dict[str, str],+ ) -> str:+ """Stop a run after a user cancel and report its terminal state.++ The runtime owns the per-run cancel event; signalling it makes workers+ mark their tasks ``cancelled`` instead of failing, so the persisted run+ stays internally consistent (and resumable) rather than looking crashed.+ """+ runtime.cancel_run(run_id)+ self._emit_session_event(+ "swarm.cancelled",+ {"run_id": run_id, "reason": "user_cancelled"},+ )- # Wait budget elapsed but the run is still in flight. Do NOT cancel —- # the daemon thread keeps working and the agent can decide to wait- # more (re-invoke with the returned run_id) or hand off partial state- # to the user. Cancelling here used to throw away minutes of LLM cost- # whenever a preset legitimately ran past the budget.+ deadline = time.monotonic() + _CANCEL_SETTLE_SECONDSloaded = store.load_run(run_id)- if loaded is not None:- return _format_result(- store.reconcile_run(loaded, write=True), preset, variables, timed_out=True+ while loaded is not None and loaded.status.value not in (+ "completed",+ "failed",+ "cancelled",+ ):+ if time.monotonic() >= deadline:+ break+ time.sleep(_POLL_INTERVAL_SECONDS)+ loaded = store.load_run(run_id)++ if loaded is None:+ return json.dumps(+ {"status": "cancelled", "cancelled_by_user": True, "run_id": run_id},+ ensure_ascii=False,)+ settled = store.reconcile_run(loaded, write=True)+ if settled.status.value in ("completed", "failed", "cancelled"):+ return _format_result(settled, preset, variables, cancelled_by_user=True)++ # The cancel flag is set but a worker was mid-LLM-call when the settle+ # window closed. Report what we know instead of claiming a terminal+ # state the store does not have.return json.dumps(- {"status": "timeout", "error": f"Swarm run {run_id} timed out after {max_wait}s"},+ {+ "status": "cancelling",+ "cancelled_by_user": True,+ "run_id": run_id,+ "preset": preset,+ "auto_variables": variables,+ },ensure_ascii=False,)@@ -673,6 +767,7 @@ def _format_result(preset: str,variables: dict[str, str],timed_out: bool = False,+ cancelled_by_user: bool = False,) -> str:"""Format a SwarmRun into a JSON result string.@@ -681,6 +776,7 @@ def _format_result(preset: Matched preset name.variables: Extracted variables.timed_out: Whether the run was terminated due to timeout.+ cancelled_by_user: Whether the user stopped the run before it finished.Returns:JSON string with run status, report, task summaries, and token usage.@@ -696,6 +792,7 @@ def _format_result(result = {"status": run.status.value,"wait_budget_exhausted": timed_out,+ "cancelled_by_user": cancelled_by_user,"run_id": run.id,"preset": preset,"auto_variables": variables,diff --git a/agent/tests/test_session_service_mcp.py b/agent/tests/test_session_service_mcp.pyindex 86d1e5563..ff684563c 100644--- a/agent/tests/test_session_service_mcp.py+++ b/agent/tests/test_session_service_mcp.py@@ -23,7 +23,7 @@ class _DummyIndex:class _DummyAgentLoop:- def __init__(self, *, registry, llm, event_callback, max_iterations, persistent_memory) -> None:+ def __init__(self, *, registry, llm, event_callback, max_iterations, persistent_memory, cancel_event=None) -> None:del registry, llm, event_callback, max_iterations, persistent_memorydef run(self, *, user_message: str, history, session_id: str) -> dict[str, str]:diff --git a/agent/tests/test_session_tool_trail.py b/agent/tests/test_session_tool_trail.pyindex fe43cacde..4af23b276 100644--- a/agent/tests/test_session_tool_trail.py+++ b/agent/tests/test_session_tool_trail.py@@ -144,8 +144,9 @@ def test_run_with_agent_consolidates_tool_events_by_call_id(event_callback,max_iterations,persistent_memory,+ cancel_event=None,) -> None:- del registry, llm, max_iterations, persistent_memory+ del registry, llm, max_iterations, persistent_memory, cancel_eventself._event_callback = event_callbackdef run(self, *, user_message: str, history, session_id: str):diff --git a/agent/tests/test_swarm_cancel_cascade.py b/agent/tests/test_swarm_cancel_cascade.pynew file mode 100644index 000000000..d095a3666--- /dev/null+++ b/agent/tests/test_swarm_cancel_cascade.py@@ -0,0 +1,254 @@+"""Regression tests for #2055 — a user stop must actually stop a swarm run.++The bug had three layers, and this file pins the two backend ones:++1. ``SessionService.cancel_current`` only cancelled the ``AgentLoop``; the swarm+ the loop had started kept running.+2. ``SwarmTool.execute`` polled in a ``time.sleep`` loop, so even a cancelled+ session left the tool (and its worker threads) burning tokens until the wait+ budget ran out.++The frontend half (a stop button that calls the cancel endpoint) lives in the+web client and is covered by its own tests.+"""++from __future__ import annotations++import json+import threading+import time+from datetime import datetime, timedelta, timezone++import pytest++import src.swarm.runtime as rt+import src.swarm.store as store_mod+import src.tools.swarm_tool as swarm_tool+from src.swarm.models import (+ RunStatus,+ SwarmAgentSpec,+ SwarmRun,+ SwarmTask,+)+from src.tools.swarm_tool import SwarmTool+++def _iso(dt: datetime) -> str:+ return dt.astimezone(timezone.utc).isoformat()+++def _running_run(run_id: str = "r-cancel") -> SwarmRun:+ agent = SwarmAgentSpec(+ id="analyst",+ role="Analyst",+ system_prompt="x",+ timeout_seconds=300,+ )+ task = SwarmTask(id="t1", agent_id="analyst", prompt_template="do x")+ run = SwarmRun(+ id=run_id,+ preset_name="demo",+ created_at=_iso(datetime.now(timezone.utc)),+ agents=[agent],+ tasks=[task],+ )+ run.status = RunStatus.running+ return run++[email protected](autouse=True)+def _clean_index():+ """Keep the module-level run index from leaking between tests."""+ rt._ACTIVE_RUNS.clear()+ yield+ rt._ACTIVE_RUNS.clear()+++# ---------------------------------------------------------------------------+# 1. SwarmTool honours the session cancel flag+# ---------------------------------------------------------------------------+++def test_execute_returns_cancelled_without_waiting_for_the_poll(tmp_path, monkeypatch):+ """A cancelled session must end the tool call, not the 5s poll interval."""+ monkeypatch.setattr(store_mod, "swarm_runs_root", lambda: tmp_path)+ monkeypatch.setattr(swarm_tool, "_POLL_INTERVAL_SECONDS", 0.01)+ monkeypatch.setattr(swarm_tool, "_CANCEL_SETTLE_SECONDS", 1.0)++ run = _running_run()+ store = store_mod.SwarmStore(base_dir=tmp_path)+ store.create_run(run)++ cancel_calls: list[str] = []++ def fake_start_run(self, preset_name, variables, **kwargs):+ return run++ def fake_cancel_run(self, run_id):+ cancel_calls.append(run_id)+ # Mimic a worker honouring the flag at the end of its current step.+ cancelled = store.load_run(run_id)+ assert cancelled is not None+ cancelled.status = RunStatus.cancelled+ store.update_run(cancelled)+ return True++ monkeypatch.setattr(rt.SwarmRuntime, "start_run", fake_start_run)+ monkeypatch.setattr(rt.SwarmRuntime, "cancel_run", fake_cancel_run)+ monkeypatch.setattr(swarm_tool, "_resolve_preset", lambda prompt, name: ("demo", None))+ monkeypatch.setattr(swarm_tool, "_build_variables", lambda preset, prompt: ({}, None))++ stop = threading.Event()+ tool = SwarmTool(session_id="sess-1", cancel_event=stop)++ def cancel_soon():+ time.sleep(0.05)+ stop.set()++ threading.Thread(target=cancel_soon, daemon=True).start()++ started = time.monotonic()+ payload = json.loads(tool.execute(prompt="analyse NVDA"))+ elapsed = time.monotonic() - started++ assert payload["status"] == "cancelled", payload+ assert payload["cancelled_by_user"] is True+ assert payload["run_id"] == "r-cancel"+ assert cancel_calls == ["r-cancel"]+ # Budget is 300s+ and the poll interval is 5s in production; anything close+ # to that means the flag was not being watched.+ assert elapsed < 1.0, f"cancel took {elapsed:.2f}s"+ # A cancelled run is terminal, so it must not linger in the index.+ assert rt.active_run_ids("sess-1") == []+++def test_execute_does_not_cancel_on_budget_exhaustion(tmp_path, monkeypatch):+ """Guard the old behaviour: a timed-out wait must leave the run alive."""+ monkeypatch.setattr(store_mod, "swarm_runs_root", lambda: tmp_path)+ monkeypatch.setattr(swarm_tool, "_POLL_INTERVAL_SECONDS", 0.01)+ monkeypatch.setattr(swarm_tool, "_max_wait_seconds", lambda: 0)++ run = _running_run("r-timeout")+ store = store_mod.SwarmStore(base_dir=tmp_path)+ store.create_run(run)++ monkeypatch.setattr(rt.SwarmRuntime, "start_run", lambda self, p, v, **kw: run)++ def boom(self, run_id): # pragma: no cover - must never be reached+ raise AssertionError("budget exhaustion must not cancel the run")++ monkeypatch.setattr(rt.SwarmRuntime, "cancel_run", boom)+ monkeypatch.setattr(swarm_tool, "_resolve_preset", lambda prompt, name: ("demo", None))+ monkeypatch.setattr(swarm_tool, "_build_variables", lambda preset, prompt: ({}, None))++ tool = SwarmTool(session_id="sess-2", cancel_event=threading.Event())+ payload = json.loads(tool.execute(prompt="analyse NVDA"))++ assert payload["status"] == "running"+ assert payload["wait_budget_exhausted"] is True+ # Still indexed: the user may stop it after the tool returned.+ assert rt.active_run_ids("sess-2") == ["r-timeout"]+++# ---------------------------------------------------------------------------+# 2. The run index the session uses to reach a run it no longer polls+# ---------------------------------------------------------------------------+++def test_cancel_runs_for_session_only_touches_its_own_runs():+ signalled: list[str] = []++ def cancel(run_id):+ signalled.append(run_id)+ return True++ rt.register_active_run("r1", "sess-a", lambda: cancel("r1"))+ rt.register_active_run("r2", "sess-b", lambda: cancel("r2"))++ assert rt.cancel_runs_for_session("sess-a") == 1+ assert signalled == ["r1"]+ # Signalled runs leave the index so a second stop is a no-op.+ assert rt.cancel_runs_for_session("sess-a") == 0+ assert rt.active_run_ids("sess-b") == ["r2"]+++def test_cancel_indexed_run_reaches_a_foreign_runtime_run():+ """The HTTP endpoint holds a different SwarmRuntime; the index bridges it."""+ rt.register_active_run("r1", "sess-a", lambda: True)++ assert rt.cancel_indexed_run("r1") is True+ assert rt.cancel_indexed_run("r1") is False+++# ---------------------------------------------------------------------------+# 3. SessionService.cancel_current cascades+# ---------------------------------------------------------------------------+++class _FakeLoop:+ def __init__(self):+ self.cancelled = False++ def cancel(self):+ self.cancelled = True+++def _bare_service():+ from src.session.service import SessionService++ service = SessionService.__new__(SessionService)+ service._active_loops = {}+ service._active_tasks = {}+ service._user_cancel_requests = set()+ return service+++def test_cancel_current_cancels_the_swarm_of_that_session(monkeypatch):+ seen: list[str] = []++ def fake_cancel_runs_for_session(session_id):+ seen.append(session_id)+ return 1++ monkeypatch.setattr(rt, "cancel_runs_for_session", fake_cancel_runs_for_session)++ service = _bare_service()+ loop = _FakeLoop()+ service._active_loops["sess-1"] = loop++ assert service.cancel_current("sess-1") is True+ assert loop.cancelled is True+ assert seen == ["sess-1"]+++def test_cancel_current_stops_a_swarm_whose_turn_already_ended(monkeypatch):+ """No loop, no task — the run outlived the turn and is still cancellable."""+ monkeypatch.setattr(rt, "cancel_runs_for_session", lambda session_id: 2)++ service = _bare_service()++ assert service.cancel_current("sess-2") is True+++def test_cancel_current_reports_false_when_nothing_is_running(monkeypatch):+ monkeypatch.setattr(rt, "cancel_runs_for_session", lambda session_id: 0)++ service = _bare_service()++ assert service.cancel_current("sess-3") is False+++# ---------------------------------------------------------------------------+# 4. The shared flag wiring the loop and the tool together+# ---------------------------------------------------------------------------+++def test_agent_loop_accepts_a_shared_cancel_event():+ """AgentLoop must reuse the caller's flag, otherwise cancel() cannot reach+ the tools that were built before the loop existed."""+ import inspect++ from src.agent.loop import AgentLoop++ signature = inspect.signature(AgentLoop.__init__)+ assert "cancel_event" in signature.parametersdiff --git a/agent/tests/test_swarm_status_hydration.py b/agent/tests/test_swarm_status_hydration.pyindex a54931404..9fc6e361d 100644--- a/agent/tests/test_swarm_status_hydration.py+++ b/agent/tests/test_swarm_status_hydration.py@@ -534,16 +534,29 @@ def test_swarm_tool_format_result_preserves_running_status_on_budget_out():def test_swarm_tool_no_longer_cancels_on_budget_out():- """Source-level guard: the SwarmTool wait loop must not call cancel_run- when its budget elapses — that used to throw away in-flight LLM work."""+ """Source-level guard: the budget-exhaustion branch of the SwarmTool wait+ loop must not call cancel_run — that used to throw away in-flight LLM work.++ Cancelling the run is allowed only when the *user* stops it, so the guard now+ covers the tail of ``execute`` (everything after the budget note) instead of+ the whole method.+ """import inspectimport src.tools.swarm_tool as swarm_toolsource = inspect.getsource(swarm_tool.SwarmTool.execute)- assert "cancel_run" not in source, (+ marker = "# Wait budget elapsed"+ assert marker in source, "budget-exhaustion branch marker is gone"+ tail = source[source.index(marker) :]+ assert "cancel_run" not in tail, ("SwarmTool.execute must not cancel the run on budget exhaustion; ""return partial state and let the agent decide.")+ # The only legitimate trigger is the session cancel flag shared with AgentLoop.+ assert "_cancel_event" in source, (+ "SwarmTool.execute must watch the session cancel flag so a user stop "+ "reaches the run."+ )def test_run_swarm_first_progress_frame_carries_run_id(tmp_path, monkeypatch):