🤖 refactor: consolidate frontend context usage calculations#2306
Open
ammar-agent wants to merge 4 commits intomainfrom
Open
🤖 refactor: consolidate frontend context usage calculations#2306ammar-agent wants to merge 4 commits intomainfrom
ammar-agent wants to merge 4 commits intomainfrom
Conversation
Three locations leaked stale pre-compaction data into context usage calculations after compaction completed: 1. WorkspaceStore.getWorkspaceUsage() searched backward through all messages for lastContextUsage without stopping at the compaction boundary, finding stale pre-compaction values that inflated the context usage bar and triggered premature auto-compaction. 2. WorkspaceConsumerManager.executeCalculation() passed all messages (including pre-boundary ones) to token stats calculation, inflating the consumer/file breakdown in the costs tab. 3. compactionHandler.sanitizeCompactionStreamEndEvent() stripped providerMetadata but not contextUsage from the stream-end event, leaving stale usage data on the boundary message.
Add shared utilities to eliminate duplicated context usage derivations: 1. currentContextUsage on WorkspaceUsageState - pre-derived liveUsage ?? lastContextUsage so 5 consumers don't each re-derive it manually. 2. getContextTokens() in usageAggregator - shared formula for input + cached + cacheCreate, replacing private copy in autoCompactionCheck and inline formula in useContextSwitchWarning. 3. Move getEffectiveContextLimit() from browser/utils/compaction to common/utils/tokens - its only deps were already in common. tokenMeterUtils now uses it instead of inlining the supports1MContext check. 4. getSessionCostTotal() in usageAggregator - shared helper for combining sessionTotal + liveCostUsage, simplifying CostsTab and CostsTabLabel.
- CostsTab: use getEffectiveContextLimit() for compaction model limit instead of manually replicating has1MContext && supports1MContext logic - CostsTab: remove stale comment referencing lastContextUsage - CostsTab: simplify hasUsageData check using currentContextUsage - TabLabels: fix dead ternary (both branches returned 'text-muted'), remove unused cn import - tokenStatsCalculator: remove stale backward-compat re-export of createDisplayUsage (all consumers import from displayUsage.ts directly) - autoCompactionCheck test: remove dead _historicalTokens parameter from createMockUsage helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Consolidates duplicated context usage derivations across the frontend into shared utilities, and performs additional cleanup of dead code, stale comments, and inconsistent patterns in the token/usage area.
Background
PR #2303 fixed a bug where pre-compaction context leaked into usage calculations — but the fix required patching 3 separate locations because the concern of "what is the current context usage" was scattered across many consumers. This refactor eliminates that duplication and cleans up adjacent code.
Implementation
Shared utilities (commit 1)
currentContextUsageonWorkspaceUsageState— the store now pre-derivesliveUsage ?? lastContextUsageso 5 consumer sites don't each re-derive it:ChatInput/index.tsxCostsTab.tsx(×2)useContextSwitchWarning.tsautoCompactionCheck.tsgetContextTokens()inusageAggregator.ts— promotes the private helper fromautoCompactionCheckand the inline formula inuseContextSwitchWarninginto a single export:input + cached + cacheCreate.getEffectiveContextLimit()moved tocommon/utils/tokens/— it only depended ongetModelStatsandsupports1MContext(both incommon/), but lived inbrowser/utils/compaction/.tokenMeterUtils.tsnow uses it instead of inlining thesupports1MContextcheck.getSessionCostTotal()inusageAggregator.ts— extracts the repeatedsessionTotal + liveCostUsageaggregation from bothCostsTabandCostsTabLabel.Additional cleanup (commit 2)
getEffectiveContextLimit()CostsTab.tsxhas1MContext && supports1MContext ? 1M : stats.max_input_tokensfor compaction model limitCostsTab.tsxcurrentContextUsagehasUsageDataCostsTab.tsxcurrentContextUsage !== undefinedreplaces checking bothlastContextUsageandliveUsageTabLabels.tsx"text-muted"— simplified and removed unusedcnimporttokenStatsCalculator.tsexport { createDisplayUsage }was unused — all consumers import fromdisplayUsage.tsdirectlyautoCompactionCheck.test.ts_historicalTokensparam increateMockUsagewas marked unused since session-usage migrationValidation
make typecheck— both renderer and main configs passcurrentContextUsagefield)make static-check— full passGenerated with
mux• Model:anthropic:claude-opus-4-6• Thinking:xhigh• Cost:$13.79