Skip to content

Commit a62ff19

Browse files
artalesteipete
authored andcommitted
fix(agent): isolate last-turn total in token usage reporting (#17016)
recordAssistantUsage accumulated cacheRead across the entire multi-turn run, and totalTokens was clamped to contextTokens. This caused session_status to report 100% context usage regardless of actual load. Changes: - run.ts: capture lastTurnTotal from the most recent model call and inject it into the normalized usage before it reaches agentMeta. - usage-reporting.test.ts: verify usage.total reflects current turn, not accumulated total. Fixes #17016
1 parent d6acd71 commit a62ff19

2 files changed

Lines changed: 121 additions & 0 deletions

File tree

‎src/agents/pi-embedded-runner/run.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -528,6 +528,7 @@ export async function runEmbeddedPiAgent(
528528
// Keep prompt size from the latest model call so session totalTokens
529529
// reflects current context usage, not accumulated tool-loop usage.
530530
lastRunPromptUsage = lastAssistantUsage ?? attemptUsage;
531+
const lastTurnTotal = lastAssistantUsage?.total ?? attemptUsage?.total;
531532
const attemptCompactionCount = Math.max(0, attempt.compactionCount ?? 0);
532533
autoCompactionCount += attemptCompactionCount;
533534
const formattedAssistantErrorText = lastAssistant
@@ -927,6 +928,9 @@ export async function runEmbeddedPiAgent(
927928
}
928929

929930
const usage = toNormalizedUsage(usageAccumulator);
931+
if (usage && lastTurnTotal && lastTurnTotal > 0) {
932+
usage.total = lastTurnTotal;
933+
}
930934
// Extract the last individual API call's usage for context-window
931935
// utilization display. The accumulated `usage` sums input tokens
932936
// across all calls (tool-use loops, compaction retries), which
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
import "./run.overflow-compaction.mocks.shared.js";
2+
import { beforeEach, describe, expect, it, vi } from "vitest";
3+
4+
vi.mock("../auth-profiles.js", () => ({
5+
isProfileInCooldown: vi.fn(() => false),
6+
markAuthProfileFailure: vi.fn(async () => {}),
7+
markAuthProfileGood: vi.fn(async () => {}),
8+
markAuthProfileUsed: vi.fn(async () => {}),
9+
}));
10+
11+
vi.mock("../usage.js", () => ({
12+
normalizeUsage: vi.fn((usage?: unknown) =>
13+
usage && typeof usage === "object" ? usage : undefined,
14+
),
15+
derivePromptTokens: vi.fn(
16+
(usage?: { input?: number; cacheRead?: number; cacheWrite?: number }) => {
17+
if (!usage) {
18+
return undefined;
19+
}
20+
const input = usage.input ?? 0;
21+
const cacheRead = usage.cacheRead ?? 0;
22+
const cacheWrite = usage.cacheWrite ?? 0;
23+
const sum = input + cacheRead + cacheWrite;
24+
return sum > 0 ? sum : undefined;
25+
},
26+
),
27+
}));
28+
29+
vi.mock("../workspace-run.js", () => ({
30+
resolveRunWorkspaceDir: vi.fn((params: { workspaceDir: string }) => ({
31+
workspaceDir: params.workspaceDir,
32+
usedFallback: false,
33+
fallbackReason: undefined,
34+
agentId: "main",
35+
})),
36+
redactRunIdentifier: vi.fn((value?: string) => value ?? ""),
37+
}));
38+
39+
vi.mock("../pi-embedded-helpers.js", () => ({
40+
formatBillingErrorMessage: vi.fn(() => ""),
41+
classifyFailoverReason: vi.fn(() => null),
42+
formatAssistantErrorText: vi.fn(() => ""),
43+
isAuthAssistantError: vi.fn(() => false),
44+
isBillingAssistantError: vi.fn(() => false),
45+
isCompactionFailureError: vi.fn(() => false),
46+
isLikelyContextOverflowError: vi.fn((msg?: string) => {
47+
const lower = (msg ?? "").toLowerCase();
48+
return lower.includes("request_too_large") || lower.includes("context window exceeded");
49+
}),
50+
isFailoverAssistantError: vi.fn(() => false),
51+
isFailoverErrorMessage: vi.fn(() => false),
52+
parseImageSizeError: vi.fn(() => null),
53+
parseImageDimensionError: vi.fn(() => null),
54+
isRateLimitAssistantError: vi.fn(() => false),
55+
isTimeoutErrorMessage: vi.fn(() => false),
56+
pickFallbackThinkingLevel: vi.fn(() => null),
57+
}));
58+
59+
import { runEmbeddedPiAgent } from "./run.js";
60+
import { runEmbeddedAttempt } from "./run/attempt.js";
61+
62+
const mockedRunEmbeddedAttempt = vi.mocked(runEmbeddedAttempt);
63+
64+
describe("runEmbeddedPiAgent usage reporting", () => {
65+
beforeEach(() => {
66+
vi.clearAllMocks();
67+
});
68+
69+
it("reports total usage from the last turn instead of accumulated total", async () => {
70+
// Simulate a multi-turn run result.
71+
// Turn 1: Input 100, Output 50. Total 150.
72+
// Turn 2: Input 150, Output 50. Total 200.
73+
74+
// The accumulated usage (attemptUsage) will be the sum:
75+
// Input: 100 + 150 = 250 (Note: runEmbeddedAttempt actually returns accumulated usage)
76+
// Output: 50 + 50 = 100
77+
// Total: 150 + 200 = 350
78+
79+
// The last assistant usage (lastAssistant.usage) will be Turn 2:
80+
// Input: 150, Output 50, Total 200.
81+
82+
// We expect result.meta.agentMeta.usage.total to be 200 (last turn total).
83+
// The bug causes it to be 350 (accumulated total).
84+
85+
mockedRunEmbeddedAttempt.mockResolvedValueOnce({
86+
aborted: false,
87+
promptError: null,
88+
timedOut: false,
89+
sessionIdUsed: "test-session",
90+
assistantTexts: ["Response 1", "Response 2"],
91+
lastAssistant: {
92+
usage: { input: 150, output: 50, total: 200 },
93+
stopReason: "end_turn",
94+
},
95+
attemptUsage: { input: 250, output: 100, total: 350 },
96+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
97+
} as any);
98+
99+
const result = await runEmbeddedPiAgent({
100+
sessionId: "test-session",
101+
sessionKey: "test-key",
102+
sessionFile: "/tmp/session.json",
103+
workspaceDir: "/tmp/workspace",
104+
prompt: "hello",
105+
timeoutMs: 30000,
106+
runId: "run-1",
107+
});
108+
109+
// Check usage in meta
110+
const usage = result.meta.agentMeta.usage;
111+
expect(usage).toBeDefined();
112+
113+
// Check if total matches the last turn's total (200)
114+
// If the bug exists, it will likely be 350
115+
expect(usage?.total).toBe(200);
116+
});
117+
});

0 commit comments

Comments
 (0)