fix(server): usage counts every configured provider instance #8470
ClosedDonovanMontoya(GitHub profile, opens in a new tab)wants to merge 10 commits into
main fromrefs/pull/8470/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:L
- apps/server/src/usage/usageProviderHomes.ts line 74OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +54,21 @@54+55+ // Disabled instances still scan: usage covers turns driven outside T3 Code,56+ // and a paused instance's transcripts are still this machine's spend.57+ for (const envelope of Object.values(instances)) {58+ if (envelope.driver === "claudeAgent") {59+ // An envelope whose config fails to decode is already surfaced as an60+ // unavailable instance by the registry; usage just skips it.61+ const config = yield* decodeClaudeSettings(envelope.config ?? {}).pipe(62+ Effect.catchCause(() => Effect.succeed(null)),63+ );64+ if (config === null) continue;65+ if (config.homePath.trim().length > 0) {66+ pushUnique(claudeHomePaths, yield* resolveClaudeHomePath(config));67+ continue;68+ }69+ const environment = mergeProviderInstanceEnvironment(envelope.environment, {});70+ const configDir = environment["CLAUDE_CONFIG_DIR"]?.trim() ?? "";71+ pushUnique(72+ claudeHomePaths,73+ configDir.length > 074+ ? path.resolve(expandHomePath(configDir))
- apps/server/src/usage/usageProviderHomes.ts line 74OutdatedResolvedby DonovanMontoya(GitHub profile, opens in a new tab)@@ -0,0 +54,21 @@54+55+ // Disabled instances still scan: usage covers turns driven outside T3 Code,56+ // and a paused instance's transcripts are still this machine's spend.57+ for (const envelope of Object.values(instances)) {58+ if (envelope.driver === "claudeAgent") {59+ // An envelope whose config fails to decode is already surfaced as an60+ // unavailable instance by the registry; usage just skips it.61+ const config = yield* decodeClaudeSettings(envelope.config ?? {}).pipe(62+ Effect.catchCause(() => Effect.succeed(null)),63+ );64+ if (config === null) continue;65+ if (config.homePath.trim().length > 0) {66+ pushUnique(claudeHomePaths, yield* resolveClaudeHomePath(config));67+ continue;68+ }69+ const environment = mergeProviderInstanceEnvironment(envelope.environment, {});70+ const configDir = environment["CLAUDE_CONFIG_DIR"]?.trim() ?? "";71+ pushUnique(72+ claudeHomePaths,73+ configDir.length > 074+ ? path.resolve(expandHomePath(configDir))apps/server/src/usage/usageProviderHomes.ts lines 82 to 83OutdatedResolvedby DonovanMontoya(GitHub profile, opens in a new tab)@@ -0,0 +63,21 @@63+ );64+ if (config === null) continue;65+ if (config.homePath.trim().length > 0) {66+ pushUnique(claudeHomePaths, yield* resolveClaudeHomePath(config));67+ continue;68+ }69+ const environment = mergeProviderInstanceEnvironment(envelope.environment, {});70+ const configDir = environment["CLAUDE_CONFIG_DIR"]?.trim() ?? "";71+ pushUnique(72+ claudeHomePaths,73+ configDir.length > 074+ ? path.resolve(expandHomePath(configDir))75+ : yield* resolveClaudeHomePath(config),76+ );77+ } else if (envelope.driver === "codex") {78+ const config = yield* decodeCodexSettings(envelope.config ?? {}).pipe(79+ Effect.catchCause(() => Effect.succeed(null)),80+ );81+ if (config === null) continue;82+ const layout = yield* resolveCodexHomeLayout(config);83+ pushUnique(codexSessionDirs, path.join(layout.sharedHomePath, "sessions"));
- apps/server/src/usage/UsageService.ts line 275Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -240,0 +224,21 @@224+ const homes = yield* resolveUsageProviderHomes(settings, hostEnvironment);225+226+ const dirs: Array<{227+ provider: UsageProviderKind;228+ dir: string;229+ fileName?: string;230+ }> = [];231+ const claudeDirs = new Set<string>();232+ for (const home of homes.claudeHomePaths) {233+ // Distinct homes can probe to the same transcript dir (e.g. `~/x` with234+ // a nested `.claude` next to `~/x/.claude` itself), so dedupe post-probe.235+ const dir = yield* resolveClaudeTranscriptDir(home);236+ if (claudeDirs.has(dir)) continue;237+ claudeDirs.add(dir);238+ dirs.push({ provider: "claude", dir });239+ }240+ for (const dir of homes.codexSessionDirs) {241+ dirs.push({ provider: "codex", dir });242+ }243+ dirs.push({ provider: "grok", dir: homes.grokSessionsDir, fileName: "updates.jsonl" });244+ return dirs;
- packages/shared/src/usageMerge.ts line 149OutdatedResolvedby DonovanMontoya(GitHub profile, opens in a new tab)@@ -126,4 +133,17 @@126- duplicates.push(`${environment.label}: ${source.fingerprint.resolvedHomePath}`);127- continue;128- }129- ownerByFingerprint.set(key, environment.environmentId);133+ const provider = source.fingerprint.provider;134+ const group = byProvider.get(provider) ?? { keys: [], paths: [] };135+ group.keys.push(fingerprintKey(source.fingerprint));136+ group.paths.push(source.fingerprint.resolvedHomePath);137+ byProvider.set(provider, group);138+ }139+ for (const [provider, group] of byProvider) {140+ groups.push({141+ environmentId: environment.environmentId,142+ label: environment.label,143+ provider,144+ ...group,145+ });146+ }147+ }148+ groups.sort(149+ (a, b) => b.keys.length - a.keys.length || a.environmentId.localeCompare(b.environmentId),
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- docs/user/usage.md lines 6 to 7OutdatedResolvedby DonovanMontoya(GitHub profile, opens in a new tab)@@ -2,5 +2,6 @@2233 The Usage page combines Codex, Claude Code, and Grok Build activity from your connected44 environments. It reads the providers' local session history and shows API-equivalent token cost,5-processed tokens, cache savings, provider shares, and model breakdowns. Subscription billing is6-separate from the raw token cost shown here.5+processed tokens, cache savings, provider shares, and model breakdowns. If you have configured6+multiple instances of a provider (for example separate Claude accounts with their own config7+directories), each instance's history is included. Subscription billing is separate from the raw
- packages/contracts/src/usage.ts line 96Resolvedby DonovanMontoya(GitHub profile, opens in a new tab)@@ -80,12 +82,15 @@8082 export type UsageTokenTotals = typeof UsageTokenTotals.Type;81838284 /**83- * One `(day, hourStart?, provider, model)` cell. `hourStart` is the UTC start84- * instant of a rolling bucket and is present only for hourly requests.85+ * One `(sourceIndex, day, hourStart?, provider, model)` cell. `sourceIndex`86+ * points into the enclosing summary's `sources` array. `hourStart` is the UTC87+ * start instant of a rolling bucket and is present only for hourly requests.8588 *8689 * `costUsd` is the raw API-equivalent cost of these tokens. It is not money8790 * spent: subscription plans bill separately. `unpricedRecords` counts records8891 * whose tokens are included in the token totals but which contributed nothing8992 * to `costUsd`.9093 */9194 export const UsageBucket = Schema.Struct({95+ /** Defaults only so an older summary can decode before its version is rejected. */96+ sourceIndex: NonNegativeInt.pipe(Schema.withDecodingDefault(Effect.succeed(0))),
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:
632c3d97-c14c-48f3-8e50-a5104daea92f📥 Commits
Reviewing files that changed from the base of the PR and between 5d3c2a6501452d66e233f3ad513c7291c51033fd and 87efc093ff97cd8545f30130bbf2b21674f3791b.
📒 Files selected for processing (6)
apps/server/src/usage/UsageService.test.tsapps/server/src/usage/UsageService.tsapps/server/src/usage/usageProviderHomes.test.tsapps/server/src/usage/usageProviderHomes.tspackages/shared/src/usageMerge.test.tspackages/shared/src/usageMerge.tsIncluded review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
📝 Walkthrough
Walkthrough#
The usage scan resolves transcript homes from configured provider instances. It supports custom Claude and Codex homes, preserves Grok resolution, canonicalizes paths, and tracks source ownership during aggregation and merging.
Changes#
Usage discovery and merge
packages/contracts/src/usage.ts,packages/contracts/src/usage.test.ts,apps/web/src/state/usage.test.tsxsourceIndex. Contract version 6 validates source ownership and source-index bounds.apps/server/src/usage/usageProviderHomes.ts,apps/server/src/usage/usageProviderHomes.test.tsapps/server/src/usage/UsageService.ts,apps/server/src/usage/usageAggregation.ts,apps/server/src/usage/UsageService.test.ts,apps/server/src/usage/usageAggregation.test.ts,docs/user/usage.mdpackages/shared/src/usageMerge.ts,packages/shared/src/usageMerge.test.tsduplicateSources, while unique homes remain in merged totals.Priority: ➖ Normal
Estimated code review effort: 4 (Complex) | ~45 minutes
Change: Bug fix · Severity of issue fixed: Low
Suggested reviewers:
juliusmarmingeSequence Diagram(s)#
Merge Risk: ⚪ Minimal · up to
87efcThe usage discovery, source ownership, and merge changes have no identified merge-blocking risk.
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
#5805requires usage scanning for Codex instances configured throughproviderInstances, including customCODEX_HOMEand Codex shadow homes.resolveUsageProviderHomesderives instance confi…#5805. Claude and Grok handling uses the shared provider-home resolution and scan path, which preserves existing provider coverage and prevents duplicate or missing usa…✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands.