Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(frontend): count failed/cancelled swarm tokens; hydrate run usage on replay

shadowinlifeb7f71bc703fb
diff --git a/frontend/src/hooks/useLlmUsageCounter.ts b/frontend/src/hooks/useLlmUsageCounter.ts
index 35390727e..104accd5c 100644
--- a/frontend/src/hooks/useLlmUsageCounter.ts
+++ b/frontend/src/hooks/useLlmUsageCounter.ts
@@ -3,7 +3,8 @@
*
* The backend emits one `llm_usage` event per agent iteration carrying the
* provider-reported usage DELTA plus `iter` and `attempt_id`
- * (agent/src/session/service.py). useSSE dedups by Last-Event-ID, but a
+ * (emitted at agent/src/agent/loop.py; `attempt_id` injected at
+ * agent/src/session/service.py). useSSE dedups by Last-Event-ID, but a
* reconnect replay can still deliver an already-applied iteration, so
* accumulation is keyed idempotently on `(attemptId, iter)` and a new
* attempt_id resets the running totals to zero.
diff --git a/frontend/src/lib/__tests__/swarmStatus.usage.test.ts b/frontend/src/lib/__tests__/swarmStatus.usage.test.ts
index feb7127bd..38c21fa61 100644
--- a/frontend/src/lib/__tests__/swarmStatus.usage.test.ts
+++ b/frontend/src/lib/__tests__/swarmStatus.usage.test.ts
@@ -1,6 +1,7 @@
import {
applySwarmEvent,
buildSwarmStatusFromToolResultPreview,
+ mergeSwarmRunUsage,
} from "../swarmStatus";
import type { SwarmRunStatus } from "@/types/agent";
@@ -191,3 +192,88 @@ describe("swarmStatus tool-result preview token_usage", () => {
expect(status?.total_input_tokens).toBeUndefined();
});
});
+
+describe("swarmStatus failed/cancelled task token telemetry", () => {
+ it("counts tokens from a failed task so the live card matches the run total", () => {
+ const next = applySwarmEvent(baseStatus(), {
+ type: "task_failed",
+ agent_id: "analyst",
+ task_id: "t1",
+ timestamp: "2026-07-29T12:01:00.000Z",
+ data: {
+ error: "boom",
+ input_tokens: 1000,
+ output_tokens: 200,
+ cache_read_tokens: 50,
+ cache_creation_tokens: 10,
+ token_source: "estimated",
+ },
+ });
+
+ expect(next.total_input_tokens).toBe(1000);
+ expect(next.total_output_tokens).toBe(200);
+ expect(next.token_source).toBe("estimated");
+ });
+
+ it("counts tokens from a cancelled task", () => {
+ const next = applySwarmEvent(baseStatus(), {
+ type: "task_cancelled",
+ agent_id: "risk",
+ task_id: "t2",
+ timestamp: "2026-07-29T12:01:00.000Z",
+ data: { input_tokens: 300, output_tokens: 40 },
+ });
+
+ expect(next.total_input_tokens).toBe(300);
+ expect(next.total_output_tokens).toBe(40);
+ });
+
+ it("does not wipe totals when a failure event carries no token fields", () => {
+ const withTokens = applySwarmEvent(
+ baseStatus(),
+ completedEvent("analyst", "t1", { input_tokens: 500, output_tokens: 60 }),
+ );
+ const next = applySwarmEvent(withTokens, {
+ type: "worker_failed",
+ agent_id: "risk",
+ task_id: "t2",
+ timestamp: "2026-07-29T12:02:00.000Z",
+ data: { error: "network" },
+ });
+
+ expect(next.total_input_tokens).toBe(500);
+ expect(next.total_output_tokens).toBe(60);
+ });
+});
+
+describe("swarmStatus REST usage hydration", () => {
+ it("merges run-level totals and the provenance label from the detail payload", () => {
+ const hydrated = mergeSwarmRunUsage(baseStatus(), {
+ total_input_tokens: 853341,
+ total_output_tokens: 34681,
+ provider: "dashscope",
+ model: "glm-5.1",
+ token_source: "provider",
+ });
+
+ expect(hydrated.runId).toBe("run-usage");
+ expect(hydrated.total_input_tokens).toBe(853341);
+ expect(hydrated.total_output_tokens).toBe(34681);
+ expect(hydrated.provider).toBe("dashscope");
+ expect(hydrated.model).toBe("glm-5.1");
+ expect(hydrated.token_source).toBe("provider");
+ });
+
+ it("keeps existing totals and label when the payload redacts or omits them", () => {
+ const current: SwarmRunStatus = {
+ ...baseStatus(),
+ total_input_tokens: 10,
+ token_source: "provider",
+ };
+
+ const hydrated = mergeSwarmRunUsage(current, { token_source: "[redacted]" });
+
+ expect(hydrated.total_input_tokens).toBe(10);
+ expect(hydrated.token_source).toBe("provider");
+ });
+});
diff --git a/frontend/src/lib/swarmStatus.ts b/frontend/src/lib/swarmStatus.ts
index 04d3c2e56..e36146442 100644
--- a/frontend/src/lib/swarmStatus.ts
+++ b/frontend/src/lib/swarmStatus.ts
@@ -300,26 +300,42 @@ export function applySwarmEvent(current: SwarmRunStatus, rawEvent: unknown): Swa
}
if (["task_failed", "worker_failed", "worker_timeout", "worker_incomplete"].includes(type)) {
- return updateAgent(current, { agentId, taskId }, (agent) => ({
+ const withTokens = updateAgent(current, { agentId, taskId }, (agent) => ({
...agent,
status: "failed",
elapsed_s: agent.startedAt && eventTime
? Math.max(0, (eventTime - agent.startedAt) / 1000)
: agent.elapsed_s,
error: asString(data.error) || asString(data.reason) || agent.error,
+ 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({
+ ...withTokens,
+ token_source: mergeTokenSource(current.token_source, data.token_source),
+ });
}
if (type === "task_cancelled" || type === "worker_cancelled") {
// cancel_run() reached this worker mid-flight: a user stop, not a failure.
- return updateAgent(current, { agentId, taskId }, (agent) => ({
+ const withTokens = updateAgent(current, { agentId, taskId }, (agent) => ({
...agent,
status: "cancelled",
elapsed_s: agent.startedAt && eventTime
? Math.max(0, (eventTime - agent.startedAt) / 1000)
: agent.elapsed_s,
iterations: asNumber(data.iterations) ?? agent.iterations,
+ 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({
+ ...withTokens,
+ token_source: mergeTokenSource(current.token_source, data.token_source),
+ });
}
if (type === "task_blocked") {
@@ -394,3 +410,17 @@ export function buildSwarmStatusFromToolResultPreview(preview: string): SwarmRun
};
}
}
+
+export function mergeSwarmRunUsage(
+ status: SwarmRunStatus,
+ payload: Record<string, unknown>,
+): SwarmRunStatus {
+ return {
+ ...status,
+ total_input_tokens: asNumber(payload.total_input_tokens) ?? status.total_input_tokens,
+ total_output_tokens: asNumber(payload.total_output_tokens) ?? status.total_output_tokens,
+ provider: asString(payload.provider) || status.provider,
+ model: asString(payload.model) || status.model,
+ token_source: asTokenSource(payload.token_source) ?? status.token_source,
+ };
+}
diff --git a/frontend/src/pages/Agent.tsx b/frontend/src/pages/Agent.tsx
index e9df1502e..db0b4446b 100644
--- a/frontend/src/pages/Agent.tsx
+++ b/frontend/src/pages/Agent.tsx
@@ -44,6 +44,7 @@ import {
applySwarmEvent,
buildSwarmStatusFromStarted,
buildSwarmStatusFromToolResultPreview,
+ mergeSwarmRunUsage,
} from "@/lib/swarmStatus";
import { buildToolTimelineMessages } from "@/pages/agentToolTimeline";
@@ -78,6 +79,14 @@ function groupMessages(msgs: StoredAgentMessage[]): MsgGroup[] {
const act = () => useAgentStore.getState();
+function hydrateSwarmRunUsage(runId: string): void {
+ void api.getSwarmRun(runId).then((payload) => {
+ const current = act().swarmRuns[runId];
+ if (!current) return;
+ act().upsertSwarmStatus(mergeSwarmRunUsage(current, payload));
+ }).catch(() => undefined);
+}
+
function eventCallId(data: Record<string, unknown>): string | undefined {
return typeof data.call_id === "string" && data.call_id
? data.call_id
@@ -846,6 +855,7 @@ export function Agent() {
const fallback = buildSwarmStatusFromToolResultPreview(String(d.preview || ""));
if (fallback && !act().swarmRuns[fallback.runId]) {
act().upsertSwarmStatus(fallback);
+ hydrateSwarmRunUsage(fallback.runId);
}
}
},
diff --git a/frontend/src/types/agent.ts b/frontend/src/types/agent.ts
index a948a9c65..13baaa48b 100644
--- a/frontend/src/types/agent.ts
+++ b/frontend/src/types/agent.ts
@@ -41,8 +41,9 @@ export interface SwarmRunStatus {
startedAt: number;
completedAt?: number;
agents: SwarmAgentStatus[];
- // Run-level cost telemetry from GET /swarm/runs/{id}; names mirror the backend
- // response keys. All optional: absent on runs created before the fields existed.
+ // Run-level cost telemetry. Names mirror the GET /swarm/runs/{id} response,
+ // but the values arrive from swarm events or, on replay, are hydrated from
+ // that endpoint. All optional: absent on runs created before the fields existed.
total_input_tokens?: number;
total_output_tokens?: number;
provider?: string | null;