Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(frontend): show swarm token totals with provider-vs-estimated labeling (11 locales)

shadowinlife11511f8312dd
diff --git a/agent/src/tools/swarm_tool.py b/agent/src/tools/swarm_tool.py
index a3b9b101c..9def2c4f3 100644
--- a/agent/src/tools/swarm_tool.py
+++ b/agent/src/tools/swarm_tool.py
@@ -705,6 +705,7 @@ def _format_result(
"token_usage": {
"total_input_tokens": run.total_input_tokens,
"total_output_tokens": run.total_output_tokens,
+ "token_source": run.token_source,
},
}
return json.dumps(result, ensure_ascii=False, indent=2)
diff --git a/frontend/src/components/chat/SwarmDashboard.tsx b/frontend/src/components/chat/SwarmDashboard.tsx
index 9ab378ea9..b08237fbe 100644
--- a/frontend/src/components/chat/SwarmDashboard.tsx
+++ b/frontend/src/components/chat/SwarmDashboard.tsx
@@ -8,6 +8,7 @@ import {
ShieldAlert,
XCircle,
} from "lucide-react";
+import { abbreviateNum } from "@/lib/formatters";
import {
localizeStatus,
type ManifestTranslation,
@@ -121,6 +122,35 @@ function agentKey(agent: SwarmAgentStatus): string {
return agent.taskId || agent.agentId;
}
+function agentTokenText(agent: SwarmAgentStatus): string | null {
+ const input = agent.input_tokens != null && agent.input_tokens > 0
+ ? abbreviateNum(agent.input_tokens)
+ : null;
+ const output = agent.output_tokens != null && agent.output_tokens > 0
+ ? abbreviateNum(agent.output_tokens)
+ : null;
+ if (!input && !output) return null;
+ return `↑${input ?? "—"} ↓${output ?? "—"}`;
+}
+
+function AgentTokens({
+ agent,
+ t,
+ className,
+}: {
+ agent: SwarmAgentStatus;
+ t: ManifestTranslation;
+ className: string;
+}) {
+ const tokens = agentTokenText(agent);
+ if (!tokens) return null;
+ return (
+ <div className={className} title={t("runDetail.llmUsage.tab")}>
+ {tokens}
+ </div>
+ );
+}
+
function WideAgentRow({
agent,
isActive,
@@ -179,6 +209,11 @@ function WideAgentRow({
{agent.iterations}
</div>
)}
+ <AgentTokens
+ agent={agent}
+ className="truncate text-[10px]"
+ t={t}
+ />
</div>
<div
className={[
@@ -232,6 +267,11 @@ function NarrowAgentCard({
<span className="sr-only">{t("swarmStatus.tool")}</span>
{agent.tool ? localizeToolName(agent.tool, agent.tool) : "-"}
</span>
+ <AgentTokens
+ agent={agent}
+ className="shrink-0"
+ t={t}
+ />
<span className="shrink-0">
<span className="sr-only">{t("swarmStatus.time")}</span>
{formatElapsed(agent.elapsed_s, t)}
diff --git a/frontend/src/components/chat/SwarmStatusCard.tsx b/frontend/src/components/chat/SwarmStatusCard.tsx
index 3b4291d4b..f7e997e5f 100644
--- a/frontend/src/components/chat/SwarmStatusCard.tsx
+++ b/frontend/src/components/chat/SwarmStatusCard.tsx
@@ -2,6 +2,7 @@ import { useTranslation } from "react-i18next";
import { memo } from "react";
import { Clock, Users } from "lucide-react";
import { SwarmDashboard } from "@/components/chat/SwarmDashboard";
+import { abbreviateNum } from "@/lib/formatters";
import {
localizePreset,
localizeStatus,
@@ -106,6 +107,56 @@ function LayerStepper({
);
}
+function formatPositive(value: number | undefined): string | null {
+ return value != null && Number.isFinite(value) && value > 0
+ ? abbreviateNum(value)
+ : null;
+}
+
+/**
+ * Run-level token totals with provenance labeling: an explicit "estimated"
+ * badge for heuristic counts, an "unlabeled" badge when the source is unknown
+ * (pre-telemetry runs). Only "provider" — the exact-usage case — renders
+ * without a badge, so a partly-estimated total can never read as billed data.
+ */
+function TokenUsageLine({
+ status,
+ t,
+}: {
+ status: SwarmRunStatus;
+ t: ManifestTranslation;
+}) {
+ const input = formatPositive(status.total_input_tokens);
+ const output = formatPositive(status.total_output_tokens);
+ if (!input && !output) return null;
+
+ const label = t("swarmStatus.tokens", {
+ input: input ?? "—",
+ output: output ?? "—",
+ });
+
+ return (
+ <div className="mt-2 flex flex-wrap items-center gap-1.5 text-[11px] text-muted-foreground">
+ <span
+ className="font-mono"
+ title={`\u2191${String(status.total_input_tokens ?? 0)} \u2193${String(status.total_output_tokens ?? 0)}`}
+ >
+ {label}
+ </span>
+ {status.token_source === "estimated" && (
+ <span className="rounded-full bg-amber-500/10 px-1.5 py-0.5 text-[10px] font-medium text-amber-600 dark:text-amber-400">
+ {t("swarmStatus.estimated")}
+ </span>
+ )}
+ {status.token_source == null && (
+ <span className="rounded-full bg-muted px-1.5 py-0.5 text-[10px] font-medium">
+ {t("swarmStatus.tokenSourceUnlabeled")}
+ </span>
+ )}
+ </div>
+ );
+}
+
function runTone(status: SwarmRunStatus["status"]): string {
switch (status) {
case "completed":
@@ -177,6 +228,8 @@ export const SwarmStatusCard = memo(function SwarmStatusCard({ status }: Props)
</div>
)}
+ <TokenUsageLine status={status} t={t} />
+
<SwarmDashboard
agents={status.agents}
emptyStatus={localizeStatus(status.status, t)}
diff --git a/frontend/src/components/chat/__tests__/SwarmStatusCard.usage.test.tsx b/frontend/src/components/chat/__tests__/SwarmStatusCard.usage.test.tsx
new file mode 100644
index 000000000..632e0ab0a
--- /dev/null
+++ b/frontend/src/components/chat/__tests__/SwarmStatusCard.usage.test.tsx
@@ -0,0 +1,132 @@
+import { render, screen } from "@testing-library/react";
+import { SwarmStatusCard } from "../SwarmStatusCard";
+import type { SwarmRunStatus } from "@/types/agent";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: Record<string, string | number>) => {
+ if (key === "swarmStatus.tokens") {
+ return `↑${String(options?.input ?? "")} ↓${String(options?.output ?? "")} tokens`;
+ }
+ if (key === "swarmStatus.estimated") return "estimated";
+ if (key === "swarmStatus.tokenSourceUnlabeled") return "source unlabeled";
+ return key;
+ },
+ }),
+}));
+
+function statusWith(overrides: Partial<SwarmRunStatus>): SwarmRunStatus {
+ return {
+ runId: "run-usage",
+ preset: "demo_team",
+ status: "completed",
+ currentLayer: 0,
+ totalLayers: 0,
+ startedAt: 0,
+ agents: [
+ { agentId: "analyst", taskId: "t1", status: "done", input_tokens: 4200, output_tokens: 1300 },
+ ],
+ ...overrides,
+ };
+}
+
+describe("SwarmStatusCard token usage line", () => {
+ it("shows exact totals with a provider source and no caveat badge", () => {
+ const { container } = render(
+ <SwarmStatusCard
+ status={statusWith({
+ total_input_tokens: 4200,
+ total_output_tokens: 1300,
+ token_source: "provider",
+ })}
+ />,
+ );
+
+ expect(container.innerHTML).toContain("4200");
+ expect(container.innerHTML).toContain("1300");
+ expect(container.textContent).toContain("↑");
+ expect(container.textContent).toContain("↓");
+ expect(screen.queryByText("estimated")).toBeNull();
+ expect(screen.queryByText("source unlabeled")).toBeNull();
+ });
+
+ it("shows a visible estimated badge when the source is estimated", () => {
+ render(
+ <SwarmStatusCard
+ status={statusWith({
+ total_input_tokens: 4200,
+ total_output_tokens: 1300,
+ token_source: "estimated",
+ })}
+ />,
+ );
+
+ expect(screen.getByText("estimated")).toBeInTheDocument();
+ expect(screen.queryByText("source unlabeled")).toBeNull();
+ });
+
+ it("shows the honest unlabeled badge — not provider, not estimated — when the source is missing", () => {
+ render(
+ <SwarmStatusCard
+ status={statusWith({
+ total_input_tokens: 4200,
+ total_output_tokens: 1300,
+ })}
+ />,
+ );
+
+ expect(screen.getByText("source unlabeled")).toBeInTheDocument();
+ expect(screen.queryByText("estimated")).toBeNull();
+ });
+
+ it("treats an explicit null source as unlabeled", () => {
+ render(
+ <SwarmStatusCard
+ status={statusWith({
+ total_input_tokens: 4200,
+ total_output_tokens: 1300,
+ token_source: null,
+ })}
+ />,
+ );
+
+ expect(screen.getByText("source unlabeled")).toBeInTheDocument();
+ });
+
+ it("renders no token line and no badge for zero totals", () => {
+ const { container } = render(
+ <SwarmStatusCard
+ status={statusWith({
+ agents: [{ agentId: "analyst", taskId: "t1", status: "done" }],
+ total_input_tokens: 0,
+ total_output_tokens: 0,
+ })}
+ />,
+ );
+
+ expect(container.textContent).not.toContain("↑");
+ expect(screen.queryByText("source unlabeled")).toBeNull();
+ });
+
+ it("formats the run line through abbreviateNum", () => {
+ const { container } = render(
+ <SwarmStatusCard
+ status={statusWith({
+ total_input_tokens: 15000,
+ total_output_tokens: 1300,
+ token_source: "provider",
+ })}
+ />,
+ );
+
+ expect(container.textContent).toContain("↑15K");
+ expect(container.textContent).toContain("↓1,300");
+ });
+
+ it("shows per-agent tokens inside the dashboard rows", () => {
+ const { container } = render(<SwarmStatusCard status={statusWith({})} />);
+
+ const rowgroup = container.querySelector('[role="rowgroup"]');
+ expect(rowgroup?.textContent).toContain("↑4,200 ↓1,300");
+ });
+});
diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.json
index 04450690f..e04143788 100644
--- a/frontend/src/i18n/locales/ar.json
+++ b/frontend/src/i18n/locales/ar.json
@@ -1849,7 +1849,10 @@
"output": "المخرجات",
"waitingForEvents": "بانتظار أحداث الوكيل...",
"teamStarting": "الفريق قيد التشغيل — أولى التحديثات خلال ثوانٍ…",
- "detailsUnavailable": "التفاصيل غير متاحة"
+ "detailsUnavailable": "التفاصيل غير متاحة",
+ "tokens": "↑{{input}} ↓{{output}} رموز",
+ "estimated": "تقديرية",
+ "tokenSourceUnlabeled": "مصدر غير موسوم"
},
"mandate": {
"runtimeMandate": "تفويض وقت تشغيل الموصل",
diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.json
index 3dcc96c8a..7059dd4dc 100644
--- a/frontend/src/i18n/locales/de.json
+++ b/frontend/src/i18n/locales/de.json
@@ -1854,7 +1854,10 @@
"output": "Ausgabe",
"waitingForEvents": "Warten auf Agent-Ereignisse...",
"teamStarting": "Das Team startet — erste Updates in wenigen Sekunden…",
- "detailsUnavailable": "Details nicht verfügbar"
+ "detailsUnavailable": "Details nicht verfügbar",
+ "tokens": "↑{{input}} ↓{{output}} Tokens",
+ "estimated": "geschätzt",
+ "tokenSourceUnlabeled": "Quelle nicht gekennzeichnet"
},
"mandate": {
"runtimeMandate": "Connector-Runtime-Mandat",
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json
index 3d1c942a2..dee0f71c9 100644
--- a/frontend/src/i18n/locales/en.json
+++ b/frontend/src/i18n/locales/en.json
@@ -1854,7 +1854,10 @@
"output": "Output",
"waitingForEvents": "Waiting for agent events...",
"teamStarting": "The team is spinning up — first updates in a few seconds…",
- "detailsUnavailable": "details unavailable"
+ "detailsUnavailable": "details unavailable",
+ "tokens": "↑{{input}} ↓{{output}} tokens",
+ "estimated": "estimated",
+ "tokenSourceUnlabeled": "source unlabeled"
},
"mandate": {
"runtimeMandate": "Connector runtime mandate",
diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.json
index 233cdc6d8..83831db53 100644
--- a/frontend/src/i18n/locales/es.json
+++ b/frontend/src/i18n/locales/es.json
@@ -1854,7 +1854,10 @@
"output": "Salida",
"waitingForEvents": "Esperando eventos del agente...",
"teamStarting": "El equipo se está preparando — primeras actualizaciones en unos segundos…",
- "detailsUnavailable": "detalles no disponibles"
+ "detailsUnavailable": "detalles no disponibles",
+ "tokens": "↑{{input}} ↓{{output}} tokens",
+ "estimated": "estimados",
+ "tokenSourceUnlabeled": "fuente sin etiqueta"
},
"mandate": {
"runtimeMandate": "Mandato de runtime del conector",
diff --git a/frontend/src/i18n/locales/fa.json b/frontend/src/i18n/locales/fa.json
index b341ee2c7..384cf77f2 100644
--- a/frontend/src/i18n/locales/fa.json
+++ b/frontend/src/i18n/locales/fa.json
@@ -1854,7 +1854,10 @@
"output": "خروجی",
"waitingForEvents": "در انتظار رویدادهای ایجنت…",
"teamStarting": "تیم در حال آماده‌سازی است — اولین به‌روزرسانی‌ها در چند ثانیه…",
- "detailsUnavailable": "جزئیات در دسترس نیست"
+ "detailsUnavailable": "جزئیات در دسترس نیست",
+ "tokens": "↑{{input}} ↓{{output}} توکن",
+ "estimated": "تخمینی",
+ "tokenSourceUnlabeled": "منبع بدون برچسب"
},
"mandate": {
"runtimeMandate": "ماندیت ران‌تایم کانکتور",
diff --git a/frontend/src/i18n/locales/id.json b/frontend/src/i18n/locales/id.json
index d0e8dc150..cd3f1a708 100644
--- a/frontend/src/i18n/locales/id.json
+++ b/frontend/src/i18n/locales/id.json
@@ -1854,7 +1854,10 @@
"output": "Output",
"waitingForEvents": "Menunggu event dari Agent...",
"teamStarting": "Tim sedang dimulai — update pertama akan muncul dalam beberapa detik…",
- "detailsUnavailable": "detail tidak tersedia"
+ "detailsUnavailable": "detail tidak tersedia",
+ "tokens": "↑{{input}} ↓{{output}} token",
+ "estimated": "estimasi",
+ "tokenSourceUnlabeled": "sumber tanpa label"
},
"mandate": {
"runtimeMandate": "Mandat runtime connector",
diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.json
index 68d5ca73b..5c2e29875 100644
--- a/frontend/src/i18n/locales/ja.json
+++ b/frontend/src/i18n/locales/ja.json
@@ -1849,7 +1849,10 @@
"output": "出力",
"waitingForEvents": "エージェントイベントを待機中...",
"teamStarting": "チームを起動中です。数秒で最初の進捗が届きます…",
- "detailsUnavailable": "詳細は利用できません"
+ "detailsUnavailable": "詳細は利用できません",
+ "tokens": "↑{{input}} ↓{{output}} トークン",
+ "estimated": "推定",
+ "tokenSourceUnlabeled": "出典未表記"
},
"mandate": {
"runtimeMandate": "コネクタマンデート",
diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.json
index 5c4434879..fb9a8c750 100644
--- a/frontend/src/i18n/locales/ko.json
+++ b/frontend/src/i18n/locales/ko.json
@@ -1849,7 +1849,10 @@
"output": "출력",
"waitingForEvents": "에이전트 이벤트 대기 중...",
"teamStarting": "팀을 시작하는 중입니다. 몇 초 후 첫 진행 상황이 도착합니다…",
- "detailsUnavailable": "세부 정보 없음"
+ "detailsUnavailable": "세부 정보 없음",
+ "tokens": "↑{{input}} ↓{{output}} 토큰",
+ "estimated": "추정",
+ "tokenSourceUnlabeled": "출처 미표기"
},
"mandate": {
"runtimeMandate": "커넥터 mandate",
diff --git a/frontend/src/i18n/locales/pt-BR.json b/frontend/src/i18n/locales/pt-BR.json
index c6e7f22a9..8bf5c1d7b 100644
--- a/frontend/src/i18n/locales/pt-BR.json
+++ b/frontend/src/i18n/locales/pt-BR.json
@@ -1854,7 +1854,10 @@
"output": "Saída",
"waitingForEvents": "Aguardando eventos do agente...",
"teamStarting": "A equipe está girando – primeiras atualizações em alguns segundos…",
- "detailsUnavailable": "detalhes indisponíveis"
+ "detailsUnavailable": "detalhes indisponíveis",
+ "tokens": "↑{{input}} ↓{{output}} tokens",
+ "estimated": "estimados",
+ "tokenSourceUnlabeled": "fonte sem rótulo"
},
"mandate": {
"runtimeMandate": "Mandato de runtime do conector",
diff --git a/frontend/src/i18n/locales/tr.json b/frontend/src/i18n/locales/tr.json
index b140c4bb0..c099099a3 100644
--- a/frontend/src/i18n/locales/tr.json
+++ b/frontend/src/i18n/locales/tr.json
@@ -1820,7 +1820,10 @@
"output": "Çıktı",
"waitingForEvents": "Aracı olayları bekleniyor…",
"teamStarting": "Ekip hazırlanıyor; ilk güncellemeler birkaç saniye içinde…",
- "detailsUnavailable": "ayrıntılar alınamıyor"
+ "detailsUnavailable": "ayrıntılar alınamıyor",
+ "tokens": "↑{{input}} ↓{{output}} belirteç",
+ "estimated": "tahmini",
+ "tokenSourceUnlabeled": "kaynak etiketsiz"
},
"mandate": {
"runtimeMandate": "Bağlantı işlem yetkisi",
diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.json
index 0f4461e2f..5a00a8f78 100644
--- a/frontend/src/i18n/locales/zh-CN.json
+++ b/frontend/src/i18n/locales/zh-CN.json
@@ -1849,7 +1849,10 @@
"output": "输出",
"waitingForEvents": "等待智能体事件...",
"teamStarting": "智能体团队正在启动,稍等几秒就有第一批进展…",
- "detailsUnavailable": "暂无详细信息"
+ "detailsUnavailable": "暂无详细信息",
+ "tokens": "↑{{input}} ↓{{output}} Token",
+ "estimated": "估算",
+ "tokenSourceUnlabeled": "来源未标注"
},
"mandate": {
"runtimeMandate": "连接器交易授权(mandate)",
diff --git a/frontend/src/lib/__tests__/swarmStatus.usage.test.ts b/frontend/src/lib/__tests__/swarmStatus.usage.test.ts
new file mode 100644
index 000000000..feb7127bd
--- /dev/null
+++ b/frontend/src/lib/__tests__/swarmStatus.usage.test.ts
@@ -0,0 +1,193 @@
+import {
+ applySwarmEvent,
+ buildSwarmStatusFromToolResultPreview,
+} from "../swarmStatus";
+import type { SwarmRunStatus } from "@/types/agent";
+
+function baseStatus(): SwarmRunStatus {
+ return {
+ runId: "run-usage",
+ preset: "demo_team",
+ status: "running",
+ currentLayer: 0,
+ totalLayers: 2,
+ startedAt: 0,
+ agents: [
+ { agentId: "analyst", taskId: "t1", status: "running" },
+ { agentId: "risk", taskId: "t2", status: "running" },
+ ],
+ };
+}
+
+function completedEvent(
+ agentId: string,
+ taskId: string,
+ data: Record<string, unknown>,
+) {
+ return {
+ type: "task_completed",
+ agent_id: agentId,
+ task_id: taskId,
+ timestamp: "2026-07-29T12:01:00.000Z",
+ data,
+ };
+}
+
+describe("swarmStatus task token telemetry", () => {
+ it("stores per-task tokens and derives the run totals on task_completed", () => {
+ const next = applySwarmEvent(baseStatus(), completedEvent("analyst", "t1", {
+ iterations: 4,
+ input_tokens: 4200,
+ output_tokens: 1300,
+ cache_read_tokens: 900,
+ cache_creation_tokens: 120,
+ token_source: "provider",
+ }));
+
+ const agent = next.agents.find((a) => a.agentId === "analyst");
+ expect(agent?.input_tokens).toBe(4200);
+ expect(agent?.output_tokens).toBe(1300);
+ expect(agent?.cache_read_tokens).toBe(900);
+ expect(agent?.cache_creation_tokens).toBe(120);
+ expect(next.total_input_tokens).toBe(4200);
+ expect(next.total_output_tokens).toBe(1300);
+ expect(next.token_source).toBe("provider");
+ });
+
+ it("does not double the run totals when the same event is replayed", () => {
+ const event = completedEvent("analyst", "t1", {
+ input_tokens: 4200,
+ output_tokens: 1300,
+ token_source: "provider",
+ });
+ const once = applySwarmEvent(baseStatus(), event);
+ const twice = applySwarmEvent(once, event);
+
+ expect(twice.total_input_tokens).toBe(4200);
+ expect(twice.total_output_tokens).toBe(1300);
+ expect(twice.token_source).toBe("provider");
+ });
+
+ it("sums totals across agents as each task completes", () => {
+ let status = applySwarmEvent(baseStatus(), completedEvent("analyst", "t1", {
+ input_tokens: 4200,
+ output_tokens: 1300,
+ token_source: "provider",
+ }));
+ status = applySwarmEvent(status, completedEvent("risk", "t2", {
+ input_tokens: 800,
+ output_tokens: 200,
+ token_source: "estimated",
+ }));
+
+ expect(status.total_input_tokens).toBe(5000);
+ expect(status.total_output_tokens).toBe(1500);
+ expect(status.token_source).toBe("estimated");
+ });
+
+ it("keeps a real label when a replayed event carries a null token_source", () => {
+ let status = applySwarmEvent(baseStatus(), completedEvent("analyst", "t1", {
+ input_tokens: 4200,
+ output_tokens: 1300,
+ token_source: "provider",
+ }));
+ status = applySwarmEvent(status, completedEvent("risk", "t2", {
+ input_tokens: 800,
+ output_tokens: 200,
+ token_source: null,
+ }));
+
+ expect(status.token_source).toBe("provider");
+ expect(status.total_input_tokens).toBe(5000);
+ });
+
+ it("leaves run totals undefined — never 0 — when no event reports tokens", () => {
+ const status = applySwarmEvent(baseStatus(), completedEvent("analyst", "t1", {
+ iterations: 2,
+ summary: "done",
+ }));
+
+ expect(status.total_input_tokens).toBeUndefined();
+ expect(status.total_output_tokens).toBeUndefined();
+ expect(status.token_source).toBeUndefined();
+ expect(status.agents[0].status).toBe("done");
+ });
+
+ it("a tokenless worker_completed does not wipe existing task totals", () => {
+ let status = applySwarmEvent(baseStatus(), completedEvent("analyst", "t1", {
+ input_tokens: 4200,
+ output_tokens: 1300,
+ token_source: "provider",
+ }));
+ status = applySwarmEvent(status, {
+ type: "worker_completed",
+ agent_id: "analyst",
+ task_id: "t1",
+ timestamp: "2026-07-29T12:02:00.000Z",
+ data: { iterations: 5 },
+ });
+
+ expect(status.total_input_tokens).toBe(4200);
+ expect(status.total_output_tokens).toBe(1300);
+ expect(status.token_source).toBe("provider");
+ });
+});
+
+describe("swarmStatus tool-result preview token_usage", () => {
+ function previewWith(tokenUsage: unknown): string {
+ return JSON.stringify({
+ status: "completed",
+ run_id: "run-9",
+ preset: "demo_team",
+ final_report: "",
+ tasks: [],
+ token_usage: tokenUsage,
+ });
+ }
+
+ it("parses run totals and token_source from the run_swarm result preview", () => {
+ const status = buildSwarmStatusFromToolResultPreview(
+ previewWith({
+ total_input_tokens: 5000,
+ total_output_tokens: 1500,
+ token_source: "estimated",
+ }),
+ );
+
+ expect(status?.runId).toBe("run-9");
+ expect(status?.total_input_tokens).toBe(5000);
+ expect(status?.total_output_tokens).toBe(1500);
+ expect(status?.token_source).toBe("estimated");
+ });
+
+ it("treats a null token_source in the preview as unlabeled, not provider", () => {
+ const status = buildSwarmStatusFromToolResultPreview(
+ previewWith({ total_input_tokens: 10, total_output_tokens: 2, token_source: null }),
+ );
+
+ expect(status?.total_input_tokens).toBe(10);
+ expect(status?.token_source).toBeUndefined();
+ });
+
+ it("keeps the pre-existing parse behaviour for results without token_usage", () => {
+ const status = buildSwarmStatusFromToolResultPreview(
+ previewWith(undefined),
+ );
+
+ expect(status?.runId).toBe("run-9");
+ expect(status?.status).toBe("completed");
+ expect(status?.total_input_tokens).toBeUndefined();
+ expect(status?.total_output_tokens).toBeUndefined();
+ expect(status?.token_source).toBeUndefined();
+ });
+
+ it("the truncated-JSON fallback path still recovers identity fields", () => {
+ const truncated = '{"status": "completed", "run_id": "run-9", "preset": "demo_team", "token_u';
+ const status = buildSwarmStatusFromToolResultPreview(truncated);
+
+ expect(status?.runId).toBe("run-9");
+ expect(status?.preset).toBe("demo_team");
+ expect(status?.status).toBe("completed");
+ expect(status?.total_input_tokens).toBeUndefined();
+ });
+});
diff --git a/frontend/src/lib/swarmStatus.ts b/frontend/src/lib/swarmStatus.ts
index 158f041e4..04d3c2e56 100644
--- a/frontend/src/lib/swarmStatus.ts
+++ b/frontend/src/lib/swarmStatus.ts
@@ -18,6 +18,43 @@ function asNumber(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
+function asTokenSource(value: unknown): SwarmRunStatus["token_source"] {
+ return value === "provider" || value === "estimated" ? value : undefined;
+}
+
+/**
+ * Conservative provenance merge — mirrors the backend runtime's
+ * `_merge_token_source`: a missing/unknown incoming label never overwrites a
+ * real one, and one "estimated" contribution contaminates the cumulative total.
+ */
+function mergeTokenSource(
+ current: SwarmRunStatus["token_source"],
+ incoming: unknown,
+): SwarmRunStatus["token_source"] {
+ const label = asTokenSource(incoming);
+ if (label === undefined) return current;
+ if (current == null || label === "estimated") return label;
+ return current;
+}
+
+/**
+ * Recompute run totals as the sum over agents. Idempotent under replayed
+ * events because each task_completed re-sets (not accumulates) its agent's
+ * own values. Returns undefined — never a fabricated 0 — when no agent
+ * reported a given direction.
+ */
+function recomputeRunTokenTotals(status: SwarmRunStatus): SwarmRunStatus {
+ const sum = (pick: (agent: SwarmAgentStatus) => number | undefined) => {
+ const values = status.agents.map(pick).filter((v): v is number => v != null);
+ return values.length > 0 ? values.reduce((acc, v) => acc + v, 0) : undefined;
+ };
+ return {
+ ...status,
+ total_input_tokens: sum((agent) => agent.input_tokens),
+ total_output_tokens: sum((agent) => agent.output_tokens),
+ };
+}
+
function timestampMs(value: unknown): number | undefined {
if (typeof value !== "string") return undefined;
const parsed = new Date(value).getTime();
@@ -243,7 +280,7 @@ export function applySwarmEvent(current: SwarmRunStatus, rawEvent: unknown): Swa
}
if (type === "task_completed" || type === "worker_completed") {
- return updateAgent(current, { agentId, taskId }, (agent) => ({
+ const withTaskTokens = updateAgent(current, { agentId, taskId }, (agent) => ({
...agent,
status: "done",
elapsed_s: agent.startedAt && eventTime
@@ -251,7 +288,15 @@ export function applySwarmEvent(current: SwarmRunStatus, rawEvent: unknown): Swa
: agent.elapsed_s,
iterations: asNumber(data.iterations) ?? agent.iterations,
lastText: asString(data.summary) || agent.lastText,
+ input_tokens: asNumber(data.input_tokens) ?? agent.input_tokens,
+ output_tokens: asNumber(data.output_tokens) ?? agent.output_tokens,
+ cache_read_tokens: asNumber(data.cache_read_tokens) ?? agent.cache_read_tokens,
+ cache_creation_tokens: asNumber(data.cache_creation_tokens) ?? agent.cache_creation_tokens,
}));
+ return recomputeRunTokenTotals({
+ ...withTaskTokens,
+ token_source: mergeTokenSource(current.token_source, data.token_source),
+ });
}
if (["task_failed", "worker_failed", "worker_timeout", "worker_incomplete"].includes(type)) {
@@ -307,6 +352,7 @@ export function buildSwarmStatusFromToolResultPreview(preview: string): SwarmRun
if (!runId) return null;
const times = serverRunTimes(parsed);
const status = normalizeRunStatus(parsed.status);
+ const usage = asRecord(parsed.token_usage);
return {
runId,
preset: asString(parsed.preset) || "swarm",
@@ -317,6 +363,9 @@ export function buildSwarmStatusFromToolResultPreview(preview: string): SwarmRun
completedAt: ["completed", "failed", "cancelled"].includes(status)
? times.completedAt
: undefined,
+ total_input_tokens: asNumber(usage.total_input_tokens),
+ total_output_tokens: asNumber(usage.total_output_tokens),
+ token_source: asTokenSource(usage.token_source),
agents: [],
};
} catch {
diff --git a/frontend/src/types/agent.ts b/frontend/src/types/agent.ts
index d46a67b3b..a948a9c65 100644
--- a/frontend/src/types/agent.ts
+++ b/frontend/src/types/agent.ts
@@ -24,6 +24,12 @@ export interface SwarmAgentStatus {
lastText?: string;
error?: string;
layer?: number;
+ // Per-task cost telemetry from the swarm.event task_completed payload.
+ // Names mirror the backend event keys; absent when the worker never reported.
+ input_tokens?: number;
+ output_tokens?: number;
+ cache_read_tokens?: number;
+ cache_creation_tokens?: number;
}
export interface SwarmRunStatus {