fix(core): use output-only tokens and accumulate across subagent rounds

Subagent token display had two bugs:
- Used totalTokenCount (input+output) instead of candidatesTokenCount
  (output-only), causing mixed units when aggregated with main stream
- Overwrote tokenCount per round instead of accumulating, so multi-round
  subagents only showed the last round's count

Co-Authored-By: Qwen-Coder <noreply@qwen.ai>
This commit is contained in:
qqqys 2026-04-17 10:37:13 +08:00
parent fd2767c9db
commit d393f23dfa

View file

@ -486,16 +486,21 @@ class AgentToolInvocation extends BaseToolInvocation<AgentParams, ToolResult> {
}); });
// Track real-time token consumption from subagent API calls. // Track real-time token consumption from subagent API calls.
// Each USAGE_METADATA event carries the cumulative totalTokenCount for the // Each USAGE_METADATA event carries per-round usage, so we accumulate
// subagent session, so we replace (not accumulate) on every event. // output tokens across rounds. We use candidatesTokenCount (output-only)
// to stay consistent with the main stream's chars/4 output-token estimate.
let accumulatedOutputTokens = 0;
this.eventEmitter.on( this.eventEmitter.on(
AgentEventType.USAGE_METADATA, AgentEventType.USAGE_METADATA,
(...args: unknown[]) => { (...args: unknown[]) => {
const event = args[0] as AgentUsageEvent; const event = args[0] as AgentUsageEvent;
const total = const outputTokens = event.usage?.candidatesTokenCount ?? 0;
event.usage?.totalTokenCount ?? event.usage?.promptTokenCount ?? 0; if (outputTokens > 0) {
if (total > 0) { accumulatedOutputTokens += outputTokens;
this.updateDisplay({ tokenCount: total }, updateOutput); this.updateDisplay(
{ tokenCount: accumulatedOutputTokens },
updateOutput,
);
} }
}, },
); );