Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat(usage): split usage per provider instance home #5738

ClosedzenDevNomad(GitHub profile, opens in a new tab)wants to merge 2 commits intomain fromrefs/pull/5738/headopened View on GitHub

Stacked on #5806 — the first commit here is that PR; this one adds per-home attribution on top. Staying draft until #5806 lands.

What Changed

With #5806 the scan reads every configured provider instance's home, but everything still pools into one series per provider. This PR attributes usage to the home it came from and renders one series per home, labelled with the instance's user-configured display name (e.g. Codex · Personal for an instance named "Personal"):

  • UsageBucket carries homePath + homeLabel and UsageSource carries label (contract v4, with decoding defaults so a pre-v4 summary still decodes and the version check excludes it as stale instead of the RPC response failing).
  • Each directory is labelled after the instance that owns it directly; shadow overlays share the direct instance's home and label. Default slot beats named extras when they share a home.
  • The web merge keys series by (provider, homeLabel) and claims cross-environment ownership per directory instead of per provider kind — fixing the over-count edge noted in #5806 where environments with partially overlapping directory sets double count the overlap.
  • Summary rows, daily chart, legend and day table render per series with a distinct shade per home. Single-home setups render exactly as before.
  • Extending UsageProviderKind is now compile-guided (exhaustive parser dispatch, branding records) instead of silently reusing another provider's parser.

Why

Multiple instances of one provider usually mean separate accounts or billing contexts (work vs personal subscriptions, API-key providers). Pooled totals cannot answer which context the spend belongs to. Instances overlaid on one shared home via shadow homes stay merged under the shared home's label: rollouts carry no account identity, so a per-account split within one home is not derivable from disk.

UI Changes

