Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(web): show swarm agent status in chat (#188)

Chengcheng Dingf194e51f4d5d
diff --git a/agent/src/tools/__init__.py b/agent/src/tools/__init__.py
index c246f3a95..3e0a34289 100644
--- a/agent/src/tools/__init__.py
+++ b/agent/src/tools/__init__.py
@@ -142,7 +142,7 @@ def build_registry(
elif cls in goal_tool_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))
+ registry.register(cls(include_shell_tools=include_shell_tools, event_callback=event_callback))
else:
registry.register(cls())
except Exception as exc:
diff --git a/agent/src/tools/swarm_tool.py b/agent/src/tools/swarm_tool.py
index df7ae69ac..5c5584044 100644
--- a/agent/src/tools/swarm_tool.py
+++ b/agent/src/tools/swarm_tool.py
@@ -585,14 +585,30 @@ class SwarmTool(BaseTool):
is_readonly = False
repeatable = True # loop.py dedups by tool name; each prompt is a distinct run (#42)
- def __init__(self, *, include_shell_tools: bool = False) -> None:
+ def __init__(
+ self,
+ *,
+ include_shell_tools: bool = False,
+ event_callback: Any | None = None,
+ ) -> None:
"""Initialize the swarm launcher.
Args:
include_shell_tools: Whether worker registries may include shell
execution tools requested by presets.
+ event_callback: Optional session event bridge used by the web chat.
"""
self.include_shell_tools = include_shell_tools
+ self._event_callback = event_callback
+
+ def _emit_session_event(self, event_type: str, data: dict[str, Any]) -> None:
+ """Forward swarm status to the hosting session SSE channel if present."""
+ if self._event_callback is None:
+ return
+ try:
+ self._event_callback(event_type, data)
+ except Exception:
+ logger.warning("Failed to forward %s to session event stream", event_type, exc_info=True)
def execute(self, **kwargs: Any) -> str:
"""Start a swarm run: auto-match preset, extract variables, wait for completion.
@@ -638,10 +654,25 @@ class SwarmTool(BaseTool):
agent_config=agent_config,
)
+ pending_live_events: list[dict[str, Any]] = []
+ run_id_holder: dict[str, str | None] = {"run_id": None}
+
try:
+ def _live_callback(event: Any) -> None:
+ payload = event.model_dump()
+ current_run_id = run_id_holder["run_id"]
+ if current_run_id is None:
+ pending_live_events.append(payload)
+ return
+ self._emit_session_event(
+ "swarm.event",
+ {"run_id": current_run_id, "event": payload},
+ )
+
run = runtime.start_run(
preset,
variables,
+ live_callback=_live_callback if self._event_callback is not None else None,
include_shell_tools=self.include_shell_tools,
)
except FileNotFoundError as exc:
@@ -661,7 +692,25 @@ class SwarmTool(BaseTool):
)
run_id = run.id
+ run_id_holder["run_id"] = run_id
logger.info("SwarmTool: started run %s (preset=%s)", run_id, preset)
+ self._emit_session_event(
+ "swarm.started",
+ {
+ "run_id": run_id,
+ "preset": preset,
+ "variables": variables,
+ "status": run.status.value,
+ "agents": [agent.model_dump() for agent in run.agents],
+ "tasks": [task.model_dump() for task in run.tasks],
+ },
+ )
+ for event_payload in pending_live_events:
+ self._emit_session_event(
+ "swarm.event",
+ {"run_id": run_id, "event": event_payload},
+ )
+ pending_live_events.clear()
t0 = time.monotonic()
while time.monotonic() - t0 < _MAX_WAIT_SECONDS:
diff --git a/agent/tests/test_swarm_status_hydration.py b/agent/tests/test_swarm_status_hydration.py
index 00e751b41..eb3b7ed7c 100644
--- a/agent/tests/test_swarm_status_hydration.py
+++ b/agent/tests/test_swarm_status_hydration.py
@@ -591,3 +591,95 @@ def test_worker_source_wires_heartbeat_around_tool_execute():
exec_idx = source.find("registry.execute(", timer_idx)
next_dedent = source.find("\n ", exec_idx) # exit the `with` block
assert 0 < timer_idx < exec_idx < next_dedent
+
+
+def test_swarm_tool_forwards_started_and_live_events(monkeypatch):
+ """Web chat sessions should receive a status card seed plus live swarm events."""
+ import src.tools.swarm_tool as swarm_tool
+
+ run = _base_run("r-web-chat")
+ run.status = RunStatus.running
+ captured: list[tuple[str, dict]] = []
+
+ class FakeStore:
+ def __init__(self, base_dir):
+ self.base_dir = base_dir
+
+ def load_run(self, run_id):
+ return run if run_id == run.id else None
+
+ def reconcile_run(self, loaded, write=False):
+ return loaded
+
+ class FakeRuntime:
+ def __init__(self, store, max_workers=4, agent_config=None):
+ self._store = store
+
+ def start_run(self, preset, variables, live_callback=None, include_shell_tools=False):
+ assert live_callback is not None
+ live_callback(
+ SwarmEvent(
+ type="task_started",
+ agent_id="analyst",
+ task_id="t1",
+ data={},
+ timestamp=_iso(datetime.now(timezone.utc)),
+ )
+ )
+ return run
+
+ monkeypatch.setattr(swarm_tool, "_MAX_WAIT_SECONDS", 0)
+ monkeypatch.setattr(swarm_tool, "_match_preset", lambda prompt: "demo")
+ monkeypatch.setattr(swarm_tool, "_build_variables", lambda preset, prompt: {"goal": prompt})
+ monkeypatch.setattr("src.config.load_swarm_agent_config", lambda: None)
+ monkeypatch.setattr("src.swarm.store.SwarmStore", FakeStore)
+ monkeypatch.setattr("src.swarm.runtime.SwarmRuntime", FakeRuntime)
+
+ tool = swarm_tool.SwarmTool(event_callback=lambda etype, data: captured.append((etype, data)))
+ payload = json.loads(tool.execute(prompt="analyze AAPL"))
+
+ assert payload["run_id"] == "r-web-chat"
+ assert captured[0][0] == "swarm.started"
+ assert captured[0][1]["run_id"] == "r-web-chat"
+ assert captured[0][1]["agents"][0]["id"] == "analyst"
+ assert captured[1][0] == "swarm.event"
+ assert captured[1][1]["run_id"] == "r-web-chat"
+ assert captured[1][1]["event"]["type"] == "task_started"
+
+
+def test_swarm_tool_without_session_callback_preserves_plain_runtime(monkeypatch):
+ """No session bridge means no live callback is installed."""
+ import src.tools.swarm_tool as swarm_tool
+
+ run = _base_run("r-no-session")
+ run.status = RunStatus.running
+
+ class FakeStore:
+ def __init__(self, base_dir):
+ self.base_dir = base_dir
+
+ def load_run(self, run_id):
+ return run if run_id == run.id else None
+
+ def reconcile_run(self, loaded, write=False):
+ return loaded
+
+ class FakeRuntime:
+ def __init__(self, store, max_workers=4, agent_config=None):
+ self._store = store
+
+ def start_run(self, preset, variables, live_callback=None, include_shell_tools=False):
+ assert live_callback is None
+ return run
+
+ monkeypatch.setattr(swarm_tool, "_MAX_WAIT_SECONDS", 0)
+ monkeypatch.setattr(swarm_tool, "_match_preset", lambda prompt: "demo")
+ monkeypatch.setattr(swarm_tool, "_build_variables", lambda preset, prompt: {"goal": prompt})
+ monkeypatch.setattr("src.config.load_swarm_agent_config", lambda: None)
+ monkeypatch.setattr("src.swarm.store.SwarmStore", FakeStore)
+ monkeypatch.setattr("src.swarm.runtime.SwarmRuntime", FakeRuntime)
+
+ payload = json.loads(swarm_tool.SwarmTool().execute(prompt="analyze AAPL"))
+
+ assert payload["run_id"] == "r-no-session"
+ assert payload["status"] == "running"
diff --git a/frontend/src/components/chat/SwarmStatusCard.tsx b/frontend/src/components/chat/SwarmStatusCard.tsx
new file mode 100644
index 000000000..2d9d6b837
--- /dev/null
+++ b/frontend/src/components/chat/SwarmStatusCard.tsx
@@ -0,0 +1,174 @@
+import { memo } from "react";
+import {
+ CheckCircle2,
+ Circle,
+ Clock,
+ Loader2,
+ RotateCcw,
+ ShieldAlert,
+ Users,
+ XCircle,
+} from "lucide-react";
+import { ProgressBar } from "@/components/chat/ProgressBar";
+import { localizeToolName } from "@/lib/tools";
+import type { SwarmAgentDisplayStatus, SwarmRunStatus } from "@/types/agent";
+
+interface Props {
+ status: SwarmRunStatus;
+}
+
+function formatElapsed(seconds: number | undefined): string {
+ if (seconds == null || !Number.isFinite(seconds) || seconds <= 0) return "-";
+ if (seconds < 60) return `${seconds.toFixed(seconds < 10 ? 1 : 0)}s`;
+ const mins = Math.floor(seconds / 60);
+ const secs = Math.round(seconds % 60);
+ return `${mins}m ${secs}s`;
+}
+
+function statusTone(status: SwarmAgentDisplayStatus): string {
+ switch (status) {
+ case "done":
+ return "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400";
+ case "failed":
+ return "bg-destructive/10 text-destructive";
+ case "blocked":
+ return "bg-amber-500/10 text-amber-600 dark:text-amber-400";
+ case "retry":
+ return "bg-sky-500/10 text-sky-600 dark:text-sky-400";
+ case "running":
+ return "bg-primary/10 text-primary";
+ case "cancelled":
+ return "bg-muted text-muted-foreground";
+ case "waiting":
+ default:
+ return "bg-muted text-muted-foreground";
+ }
+}
+
+function StatusIcon({ status }: { status: SwarmAgentDisplayStatus }) {
+ switch (status) {
+ case "done":
+ return <CheckCircle2 className="h-3 w-3" />;
+ case "failed":
+ return <XCircle className="h-3 w-3" />;
+ case "blocked":
+ return <ShieldAlert className="h-3 w-3" />;
+ case "retry":
+ return <RotateCcw className="h-3 w-3" />;
+ case "running":
+ return <Loader2 className="h-3 w-3 animate-spin" />;
+ case "cancelled":
+ return <XCircle className="h-3 w-3" />;
+ case "waiting":
+ default:
+ return <Circle className="h-3 w-3" />;
+ }
+}
+
+function runTone(status: SwarmRunStatus["status"]): string {
+ switch (status) {
+ case "completed":
+ return "text-emerald-600 dark:text-emerald-400";
+ case "failed":
+ return "text-destructive";
+ case "cancelled":
+ return "text-muted-foreground";
+ case "running":
+ return "text-primary";
+ case "pending":
+ case "unknown":
+ default:
+ return "text-muted-foreground";
+ }
+}
+
+export const SwarmStatusCard = memo(function SwarmStatusCard({ status }: Props) {
+ const done = status.agents.filter((agent) => ["done", "failed", "blocked", "cancelled"].includes(agent.status)).length;
+ const total = status.agents.length;
+ const layerTotal = Math.max(status.totalLayers, status.currentLayer + 1, 1);
+ const layerCurrent = Math.min(status.currentLayer + 1, layerTotal);
+
+ return (
+ <div className="flex gap-3">
+ <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary/10 text-primary">
+ <Users className="h-4 w-4" />
+ </div>
+ <div className="min-w-0 flex-1 rounded-lg border bg-background p-3 shadow-sm">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <div className="flex min-w-0 items-center gap-2">
+ <span className="truncate text-sm font-semibold text-foreground">{status.preset}</span>
+ <span className={["shrink-0 text-xs font-medium capitalize", runTone(status.status)].join(" ")}>
+ {status.status.replace(/_/g, " ")}
+ </span>
+ </div>
+ <div className="flex items-center gap-2 text-[11px] text-muted-foreground">
+ <Clock className="h-3 w-3" />
+ <span>{done}/{total || 0} agents</span>
+ </div>
+ </div>
+
+ <div className="mt-3 grid gap-2 sm:grid-cols-[minmax(0,1fr)_9rem] sm:items-center">
+ <ProgressBar
+ current={total ? done : 0}
+ total={Math.max(total, 1)}
+ height="xs"
+ showCount
+ ariaLabel="Swarm agent progress"
+ />
+ <div className="text-right font-mono text-[11px] text-muted-foreground">
+ Layer {layerCurrent}/{layerTotal}
+ </div>
+ </div>
+
+ <div className="mt-3 overflow-x-auto">
+ <div className="min-w-[620px]">
+ <div className="grid grid-cols-[10rem_7rem_9rem_5rem_4rem_minmax(0,1fr)] gap-2 border-b pb-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
+ <span>Agent</span>
+ <span>Status</span>
+ <span>Tool</span>
+ <span className="text-right">Time</span>
+ <span className="text-right">Iters</span>
+ <span>Output</span>
+ </div>
+ <div className="divide-y">
+ {status.agents.map((agent) => (
+ <div
+ key={`${agent.taskId || agent.agentId}`}
+ className="grid grid-cols-[10rem_7rem_9rem_5rem_4rem_minmax(0,1fr)] gap-2 py-2 text-xs"
+ >
+ <div className="min-w-0">
+ <div className="truncate font-medium text-foreground">{agent.agentId}</div>
+ {agent.role && <div className="truncate text-[10px] text-muted-foreground">{agent.role}</div>}
+ </div>
+ <div>
+ <span className={["inline-flex items-center gap-1 rounded-full px-1.5 py-0.5 text-[10px] font-medium capitalize", statusTone(agent.status)].join(" ")}>
+ <StatusIcon status={agent.status} />
+ {agent.status}
+ </span>
+ </div>
+ <div className="truncate font-mono text-[11px] text-muted-foreground" title={agent.tool || ""}>
+ {agent.tool ? localizeToolName(agent.tool, agent.tool) : "-"}
+ </div>
+ <div className="text-right font-mono text-[11px] text-muted-foreground">
+ {formatElapsed(agent.elapsed_s)}
+ </div>
+ <div className="text-right font-mono text-[11px] text-muted-foreground">
+ {agent.iterations ?? "-"}
+ </div>
+ <div className={["truncate text-[11px]", agent.error ? "text-destructive" : "text-muted-foreground"].join(" ")} title={agent.error || agent.lastText || ""}>
+ {agent.error || agent.lastText || "-"}
+ </div>
+ </div>
+ ))}
+ {status.agents.length === 0 && (
+ <div className="py-3 text-xs text-muted-foreground">
+ Waiting for agent events...
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+});
diff --git a/frontend/src/components/chat/__tests__/SwarmStatusCard.test.tsx b/frontend/src/components/chat/__tests__/SwarmStatusCard.test.tsx
new file mode 100644
index 000000000..08c13809a
--- /dev/null
+++ b/frontend/src/components/chat/__tests__/SwarmStatusCard.test.tsx
@@ -0,0 +1,118 @@
+// @vitest-environment node
+
+import { renderToStaticMarkup } from "react-dom/server";
+import { SwarmStatusCard } from "../SwarmStatusCard";
+import {
+ applySwarmEvent,
+ buildSwarmStatusFromStarted,
+ buildSwarmStatusFromToolResultPreview,
+} from "@/lib/swarmStatus";
+import type { SwarmRunStatus } from "@/types/agent";
+
+function makeStatus(overrides: Partial<SwarmRunStatus> = {}): SwarmRunStatus {
+ return {
+ runId: "r1",
+ preset: "demo_team",
+ status: "running",
+ currentLayer: 0,
+ totalLayers: 2,
+ startedAt: Date.now(),
+ agents: [
+ { agentId: "macro", status: "waiting", iterations: 0 },
+ { agentId: "risk", status: "running", tool: "read_file", elapsed_s: 12, iterations: 2, lastText: "checking exposure" },
+ { agentId: "pm", status: "done", tool: "write_file ok", elapsed_s: 30, iterations: 4, lastText: "report complete" },
+ { agentId: "qa", status: "failed", error: "missing data" },
+ { agentId: "ops", status: "blocked", error: "Blocked by qa" },
+ { agentId: "retry_agent", status: "retry", tool: "retry 2" },
+ ],
+ ...overrides,
+ };
+}
+
+describe("SwarmStatusCard", () => {
+ it("renders agent status rows", () => {
+ const html = renderToStaticMarkup(<SwarmStatusCard status={makeStatus()} />);
+
+ expect(html).toContain("demo_team");
+ expect(html).toContain("running");
+ expect(html).toContain("waiting");
+ expect(html).toContain("done");
+ expect(html).toContain("failed");
+ expect(html).toContain("blocked");
+ expect(html).toContain("retry");
+ expect(html).toContain("checking exposure");
+ expect(html).toContain("missing data");
+ });
+
+ it("shows empty state while waiting for events", () => {
+ const html = renderToStaticMarkup(<SwarmStatusCard status={makeStatus({ agents: [] })} />);
+
+ expect(html).toContain("Waiting for agent events...");
+ });
+
+ it("builds a card model from swarm.started payload", () => {
+ const status = buildSwarmStatusFromStarted({
+ run_id: "r-start",
+ preset: "research_team",
+ status: "running",
+ agents: [{ id: "analyst", role: "Analyst" }],
+ tasks: [{ id: "t1", agent_id: "analyst", status: "pending" }],
+ });
+
+ expect(status?.runId).toBe("r-start");
+ expect(status?.agents[0]).toMatchObject({
+ agentId: "analyst",
+ taskId: "t1",
+ role: "Analyst",
+ status: "waiting",
+ });
+ });
+
+ it("updates tool and completion state from swarm events", () => {
+ const initial = buildSwarmStatusFromStarted({
+ run_id: "r-events",
+ preset: "research_team",
+ status: "running",
+ agents: [{ id: "analyst", role: "Analyst" }],
+ tasks: [{ id: "t1", agent_id: "analyst", status: "pending" }],
+ })!;
+
+ const started = applySwarmEvent(initial, {
+ type: "task_started",
+ agent_id: "analyst",
+ task_id: "t1",
+ data: {},
+ timestamp: "2026-06-07T12:00:00Z",
+ });
+ const called = applySwarmEvent(started, {
+ type: "tool_call",
+ agent_id: "analyst",
+ task_id: "t1",
+ data: { tool: "read_file", iteration: 0 },
+ timestamp: "2026-06-07T12:00:01Z",
+ });
+ const done = applySwarmEvent(called, {
+ type: "task_completed",
+ task_id: "t1",
+ data: { iterations: 3, summary: "analysis complete" },
+ timestamp: "2026-06-07T12:00:05Z",
+ });
+
+ expect(done.agents[0]).toMatchObject({
+ status: "done",
+ tool: "read_file",
+ iterations: 3,
+ lastText: "analysis complete",
+ });
+ });
+
+ it("builds fallback status from run_swarm tool result preview", () => {
+ const status = buildSwarmStatusFromToolResultPreview('{"status":"completed","run_id":"r-final","preset":"demo"}');
+
+ expect(status).toMatchObject({
+ runId: "r-final",
+ preset: "demo",
+ status: "completed",
+ });
+ });
+});
diff --git a/frontend/src/hooks/useSSE.ts b/frontend/src/hooks/useSSE.ts
index 357bb12a3..b3c857c76 100644
--- a/frontend/src/hooks/useSSE.ts
+++ b/frontend/src/hooks/useSSE.ts
@@ -81,7 +81,8 @@ export function useSSE(config?: SSEConfig) {
// Only subscribe to event types the backend actually emits
const knownTypes = [
"text_delta", "thinking_done", "tool_call", "tool_result", "compact",
- "tool_heartbeat", "llm_usage",
+ "tool_heartbeat", "tool_progress", "llm_usage",
+ "swarm.started", "swarm.event",
"attempt.created", "attempt.started", "attempt.completed", "attempt.failed",
"message.received", "session.created",
"goal.created", "goal.evidence", "goal.updated",
diff --git a/frontend/src/lib/swarmStatus.ts b/frontend/src/lib/swarmStatus.ts
new file mode 100644
index 000000000..071d10b7b
--- /dev/null
+++ b/frontend/src/lib/swarmStatus.ts
@@ -0,0 +1,288 @@
+import type {
+ SwarmAgentDisplayStatus,
+ SwarmAgentStatus,
+ SwarmRunStatus,
+} from "@/types/agent";
+
+type AnyRecord = Record<string, unknown>;
+
+function asRecord(value: unknown): AnyRecord {
+ return value && typeof value === "object" ? value as AnyRecord : {};
+}
+
+function asString(value: unknown, fallback = ""): string {
+ return typeof value === "string" ? value : fallback;
+}
+
+function asNumber(value: unknown): number | undefined {
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
+}
+
+function timestampMs(value: unknown, fallback = Date.now()): number {
+ if (typeof value !== "string") return fallback;
+ const parsed = new Date(value).getTime();
+ return Number.isFinite(parsed) ? parsed : fallback;
+}
+
+function normalizeRunStatus(value: unknown): SwarmRunStatus["status"] {
+ const status = asString(value, "unknown");
+ if (["pending", "running", "completed", "failed", "cancelled"].includes(status)) {
+ return status as SwarmRunStatus["status"];
+ }
+ return "unknown";
+}
+
+function mapTaskStatus(value: unknown): SwarmAgentDisplayStatus {
+ switch (asString(value)) {
+ case "in_progress":
+ return "running";
+ case "completed":
+ return "done";
+ case "failed":
+ return "failed";
+ case "blocked":
+ return "blocked";
+ case "cancelled":
+ return "cancelled";
+ case "pending":
+ default:
+ return "waiting";
+ }
+}
+
+function eventAgentKey(event: AnyRecord): { agentId: string; taskId?: string } {
+ const data = asRecord(event.data);
+ return {
+ agentId: asString(event.agent_id) || asString(data.agent_id),
+ taskId: asString(event.task_id) || asString(data.task_id) || undefined,
+ };
+}
+
+function updateAgent(
+ status: SwarmRunStatus,
+ selector: { agentId?: string; taskId?: string },
+ update: (agent: SwarmAgentStatus) => SwarmAgentStatus,
+): SwarmRunStatus {
+ const idx = status.agents.findIndex((agent) => (
+ (selector.taskId && agent.taskId === selector.taskId) ||
+ (selector.agentId && agent.agentId === selector.agentId)
+ ));
+ if (idx < 0) {
+ if (!selector.agentId) return status;
+ return {
+ ...status,
+ agents: [
+ ...status.agents,
+ update({ agentId: selector.agentId, taskId: selector.taskId, status: "waiting" }),
+ ],
+ };
+ }
+
+ const agents = [...status.agents];
+ agents[idx] = update(agents[idx]);
+ return { ...status, agents };
+}
+
+export function buildSwarmStatusFromStarted(data: AnyRecord, now = Date.now()): SwarmRunStatus | null {
+ const runId = asString(data.run_id);
+ if (!runId) return null;
+
+ const agentMeta = new Map<string, { role?: string }>();
+ const agentsRaw = Array.isArray(data.agents) ? data.agents : [];
+ for (const item of agentsRaw) {
+ const agent = asRecord(item);
+ const id = asString(agent.id);
+ if (id) agentMeta.set(id, { role: asString(agent.role) || undefined });
+ }
+
+ const tasksRaw = Array.isArray(data.tasks) ? data.tasks : [];
+ const agents: SwarmAgentStatus[] = tasksRaw.map((item) => {
+ const task = asRecord(item);
+ const agentId = asString(task.agent_id);
+ const meta = agentMeta.get(agentId);
+ return {
+ agentId,
+ taskId: asString(task.id) || undefined,
+ role: meta?.role,
+ status: mapTaskStatus(task.status),
+ iterations: asNumber(task.worker_iterations) ?? 0,
+ lastText: asString(task.summary) || undefined,
+ error: asString(task.error) || undefined,
+ };
+ }).filter((agent) => agent.agentId);
+
+ for (const [agentId, meta] of agentMeta) {
+ if (!agents.some((agent) => agent.agentId === agentId)) {
+ agents.push({ agentId, role: meta.role, status: "waiting", iterations: 0 });
+ }
+ }
+
+ return {
+ runId,
+ preset: asString(data.preset) || asString(data.preset_name) || "swarm",
+ status: normalizeRunStatus(data.status),
+ currentLayer: 0,
+ totalLayers: 0,
+ startedAt: now,
+ agents,
+ };
+}
+
+export function applySwarmEvent(current: SwarmRunStatus, rawEvent: unknown, now = Date.now()): SwarmRunStatus {
+ const event = asRecord(rawEvent);
+ const data = asRecord(event.data);
+ const type = asString(event.type);
+ const eventTime = timestampMs(event.timestamp, now);
+ const { agentId, taskId } = eventAgentKey(event);
+
+ if (type === "layer_started") {
+ const layer = asNumber(data.layer) ?? current.currentLayer;
+ return {
+ ...current,
+ status: "running",
+ currentLayer: layer,
+ totalLayers: Math.max(current.totalLayers, layer + 1),
+ };
+ }
+
+ if (type === "run_started") {
+ return { ...current, status: "running", startedAt: current.startedAt || eventTime };
+ }
+
+ if (type === "run_completed") {
+ return {
+ ...current,
+ status: normalizeRunStatus(data.status),
+ completedAt: eventTime,
+ };
+ }
+
+ if (type === "run_error") {
+ return { ...current, status: "failed", completedAt: eventTime };
+ }
+
+ if (type === "task_started" || type === "worker_started") {
+ return updateAgent(current, { agentId, taskId }, (agent) => ({
+ ...agent,
+ agentId: agent.agentId || agentId,
+ taskId: agent.taskId || taskId,
+ status: "running",
+ startedAt: eventTime,
+ }));
+ }
+
+ if (type === "tool_call") {
+ return updateAgent(current, { agentId, taskId }, (agent) => ({
+ ...agent,
+ status: "running",
+ tool: asString(data.tool, agent.tool || "?"),
+ iterations: Math.max(agent.iterations ?? 0, (asNumber(data.iteration) ?? (agent.iterations ?? 0)) + 1),
+ }));
+ }
+
+ if (type === "tool_result") {
+ return updateAgent(current, { agentId, taskId }, (agent) => {
+ const tool = asString(data.tool, agent.tool || "?");
+ const ok = asString(data.status, "ok") === "ok";
+ return {
+ ...agent,
+ tool: `${tool} ${ok ? "ok" : "error"}`,
+ elapsed_s: (asNumber(data.elapsed_ms) ?? 0) / 1000 || agent.elapsed_s,
+ };
+ });
+ }
+
+ if (type === "task_heartbeat") {
+ return updateAgent(current, { agentId, taskId }, (agent) => ({
+ ...agent,
+ status: agent.status === "waiting" ? "running" : agent.status,
+ tool: asString(data.tool, agent.tool || ""),
+ elapsed_s: asNumber(data.elapsed_s) ?? agent.elapsed_s,
+ }));
+ }
+
+ if (type === "worker_text") {
+ const content = asString(data.content).trim();
+ const lastLine = content.split("\n").map((line) => line.trim()).filter(Boolean).pop();
+ if (!lastLine) return current;
+ return updateAgent(current, { agentId, taskId }, (agent) => ({
+ ...agent,
+ lastText: lastLine.slice(0, 160),
+ }));
+ }
+
+ if (type === "task_completed" || type === "worker_completed") {
+ return updateAgent(current, { agentId, taskId }, (agent) => ({
+ ...agent,
+ status: "done",
+ elapsed_s: agent.startedAt ? Math.max(0, (eventTime - agent.startedAt) / 1000) : agent.elapsed_s,
+ iterations: asNumber(data.iterations) ?? agent.iterations,
+ lastText: asString(data.summary) || agent.lastText,
+ }));
+ }
+
+ if (["task_failed", "worker_failed", "worker_timeout", "worker_incomplete"].includes(type)) {
+ return updateAgent(current, { agentId, taskId }, (agent) => ({
+ ...agent,
+ status: "failed",
+ elapsed_s: agent.startedAt ? Math.max(0, (eventTime - agent.startedAt) / 1000) : agent.elapsed_s,
+ error: asString(data.error) || asString(data.reason) || agent.error,
+ }));
+ }
+
+ if (type === "task_blocked") {
+ const blockedBy = Array.isArray(data.blocked_by) ? data.blocked_by.join(", ") : asString(data.reason);
+ return updateAgent(current, { agentId, taskId }, (agent) => ({
+ ...agent,
+ status: "blocked",
+ error: blockedBy ? `Blocked by ${blockedBy}` : agent.error,
+ }));
+ }
+
+ if (type === "task_retry") {
+ const attempt = asNumber(data.attempt);
+ return updateAgent(current, { agentId, taskId }, (agent) => ({
+ ...agent,
+ status: "retry",
+ tool: attempt ? `retry ${attempt}` : "retry",
+ }));
+ }
+
+ return current;
+}
+
+export function buildSwarmStatusFromToolResultPreview(preview: string, now = Date.now()): SwarmRunStatus | null {
+ if (!preview.includes("run_id") && !preview.includes("preset")) return null;
+
+ try {
+ const parsed = JSON.parse(preview) as AnyRecord;
+ const runId = asString(parsed.run_id);
+ if (!runId) return null;
+ return {
+ runId,
+ preset: asString(parsed.preset) || "swarm",
+ status: normalizeRunStatus(parsed.status),
+ currentLayer: 0,
+ totalLayers: 0,
+ startedAt: now,
+ completedAt: ["completed", "failed", "cancelled"].includes(asString(parsed.status)) ? now : undefined,
+ agents: [],
+ };
+ } catch {
+ const runId = preview.match(/"run_id"\s*:\s*"([^"]+)"/)?.[1];
+ if (!runId) return null;
+ const preset = preview.match(/"preset"\s*:\s*"([^"]+)"/)?.[1] || "swarm";
+ const rawStatus = preview.match(/"status"\s*:\s*"([^"]+)"/)?.[1] || "unknown";
+ const status = normalizeRunStatus(rawStatus);
+ return {
+ runId,
+ preset,
+ status,
+ currentLayer: 0,
+ totalLayers: 0,
+ startedAt: now,
+ completedAt: ["completed", "failed", "cancelled"].includes(status) ? now : undefined,
+ agents: [],
+ };
+ }
+}
diff --git a/frontend/src/pages/Agent.tsx b/frontend/src/pages/Agent.tsx
index c2079992e..9890dac18 100644
--- a/frontend/src/pages/Agent.tsx
+++ b/frontend/src/pages/Agent.tsx
@@ -15,6 +15,12 @@ import { ConversationTimeline } from "@/components/chat/ConversationTimeline";
import { ToolProgressIndicator } from "@/components/chat/ToolProgressIndicator";
import { MandateProposalCard } from "@/components/chat/MandateProposalCard";
import { RunnerStatus } from "@/components/chat/RunnerStatus";
+import { SwarmStatusCard } from "@/components/chat/SwarmStatusCard";
+import {
+ applySwarmEvent,
+ buildSwarmStatusFromStarted,
+ buildSwarmStatusFromToolResultPreview,
+} from "@/lib/swarmStatus";
/* ---------- Message grouping ---------- */
type MsgGroup =
@@ -431,6 +437,12 @@ export function Agent() {
elapsed_s: undefined,
progress: undefined,
});
+ if (toolName === "run_swarm") {
+ const fallback = buildSwarmStatusFromToolResultPreview(String(d.preview || ""));
+ if (fallback && !act().messages.some((m) => m.type === "swarm_status" && m.swarmRunId === fallback.runId)) {
+ act().upsertSwarmStatus(fallback);
+ }
+ }
},
tool_heartbeat: (d) => {
@@ -564,6 +576,24 @@ export function Agent() {
loadGoalSnapshot(sid);
},
+ "swarm.started": (d) => {
+ touch();
+ const status = buildSwarmStatusFromStarted(d);
+ if (!status) return;
+ act().upsertSwarmStatus(status);
+ scrollToBottom();
+ },
+
+ "swarm.event": (d) => {
+ touch();
+ if (act().status !== "streaming") act().setStatus("streaming");
+ const runId = String(d.run_id || "");
+ const event = d.event;
+ if (!runId || !event) return;
+ act().updateSwarmStatus(runId, (current) => applySwarmEvent(current, event));
+ scrollToBottom();
+ },
+
"goal.evidence": () => {
touch();
loadGoalSnapshot(sid);
@@ -944,6 +974,8 @@ export function Agent() {
lines.push(`## Error (${time})`, ``, msg.content, ``);
} else if (msg.type === "tool_call") {
lines.push(`> Tool call: ${msg.tool || "unknown"}`, ``);
+ } else if (msg.type === "swarm_status") {
+ lines.push(`> Swarm status: ${msg.swarmStatus?.preset || "swarm"} ${msg.swarmStatus?.status || ""}`, ``);
} else if (msg.type === "run_complete") {
lines.push(`> Backtest complete: ${msg.runId || ""}`, ``);
}
@@ -1084,6 +1116,13 @@ export function Agent() {
);
}
const msgIdx = messages.indexOf(g.msg);
+ if (g.msg.type === "swarm_status" && g.msg.swarmStatus) {
+ return (
+ <div key={row.key} data-msg-idx={msgIdx}>
+ <SwarmStatusCard status={g.msg.swarmStatus} />
+ </div>
+ );
+ }
return (
<div key={row.key} data-msg-idx={msgIdx}>
<MessageBubble msg={g.msg} onRetry={g.msg.type === "error" ? handleRetry : undefined} />
@@ -1092,7 +1131,7 @@ export function Agent() {
})}
{/* Pre-stream placeholder: visible after Send, before first SSE event */}
- {status === "streaming" && !streamingText && toolCalls.length === 0 && (
+ {status === "streaming" && !streamingText && toolCalls.length === 0 && !messages.some((m) => m.type === "swarm_status" && m.swarmStatus?.status === "running") && (
<div className="flex gap-3">
<AgentAvatar />
<div className="flex-1 min-w-0 flex items-center gap-2 text-xs text-muted-foreground pt-1">
diff --git a/frontend/src/stores/agent.ts b/frontend/src/stores/agent.ts
index 5ab2cf203..3bd172e39 100644
--- a/frontend/src/stores/agent.ts
+++ b/frontend/src/stores/agent.ts
@@ -1,5 +1,5 @@
import { create } from "zustand";
-import type { AgentMessage, ToolCallEntry } from "@/types/agent";
+import type { AgentMessage, SwarmRunStatus, ToolCallEntry } from "@/types/agent";
const SESSION_CACHE_MAX = 5;
const _sessionCache = new Map<string, AgentMessage[]>();
@@ -27,6 +27,8 @@ interface AgentState {
addToolCall: (entry: ToolCallEntry) => void;
updateToolCall: (id: string, update: Partial<ToolCallEntry>) => void;
+ upsertSwarmStatus: (status: SwarmRunStatus) => void;
+ updateSwarmStatus: (runId: string, updater: (status: SwarmRunStatus) => SwarmRunStatus) => void;
cacheSession: (sid: string, msgs: AgentMessage[]) => void;
getCachedSession: (sid: string) => AgentMessage[] | undefined;
@@ -81,6 +83,37 @@ export const useAgentStore = create<AgentState>((set) => ({
set((s) => ({
toolCalls: s.toolCalls.map((tc) => tc.id === id ? { ...tc, ...update } : tc),
})),
+ upsertSwarmStatus: (swarmStatus) =>
+ set((s) => {
+ const idx = s.messages.findIndex((m) => m.type === "swarm_status" && m.swarmRunId === swarmStatus.runId);
+ if (idx >= 0) {
+ const messages = [...s.messages];
+ messages[idx] = { ...messages[idx], swarmStatus, timestamp: Date.now() };
+ return { messages };
+ }
+ return {
+ messages: [
+ ...s.messages,
+ {
+ id: `swarm_${swarmStatus.runId}`,
+ type: "swarm_status",
+ content: "",
+ swarmRunId: swarmStatus.runId,
+ swarmStatus,
+ timestamp: Date.now(),
+ },
+ ],
+ };
+ }),
+ updateSwarmStatus: (runId, updater) =>
+ set((s) => {
+ const idx = s.messages.findIndex((m) => m.type === "swarm_status" && m.swarmRunId === runId && m.swarmStatus);
+ if (idx < 0) return {};
+ const messages = [...s.messages];
+ const current = messages[idx].swarmStatus!;
+ messages[idx] = { ...messages[idx], swarmStatus: updater(current), timestamp: Date.now() };
+ return { messages };
+ }),
cacheSession: (sid, msgs) => {
_sessionCache.delete(sid);
diff --git a/frontend/src/tests/setup.ts b/frontend/src/tests/setup.ts
index 58b819f3b..2b649ad91 100644
--- a/frontend/src/tests/setup.ts
+++ b/frontend/src/tests/setup.ts
@@ -10,16 +10,18 @@ globalThis.ResizeObserver = class {
} as unknown as typeof ResizeObserver;
// jsdom doesn't implement matchMedia
-Object.defineProperty(window, "matchMedia", {
- writable: true,
- value: (query: string) => ({
- matches: false,
- media: query,
- onchange: null,
- addListener: () => {},
- removeListener: () => {},
- addEventListener: () => {},
- removeEventListener: () => {},
- dispatchEvent: () => false,
- }),
-});
+if (typeof window !== "undefined") {
+ Object.defineProperty(window, "matchMedia", {
+ writable: true,
+ value: (query: string) => ({
+ matches: false,
+ media: query,
+ onchange: null,
+ addListener: () => {},
+ removeListener: () => {},
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ dispatchEvent: () => false,
+ }),
+ });
+}
diff --git a/frontend/src/types/agent.ts b/frontend/src/types/agent.ts
index a2ff44076..8269885e0 100644
--- a/frontend/src/types/agent.ts
+++ b/frontend/src/types/agent.ts
@@ -1,7 +1,41 @@
/** Chat message types */
export type AgentMessageType =
| "user" | "thinking" | "tool_call" | "tool_result"
- | "answer" | "error" | "run_complete" | "compact";
+ | "answer" | "error" | "run_complete" | "compact" | "swarm_status";
+
+export type SwarmAgentDisplayStatus =
+ | "waiting"
+ | "running"
+ | "done"
+ | "failed"
+ | "blocked"
+ | "retry"
+ | "cancelled";
+
+export interface SwarmAgentStatus {
+ agentId: string;
+ taskId?: string;
+ role?: string;
+ status: SwarmAgentDisplayStatus;
+ tool?: string;
+ elapsed_s?: number;
+ iterations?: number;
+ startedAt?: number;
+ lastText?: string;
+ error?: string;
+ layer?: number;
+}
+
+export interface SwarmRunStatus {
+ runId: string;
+ preset: string;
+ status: "pending" | "running" | "completed" | "failed" | "cancelled" | "unknown";
+ currentLayer: number;
+ totalLayers: number;
+ startedAt: number;
+ completedAt?: number;
+ agents: SwarmAgentStatus[];
+}
export interface AgentMessage {
id: string;
@@ -13,6 +47,8 @@ export interface AgentMessage {
elapsed_ms?: number;
timestamp: number;
runId?: string;
+ swarmRunId?: string;
+ swarmStatus?: SwarmRunStatus;
metrics?: Record<string, number>;
equityCurve?: Array<{ time: string; equity: number | string }>;
/** Phase label for thinking entries */
diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts
index f4f78ca66..71d4de508 100644
--- a/frontend/vite.config.ts
+++ b/frontend/vite.config.ts
@@ -16,7 +16,7 @@ const PROXY_PATHS = [
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), "");
- const apiTarget = env.VITE_API_URL || "http://localhost:8899";
+ const apiTarget = env.VITE_API_URL || "http://127.0.0.1:8899";
const apiProxy = { target: apiTarget, changeOrigin: true };
const apiProxyWithHtmlFallback = {
...apiProxy,