Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix: repair botched main merge in token accounting
The `Merge branch 'main'` commit left several files in an inconsistent
state. This repairs them:

- jsonl-metrics.ts: getTokenMetrics had a corrupted body (duplicate
  variable declarations plus leftover pre-refactor loop code referencing
  out-of-scope symbols), causing TS1005 syntax errors. Rebuilt it to use
  the sumUsage/getFinalizedUsageEntries/computeContextLength helpers and
  to emit the hot/cold cacheReadTokens/cacheCreationTokens split that
  main added and the cache-metrics widget depends on. sumUsage now tracks
  that split too.
- jsonl-metrics.test.ts: added cacheReadTokens/cacheCreationTokens to the
  three subagent-token assertions so they match the current shape.
- ccstatusline.ts: fixed import ordering (token-subagents after terminal).
- TokensInput/TokensOutput: the widgets still checked context_window
  before tokenMetrics, contradicting the PR's own tests ("prefers
  cumulative tokenMetrics for all token widgets"). Reordered so
  tokenMetrics wins and context_window is the main-only fallback, and
  dropped the now-redundant duplicate fallback branches.

tsc --noEmit and eslint are clean; the token/jsonl suites (37 tests) pass.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
  • Loading branch information
elhoim and claude committed Jul 4, 2026
commit 0f89739d41addcdad792c9b7999e58a085ef3de9
2 changes: 1 addition & 1 deletion src/ccstatusline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,11 @@ import {
getWidgetSpeedWindowSeconds,
isWidgetSpeedWindowEnabled
} from './utils/speed-window';
import { isWidgetSubagentsEnabled } from './utils/token-subagents';
import {
getPackageVersion,
getTerminalWidth
} from './utils/terminal';
import { isWidgetSubagentsEnabled } from './utils/token-subagents';
import { prefetchUsageDataIfNeeded } from './utils/usage-prefetch';