Before (with #5806)After
One Codex seriesOne series per instance home, named by the user's instance names
Single Codex seriesPer-home series

Testing

  • Unit tests: per-home aggregation, label precedence, per-directory merge ownership, label-keyed series, v3-payload decode tolerance, exhaustive-dispatch coverage. Server 45 + web 21 usage tests green; tsgo --noEmit and vp lint clean on contracts/server/web.
  • Verified live against a real four-instance setup on top of current main (both screenshots above from the same state directory and transcripts).

Checklist

  • This PR is small and focused — it is the contract + UI half of a change split with #5806; as small as the split allows
  • I explained what changed and why
  • I included before/after screenshots for any UI changes
  • I included a video for animation/interaction changes — not applicable
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 272ac504-dc4a-4b62-a66e-8b897f7f38fc

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review

      Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

      ❤️ Share
      Comment `@coderabbitai help` to get the list of available commands.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    3. @@ -214,6 +229,13 @@
      214229 ),
      215230 );
      216231
      217- const claudeHome = yield* resolveClaudeHomePath(settings.providers.claudeAgent);
      218- const claudeDir = yield* resolveClaudeTranscriptDir(claudeHome);
      219- const codexLayout = yield* resolveCodexHomeLayout(settings.providers.codex);
      232+ const homes: ResolvedUsageHome[] = [];
      233+
      234+ for (const candidate of listProviderHomeCandidates(settings, "claude")) {
      235+ // A blob that fails to decode belongs to an instance the registry
      236+ // already reports as unavailable; the scan skips it.
      237+ const config = yield* decodeClaudeSettings(candidate.config).pipe(
      238+ Effect.catchCause(() => Effect.succeed(null)),
      239+ );
      240+ if (config === null) continue;
      241+ const claudeHome = yield* resolveClaudeHomePath({
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium usage/UsageService.ts:241

      An instance configured with a relative CLAUDE_CONFIG_DIR (via homeEnvValue) is scanned against the server process's cwd, not the workspace cwd the spawned CLI actually resolves it against. The scan finds the wrong directory (or none at all) and reports that instance's usage as missing/zero even though transcripts exist. scanHomePath returns the raw homeEnvValue when configHomePath is unset, and resolveClaudeHomePath then resolves it with path.resolve against the server cwd. The runtime resolves the same relative path against the spawned CLI's workspace cwd, so the scan looks in a different place than where transcripts are written.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/usage/UsageService.ts around line 241:
      
      An instance configured with a relative `CLAUDE_CONFIG_DIR` (via `homeEnvValue`) is scanned against the server process's cwd, not the workspace cwd the spawned CLI actually resolves it against. The scan finds the wrong directory (or none at all) and reports that instance's usage as missing/zero even though transcripts exist. `scanHomePath` returns the raw `homeEnvValue` when `configHomePath` is unset, and `resolveClaudeHomePath` then resolves it with `path.resolve` against the server cwd. The runtime resolves the same relative path against the spawned CLI's workspace cwd, so the scan looks in a different place than where transcripts are written.

      Fixed in 518ac3f. The scan now honours only absolute home-variable values (usableHomePath checks isAbsolute): a relative value resolves against each workspace's cwd at runtime, so no single directory represents it and resolving it against the server cwd would scan the wrong place. ~ values are likewise ignored — the spawn does not shell-expand them, so the CLI receives them verbatim. Covered by the "ignores home variable values the scan cannot locate" test.

      Sorry, I'm unable to act on this request because you do not have permissions within this repository.

    4. @@ -0,0 +147,21 @@
      147+ readonly isDirect: boolean;
      148+ readonly isDefault: boolean;
      149+}
      150+
      151+export interface UsageTranscriptDir {
      152+ readonly provider: UsageProviderKind;
      153+ readonly dir: string;
      154+ readonly label: string | null;
      155+}
      156+
      157+/**
      158+ * Collapses candidates that resolved to the same directory into one scan
      159+ * entry, keeping input order.
      160+ *
      161+ * Label precedence when several instances share a directory: a direct
      162+ * instance beats a shadow overlay (overlays share another instance's home),
      163+ * and the default slot beats named extras — a config-less extra instance
      164+ * resolves to the same home as the default, and that home's usage should
      165+ * render under the plain provider name, not the extra's.
      166+ */
      167+export function dedupeUsageHomes(

      🟡 Medium usage/usageHomes.ts:167

      dedupeUsageHomes keys homes by the raw home.dir string, so two instances whose directories resolve to the same physical location via symlinks (e.g. /data/codex and /home/me/codex → /data/codex) are not deduplicated. The scan then reads the same transcript files twice, producing doubled usage and cost. Consider canonicalizing each directory with realpath before building the dedup key.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/usage/usageHomes.ts around line 167:
      
      `dedupeUsageHomes` keys homes by the raw `home.dir` string, so two instances whose directories resolve to the same physical location via symlinks (e.g. `/data/codex` and `/home/me/codex` → `/data/codex`) are not deduplicated. The scan then reads the same transcript files twice, producing doubled usage and cost. Consider canonicalizing each directory with `realpath` before building the dedup key.

      Fixed in 841943e. Each resolved transcript directory is canonicalised with FileSystem.realPath (falling back to the configured path when it does not resolve, which the existing missing-directory reporting then covers) before dedupeUsageHomes keys it, so symlink aliases of one physical directory collapse to a single scan. The canonical path also flows into the source fingerprints, which additionally lets environments that configured different aliases of the same directory collapse in the client's cross-environment dedup.

      Sorry, I'm unable to act on this request because you do not have permissions within this repository.

    5. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium usage/usageHomes.ts:102

      envelope.config ?? {} converts an explicit config: null into {}, so an instance the registry marks unavailable still gets scanned. The provider's driver schema rejects null and surfaces that instance as unavailable, but here the usage scan treats it as valid defaults, scans the provider's default home, and can attribute unrelated transcripts to the invalid instance. Use a check that only substitutes {} when the property is absent — envelope.config === undefined ? {} : envelope.config — so an explicit null payload stays invalid and gets skipped by the decoder.

            config: envelope.config === undefined ? {} : envelope.config,
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/usage/usageHomes.ts around line 102:
      
      `envelope.config ?? {}` converts an explicit `config: null` into `{}`, so an instance the registry marks unavailable still gets scanned. The provider's driver schema rejects `null` and surfaces that instance as unavailable, but here the usage scan treats it as valid defaults, scans the provider's default home, and can attribute unrelated transcripts to the invalid instance. Use a check that only substitutes `{}` when the property is absent — `envelope.config === undefined ? {} : envelope.config` — so an explicit `null` payload stays invalid and gets skipped by the decoder.
    6. zenDevNomad(GitHub profile, opens in a new tab)commented

      I believe this one is a false positive: the registry applies the same nullish coalescing. ProviderInstanceRegistryLive.ts:138 decodes entry.config ?? driver.defaultConfig(), so an explicit config: null never reaches the driver schema there either — it decodes as driver defaults and the instance is available, not unavailable. (driver.defaultConfig() is decodeSync(schema)({}), so {} here produces the identical decoded value.) Switching the scan to === undefined would make it diverge from the registry: the scan would skip a home the runtime actually operates. Leaving as-is so both resolve null identically.

    7. Sorry, I'm unable to act on this request because you do not have permissions within this repository.

    8. Parking this until #5806 (the bug-fix half) is decided — keeping only one small PR open per the contributing guidelines. The branch stays available; happy to reopen or resubmit this half if there's interest in per-home attribution.

Sign in to join this conversation.