Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(swarm): resume and close event streams correctly

xkam7ar1e214ef1c817
diff --git a/agent/src/api/swarm_routes.py b/agent/src/api/swarm_routes.py
index bf95663b4..dd8703391 100644
--- a/agent/src/api/swarm_routes.py
+++ b/agent/src/api/swarm_routes.py
@@ -9,7 +9,7 @@ import json
from pathlib import Path
from typing import Any, Awaitable, Callable
-from fastapi import Depends, FastAPI, HTTPException, Query, Request
+from fastapi import Depends, FastAPI, Header, HTTPException, Query, Request
from fastapi.responses import StreamingResponse
# ---------------------------------------------------------------------------
@@ -159,16 +159,23 @@ def register_swarm_routes(
dependencies=[Depends(require_event_stream_auth)],
)
async def swarm_run_events(
- run_id: str, request: Request, last_index: int = Query(0, ge=0)
+ run_id: str,
+ request: Request,
+ last_index: int = Query(0, ge=0),
+ last_event_id: int | None = Header(None, alias="Last-Event-ID", ge=0),
):
"""SSE stream for a swarm run."""
import asyncio
_host_validate_path_param(run_id, "run_id")
runtime = _get_swarm_runtime()
+ if not runtime._store.load_run(run_id):
+ raise HTTPException(status_code=404, detail=f"Run {run_id} not found")
async def event_stream():
- idx = last_index
+ # Browser EventSource reconnects with Last-Event-ID. Keep the
+ # existing query parameter for non-browser and older clients.
+ idx = last_event_id if last_event_id is not None else last_index
while True:
if await request.is_disconnected():
break
@@ -177,14 +184,16 @@ def register_swarm_routes(
idx += 1
yield f"id: {idx}\nevent: {evt.type}\ndata: {json.dumps(evt.model_dump(), ensure_ascii=False)}\n\n"
run = runtime._store.load_run(run_id)
- if run:
- # Reconcile so a zombie running run can still close this SSE
- # stream cleanly — without it, a dead host would keep the
- # stream open forever and block the dashboard's "done" state.
- reconciled = runtime._store.reconcile_run(run, write=True)
- if reconciled.status.value in ("completed", "failed", "cancelled"):
- yield f"event: done\ndata: {{\"status\": \"{reconciled.status.value}\"}}\n\n"
- break
+ if not run:
+ yield 'event: done\ndata: {"status": "missing"}\n\n'
+ break
+ # Reconcile so a zombie running run can still close this SSE
+ # stream cleanly — without it, a dead host would keep the
+ # stream open forever and block the dashboard's "done" state.
+ reconciled = runtime._store.reconcile_run(run, write=True)
+ if reconciled.status.value in ("completed", "failed", "cancelled"):
+ yield f'event: done\ndata: {{"status": "{reconciled.status.value}"}}\n\n'
+ break
await asyncio.sleep(2)
return StreamingResponse(event_stream(), media_type="text/event-stream")
diff --git a/agent/tests/test_swarm_route_contracts.py b/agent/tests/test_swarm_route_contracts.py
new file mode 100644
index 000000000..0dee9bc58
--- /dev/null
+++ b/agent/tests/test_swarm_route_contracts.py
@@ -0,0 +1,102 @@
+"""Public swarm REST and SSE contract regressions."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from fastapi.testclient import TestClient
+
+import api_server
+import src.api.swarm_routes as swarm_routes
+from src.swarm.models import RunStatus, SwarmEvent, SwarmRun
+from src.swarm.store import SwarmStore
+
+
+def swarm_store(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> SwarmStore:
+ """Route the process-wide swarm endpoint at an isolated on-disk store."""
+ store = SwarmStore(base_dir=tmp_path / "runs")
+ monkeypatch.delenv("API_AUTH_KEY", raising=False)
+ monkeypatch.setattr(api_server, "_API_KEY", "")
+ monkeypatch.setattr(swarm_routes, "_swarm_runtime", SimpleNamespace(_store=store))
+ return store
+
+
+def _client() -> TestClient:
+ return TestClient(api_server.app, client=("127.0.0.1", 50000))
+
+
+def _create_run(
+ store: SwarmStore,
+ *,
+ run_id: str = "run-contract",
+ status: RunStatus = RunStatus.pending,
+) -> SwarmRun:
+ run = SwarmRun(
+ id=run_id,
+ preset_name="contract-test",
+ status=status,
+ created_at="2026-07-16T00:00:00+00:00",
+ completed_at=(
+ "2026-07-16T00:00:01+00:00" if status == RunStatus.completed else None
+ ),
+ )
+ store.create_run(run)
+ return run
+
+
+def test_swarm_events_returns_404_before_streaming_missing_run(
+ swarm_store: SwarmStore,
+) -> None:
+ response = _client().get("/swarm/runs/missing-run/events")
+
+ assert response.status_code == 404
+ assert response.json()["detail"] == "Run missing-run not found"
+
+
+def test_swarm_events_resumes_from_last_event_id_header(
+ swarm_store: SwarmStore,
+) -> None:
+ run = _create_run(swarm_store, status=RunStatus.completed)
+ for index in range(1, 4):
+ swarm_store.append_event(
+ run.id,
+ SwarmEvent(
+ type=f"step_{index}",
+ data={"index": index},
+ timestamp=f"2026-07-16T00:00:0{index}+00:00",
+ ),
+ )
+
+ response = _client().get(
+ f"/swarm/runs/{run.id}/events?last_index=1",
+ headers={"Last-Event-ID": "2"},
+ )
+
+ assert response.status_code == 200
+ assert "event: step_1" not in response.text
+ assert "event: step_2" not in response.text
+ assert "id: 3\nevent: step_3" in response.text
+ assert 'event: done\ndata: {"status": "completed"}' in response.text
+
+
+def test_swarm_events_keeps_last_index_query_compatibility(
+ swarm_store: SwarmStore,
+) -> None:
+ run = _create_run(swarm_store, status=RunStatus.completed)
+ for index in range(1, 3):
+ swarm_store.append_event(
+ run.id,
+ SwarmEvent(
+ type=f"query_step_{index}",
+ timestamp=f"2026-07-16T00:00:0{index}+00:00",
+ ),
+ )
+
+ response = _client().get(f"/swarm/runs/{run.id}/events?last_index=1")
+
+ assert response.status_code == 200
+ assert "event: query_step_1" not in response.text
+ assert "id: 2\nevent: query_step_2" in response.text