fix(ui): stop the context meter from counting every internal round-trip
The token breakdown of an assistant message accumulates across every API round-trip inside the turn: each tool call re-reads the whole cached prompt, so input/cache.read add up to several times the context window. Every context-usage surface summed those fields, which is why the meter could read 330% of a 1M window whose real fill was 232,872 tokens (23.3%), and why reopening an older session jumps the readout (#2562). The server reports the final round-trip's window as tokens.total (optional in the message schema; opencode 1.18.18 returns it, verified against its live /session/:id/message API). Prefer it everywhere the window fill is displayed and fall back to summing only when the server did not send it: contextTokensFromBreakdown in tokenUtils now owns that rule, and the context store extractor, sync store getter, work status panel, context sidebar, VS Code layout, mini chat, and mobile metadata all use it instead of their own inline sums. Fixes #2562
This commit is contained in:
@@ -14,8 +14,8 @@ describe('computeContextUsage', () => {
|
||||
});
|
||||
|
||||
test('reports the latest turn rather than a sum across turns', () => {
|
||||
// Each assistant turn reports the whole window it saw, so adding them up
|
||||
// would report several times the real fill.
|
||||
// A turn's tokens describe that turn's window, so adding turns up would
|
||||
// report several times the real fill.
|
||||
const usage = computeContextUsage(
|
||||
[
|
||||
assistant({ input: 400, output: 0, reasoning: 0 }, 'old'),
|
||||
@@ -61,4 +61,24 @@ describe('computeContextUsage', () => {
|
||||
const usage = computeContextUsage([assistant({ input: 10 })], 100);
|
||||
expect(usage?.totalTokens).toBe(10);
|
||||
});
|
||||
|
||||
test('prefers the server-reported total over summing round-trip fields', () => {
|
||||
// Real payload from opencode 1.18.18: ~14 tool-call round-trips accumulated
|
||||
// cache.read to 3.29M while the 1M window really held 232,872. Summing
|
||||
// rendered 330.6%; the reported total renders the real 23.3%.
|
||||
const usage = computeContextUsage(
|
||||
[assistant({ total: 232_872, input: 0, output: 14_523, reasoning: 0, cache: { read: 3_291_956, write: 0 } })],
|
||||
1_000_000,
|
||||
);
|
||||
expect(usage?.totalTokens).toBe(232_872);
|
||||
expect(usage?.percent.toFixed(4)).toBe('23.2872');
|
||||
});
|
||||
|
||||
test('selects a message whose only signal is the reported total', () => {
|
||||
const usage = computeContextUsage(
|
||||
[assistant({ total: 5_000, input: 0, output: 0, reasoning: 0 })],
|
||||
100_000,
|
||||
);
|
||||
expect(usage?.totalTokens).toBe(5_000);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user