function hasSessionDurationInStatusJson(data: StatusJSON): boolean {
Expand Down
8 changes: 8 additions & 0 deletions src/utils/__tests__/jsonl-metrics.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,8 @@ describe('jsonl transcript metrics', () => {
inputTokens: 600, // 100 + 500
outputTokens: 110, // 50 + 60
cachedTokens: 40, // (20+10) + (5+5)
cacheReadTokens: 25, // 20 + 5
cacheCreationTokens: 15, // 10 + 5
totalTokens: 750,
contextLength: 130 // latest main-chain non-sidechain: 100 + 20 + 10
});
Expand All @@ -430,6 +432,8 @@ describe('jsonl transcript metrics', () => {
inputTokens: 600, // main 100 (sidechain dropped) + file 500
outputTokens: 110, // main 50 + file 60
cachedTokens: 40, // main 30 + file 10
cacheReadTokens: 25, // main 20 + file 5
cacheCreationTokens: 15, // main 10 + file 5
totalTokens: 750,
contextLength: 130 // unchanged — main-chain concept
});
Expand Down Expand Up @@ -458,6 +462,8 @@ describe('jsonl transcript metrics', () => {
inputTokens: 600,
outputTokens: 110,
cachedTokens: 40,
cacheReadTokens: 25, // 20 + 5
cacheCreationTokens: 15, // 10 + 5
totalTokens: 750,
contextLength: 130
});
Expand Down Expand Up @@ -491,6 +497,8 @@ describe('jsonl transcript metrics', () => {
inputTokens: 140, // 10 + 100 + 30
outputTokens: 245, // 5 + 200 + 40
cachedTokens: 0,
cacheReadTokens: 0,
cacheCreationTokens: 0,
totalTokens: 385,
contextLength: 10 // 10 + 0 + 0
});
Expand Down
43 changes: 11 additions & 32 deletions src/utils/jsonl-metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,8 @@ export async function getSessionDuration(transcriptPath: string): Promise<string
interface TokenUsageSum {
inputTokens: number;
outputTokens: number;
cachedTokens: number;
cacheReadTokens: number;
cacheCreationTokens: number;
}

export interface TokenMetricsOptions { includeSubagents?: boolean }
Expand Down Expand Up @@ -186,7 +187,8 @@ function getFinalizedUsageEntries(lines: string[]): TranscriptLine[] {
function sumUsage(entries: TranscriptLine[], skipSidechain: boolean): TokenUsageSum {
let inputTokens = 0;
let outputTokens = 0;
let cachedTokens = 0;
let cacheReadTokens = 0;
let cacheCreationTokens = 0;

for (const data of entries) {
if (skipSidechain && data.isSidechain === true) {
Expand All @@ -198,11 +200,11 @@ function sumUsage(entries: TranscriptLine[], skipSidechain: boolean): TokenUsage
}
inputTokens += usage.input_tokens || 0;
outputTokens += usage.output_tokens || 0;
cachedTokens += usage.cache_read_input_tokens ?? 0;
cachedTokens += usage.cache_creation_input_tokens ?? 0;
cacheReadTokens += usage.cache_read_input_tokens ?? 0;
cacheCreationTokens += usage.cache_creation_input_tokens ?? 0;
}

return { inputTokens, outputTokens, cachedTokens };
return { inputTokens, outputTokens, cacheReadTokens, cacheCreationTokens };
}

// Context length is the most recent main-chain (non-sidechain, non-error)
Expand Down Expand Up @@ -248,11 +250,6 @@ export async function getTokenMetrics(
const subagentPaths = options.includeSubagents === true
? getSubagentTranscriptPaths(transcriptPath, getReferencedSubagentIds(lines))
: [];
let inputTokens = 0;
let outputTokens = 0;
let cacheReadTokens = 0;
let cacheCreationTokens = 0;
let contextLength = 0;

// When separate subagent files exist, inline sidechain rows are represented
// there — drop them from the main pass to avoid double counting. When no
Expand All @@ -262,7 +259,8 @@ export async function getTokenMetrics(

let inputTokens = mainSum.inputTokens;
let outputTokens = mainSum.outputTokens;
let cachedTokens = mainSum.cachedTokens;
let cacheReadTokens = mainSum.cacheReadTokens;
let cacheCreationTokens = mainSum.cacheCreationTokens;

if (subagentPaths.length > 0) {
const subagentSums = await Promise.all(subagentPaths.map(async (subagentPath) => {
Expand All @@ -277,33 +275,14 @@ export async function getTokenMetrics(
for (const sum of subagentSums) {
if (!sum) {
continue;
inputTokens += usage.input_tokens || 0;
outputTokens += usage.output_tokens || 0;
cacheReadTokens += usage.cache_read_input_tokens ?? 0;
cacheCreationTokens += usage.cache_creation_input_tokens ?? 0;

// Track the most recent entry with isSidechain: false (or undefined, which defaults to main chain)
// Also skip API error messages (synthetic messages with 0 tokens)
if (data.isSidechain !== true && data.timestamp && !data.isApiErrorMessage) {
const entryTime = new Date(data.timestamp);
if (!mostRecentTimestamp || entryTime > mostRecentTimestamp) {
mostRecentTimestamp = entryTime;
mostRecentMainChainEntry = data;
}
inputTokens += sum.inputTokens;
outputTokens += sum.outputTokens;
cachedTokens += sum.cachedTokens;
cacheReadTokens += sum.cacheReadTokens;
cacheCreationTokens += sum.cacheCreationTokens;
}
}

// Calculate context length from the most recent main chain message
if (mostRecentMainChainEntry?.message?.usage) {
const usage = mostRecentMainChainEntry.message.usage;
contextLength = (usage.input_tokens || 0)
+ (usage.cache_read_input_tokens ?? 0)
+ (usage.cache_creation_input_tokens ?? 0);
}

const cachedTokens = cacheReadTokens + cacheCreationTokens;
const totalTokens = inputTokens + outputTokens + cachedTokens;

Expand Down
21 changes: 8 additions & 13 deletions src/widgets/TokensInput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,26 +36,21 @@ export class TokensInputWidget implements Widget {
return formatRawOrLabeledValue(item, label, '15.2k');
}

// The stdin context_window payload is main-only; skip it when subagents are on.
// Prefer the cumulative token metrics (subagent-inclusive when opted in).
const metrics = tokenMetricsForWidget(item, context);
if (metrics) {
return formatRawOrLabeledValue(item, label, formatTokens(metrics.inputTokens));
}

// Fall back to the stdin context_window payload, which is main-only —
// skip it when subagents are on.
if (!subagents) {
const inputTotalTokens = getContextWindowInputTotalTokens(context.data);
if (inputTotalTokens !== null) {
return formatRawOrLabeledValue(item, label, formatTokens(inputTotalTokens));
}
}

const metrics = tokenMetricsForWidget(item, context);
if (metrics) {
return formatRawOrLabeledValue(item, label, formatTokens(metrics.inputTokens));
}
if (context.tokenMetrics) {
return formatRawOrLabeledValue(item, 'In: ', formatTokens(context.tokenMetrics.inputTokens));
}

const inputTotalTokens = getContextWindowInputTotalTokens(context.data);
if (inputTotalTokens !== null) {
return formatRawOrLabeledValue(item, 'In: ', formatTokens(inputTotalTokens));
}
return null;
}

Expand Down
21 changes: 8 additions & 13 deletions src/widgets/TokensOutput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,26 +36,21 @@ export class TokensOutputWidget implements Widget {
return formatRawOrLabeledValue(item, label, '3.4k');
}

// The stdin context_window payload is main-only; skip it when subagents are on.
// Prefer the cumulative token metrics (subagent-inclusive when opted in).
const metrics = tokenMetricsForWidget(item, context);
if (metrics) {
return formatRawOrLabeledValue(item, label, formatTokens(metrics.outputTokens));
}

// Fall back to the stdin context_window payload, which is main-only —
// skip it when subagents are on.
if (!subagents) {
const outputTotalTokens = getContextWindowOutputTotalTokens(context.data);
if (outputTotalTokens !== null) {
return formatRawOrLabeledValue(item, label, formatTokens(outputTotalTokens));
}
}

const metrics = tokenMetricsForWidget(item, context);
if (metrics) {
return formatRawOrLabeledValue(item, label, formatTokens(metrics.outputTokens));
}
if (context.tokenMetrics) {
return formatRawOrLabeledValue(item, 'Out: ', formatTokens(context.tokenMetrics.outputTokens));
}

const outputTotalTokens = getContextWindowOutputTotalTokens(context.data);
if (outputTotalTokens !== null) {
return formatRawOrLabeledValue(item, 'Out: ', formatTokens(outputTotalTokens));
}
return null;
}

Expand Down