From 07bd574294b886195eceb762ab9281f8d2d4953b Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sun, 2 Aug 2026 02:32:29 -0700 Subject: [PATCH] refactor(usage): share the Codex/OpenCode scan fold behind a provider contract (#12082) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * refactor(usage): share the session/daily fold between Codex and OpenCode The Codex and OpenCode scanners each carried their own byte-identical copy of the ~325-line aggregation pipeline (createEmptySession, the three breakdown folds, finalizeSessions, mergeSessions, mergeDailyAggregates). Two copies means a token-accounting fix — a bucket that double-counts, a merge that drops a breakdown row — lands in one provider and silently not the other. The copies had already started to drift in comments only; the next drift would have been in arithmetic. The providers differ in exactly one dimension: the extra metric folded alongside the token counters (Codex `hasInferredPricing`, OpenCode `estimatedCostUsd`). That is now injected as an empty/fromEvent/fold triple, so the shared code stays generic without collapsing the two record schemas into a nullable union. The clone strategy stays per-provider (`cloneSessionForMerge` vs `structuredClone`) rather than being unified on the assumption that the difference is accidental. `usage-provider-contract.ts` is the seam a plugin-contributed usage source will implement. It is deliberately generic over each provider's record types: Claude bills per turn while Codex/OpenCode bill per event, and `cachedInput` is a subset of `input` for the latter but a peer bucket for Claude, so a single normalized record would push nullable handling onto every consumer. No behavior change. Emitted objects are byte-identical, including key insertion order — verified by diffing JSON.stringify of the scan output before and after across mixed models, mixed locations, an inferred-pricing flip, and null vs non-null cost. Persisted field names and schemaVersion are untouched, so caches do not invalidate. * refactor(usage): make the provider contract load-bearing and dedupe worktree refs Follow-up to the aggregation extraction, addressing three review points. `UsageProvider`/`UsageScanResult` were declaration-only, which is the same speculative-interface problem #12077 just deleted 8,900 lines of. They are now implemented by both real providers via `satisfies`, so the seam is typechecked against actual scan functions rather than asserted. The blocker was that codex returns `processedFiles` and opencode returns `processedDatabases`; rather than rename persisted-adjacent fields, the source key is a type parameter, so each provider keeps its own on-disk name and the contract still binds. Verified the constraint bites: swapping the key to 'processedSources' fails typecheck. `schemaVersion` is part of provider identity in the contract, so each provider's SCHEMA_VERSION constant (with its cache-invalidation rationale) moves into the provider module and the store imports it. Values are unchanged (codex 5, opencode 2) and the stores compare them exactly as before, so no cache invalidates. This also keeps store -> provider -> scanner acyclic. `UsageWorktreeRef` collided with the existing export in usage-worktree-metadata (3 fields, no repoId). Two different exported types under one name in src/main is worse than the duplication being removed, so the scan-input type is now `UsageScanWorktreeRef`; usage-worktree-metadata is untouched. `createWorktreeRefs` was triplicated. Codex, OpenCode, and Claude copies are byte-identical apart from the return type name (verified by diff), and all three ref types have the same four fields, so one shared copy replaces all three. This is the only change to claude-usage/. No behavior change: same functions, same arguments, same call order. The store tests' `./scanner` mock still intercepts scanning because the provider captures the mocked binding; their now-inert `createWorktreeRefs` mock key is dropped so it does not read as still mocking something. --- src/main/claude-usage/scanner.ts | 19 - src/main/claude-usage/store.ts | 3 +- src/main/codex-usage/codex-usage-provider.ts | 20 + src/main/codex-usage/scanner.ts | 409 ++--------------- src/main/codex-usage/store.test.ts | 1 - src/main/codex-usage/store.ts | 10 +- .../opencode-usage/opencode-usage-provider.ts | 23 + src/main/opencode-usage/scanner.ts | 414 ++---------------- src/main/opencode-usage/store.test.ts | 1 - src/main/opencode-usage/store.ts | 9 +- src/main/usage/usage-event-aggregation.ts | 269 ++++++++++++ src/main/usage/usage-path-comparison.ts | 20 + src/main/usage/usage-provider-contract.ts | 41 ++ src/main/usage/usage-record-coercion.ts | 11 + src/main/usage/usage-rollup-merge.ts | 117 +++++ src/main/usage/usage-rollup-records.ts | 111 +++++ src/main/usage/usage-worktree-refs.ts | 20 + 17 files changed, 695 insertions(+), 803 deletions(-) create mode 100644 src/main/codex-usage/codex-usage-provider.ts create mode 100644 src/main/opencode-usage/opencode-usage-provider.ts create mode 100644 src/main/usage/usage-event-aggregation.ts create mode 100644 src/main/usage/usage-path-comparison.ts create mode 100644 src/main/usage/usage-provider-contract.ts create mode 100644 src/main/usage/usage-record-coercion.ts create mode 100644 src/main/usage/usage-rollup-merge.ts create mode 100644 src/main/usage/usage-rollup-records.ts create mode 100644 src/main/usage/usage-worktree-refs.ts diff --git a/src/main/claude-usage/scanner.ts b/src/main/claude-usage/scanner.ts index 5006a73db..e6c4f0fc8 100644 --- a/src/main/claude-usage/scanner.ts +++ b/src/main/claude-usage/scanner.ts @@ -4,7 +4,6 @@ import { join, basename } from 'node:path' import { realpath, readdir, stat } from 'node:fs/promises' import { createReadStream } from 'node:fs' import { createInterface } from 'node:readline' -import type { Repo } from '../../shared/types' import type { ClaudeUsageAttributedTurn, ClaudeUsageDailyAggregate, @@ -739,24 +738,6 @@ export async function scanClaudeUsageFiles( } } -export function createWorktreeRefs( - repos: Repo[], - worktreesByRepo: Map -): ClaudeUsageWorktreeRef[] { - const refs: ClaudeUsageWorktreeRef[] = [] - for (const repo of repos) { - for (const worktree of worktreesByRepo.get(repo.id) ?? []) { - refs.push({ - repoId: repo.id, - worktreeId: worktree.worktreeId, - path: worktree.path, - displayName: worktree.displayName - }) - } - } - return refs -} - export function getSessionProjectLabel(locationBreakdown: ClaudeUsageLocationBreakdown[]): string { if (locationBreakdown.length === 0) { return 'Unknown location' diff --git a/src/main/claude-usage/store.ts b/src/main/claude-usage/store.ts index e21329282..180f7660b 100644 --- a/src/main/claude-usage/store.ts +++ b/src/main/claude-usage/store.ts @@ -18,7 +18,8 @@ import type { AutomationRunUsage } from '../../shared/automations-types' import type { Store } from '../persistence' import { loadKnownUsageWorktreesByRepo, type UsageWorktreeRef } from '../usage-worktree-metadata' import type { ClaudeUsagePersistedState } from './types' -import { createWorktreeRefs, getSessionProjectLabel, scanClaudeUsageFiles } from './scanner' +import { createWorktreeRefs } from '../usage/usage-worktree-refs' +import { getSessionProjectLabel, scanClaudeUsageFiles } from './scanner' // Why: v5 widens Claude ownership keys (message-id / uuid fallbacks). Older // caches either lack ownership or used narrower keys and can under/over-count diff --git a/src/main/codex-usage/codex-usage-provider.ts b/src/main/codex-usage/codex-usage-provider.ts new file mode 100644 index 000000000..a831401de --- /dev/null +++ b/src/main/codex-usage/codex-usage-provider.ts @@ -0,0 +1,20 @@ +import type { UsageProvider } from '../usage/usage-provider-contract' +import { scanCodexUsageFiles } from './scanner' +import type { CodexUsageDailyAggregate, CodexUsagePersistedFile, CodexUsageSession } from './types' + +// Why: v5 keys Codex ownership on raw token_count identity without session id +// so forks that rewrite session_meta still match. Older caches used session- +// scoped keys and can double-count after fork/resume (#8006). +export const CODEX_USAGE_SCHEMA_VERSION = 5 + +export const codexUsageProvider = { + id: 'codex', + label: 'Codex', + schemaVersion: CODEX_USAGE_SCHEMA_VERSION, + scan: scanCodexUsageFiles +} satisfies UsageProvider< + 'processedFiles', + CodexUsagePersistedFile, + CodexUsageSession, + CodexUsageDailyAggregate +> diff --git a/src/main/codex-usage/scanner.ts b/src/main/codex-usage/scanner.ts index 86da9db67..20d22c00d 100644 --- a/src/main/codex-usage/scanner.ts +++ b/src/main/codex-usage/scanner.ts @@ -3,30 +3,29 @@ import { basename, join, win32, posix } from 'node:path' import { createReadStream, existsSync } from 'node:fs' import { realpath, readdir, stat } from 'node:fs/promises' import { createInterface } from 'node:readline' -import type { Repo } from '../../shared/types' import { areWorktreePathsEqual } from '../ipc/worktree-logic' import { getOrcaManagedCodexHomePath, getSystemCodexHomePath } from '../codex/codex-home-paths' import { getCodexAccountHomeSessionDirectories } from '../codex/codex-account-home-discovery' import { getLegacyCopiedCodexSessionBridgeScanPreference } from '../codex/codex-session-bridge' import { canonicalizeUsageWorktreePaths } from '../usage-worktree-canonicalizer' +import { createUsageEventAggregation } from '../usage/usage-event-aggregation' +import { + looksLikeWindowsPath, + normalizeComparablePath, + normalizeFsPath +} from '../usage/usage-path-comparison' +import { ensureNumber, extractString } from '../usage/usage-record-coercion' +import type { UsageScanWorktreeRef } from '../usage/usage-provider-contract' import type { CodexUsageAttributedEvent, CodexUsageDailyAggregate, - CodexUsageLocationBreakdown, - CodexUsageLocationModelBreakdown, - CodexUsageModelBreakdown, CodexUsageParsedEvent, CodexUsagePersistedFile, CodexUsageProcessedFile, CodexUsageSession } from './types' -export type CodexUsageWorktreeRef = { - repoId: string - worktreeId: string - path: string - displayName: string -} +export type CodexUsageWorktreeRef = UsageScanWorktreeRef type CodexUsageRawRecord = { timestamp?: string @@ -58,28 +57,6 @@ type CodexUsageDeltaResolution = const YIELD_EVERY_FILES = 10 const YIELD_EVERY_DISCOVERY_ENTRIES = 100 -function ensureNumber(value: unknown): number { - return typeof value === 'number' && Number.isFinite(value) ? value : 0 -} - -function normalizeComparablePath(pathValue: string, platform = process.platform): string { - const normalized = pathValue.replace(/\\/g, '/') - return platform === 'win32' || looksLikeWindowsPath(pathValue) - ? normalized.toLowerCase() - : normalized -} - -function normalizeFsPath(pathValue: string, platform = process.platform): string { - if (platform === 'win32' || looksLikeWindowsPath(pathValue)) { - return win32.normalize(win32.resolve(pathValue)) - } - return posix.normalize(posix.resolve(pathValue)) -} - -function looksLikeWindowsPath(pathValue: string): boolean { - return /^[A-Za-z]:[\\/]/.test(pathValue) || pathValue.startsWith('\\\\') -} - async function canonicalizePath(pathValue: string): Promise { try { const resolved = await realpath(pathValue) @@ -414,14 +391,6 @@ function buildCodexUsageEventKey( return [timestamp, tupleOf(totalUsage), tupleOf(lastUsage)].join('|') } -function extractString(value: unknown): string | null { - if (typeof value !== 'string') { - return null - } - const trimmed = value.trim() - return trimmed.length > 0 ? trimmed : null -} - function extractModel(value: unknown): string | null { if (value == null || typeof value !== 'object') { return null @@ -568,331 +537,29 @@ export async function attributeCodexUsageEvent( } } -function createEmptySession(event: CodexUsageAttributedEvent): CodexUsageSession { - return { - sessionId: event.sessionId, - firstTimestamp: event.timestamp, - lastTimestamp: event.timestamp, - primaryModel: event.model, - hasMixedModels: false, - primaryProjectLabel: event.projectLabel, - hasMixedLocations: false, - primaryWorktreeId: event.worktreeId, - primaryRepoId: event.repoId, - eventCount: 0, - totalInputTokens: 0, - totalCachedInputTokens: 0, - totalOutputTokens: 0, - totalReasoningOutputTokens: 0, - totalTokens: 0, - hasInferredPricing: false, - locationBreakdown: [], - modelBreakdown: [], - locationModelBreakdown: [] - } -} +type CodexUsageMetric = { hasInferredPricing: boolean } -function createEmptyDailyAggregate(event: CodexUsageAttributedEvent): CodexUsageDailyAggregate { - return { - day: event.day, - model: event.model, - projectKey: event.projectKey, - projectLabel: event.projectLabel, - repoId: event.repoId, - worktreeId: event.worktreeId, - eventCount: 0, - inputTokens: 0, - cachedInputTokens: 0, - outputTokens: 0, - reasoningOutputTokens: 0, - totalTokens: 0, - hasInferredPricing: false - } -} - -function mergeLocationBreakdown( - target: CodexUsageLocationBreakdown[], - event: CodexUsageAttributedEvent -): void { - const existing = target.find((entry) => entry.locationKey === event.projectKey) ?? null - if (existing) { - existing.eventCount++ - existing.inputTokens += event.inputTokens - existing.cachedInputTokens += event.cachedInputTokens - existing.outputTokens += event.outputTokens - existing.reasoningOutputTokens += event.reasoningOutputTokens - existing.totalTokens += event.totalTokens - existing.hasInferredPricing ||= event.hasInferredPricing - return - } - - target.push({ - locationKey: event.projectKey, - projectLabel: event.projectLabel, - repoId: event.repoId, - worktreeId: event.worktreeId, - eventCount: 1, - inputTokens: event.inputTokens, - cachedInputTokens: event.cachedInputTokens, - outputTokens: event.outputTokens, - reasoningOutputTokens: event.reasoningOutputTokens, - totalTokens: event.totalTokens, - hasInferredPricing: event.hasInferredPricing - }) -} - -function mergeModelBreakdown( - target: CodexUsageModelBreakdown[], - event: CodexUsageAttributedEvent -): void { - const key = event.model ?? 'unknown' - const existing = target.find((entry) => entry.modelKey === key) ?? null - if (existing) { - existing.eventCount++ - existing.inputTokens += event.inputTokens - existing.cachedInputTokens += event.cachedInputTokens - existing.outputTokens += event.outputTokens - existing.reasoningOutputTokens += event.reasoningOutputTokens - existing.totalTokens += event.totalTokens - existing.hasInferredPricing ||= event.hasInferredPricing - return - } - - target.push({ - modelKey: key, - modelLabel: event.model ?? 'Unknown model', - eventCount: 1, - inputTokens: event.inputTokens, - cachedInputTokens: event.cachedInputTokens, - outputTokens: event.outputTokens, - reasoningOutputTokens: event.reasoningOutputTokens, - totalTokens: event.totalTokens, - hasInferredPricing: event.hasInferredPricing - }) -} - -function mergeLocationModelBreakdown( - target: CodexUsageLocationModelBreakdown[], - event: CodexUsageAttributedEvent -): void { - const modelKey = event.model ?? 'unknown' - const existing = - target.find((entry) => entry.locationKey === event.projectKey && entry.modelKey === modelKey) ?? - null - if (existing) { - existing.eventCount++ - existing.inputTokens += event.inputTokens - existing.cachedInputTokens += event.cachedInputTokens - existing.outputTokens += event.outputTokens - existing.reasoningOutputTokens += event.reasoningOutputTokens - existing.totalTokens += event.totalTokens - existing.hasInferredPricing ||= event.hasInferredPricing - return - } - - target.push({ - locationKey: event.projectKey, - modelKey, - modelLabel: event.model ?? 'Unknown model', - repoId: event.repoId, - worktreeId: event.worktreeId, - eventCount: 1, - inputTokens: event.inputTokens, - cachedInputTokens: event.cachedInputTokens, - outputTokens: event.outputTokens, - reasoningOutputTokens: event.reasoningOutputTokens, - totalTokens: event.totalTokens, - hasInferredPricing: event.hasInferredPricing - }) -} - -function aggregateCodexUsage(events: CodexUsageAttributedEvent[]): { - sessions: CodexUsageSession[] - dailyAggregates: CodexUsageDailyAggregate[] -} { - const sessionsById = new Map() - const dailyByKey = new Map() - - for (const event of events) { - const session = sessionsById.get(event.sessionId) ?? createEmptySession(event) - if (!sessionsById.has(event.sessionId)) { - sessionsById.set(event.sessionId, session) +const codexUsageAggregation = createUsageEventAggregation< + CodexUsageAttributedEvent, + CodexUsageMetric +>({ + metric: { + empty: () => ({ hasInferredPricing: false }), + fromEvent: (event) => ({ hasInferredPricing: event.hasInferredPricing }), + fold: (target, source) => { + target.hasInferredPricing ||= source.hasInferredPricing } - if (event.timestamp < session.firstTimestamp) { - session.firstTimestamp = event.timestamp - } - if (event.timestamp >= session.lastTimestamp) { - session.lastTimestamp = event.timestamp - } - session.eventCount++ - session.totalInputTokens += event.inputTokens - session.totalCachedInputTokens += event.cachedInputTokens - session.totalOutputTokens += event.outputTokens - session.totalReasoningOutputTokens += event.reasoningOutputTokens - session.totalTokens += event.totalTokens - session.hasInferredPricing ||= event.hasInferredPricing - mergeLocationBreakdown(session.locationBreakdown, event) - mergeModelBreakdown(session.modelBreakdown, event) - mergeLocationModelBreakdown(session.locationModelBreakdown, event) - - const dailyKey = [event.day, event.model ?? 'unknown', event.projectKey].join('::') - const daily = dailyByKey.get(dailyKey) ?? createEmptyDailyAggregate(event) - if (!dailyByKey.has(dailyKey)) { - dailyByKey.set(dailyKey, daily) - } - daily.eventCount++ - daily.inputTokens += event.inputTokens - daily.cachedInputTokens += event.cachedInputTokens - daily.outputTokens += event.outputTokens - daily.reasoningOutputTokens += event.reasoningOutputTokens - daily.totalTokens += event.totalTokens - daily.hasInferredPricing ||= event.hasInferredPricing - } - - return { - sessions: finalizeSessions(sessionsById), - dailyAggregates: [...dailyByKey.values()].sort((left, right) => - left.day === right.day - ? left.projectLabel.localeCompare(right.projectLabel) - : left.day.localeCompare(right.day) - ) - } -} - -function finalizeSessions(sessionsById: Map): CodexUsageSession[] { - for (const session of sessionsById.values()) { - session.locationBreakdown.sort((left, right) => right.totalTokens - left.totalTokens) - session.modelBreakdown.sort((left, right) => right.totalTokens - left.totalTokens) - const primaryLocation = session.locationBreakdown[0] ?? null - const primaryModel = session.modelBreakdown[0] ?? null - session.primaryProjectLabel = - session.locationBreakdown.length <= 1 - ? (primaryLocation?.projectLabel ?? 'Unknown location') - : 'Multiple locations' - session.hasMixedLocations = session.locationBreakdown.length > 1 - session.primaryWorktreeId = primaryLocation?.worktreeId ?? null - session.primaryRepoId = primaryLocation?.repoId ?? null - session.primaryModel = - session.modelBreakdown.length <= 1 ? (primaryModel?.modelLabel ?? null) : 'Mixed models' - session.hasMixedModels = session.modelBreakdown.length > 1 - } - - return [...sessionsById.values()].sort((left, right) => - right.lastTimestamp.localeCompare(left.lastTimestamp) - ) -} - -function mergeSessions( - target: Map, - sessions: CodexUsageSession[] -): void { - for (const session of sessions) { - const existing = target.get(session.sessionId) - if (!existing) { - target.set(session.sessionId, cloneSessionForMerge(session)) - continue - } - - existing.firstTimestamp = - session.firstTimestamp < existing.firstTimestamp - ? session.firstTimestamp - : existing.firstTimestamp - existing.lastTimestamp = - session.lastTimestamp > existing.lastTimestamp - ? session.lastTimestamp - : existing.lastTimestamp - existing.eventCount += session.eventCount - existing.totalInputTokens += session.totalInputTokens - existing.totalCachedInputTokens += session.totalCachedInputTokens - existing.totalOutputTokens += session.totalOutputTokens - existing.totalReasoningOutputTokens += session.totalReasoningOutputTokens - existing.totalTokens += session.totalTokens - existing.hasInferredPricing ||= session.hasInferredPricing - - for (const location of session.locationBreakdown) { - const existingLocation = - existing.locationBreakdown.find((entry) => entry.locationKey === location.locationKey) ?? - null - if (existingLocation) { - existingLocation.eventCount += location.eventCount - existingLocation.inputTokens += location.inputTokens - existingLocation.cachedInputTokens += location.cachedInputTokens - existingLocation.outputTokens += location.outputTokens - existingLocation.reasoningOutputTokens += location.reasoningOutputTokens - existingLocation.totalTokens += location.totalTokens - existingLocation.hasInferredPricing ||= location.hasInferredPricing - } else { - existing.locationBreakdown.push({ ...location }) - } - } - - for (const model of session.modelBreakdown) { - const existingModel = - existing.modelBreakdown.find((entry) => entry.modelKey === model.modelKey) ?? null - if (existingModel) { - existingModel.eventCount += model.eventCount - existingModel.inputTokens += model.inputTokens - existingModel.cachedInputTokens += model.cachedInputTokens - existingModel.outputTokens += model.outputTokens - existingModel.reasoningOutputTokens += model.reasoningOutputTokens - existingModel.totalTokens += model.totalTokens - existingModel.hasInferredPricing ||= model.hasInferredPricing - } else { - existing.modelBreakdown.push({ ...model }) - } - } - - for (const locationModel of session.locationModelBreakdown) { - const existingLocationModel = - existing.locationModelBreakdown.find( - (entry) => - entry.locationKey === locationModel.locationKey && - entry.modelKey === locationModel.modelKey - ) ?? null - if (existingLocationModel) { - existingLocationModel.eventCount += locationModel.eventCount - existingLocationModel.inputTokens += locationModel.inputTokens - existingLocationModel.cachedInputTokens += locationModel.cachedInputTokens - existingLocationModel.outputTokens += locationModel.outputTokens - existingLocationModel.reasoningOutputTokens += locationModel.reasoningOutputTokens - existingLocationModel.totalTokens += locationModel.totalTokens - existingLocationModel.hasInferredPricing ||= locationModel.hasInferredPricing - } else { - existing.locationModelBreakdown.push({ ...locationModel }) - } - } - } -} - -function cloneSessionForMerge(session: CodexUsageSession): CodexUsageSession { - return { + }, + cloneSessionForMerge: (session) => ({ ...session, locationBreakdown: session.locationBreakdown.map((entry) => ({ ...entry })), modelBreakdown: session.modelBreakdown.map((entry) => ({ ...entry })), locationModelBreakdown: session.locationModelBreakdown.map((entry) => ({ ...entry })) - } -} + }) +}) -function mergeDailyAggregates( - target: Map, - dailyAggregates: CodexUsageDailyAggregate[] -): void { - for (const aggregate of dailyAggregates) { - const key = [aggregate.day, aggregate.model ?? 'unknown', aggregate.projectKey].join('::') - const existing = target.get(key) - if (!existing) { - target.set(key, { ...aggregate }) - continue - } - existing.eventCount += aggregate.eventCount - existing.inputTokens += aggregate.inputTokens - existing.cachedInputTokens += aggregate.cachedInputTokens - existing.outputTokens += aggregate.outputTokens - existing.reasoningOutputTokens += aggregate.reasoningOutputTokens - existing.totalTokens += aggregate.totalTokens - existing.hasInferredPricing ||= aggregate.hasInferredPricing - } -} +const { finalizeSessions, mergeSessions, mergeDailyAggregates, sortDailyAggregates } = + codexUsageAggregation export function parseCodexUsageRecord( line: string, @@ -1042,7 +709,7 @@ export async function parseCodexUsageFile( return { ...processedFile, - ...aggregateCodexUsage(events), + ...codexUsageAggregation.aggregate(events), ownedEventKeys: [...ownedEventKeys], hasDeferredClaims } @@ -1154,28 +821,6 @@ export async function scanCodexUsageFiles( return { processedFiles, sessions: finalizeSessions(sessionsById), - dailyAggregates: [...dailyByKey.values()].sort((left, right) => - left.day === right.day - ? left.projectLabel.localeCompare(right.projectLabel) - : left.day.localeCompare(right.day) - ) + dailyAggregates: sortDailyAggregates(dailyByKey) } } - -export function createWorktreeRefs( - repos: Repo[], - worktreesByRepo: Map -): CodexUsageWorktreeRef[] { - const refs: CodexUsageWorktreeRef[] = [] - for (const repo of repos) { - for (const worktree of worktreesByRepo.get(repo.id) ?? []) { - refs.push({ - repoId: repo.id, - worktreeId: worktree.worktreeId, - path: worktree.path, - displayName: worktree.displayName - }) - } - } - return refs -} diff --git a/src/main/codex-usage/store.test.ts b/src/main/codex-usage/store.test.ts index 11be8c514..83e5a43fa 100644 --- a/src/main/codex-usage/store.test.ts +++ b/src/main/codex-usage/store.test.ts @@ -52,7 +52,6 @@ vi.mock('node:fs/promises', async () => { }) vi.mock('./scanner', () => ({ - createWorktreeRefs: vi.fn(() => []), scanCodexUsageFiles: vi.fn() })) diff --git a/src/main/codex-usage/store.ts b/src/main/codex-usage/store.ts index 540d8f23e..10aad99fb 100644 --- a/src/main/codex-usage/store.ts +++ b/src/main/codex-usage/store.ts @@ -18,12 +18,10 @@ import type { AutomationRunUsage } from '../../shared/automations-types' import type { Store } from '../persistence' import { loadKnownUsageWorktreesByRepo, type UsageWorktreeRef } from '../usage-worktree-metadata' import type { CodexUsagePersistedState } from './types' -import { createWorktreeRefs, scanCodexUsageFiles } from './scanner' +import { createWorktreeRefs } from '../usage/usage-worktree-refs' +import { CODEX_USAGE_SCHEMA_VERSION, codexUsageProvider } from './codex-usage-provider' -// Why: v5 keys Codex ownership on raw token_count identity without session id -// so forks that rewrite session_meta still match. Older caches used session- -// scoped keys and can double-count after fork/resume (#8006). -const SCHEMA_VERSION = 5 +const SCHEMA_VERSION = CODEX_USAGE_SCHEMA_VERSION const STALE_MS = 5 * 60_000 const AUTOMATION_ATTRIBUTION_WINDOW_MS = 5 * 60_000 @@ -467,7 +465,7 @@ export class CodexUsageStore { const repos = this.store.getRepos() const worktreesByRepo = loadKnownUsageWorktreesByRepo(this.store, repos) const worktreeFingerprint = getWorktreeFingerprint(worktreesByRepo) - const result = await scanCodexUsageFiles( + const result = await codexUsageProvider.scan( createWorktreeRefs(repos, worktreesByRepo), this.state.worktreeFingerprint === worktreeFingerprint ? this.state.processedFiles : [] ) diff --git a/src/main/opencode-usage/opencode-usage-provider.ts b/src/main/opencode-usage/opencode-usage-provider.ts new file mode 100644 index 000000000..93af71aa9 --- /dev/null +++ b/src/main/opencode-usage/opencode-usage-provider.ts @@ -0,0 +1,23 @@ +import type { UsageProvider } from '../usage/usage-provider-contract' +import { scanOpenCodeUsageDatabases } from './scanner' +import type { + OpenCodeUsageDailyAggregate, + OpenCodeUsagePersistedDatabase, + OpenCodeUsageSession +} from './types' + +// Why: v2 adds per-database session ownership (stale sibling-copy dedupe). +// Older caches were built without it and can carry doubled sessions (#8006). +export const OPENCODE_USAGE_SCHEMA_VERSION = 2 + +export const openCodeUsageProvider = { + id: 'opencode', + label: 'OpenCode', + schemaVersion: OPENCODE_USAGE_SCHEMA_VERSION, + scan: scanOpenCodeUsageDatabases +} satisfies UsageProvider< + 'processedDatabases', + OpenCodeUsagePersistedDatabase, + OpenCodeUsageSession, + OpenCodeUsageDailyAggregate +> diff --git a/src/main/opencode-usage/scanner.ts b/src/main/opencode-usage/scanner.ts index ec532560a..b96e14be5 100644 --- a/src/main/opencode-usage/scanner.ts +++ b/src/main/opencode-usage/scanner.ts @@ -2,30 +2,29 @@ import { readdir, realpath, stat } from 'node:fs/promises' import { basename, isAbsolute, join, posix, win32 } from 'node:path' import { yieldToEventLoop } from '../../shared/event-loop-yield' -import type { Repo } from '../../shared/types' import { areWorktreePathsEqual } from '../ipc/worktree-logic' import { resolveOpenCodeDataDirectory } from '../opencode/opencode-data-directory' import Database from '../sqlite/sync-database' import { columnExists, tableExists } from './schema-helpers' import { canonicalizeUsageWorktreePaths } from '../usage-worktree-canonicalizer' +import { createUsageEventAggregation } from '../usage/usage-event-aggregation' +import { + looksLikeWindowsPath, + normalizeComparablePath, + normalizeFsPath +} from '../usage/usage-path-comparison' +import { ensureNumber, extractString } from '../usage/usage-record-coercion' +import type { UsageScanWorktreeRef } from '../usage/usage-provider-contract' import type { OpenCodeUsageAttributedEvent, OpenCodeUsageDailyAggregate, - OpenCodeUsageLocationBreakdown, - OpenCodeUsageLocationModelBreakdown, - OpenCodeUsageModelBreakdown, OpenCodeUsageParsedEvent, OpenCodeUsagePersistedDatabase, OpenCodeUsageProcessedDatabase, OpenCodeUsageSession } from './types' -export type OpenCodeUsageWorktreeRef = { - repoId: string - worktreeId: string - path: string - displayName: string -} +export type OpenCodeUsageWorktreeRef = UsageScanWorktreeRef type OpenCodeUsageRow = { id: string @@ -57,28 +56,6 @@ type OpenCodeSessionUsageRow = { const YIELD_EVERY_DATABASES = 2 -function ensureNumber(value: unknown): number { - return typeof value === 'number' && Number.isFinite(value) ? value : 0 -} - -function normalizeComparablePath(pathValue: string, platform = process.platform): string { - const normalized = pathValue.replace(/\\/g, '/') - return platform === 'win32' || looksLikeWindowsPath(pathValue) - ? normalized.toLowerCase() - : normalized -} - -function normalizeFsPath(pathValue: string, platform = process.platform): string { - if (platform === 'win32' || looksLikeWindowsPath(pathValue)) { - return win32.normalize(win32.resolve(pathValue)) - } - return posix.normalize(posix.resolve(pathValue)) -} - -function looksLikeWindowsPath(pathValue: string): boolean { - return /^[A-Za-z]:[\\/]/.test(pathValue) || pathValue.startsWith('\\\\') -} - type OpenCodeDatabaseOverride = { isConfigured: boolean path: string | null @@ -297,14 +274,6 @@ function parseJsonObject(value: unknown): Record | null { } } -function extractString(value: unknown): string | null { - if (typeof value !== 'string') { - return null - } - const trimmed = value.trim() - return trimmed.length > 0 ? trimmed : null -} - function extractModelLabel(data: Record, sessionModel: unknown): string | null { const directModel = extractString(data.modelID) ?? extractString(data.modelId) const directProvider = extractString(data.providerID) ?? extractString(data.providerId) @@ -511,333 +480,24 @@ function addCost(left: number | null, right: number | null): number | null { return (left ?? 0) + (right ?? 0) } -function createEmptySession(event: OpenCodeUsageAttributedEvent): OpenCodeUsageSession { - return { - sessionId: event.sessionId, - firstTimestamp: event.timestamp, - lastTimestamp: event.timestamp, - primaryModel: event.model, - hasMixedModels: false, - primaryProjectLabel: event.projectLabel, - hasMixedLocations: false, - primaryWorktreeId: event.worktreeId, - primaryRepoId: event.repoId, - eventCount: 0, - totalInputTokens: 0, - totalCachedInputTokens: 0, - totalOutputTokens: 0, - totalReasoningOutputTokens: 0, - totalTokens: 0, - estimatedCostUsd: null, - locationBreakdown: [], - modelBreakdown: [], - locationModelBreakdown: [] - } -} +type OpenCodeUsageMetric = { estimatedCostUsd: number | null } -function createEmptyDailyAggregate( - event: OpenCodeUsageAttributedEvent -): OpenCodeUsageDailyAggregate { - return { - day: event.day, - model: event.model, - projectKey: event.projectKey, - projectLabel: event.projectLabel, - repoId: event.repoId, - worktreeId: event.worktreeId, - eventCount: 0, - inputTokens: 0, - cachedInputTokens: 0, - outputTokens: 0, - reasoningOutputTokens: 0, - totalTokens: 0, - estimatedCostUsd: null - } -} - -function mergeLocationBreakdown( - target: OpenCodeUsageLocationBreakdown[], - event: OpenCodeUsageAttributedEvent -): void { - const existing = target.find((entry) => entry.locationKey === event.projectKey) ?? null - if (existing) { - existing.eventCount++ - existing.inputTokens += event.inputTokens - existing.cachedInputTokens += event.cachedInputTokens - existing.outputTokens += event.outputTokens - existing.reasoningOutputTokens += event.reasoningOutputTokens - existing.totalTokens += event.totalTokens - existing.estimatedCostUsd = addCost(existing.estimatedCostUsd, event.estimatedCostUsd) - return - } - - target.push({ - locationKey: event.projectKey, - projectLabel: event.projectLabel, - repoId: event.repoId, - worktreeId: event.worktreeId, - eventCount: 1, - inputTokens: event.inputTokens, - cachedInputTokens: event.cachedInputTokens, - outputTokens: event.outputTokens, - reasoningOutputTokens: event.reasoningOutputTokens, - totalTokens: event.totalTokens, - estimatedCostUsd: event.estimatedCostUsd - }) -} - -function mergeModelBreakdown( - target: OpenCodeUsageModelBreakdown[], - event: OpenCodeUsageAttributedEvent -): void { - const key = event.model ?? 'unknown' - const existing = target.find((entry) => entry.modelKey === key) ?? null - if (existing) { - existing.eventCount++ - existing.inputTokens += event.inputTokens - existing.cachedInputTokens += event.cachedInputTokens - existing.outputTokens += event.outputTokens - existing.reasoningOutputTokens += event.reasoningOutputTokens - existing.totalTokens += event.totalTokens - existing.estimatedCostUsd = addCost(existing.estimatedCostUsd, event.estimatedCostUsd) - return - } - - target.push({ - modelKey: key, - modelLabel: event.model ?? 'Unknown model', - eventCount: 1, - inputTokens: event.inputTokens, - cachedInputTokens: event.cachedInputTokens, - outputTokens: event.outputTokens, - reasoningOutputTokens: event.reasoningOutputTokens, - totalTokens: event.totalTokens, - estimatedCostUsd: event.estimatedCostUsd - }) -} - -function mergeLocationModelBreakdown( - target: OpenCodeUsageLocationModelBreakdown[], - event: OpenCodeUsageAttributedEvent -): void { - const modelKey = event.model ?? 'unknown' - const existing = - target.find((entry) => entry.locationKey === event.projectKey && entry.modelKey === modelKey) ?? - null - if (existing) { - existing.eventCount++ - existing.inputTokens += event.inputTokens - existing.cachedInputTokens += event.cachedInputTokens - existing.outputTokens += event.outputTokens - existing.reasoningOutputTokens += event.reasoningOutputTokens - existing.totalTokens += event.totalTokens - existing.estimatedCostUsd = addCost(existing.estimatedCostUsd, event.estimatedCostUsd) - return - } - - target.push({ - locationKey: event.projectKey, - modelKey, - modelLabel: event.model ?? 'Unknown model', - repoId: event.repoId, - worktreeId: event.worktreeId, - eventCount: 1, - inputTokens: event.inputTokens, - cachedInputTokens: event.cachedInputTokens, - outputTokens: event.outputTokens, - reasoningOutputTokens: event.reasoningOutputTokens, - totalTokens: event.totalTokens, - estimatedCostUsd: event.estimatedCostUsd - }) -} - -function aggregateOpenCodeUsage(events: OpenCodeUsageAttributedEvent[]): { - sessions: OpenCodeUsageSession[] - dailyAggregates: OpenCodeUsageDailyAggregate[] -} { - const sessionsById = new Map() - const dailyByKey = new Map() - - for (const event of events) { - const session = sessionsById.get(event.sessionId) ?? createEmptySession(event) - if (!sessionsById.has(event.sessionId)) { - sessionsById.set(event.sessionId, session) +const openCodeUsageAggregation = createUsageEventAggregation< + OpenCodeUsageAttributedEvent, + OpenCodeUsageMetric +>({ + metric: { + empty: () => ({ estimatedCostUsd: null }), + fromEvent: (event) => ({ estimatedCostUsd: event.estimatedCostUsd }), + fold: (target, source) => { + target.estimatedCostUsd = addCost(target.estimatedCostUsd, source.estimatedCostUsd) } - if (event.timestamp < session.firstTimestamp) { - session.firstTimestamp = event.timestamp - } - if (event.timestamp >= session.lastTimestamp) { - session.lastTimestamp = event.timestamp - } - session.eventCount++ - session.totalInputTokens += event.inputTokens - session.totalCachedInputTokens += event.cachedInputTokens - session.totalOutputTokens += event.outputTokens - session.totalReasoningOutputTokens += event.reasoningOutputTokens - session.totalTokens += event.totalTokens - session.estimatedCostUsd = addCost(session.estimatedCostUsd, event.estimatedCostUsd) - mergeLocationBreakdown(session.locationBreakdown, event) - mergeModelBreakdown(session.modelBreakdown, event) - mergeLocationModelBreakdown(session.locationModelBreakdown, event) + }, + cloneSessionForMerge: (session) => structuredClone(session) +}) - const dailyKey = [event.day, event.model ?? 'unknown', event.projectKey].join('::') - const daily = dailyByKey.get(dailyKey) ?? createEmptyDailyAggregate(event) - if (!dailyByKey.has(dailyKey)) { - dailyByKey.set(dailyKey, daily) - } - daily.eventCount++ - daily.inputTokens += event.inputTokens - daily.cachedInputTokens += event.cachedInputTokens - daily.outputTokens += event.outputTokens - daily.reasoningOutputTokens += event.reasoningOutputTokens - daily.totalTokens += event.totalTokens - daily.estimatedCostUsd = addCost(daily.estimatedCostUsd, event.estimatedCostUsd) - } - - return { - sessions: finalizeSessions(sessionsById), - dailyAggregates: [...dailyByKey.values()].sort((left, right) => - left.day === right.day - ? left.projectLabel.localeCompare(right.projectLabel) - : left.day.localeCompare(right.day) - ) - } -} - -function finalizeSessions(sessionsById: Map): OpenCodeUsageSession[] { - for (const session of sessionsById.values()) { - session.locationBreakdown.sort((left, right) => right.totalTokens - left.totalTokens) - session.modelBreakdown.sort((left, right) => right.totalTokens - left.totalTokens) - const primaryLocation = session.locationBreakdown[0] ?? null - const primaryModel = session.modelBreakdown[0] ?? null - session.primaryProjectLabel = - session.locationBreakdown.length <= 1 - ? (primaryLocation?.projectLabel ?? 'Unknown location') - : 'Multiple locations' - session.hasMixedLocations = session.locationBreakdown.length > 1 - session.primaryWorktreeId = primaryLocation?.worktreeId ?? null - session.primaryRepoId = primaryLocation?.repoId ?? null - session.primaryModel = - session.modelBreakdown.length <= 1 ? (primaryModel?.modelLabel ?? null) : 'Mixed models' - session.hasMixedModels = session.modelBreakdown.length > 1 - } - - return [...sessionsById.values()].sort((left, right) => - right.lastTimestamp.localeCompare(left.lastTimestamp) - ) -} - -function mergeSessions( - target: Map, - sessions: OpenCodeUsageSession[] -): void { - for (const session of sessions) { - const existing = target.get(session.sessionId) - if (!existing) { - target.set(session.sessionId, structuredClone(session)) - continue - } - - existing.firstTimestamp = - session.firstTimestamp < existing.firstTimestamp - ? session.firstTimestamp - : existing.firstTimestamp - existing.lastTimestamp = - session.lastTimestamp > existing.lastTimestamp - ? session.lastTimestamp - : existing.lastTimestamp - existing.eventCount += session.eventCount - existing.totalInputTokens += session.totalInputTokens - existing.totalCachedInputTokens += session.totalCachedInputTokens - existing.totalOutputTokens += session.totalOutputTokens - existing.totalReasoningOutputTokens += session.totalReasoningOutputTokens - existing.totalTokens += session.totalTokens - existing.estimatedCostUsd = addCost(existing.estimatedCostUsd, session.estimatedCostUsd) - - for (const location of session.locationBreakdown) { - const existingLocation = - existing.locationBreakdown.find((entry) => entry.locationKey === location.locationKey) ?? - null - if (existingLocation) { - existingLocation.eventCount += location.eventCount - existingLocation.inputTokens += location.inputTokens - existingLocation.cachedInputTokens += location.cachedInputTokens - existingLocation.outputTokens += location.outputTokens - existingLocation.reasoningOutputTokens += location.reasoningOutputTokens - existingLocation.totalTokens += location.totalTokens - existingLocation.estimatedCostUsd = addCost( - existingLocation.estimatedCostUsd, - location.estimatedCostUsd - ) - } else { - existing.locationBreakdown.push({ ...location }) - } - } - - for (const model of session.modelBreakdown) { - const existingModel = - existing.modelBreakdown.find((entry) => entry.modelKey === model.modelKey) ?? null - if (existingModel) { - existingModel.eventCount += model.eventCount - existingModel.inputTokens += model.inputTokens - existingModel.cachedInputTokens += model.cachedInputTokens - existingModel.outputTokens += model.outputTokens - existingModel.reasoningOutputTokens += model.reasoningOutputTokens - existingModel.totalTokens += model.totalTokens - existingModel.estimatedCostUsd = addCost( - existingModel.estimatedCostUsd, - model.estimatedCostUsd - ) - } else { - existing.modelBreakdown.push({ ...model }) - } - } - - for (const locationModel of session.locationModelBreakdown) { - const existingLocationModel = - existing.locationModelBreakdown.find( - (entry) => - entry.locationKey === locationModel.locationKey && - entry.modelKey === locationModel.modelKey - ) ?? null - if (existingLocationModel) { - existingLocationModel.eventCount += locationModel.eventCount - existingLocationModel.inputTokens += locationModel.inputTokens - existingLocationModel.cachedInputTokens += locationModel.cachedInputTokens - existingLocationModel.outputTokens += locationModel.outputTokens - existingLocationModel.reasoningOutputTokens += locationModel.reasoningOutputTokens - existingLocationModel.totalTokens += locationModel.totalTokens - existingLocationModel.estimatedCostUsd = addCost( - existingLocationModel.estimatedCostUsd, - locationModel.estimatedCostUsd - ) - } else { - existing.locationModelBreakdown.push({ ...locationModel }) - } - } - } -} - -function mergeDailyAggregates( - target: Map, - dailyAggregates: OpenCodeUsageDailyAggregate[] -): void { - for (const aggregate of dailyAggregates) { - const key = [aggregate.day, aggregate.model ?? 'unknown', aggregate.projectKey].join('::') - const existing = target.get(key) - if (!existing) { - target.set(key, { ...aggregate }) - continue - } - existing.eventCount += aggregate.eventCount - existing.inputTokens += aggregate.inputTokens - existing.cachedInputTokens += aggregate.cachedInputTokens - existing.outputTokens += aggregate.outputTokens - existing.reasoningOutputTokens += aggregate.reasoningOutputTokens - existing.totalTokens += aggregate.totalTokens - existing.estimatedCostUsd = addCost(existing.estimatedCostUsd, aggregate.estimatedCostUsd) - } -} +const { finalizeSessions, mergeSessions, mergeDailyAggregates, sortDailyAggregates } = + openCodeUsageAggregation export async function parseOpenCodeUsageDatabase( dbPath: string, @@ -874,7 +534,7 @@ export async function parseOpenCodeUsageDatabase( } return { ...processedDatabase, - ...aggregateOpenCodeUsage(events), + ...openCodeUsageAggregation.aggregate(events), ownedSessionIds: [...claimedBySessionId.entries()] .filter(([, owned]) => owned) .map(([sessionId]) => sessionId), @@ -1006,28 +666,6 @@ export async function scanOpenCodeUsageDatabases( return { processedDatabases, sessions: finalizeSessions(sessionsById), - dailyAggregates: [...dailyByKey.values()].sort((left, right) => - left.day === right.day - ? left.projectLabel.localeCompare(right.projectLabel) - : left.day.localeCompare(right.day) - ) + dailyAggregates: sortDailyAggregates(dailyByKey) } } - -export function createWorktreeRefs( - repos: Repo[], - worktreesByRepo: Map -): OpenCodeUsageWorktreeRef[] { - const refs: OpenCodeUsageWorktreeRef[] = [] - for (const repo of repos) { - for (const worktree of worktreesByRepo.get(repo.id) ?? []) { - refs.push({ - repoId: repo.id, - worktreeId: worktree.worktreeId, - path: worktree.path, - displayName: worktree.displayName - }) - } - } - return refs -} diff --git a/src/main/opencode-usage/store.test.ts b/src/main/opencode-usage/store.test.ts index 44b03eec4..6f3759efa 100644 --- a/src/main/opencode-usage/store.test.ts +++ b/src/main/opencode-usage/store.test.ts @@ -51,7 +51,6 @@ vi.mock('node:fs/promises', async () => { }) vi.mock('./scanner', () => ({ - createWorktreeRefs: vi.fn(() => []), scanOpenCodeUsageDatabases: vi.fn() })) diff --git a/src/main/opencode-usage/store.ts b/src/main/opencode-usage/store.ts index 67080d6db..c85fa519b 100644 --- a/src/main/opencode-usage/store.ts +++ b/src/main/opencode-usage/store.ts @@ -17,11 +17,10 @@ import type { import type { Store } from '../persistence' import { loadKnownUsageWorktreesByRepo, type UsageWorktreeRef } from '../usage-worktree-metadata' import type { OpenCodeUsageDailyAggregate, OpenCodeUsagePersistedState } from './types' -import { createWorktreeRefs, scanOpenCodeUsageDatabases } from './scanner' +import { createWorktreeRefs } from '../usage/usage-worktree-refs' +import { OPENCODE_USAGE_SCHEMA_VERSION, openCodeUsageProvider } from './opencode-usage-provider' -// Why: v2 adds per-database session ownership (stale sibling-copy dedupe). -// Older caches were built without it and can carry doubled sessions (#8006). -const SCHEMA_VERSION = 2 +const SCHEMA_VERSION = OPENCODE_USAGE_SCHEMA_VERSION const STALE_MS = 5 * 60_000 let _openCodeUsageFile: string | null = null @@ -253,7 +252,7 @@ export class OpenCodeUsageStore { const repos = this.store.getRepos() const worktreesByRepo = loadKnownUsageWorktreesByRepo(this.store, repos) const worktreeFingerprint = getWorktreeFingerprint(worktreesByRepo) - const result = await scanOpenCodeUsageDatabases( + const result = await openCodeUsageProvider.scan( createWorktreeRefs(repos, worktreesByRepo), this.state.worktreeFingerprint === worktreeFingerprint ? this.state.processedDatabases diff --git a/src/main/usage/usage-event-aggregation.ts b/src/main/usage/usage-event-aggregation.ts new file mode 100644 index 000000000..ca3eee175 --- /dev/null +++ b/src/main/usage/usage-event-aggregation.ts @@ -0,0 +1,269 @@ +/** + * Folds attributed usage events into per-session and per-day rollups. Shared by every + * event-based usage provider so a token-accounting fix lands in all of them at once. + */ +import { mergeUsageDailyAggregates, mergeUsageSessions } from './usage-rollup-merge' +import { + usageDailyAggregateKey, + type UsageAttributedEventFields, + type UsageDailyAggregate, + type UsageLocationBreakdown, + type UsageLocationModelBreakdown, + type UsageMetricFold, + type UsageModelBreakdown, + type UsageSession +} from './usage-rollup-records' + +export type UsageEventAggregationOptions = { + metric: UsageMetricFold + /** Codex and OpenCode clone differently today; keep each provider's strategy explicit. */ + cloneSessionForMerge(session: UsageSession): UsageSession +} + +export function createUsageEventAggregation< + TEvent extends UsageAttributedEventFields, + TMetric extends object +>(options: UsageEventAggregationOptions) { + const { metric, cloneSessionForMerge } = options + + function createEmptySession(event: TEvent): UsageSession { + return { + sessionId: event.sessionId, + firstTimestamp: event.timestamp, + lastTimestamp: event.timestamp, + primaryModel: event.model, + hasMixedModels: false, + primaryProjectLabel: event.projectLabel, + hasMixedLocations: false, + primaryWorktreeId: event.worktreeId, + primaryRepoId: event.repoId, + eventCount: 0, + totalInputTokens: 0, + totalCachedInputTokens: 0, + totalOutputTokens: 0, + totalReasoningOutputTokens: 0, + totalTokens: 0, + ...metric.empty(), + locationBreakdown: [], + modelBreakdown: [], + locationModelBreakdown: [] + } + } + + function createEmptyDailyAggregate(event: TEvent): UsageDailyAggregate { + return { + day: event.day, + model: event.model, + projectKey: event.projectKey, + projectLabel: event.projectLabel, + repoId: event.repoId, + worktreeId: event.worktreeId, + eventCount: 0, + inputTokens: 0, + cachedInputTokens: 0, + outputTokens: 0, + reasoningOutputTokens: 0, + totalTokens: 0, + ...metric.empty() + } + } + + function foldLocation( + target: UsageLocationBreakdown[], + event: TEvent, + eventMetric: TMetric + ): void { + const existing = target.find((entry) => entry.locationKey === event.projectKey) ?? null + if (existing) { + existing.eventCount++ + existing.inputTokens += event.inputTokens + existing.cachedInputTokens += event.cachedInputTokens + existing.outputTokens += event.outputTokens + existing.reasoningOutputTokens += event.reasoningOutputTokens + existing.totalTokens += event.totalTokens + metric.fold(existing, eventMetric) + return + } + + target.push({ + locationKey: event.projectKey, + projectLabel: event.projectLabel, + repoId: event.repoId, + worktreeId: event.worktreeId, + eventCount: 1, + inputTokens: event.inputTokens, + cachedInputTokens: event.cachedInputTokens, + outputTokens: event.outputTokens, + reasoningOutputTokens: event.reasoningOutputTokens, + totalTokens: event.totalTokens, + ...eventMetric + }) + } + + function foldModel( + target: UsageModelBreakdown[], + event: TEvent, + eventMetric: TMetric + ): void { + const key = event.model ?? 'unknown' + const existing = target.find((entry) => entry.modelKey === key) ?? null + if (existing) { + existing.eventCount++ + existing.inputTokens += event.inputTokens + existing.cachedInputTokens += event.cachedInputTokens + existing.outputTokens += event.outputTokens + existing.reasoningOutputTokens += event.reasoningOutputTokens + existing.totalTokens += event.totalTokens + metric.fold(existing, eventMetric) + return + } + + target.push({ + modelKey: key, + modelLabel: event.model ?? 'Unknown model', + eventCount: 1, + inputTokens: event.inputTokens, + cachedInputTokens: event.cachedInputTokens, + outputTokens: event.outputTokens, + reasoningOutputTokens: event.reasoningOutputTokens, + totalTokens: event.totalTokens, + ...eventMetric + }) + } + + function foldLocationModel( + target: UsageLocationModelBreakdown[], + event: TEvent, + eventMetric: TMetric + ): void { + const modelKey = event.model ?? 'unknown' + const existing = + target.find( + (entry) => entry.locationKey === event.projectKey && entry.modelKey === modelKey + ) ?? null + if (existing) { + existing.eventCount++ + existing.inputTokens += event.inputTokens + existing.cachedInputTokens += event.cachedInputTokens + existing.outputTokens += event.outputTokens + existing.reasoningOutputTokens += event.reasoningOutputTokens + existing.totalTokens += event.totalTokens + metric.fold(existing, eventMetric) + return + } + + target.push({ + locationKey: event.projectKey, + modelKey, + modelLabel: event.model ?? 'Unknown model', + repoId: event.repoId, + worktreeId: event.worktreeId, + eventCount: 1, + inputTokens: event.inputTokens, + cachedInputTokens: event.cachedInputTokens, + outputTokens: event.outputTokens, + reasoningOutputTokens: event.reasoningOutputTokens, + totalTokens: event.totalTokens, + ...eventMetric + }) + } + + function finalizeSessions( + sessionsById: Map> + ): UsageSession[] { + for (const session of sessionsById.values()) { + session.locationBreakdown.sort((left, right) => right.totalTokens - left.totalTokens) + session.modelBreakdown.sort((left, right) => right.totalTokens - left.totalTokens) + const primaryLocation = session.locationBreakdown[0] ?? null + const primaryModel = session.modelBreakdown[0] ?? null + session.primaryProjectLabel = + session.locationBreakdown.length <= 1 + ? (primaryLocation?.projectLabel ?? 'Unknown location') + : 'Multiple locations' + session.hasMixedLocations = session.locationBreakdown.length > 1 + session.primaryWorktreeId = primaryLocation?.worktreeId ?? null + session.primaryRepoId = primaryLocation?.repoId ?? null + session.primaryModel = + session.modelBreakdown.length <= 1 ? (primaryModel?.modelLabel ?? null) : 'Mixed models' + session.hasMixedModels = session.modelBreakdown.length > 1 + } + + return [...sessionsById.values()].sort((left, right) => + right.lastTimestamp.localeCompare(left.lastTimestamp) + ) + } + + function sortDailyAggregates( + dailyByKey: Map> + ): UsageDailyAggregate[] { + return [...dailyByKey.values()].sort((left, right) => + left.day === right.day + ? left.projectLabel.localeCompare(right.projectLabel) + : left.day.localeCompare(right.day) + ) + } + + function aggregate(events: TEvent[]): { + sessions: UsageSession[] + dailyAggregates: UsageDailyAggregate[] + } { + const sessionsById = new Map>() + const dailyByKey = new Map>() + + for (const event of events) { + const eventMetric = metric.fromEvent(event) + const session = sessionsById.get(event.sessionId) ?? createEmptySession(event) + if (!sessionsById.has(event.sessionId)) { + sessionsById.set(event.sessionId, session) + } + if (event.timestamp < session.firstTimestamp) { + session.firstTimestamp = event.timestamp + } + if (event.timestamp >= session.lastTimestamp) { + session.lastTimestamp = event.timestamp + } + session.eventCount++ + session.totalInputTokens += event.inputTokens + session.totalCachedInputTokens += event.cachedInputTokens + session.totalOutputTokens += event.outputTokens + session.totalReasoningOutputTokens += event.reasoningOutputTokens + session.totalTokens += event.totalTokens + metric.fold(session, eventMetric) + foldLocation(session.locationBreakdown, event, eventMetric) + foldModel(session.modelBreakdown, event, eventMetric) + foldLocationModel(session.locationModelBreakdown, event, eventMetric) + + const dailyKey = usageDailyAggregateKey(event) + const daily = dailyByKey.get(dailyKey) ?? createEmptyDailyAggregate(event) + if (!dailyByKey.has(dailyKey)) { + dailyByKey.set(dailyKey, daily) + } + daily.eventCount++ + daily.inputTokens += event.inputTokens + daily.cachedInputTokens += event.cachedInputTokens + daily.outputTokens += event.outputTokens + daily.reasoningOutputTokens += event.reasoningOutputTokens + daily.totalTokens += event.totalTokens + metric.fold(daily, eventMetric) + } + + return { + sessions: finalizeSessions(sessionsById), + dailyAggregates: sortDailyAggregates(dailyByKey) + } + } + + return { + aggregate, + finalizeSessions, + sortDailyAggregates, + mergeSessions: ( + target: Map>, + sessions: UsageSession[] + ): void => mergeUsageSessions(target, sessions, { fold: metric.fold, cloneSessionForMerge }), + mergeDailyAggregates: ( + target: Map>, + dailyAggregates: UsageDailyAggregate[] + ): void => mergeUsageDailyAggregates(target, dailyAggregates, metric.fold) + } +} diff --git a/src/main/usage/usage-path-comparison.ts b/src/main/usage/usage-path-comparison.ts new file mode 100644 index 000000000..135913172 --- /dev/null +++ b/src/main/usage/usage-path-comparison.ts @@ -0,0 +1,20 @@ +import { posix, win32 } from 'node:path' + +export function looksLikeWindowsPath(pathValue: string): boolean { + return /^[A-Za-z]:[\\/]/.test(pathValue) || pathValue.startsWith('\\\\') +} + +/** Key for grouping by location: slash/case differences must not fragment one folder into many. */ +export function normalizeComparablePath(pathValue: string, platform = process.platform): string { + const normalized = pathValue.replace(/\\/g, '/') + return platform === 'win32' || looksLikeWindowsPath(pathValue) + ? normalized.toLowerCase() + : normalized +} + +export function normalizeFsPath(pathValue: string, platform = process.platform): string { + if (platform === 'win32' || looksLikeWindowsPath(pathValue)) { + return win32.normalize(win32.resolve(pathValue)) + } + return posix.normalize(posix.resolve(pathValue)) +} diff --git a/src/main/usage/usage-provider-contract.ts b/src/main/usage/usage-provider-contract.ts new file mode 100644 index 000000000..2937af8b0 --- /dev/null +++ b/src/main/usage/usage-provider-contract.ts @@ -0,0 +1,41 @@ +/** + * Seam a usage source implements to be scanned by Orca, including plugin-contributed ones. + * + * Deliberately generic over each provider's record types: Claude bills per turn while + * Codex/OpenCode bill per event, and `cachedInput` is a subset of `input` for the latter but a + * peer bucket for Claude. A single normalized record would push nullable handling onto every + * consumer, so only the scan envelope is shared. + */ + +export type UsageProviderId = 'claude' | 'codex' | 'opencode' | `plugin:${string}` + +/** Scan input. Distinct from `UsageWorktreeRef` in usage-worktree-metadata, which lacks `repoId`. */ +export type UsageScanWorktreeRef = { + repoId: string + worktreeId: string + path: string + displayName: string +} + +/** + * `TSourceKey` is the provider's own name for its per-source scan cache (`processedFiles`, + * `processedDatabases`). It stays a type parameter because those names are persisted on disk. + */ +export type UsageScanResult = Record< + TSourceKey, + readonly TSource[] +> & { + sessions: readonly TSession[] + dailyAggregates: readonly TDaily[] +} + +export type UsageProvider = { + readonly id: UsageProviderId + readonly label: string + /** Bumped when the persisted projection changes shape; older caches are discarded. */ + readonly schemaVersion: number + scan( + worktrees: UsageScanWorktreeRef[], + previous: TSource[] + ): Promise> +} diff --git a/src/main/usage/usage-record-coercion.ts b/src/main/usage/usage-record-coercion.ts new file mode 100644 index 000000000..fe0700418 --- /dev/null +++ b/src/main/usage/usage-record-coercion.ts @@ -0,0 +1,11 @@ +export function ensureNumber(value: unknown): number { + return typeof value === 'number' && Number.isFinite(value) ? value : 0 +} + +export function extractString(value: unknown): string | null { + if (typeof value !== 'string') { + return null + } + const trimmed = value.trim() + return trimmed.length > 0 ? trimmed : null +} diff --git a/src/main/usage/usage-rollup-merge.ts b/src/main/usage/usage-rollup-merge.ts new file mode 100644 index 000000000..f63408f01 --- /dev/null +++ b/src/main/usage/usage-rollup-merge.ts @@ -0,0 +1,117 @@ +/** Combines rollups produced by separate sources (rollout files, sibling databases) of one provider. */ +import { + usageDailyAggregateKey, + type UsageDailyAggregate, + type UsageMetricFold, + type UsageSession +} from './usage-rollup-records' + +export type UsageRollupMergeOptions = { + fold: UsageMetricFold['fold'] + cloneSessionForMerge(session: UsageSession): UsageSession +} + +export function mergeUsageSessions( + target: Map>, + sessions: UsageSession[], + { fold, cloneSessionForMerge }: UsageRollupMergeOptions +): void { + for (const session of sessions) { + const existing = target.get(session.sessionId) + if (!existing) { + target.set(session.sessionId, cloneSessionForMerge(session)) + continue + } + + existing.firstTimestamp = + session.firstTimestamp < existing.firstTimestamp + ? session.firstTimestamp + : existing.firstTimestamp + existing.lastTimestamp = + session.lastTimestamp > existing.lastTimestamp + ? session.lastTimestamp + : existing.lastTimestamp + existing.eventCount += session.eventCount + existing.totalInputTokens += session.totalInputTokens + existing.totalCachedInputTokens += session.totalCachedInputTokens + existing.totalOutputTokens += session.totalOutputTokens + existing.totalReasoningOutputTokens += session.totalReasoningOutputTokens + existing.totalTokens += session.totalTokens + fold(existing, session) + + for (const location of session.locationBreakdown) { + const existingLocation = + existing.locationBreakdown.find((entry) => entry.locationKey === location.locationKey) ?? + null + if (existingLocation) { + existingLocation.eventCount += location.eventCount + existingLocation.inputTokens += location.inputTokens + existingLocation.cachedInputTokens += location.cachedInputTokens + existingLocation.outputTokens += location.outputTokens + existingLocation.reasoningOutputTokens += location.reasoningOutputTokens + existingLocation.totalTokens += location.totalTokens + fold(existingLocation, location) + } else { + existing.locationBreakdown.push({ ...location }) + } + } + + for (const model of session.modelBreakdown) { + const existingModel = + existing.modelBreakdown.find((entry) => entry.modelKey === model.modelKey) ?? null + if (existingModel) { + existingModel.eventCount += model.eventCount + existingModel.inputTokens += model.inputTokens + existingModel.cachedInputTokens += model.cachedInputTokens + existingModel.outputTokens += model.outputTokens + existingModel.reasoningOutputTokens += model.reasoningOutputTokens + existingModel.totalTokens += model.totalTokens + fold(existingModel, model) + } else { + existing.modelBreakdown.push({ ...model }) + } + } + + for (const locationModel of session.locationModelBreakdown) { + const existingLocationModel = + existing.locationModelBreakdown.find( + (entry) => + entry.locationKey === locationModel.locationKey && + entry.modelKey === locationModel.modelKey + ) ?? null + if (existingLocationModel) { + existingLocationModel.eventCount += locationModel.eventCount + existingLocationModel.inputTokens += locationModel.inputTokens + existingLocationModel.cachedInputTokens += locationModel.cachedInputTokens + existingLocationModel.outputTokens += locationModel.outputTokens + existingLocationModel.reasoningOutputTokens += locationModel.reasoningOutputTokens + existingLocationModel.totalTokens += locationModel.totalTokens + fold(existingLocationModel, locationModel) + } else { + existing.locationModelBreakdown.push({ ...locationModel }) + } + } + } +} + +export function mergeUsageDailyAggregates( + target: Map>, + dailyAggregates: UsageDailyAggregate[], + fold: UsageMetricFold['fold'] +): void { + for (const aggregate of dailyAggregates) { + const key = usageDailyAggregateKey(aggregate) + const existing = target.get(key) + if (!existing) { + target.set(key, { ...aggregate }) + continue + } + existing.eventCount += aggregate.eventCount + existing.inputTokens += aggregate.inputTokens + existing.cachedInputTokens += aggregate.cachedInputTokens + existing.outputTokens += aggregate.outputTokens + existing.reasoningOutputTokens += aggregate.reasoningOutputTokens + existing.totalTokens += aggregate.totalTokens + fold(existing, aggregate) + } +} diff --git a/src/main/usage/usage-rollup-records.ts b/src/main/usage/usage-rollup-records.ts new file mode 100644 index 000000000..d7511e571 --- /dev/null +++ b/src/main/usage/usage-rollup-records.ts @@ -0,0 +1,111 @@ +/** + * Record shapes every event-based usage provider (Codex, OpenCode, future plugin sources) + * rolls up to. Each provider carries exactly one extra metric alongside the token counters — + * Codex tracks inferred pricing, OpenCode tracks cost — so that metric stays generic instead + * of forcing a nullable union onto both. + */ + +export type UsageAttributedEventFields = { + sessionId: string + timestamp: string + model: string | null + day: string + projectKey: string + projectLabel: string + repoId: string | null + worktreeId: string | null + inputTokens: number + cachedInputTokens: number + outputTokens: number + reasoningOutputTokens: number + totalTokens: number +} + +export type UsageLocationBreakdown = { + locationKey: string + projectLabel: string + repoId: string | null + worktreeId: string | null + eventCount: number + inputTokens: number + cachedInputTokens: number + outputTokens: number + reasoningOutputTokens: number + totalTokens: number +} & TMetric + +export type UsageModelBreakdown = { + modelKey: string + modelLabel: string + eventCount: number + inputTokens: number + cachedInputTokens: number + outputTokens: number + reasoningOutputTokens: number + totalTokens: number +} & TMetric + +export type UsageLocationModelBreakdown = { + locationKey: string + modelKey: string + modelLabel: string + repoId: string | null + worktreeId: string | null + eventCount: number + inputTokens: number + cachedInputTokens: number + outputTokens: number + reasoningOutputTokens: number + totalTokens: number +} & TMetric + +export type UsageSession = { + sessionId: string + firstTimestamp: string + lastTimestamp: string + primaryModel: string | null + hasMixedModels: boolean + primaryProjectLabel: string + hasMixedLocations: boolean + primaryWorktreeId: string | null + primaryRepoId: string | null + eventCount: number + totalInputTokens: number + totalCachedInputTokens: number + totalOutputTokens: number + totalReasoningOutputTokens: number + totalTokens: number + locationBreakdown: UsageLocationBreakdown[] + modelBreakdown: UsageModelBreakdown[] + locationModelBreakdown: UsageLocationModelBreakdown[] +} & TMetric + +export type UsageDailyAggregate = { + day: string + model: string | null + projectKey: string + projectLabel: string + repoId: string | null + worktreeId: string | null + eventCount: number + inputTokens: number + cachedInputTokens: number + outputTokens: number + reasoningOutputTokens: number + totalTokens: number +} & TMetric + +/** How a provider seeds, reads, and combines its one extra metric. */ +export type UsageMetricFold = { + empty(): TMetric + fromEvent(event: TEvent): TMetric + fold(target: TMetric, source: TMetric): void +} + +export function usageDailyAggregateKey(record: { + day: string + model: string | null + projectKey: string +}): string { + return [record.day, record.model ?? 'unknown', record.projectKey].join('::') +} diff --git a/src/main/usage/usage-worktree-refs.ts b/src/main/usage/usage-worktree-refs.ts new file mode 100644 index 000000000..0b4347a90 --- /dev/null +++ b/src/main/usage/usage-worktree-refs.ts @@ -0,0 +1,20 @@ +import type { Repo } from '../../shared/types' +import type { UsageScanWorktreeRef } from './usage-provider-contract' + +export function createWorktreeRefs( + repos: Repo[], + worktreesByRepo: Map +): UsageScanWorktreeRef[] { + const refs: UsageScanWorktreeRef[] = [] + for (const repo of repos) { + for (const worktree of worktreesByRepo.get(repo.id) ?? []) { + refs.push({ + repoId: repo.id, + worktreeId: worktree.worktreeId, + path: worktree.path, + displayName: worktree.displayName + }) + } + } + return refs +}