fix(server): scope the Claude context meter to the parent session #8453
ClosedSamGu-NRX(GitHub profile, opens in a new tab)wants to merge 14 commits into
main fromrefs/pull/8453/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:M
- apps/server/src/provider/Layers/ClaudeAdapter.ts line 688OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -672,13 +675,14 @@672- totalProcessedTokens: Math.max(673- totalTokens,674- context.lastKnownTotalProcessedTokens ?? totalTokens,675- ),676- });677- if (!snapshot) {675+ const totalProcessedTokens = Math.max(676+ totalTokens,677+ context.lastKnownTotalProcessedTokens ?? totalTokens,678+ );679+ if (totalProcessedTokens === context.lastKnownTotalProcessedTokens) {678680 return undefined;679681 }680682683+ const usage = value as Record<string, unknown>;681684 const toolUses = finiteNonNegativeInteger(usage.tool_uses);682685 const durationMs = finiteNonNegativeInteger(usage.duration_ms);683686 return {684- ...snapshot,687+ ...lastKnown,688+ totalProcessedTokens,
- apps/server/src/provider/Layers/ClaudeAdapter.ts line 675OutdatedResolvedby SamGu-NRX(GitHub profile, opens in a new tab)@@ -660,18 +670,6 @@660- const activeTokens =661- lastUsedTokens !== undefined ? Math.max(totalTokens, lastUsedTokens) : totalTokens;662- if (lastUsedTokens !== undefined && activeTokens === lastUsedTokens) {670+ const lastKnown = context.lastKnownTokenUsage;671+ if (!lastKnown) {663672 return undefined;664673 }665674666- const usage = value as Record<string, unknown>;667- const snapshot = makeClaudeTokenUsageSnapshot({668- activeTokens,669- ...(context.lastKnownContextWindow !== undefined670- ? { contextWindow: context.lastKnownContextWindow }671- : {}),672- totalProcessedTokens: Math.max(673- totalTokens,674- context.lastKnownTotalProcessedTokens ?? totalTokens,675- ),676- });677- if (!snapshot) {675+ const totalProcessedTokens = Math.max(apps/server/src/provider/Layers/ClaudeAdapter.ts lines 906 to 911Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -675,13 +675,17 @@675- ),676- });677- if (!snapshot) {675+ const totalProcessedTokens = Math.max(676+ totalTokens,677+ context.lastKnownTotalProcessedTokens ?? totalTokens,678+ );679+ if (totalProcessedTokens === context.lastKnownTotalProcessedTokens) {678680 return undefined;679681 }680682683+ const usage = value as Record<string, unknown>;681684 const toolUses = finiteNonNegativeInteger(usage.tool_uses);682685 const durationMs = finiteNonNegativeInteger(usage.duration_ms);683686 return {684- ...snapshot,687+ ...lastKnown,688+ totalProcessedTokens,685689 ...(toolUses !== undefined ? { toolUses } : {}),686690 ...(durationMs !== undefined ? { durationMs } : {}),687691 };
- apps/server/src/provider/Layers/ClaudeAdapter.ts line 3828Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -3449,3 +3480,12 @@34493480 yield* emitRuntimeWarning(context, message.text, message);34503481 }34513482 return;3483+ case "model_refusal_fallback": {3484+ // A refusal retry swaps the model for the rest of the session, so the3485+ // recorded id has to follow or the window lookup keys a model that no3486+ // longer runs.3487+ if (message.direction === "retry") {3488+ const fallbackModel = trimmedString(message.fallback_model);3489+ if (fallbackModel) {3490+ context.currentApiModelId = fallbackModel;3491+ }
- apps/server/src/provider/Layers/ClaudeAdapter.ts line 4920Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -4413,3 +4459,4 @@44134459 startedAt,44144460 basePermissionMode: permissionMode,44154461 currentApiModelId: apiModelId,4462+ observedApiModelId: undefined,
macroscopeapp[bot](GitHub profile, opens in a new tab) approved these changes
- apps/server/src/provider/Layers/ClaudeAdapter.ts lines 3793 to 3798OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -3748,4 +3785,14 @@37483785 yield* emitRuntimeWarning(context, message.text, message);37493786 }37503787 return;3751- case "model_refusal_fallback":3788+ case "model_refusal_fallback": {3789+ // A refusal retry swaps the model for the rest of the session, so the3790+ // window lookup has to follow it. `currentApiModelId` deliberately3791+ // does not: it mirrors the user's selection for `setModel`, and moving3792+ // it here would make the next turn re-send the refused model.3793+ if (message.direction === "retry") {3794+ const fallbackModel = trimmedString(message.fallback_model);3795+ if (fallbackModel) {3796+ context.observedApiModelId = fallbackModel;3797+ }3798+ }
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:M
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
juliusmarminge closed this
Sign in to join this conversation.


Note
Reviews paused#
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Advanced
Run ID:
7f33f232-90b7-4134-bf52-8877db9b8fb7📥 Commits
Reviewing files that changed from the base of the PR and between dce55a5a7cdc38360730435a4cd9548cb21234fc and 5a233da9e87f7b3a3de0c658a7d7b3fe79ffb621.
📒 Files selected for processing (2)
apps/server/src/provider/Layers/ClaudeAdapter.test.tsapps/server/src/provider/Layers/ClaudeAdapter.tsIncluded review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.
📝 Walkthrough
Walkthrough#
The Claude adapter now tracks cumulative subagent usage by task, keeps it separate from parent context usage, and selects context windows from the serving model. Completion handling ignores total-only usage as active parent usage. Tests cover progress, completion, model changes, and event collection.
Changes#
Claude usage meter
apps/server/src/provider/Layers/ClaudeAdapter.ts,apps/server/src/provider/Layers/ClaudeAdapter.test.tstotalProcessedTokenswithout changing parentusedTokens. Tests cover missing baselines, multiple tasks, oversized totals, and persistent totals.apps/server/src/provider/Layers/ClaudeAdapter.ts,apps/server/src/provider/Layers/ClaudeAdapter.test.tsapps/server/src/provider/Layers/ClaudeAdapter.ts,apps/server/src/provider/Layers/ClaudeAdapter.test.tsPriority: ⬆️ High
Estimated code review effort: 4 (Complex) | ~45 minutes
Change: Bug fix
Suggested reviewers:
juliusmarminge,t3dotggMerge Risk: ⚪ Minimal · up to
5a233Distinct subagent task usage is cumulatively accounted for without duplicate counting, so no actionable merge risk remains.
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands.