diff --git a/src/main/codex-usage/scanner.test.ts b/src/main/codex-usage/scanner.test.ts new file mode 100644 index 000000000..7211c78ea --- /dev/null +++ b/src/main/codex-usage/scanner.test.ts @@ -0,0 +1,203 @@ +import { describe, expect, it } from 'vitest' +import { attributeCodexUsageEvent, parseCodexUsageRecord } from './scanner' + +describe('parseCodexUsageRecord', () => { + it('uses cumulative totals to avoid double-counting repeated token snapshots', () => { + const context = { + sessionId: 'session-1', + sessionCwd: null, + currentCwd: null, + currentModel: null, + previousTotals: null + } + + expect( + parseCodexUsageRecord( + JSON.stringify({ + type: 'session_meta', + payload: { id: 'session-1', cwd: '/workspace/repo' } + }), + context + ) + ).toBeNull() + + expect( + parseCodexUsageRecord( + JSON.stringify({ + type: 'turn_context', + payload: { cwd: '/workspace/repo/packages/app', model: 'gpt-5.2-codex' } + }), + context + ) + ).toBeNull() + + const first = parseCodexUsageRecord( + JSON.stringify({ + timestamp: '2026-04-09T10:00:00.000Z', + type: 'event_msg', + payload: { + type: 'token_count', + info: { + total_token_usage: { + input_tokens: 1000, + cached_input_tokens: 400, + output_tokens: 250, + reasoning_output_tokens: 100, + total_tokens: 1250 + }, + last_token_usage: { + input_tokens: 1000, + cached_input_tokens: 400, + output_tokens: 250, + reasoning_output_tokens: 100, + total_tokens: 1250 + } + } + } + }), + context + ) + + const duplicate = parseCodexUsageRecord( + JSON.stringify({ + timestamp: '2026-04-09T10:00:01.000Z', + type: 'event_msg', + payload: { + type: 'token_count', + info: { + total_token_usage: { + input_tokens: 1000, + cached_input_tokens: 400, + output_tokens: 250, + reasoning_output_tokens: 100, + total_tokens: 1250 + }, + last_token_usage: { + input_tokens: 1000, + cached_input_tokens: 400, + output_tokens: 250, + reasoning_output_tokens: 100, + total_tokens: 1250 + } + } + } + }), + context + ) + + expect(first).toEqual({ + sessionId: 'session-1', + timestamp: '2026-04-09T10:00:00.000Z', + cwd: '/workspace/repo/packages/app', + model: 'gpt-5.2-codex', + hasInferredPricing: false, + inputTokens: 1000, + cachedInputTokens: 400, + outputTokens: 250, + reasoningOutputTokens: 100, + totalTokens: 1250 + }) + expect(duplicate).toBeNull() + }) + + it('falls back to inferred gpt-5 pricing when model metadata is missing', () => { + const context = { + sessionId: 'session-1', + sessionCwd: '/workspace/repo', + currentCwd: '/workspace/repo', + currentModel: null, + previousTotals: null + } + + const parsed = parseCodexUsageRecord( + JSON.stringify({ + timestamp: '2026-04-09T10:00:00.000Z', + type: 'event_msg', + payload: { + type: 'token_count', + info: { + last_token_usage: { + input_tokens: 120, + cached_input_tokens: 20, + output_tokens: 50, + reasoning_output_tokens: 10, + total_tokens: 170 + } + } + } + }), + context + ) + + expect(parsed?.model).toBe('gpt-5') + expect(parsed?.hasInferredPricing).toBe(true) + }) +}) + +describe('attributeCodexUsageEvent', () => { + it('attributes nested cwd paths to the nearest containing worktree', async () => { + const attributed = await attributeCodexUsageEvent( + { + sessionId: 'session-1', + timestamp: '2026-04-09T10:00:00.000Z', + cwd: '/workspace/repo/app2/subdir', + model: 'gpt-5.2-codex', + hasInferredPricing: false, + inputTokens: 100, + cachedInputTokens: 10, + outputTokens: 25, + reasoningOutputTokens: 10, + totalTokens: 125 + }, + [ + { + repoId: 'repo-1', + worktreeId: 'repo-1::/workspace/repo/app', + path: '/workspace/repo/app', + displayName: 'App', + canonicalPath: '/workspace/repo/app' + }, + { + repoId: 'repo-2', + worktreeId: 'repo-2::/workspace/repo/app2', + path: '/workspace/repo/app2', + displayName: 'App 2', + canonicalPath: '/workspace/repo/app2' + } + ] + ) + + expect(attributed?.projectKey).toBe('worktree:repo-2::/workspace/repo/app2') + expect(attributed?.projectLabel).toBe('App 2') + expect(attributed?.worktreeId).toBe('repo-2::/workspace/repo/app2') + }) + + it('does not treat different Windows drives as containing paths', async () => { + const attributed = await attributeCodexUsageEvent( + { + sessionId: 'session-1', + timestamp: '2026-04-09T10:00:00.000Z', + cwd: 'D:\\other\\repo', + model: 'gpt-5.2-codex', + hasInferredPricing: false, + inputTokens: 100, + cachedInputTokens: 10, + outputTokens: 25, + reasoningOutputTokens: 10, + totalTokens: 125 + }, + [ + { + repoId: 'repo-1', + worktreeId: 'repo-1::C:\\repo', + path: 'C:\\repo', + displayName: 'Repo', + canonicalPath: 'C:\\repo' + } + ] + ) + + expect(attributed?.projectKey).toBe('cwd:d:/other/repo') + expect(attributed?.worktreeId).toBeNull() + }) +}) diff --git a/src/main/codex-usage/scanner.ts b/src/main/codex-usage/scanner.ts new file mode 100644 index 000000000..8cfc89ee8 --- /dev/null +++ b/src/main/codex-usage/scanner.ts @@ -0,0 +1,845 @@ +/* eslint-disable max-lines -- Why: Codex discovery, incremental parsing, attribution, and aggregation all depend on the same event-normalization rules. Keeping them together makes the duplicate-snapshot logic easier to audit when usage totals look wrong. */ +import { homedir } from 'os' +import { basename, join, win32, posix } from 'path' +import { createReadStream } from 'fs' +import { realpath, readdir, stat } from 'fs/promises' +import { createInterface } from 'readline' +import type { Repo } from '../../shared/types' +import { areWorktreePathsEqual } from '../ipc/worktree-logic' +import type { + CodexUsageAttributedEvent, + CodexUsageDailyAggregate, + CodexUsageLocationBreakdown, + CodexUsageLocationModelBreakdown, + CodexUsageModelBreakdown, + CodexUsageParsedEvent, + CodexUsagePersistedFile, + CodexUsageProcessedFile, + CodexUsageSession +} from './types' + +export type CodexUsageWorktreeRef = { + repoId: string + worktreeId: string + path: string + displayName: string +} + +type CodexUsageRawRecord = { + timestamp?: string + type?: string + payload?: Record +} + +type CodexUsageRawUsage = { + inputTokens: number + cachedInputTokens: number + outputTokens: number + reasoningOutputTokens: number + totalTokens: number +} + +type CodexUsageParseContext = { + sessionId: string + sessionCwd: string | null + currentCwd: string | null + currentModel: string | null + previousTotals: CodexUsageRawUsage | null +} + +const DEFAULT_CODEX_SESSIONS_DIR = join(homedir(), '.codex', 'sessions') +const LEGACY_FALLBACK_MODEL = 'gpt-5' +const YIELD_EVERY_FILES = 10 + +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) + return normalizeFsPath(resolved) + } catch { + return normalizeFsPath(pathValue) + } +} + +async function yieldToEventLoop(): Promise { + await new Promise((resolve) => setTimeout(resolve, 0)) +} + +async function walkJsonlFiles(dirPath: string): Promise { + const entries = await readdir(dirPath, { withFileTypes: true }) + const files: string[] = [] + + for (const entry of entries) { + const fullPath = join(dirPath, entry.name) + if (entry.isDirectory()) { + files.push(...(await walkJsonlFiles(fullPath))) + continue + } + if (entry.isFile() && entry.name.endsWith('.jsonl')) { + files.push(fullPath) + } + } + + return files +} + +export function getCodexSessionsDirectory(): string { + const codexHome = process.env.CODEX_HOME?.trim() + if (codexHome) { + return join(codexHome, 'sessions') + } + return DEFAULT_CODEX_SESSIONS_DIR +} + +export async function listCodexSessionFiles(): Promise { + try { + return (await walkJsonlFiles(getCodexSessionsDirectory())).sort() + } catch { + return [] + } +} + +export async function getProcessedFileInfo(filePath: string): Promise { + const fileStat = await stat(filePath) + return { + path: filePath, + mtimeMs: fileStat.mtimeMs, + size: fileStat.size + } +} + +function normalizeRawUsage(value: unknown): CodexUsageRawUsage | null { + if (value == null || typeof value !== 'object') { + return null + } + + const record = value as Record + const inputTokens = ensureNumber(record.input_tokens) + const cachedInputTokens = ensureNumber( + record.cached_input_tokens ?? record.cache_read_input_tokens + ) + const outputTokens = ensureNumber(record.output_tokens) + const reasoningOutputTokens = ensureNumber(record.reasoning_output_tokens) + const totalTokens = ensureNumber(record.total_tokens) + + return { + inputTokens, + cachedInputTokens, + outputTokens, + reasoningOutputTokens, + // Why: legacy Codex logs can omit total_tokens. Reasoning is already billed + // inside output, so synthesizing input+output matches Codex pricing instead + // of double-counting reasoning as another billable bucket. + totalTokens: totalTokens > 0 ? totalTokens : inputTokens + outputTokens + } +} + +function subtractRawUsage( + current: CodexUsageRawUsage, + previous: CodexUsageRawUsage | null +): CodexUsageRawUsage { + return { + inputTokens: Math.max(current.inputTokens - (previous?.inputTokens ?? 0), 0), + cachedInputTokens: Math.max(current.cachedInputTokens - (previous?.cachedInputTokens ?? 0), 0), + outputTokens: Math.max(current.outputTokens - (previous?.outputTokens ?? 0), 0), + reasoningOutputTokens: Math.max( + current.reasoningOutputTokens - (previous?.reasoningOutputTokens ?? 0), + 0 + ), + totalTokens: Math.max(current.totalTokens - (previous?.totalTokens ?? 0), 0) + } +} + +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 + } + + const record = value as Record + const direct = [extractString(record.model), extractString(record.model_name)].find( + (candidate) => candidate !== null + ) + if (direct) { + return direct + } + + if (record.info && typeof record.info === 'object') { + const info = record.info as Record + const infoDirect = [extractString(info.model), extractString(info.model_name)].find( + (candidate) => candidate !== null + ) + if (infoDirect) { + return infoDirect + } + if (info.metadata && typeof info.metadata === 'object') { + const metadata = info.metadata as Record + const metadataModel = extractString(metadata.model) + if (metadataModel) { + return metadataModel + } + } + } + + if (record.metadata && typeof record.metadata === 'object') { + const metadata = record.metadata as Record + return extractString(metadata.model) + } + + return null +} + +function getDefaultProjectLabel(cwd: string | null): string { + if (!cwd) { + return 'Unknown location' + } + const parts = cwd.replace(/\\/g, '/').split('/').filter(Boolean) + if (parts.length >= 2) { + return parts.slice(-2).join('/') + } + return parts.at(-1) ?? cwd +} + +function localDayFromTimestamp(timestamp: string): string | null { + const parsed = new Date(timestamp) + if (Number.isNaN(parsed.getTime())) { + return null + } + const year = parsed.getFullYear() + const month = String(parsed.getMonth() + 1).padStart(2, '0') + const day = String(parsed.getDate()).padStart(2, '0') + return `${year}-${month}-${day}` +} + +async function buildWorktreesWithCanonicalPaths( + worktrees: CodexUsageWorktreeRef[] +): Promise<(CodexUsageWorktreeRef & { canonicalPath: string })[]> { + const canonicalized = await Promise.all( + worktrees.map(async (worktree) => ({ + ...worktree, + canonicalPath: await canonicalizePath(worktree.path) + })) + ) + + return canonicalized.sort((left, right) => right.canonicalPath.length - left.canonicalPath.length) +} + +function isContainingPath(candidatePath: string, targetPath: string): boolean { + const useWin32 = looksLikeWindowsPath(candidatePath) || looksLikeWindowsPath(targetPath) + const relativePath = useWin32 + ? win32.relative(candidatePath, targetPath) + : posix.relative(candidatePath, targetPath) + if (!relativePath) { + return true + } + // Why: on Windows, `path.relative('C:\\repo', 'D:\\other')` returns an + // absolute `D:\\other` path instead of a `..`-prefixed relative. Treating + // that as "contained" would attribute off-drive Codex usage to the wrong + // Orca worktree. + const isAbsoluteRelative = useWin32 + ? win32.isAbsolute(relativePath) + : posix.isAbsolute(relativePath) + return !isAbsoluteRelative && !relativePath.startsWith('..') && relativePath !== '.' +} + +function findContainingWorktree( + cwd: string, + worktrees: (CodexUsageWorktreeRef & { canonicalPath: string })[] +): CodexUsageWorktreeRef | null { + const normalizedCwd = normalizeFsPath(cwd) + for (const worktree of worktrees) { + if (areWorktreePathsEqual(worktree.canonicalPath, normalizedCwd)) { + return worktree + } + if (isContainingPath(worktree.canonicalPath, normalizedCwd)) { + return worktree + } + } + return null +} + +export async function attributeCodexUsageEvent( + event: CodexUsageParsedEvent, + worktrees: (CodexUsageWorktreeRef & { canonicalPath: string })[] +): Promise { + const day = localDayFromTimestamp(event.timestamp) + if (!day) { + return null + } + + let repoId: string | null = null + let worktreeId: string | null = null + let projectKey = 'unscoped' + let projectLabel = getDefaultProjectLabel(event.cwd) + + if (event.cwd) { + const worktree = findContainingWorktree(event.cwd, worktrees) + if (worktree) { + repoId = worktree.repoId + worktreeId = worktree.worktreeId + projectKey = `worktree:${worktree.worktreeId}` + projectLabel = worktree.displayName + } else { + // Why: all-local mode should still collapse repeated off-Orca sessions by + // location, but those keys must normalize slash/case differences so the + // same folder does not fragment into multiple "projects" across platforms. + projectKey = `cwd:${normalizeComparablePath(event.cwd)}` + } + } + + return { + ...event, + day, + projectKey, + projectLabel, + repoId, + worktreeId + } +} + +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: [] + } +} + +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) + } + 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, 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.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 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 + } +} + +export function parseCodexUsageRecord( + line: string, + context: CodexUsageParseContext +): CodexUsageParsedEvent | null { + let parsed: CodexUsageRawRecord + try { + parsed = JSON.parse(line) as CodexUsageRawRecord + } catch { + return null + } + + if (!parsed.type || !parsed.payload) { + return null + } + + if (parsed.type === 'session_meta') { + context.sessionId = extractString(parsed.payload.id) ?? context.sessionId + context.sessionCwd = extractString(parsed.payload.cwd) + if (!context.currentCwd && context.sessionCwd) { + context.currentCwd = context.sessionCwd + } + return null + } + + if (parsed.type === 'turn_context') { + context.currentCwd = + extractString(parsed.payload.cwd) ?? context.currentCwd ?? context.sessionCwd + context.currentModel = extractModel(parsed.payload) ?? context.currentModel + return null + } + + if (parsed.type !== 'event_msg' || parsed.payload.type !== 'token_count' || !parsed.timestamp) { + return null + } + + const info = parsed.payload.info + if (info == null || typeof info !== 'object') { + // Why: Codex emits token_count snapshots with null info for rate-limit + // updates. Treating them as malformed usage would make active sessions look + // flaky and create false scan errors for perfectly valid logs. + return null + } + + const record = info as Record + const totalUsage = normalizeRawUsage(record.total_token_usage) + const lastUsage = normalizeRawUsage(record.last_token_usage) + let delta = totalUsage ? subtractRawUsage(totalUsage, context.previousTotals) : lastUsage + if (totalUsage) { + context.previousTotals = totalUsage + } + if (!delta) { + return null + } + + delta = { + ...delta, + cachedInputTokens: Math.min(delta.cachedInputTokens, delta.inputTokens) + } + + if ( + delta.inputTokens === 0 && + delta.cachedInputTokens === 0 && + delta.outputTokens === 0 && + delta.reasoningOutputTokens === 0 && + delta.totalTokens === 0 + ) { + return null + } + + const resolvedModel = extractModel(parsed.payload) ?? context.currentModel + const model = resolvedModel ?? LEGACY_FALLBACK_MODEL + const hasInferredPricing = resolvedModel === null + + return { + sessionId: context.sessionId, + timestamp: parsed.timestamp, + cwd: context.currentCwd ?? context.sessionCwd, + model, + hasInferredPricing, + inputTokens: delta.inputTokens, + cachedInputTokens: delta.cachedInputTokens, + outputTokens: delta.outputTokens, + reasoningOutputTokens: delta.reasoningOutputTokens, + totalTokens: delta.totalTokens + } +} + +export async function parseCodexUsageFile( + filePath: string, + worktrees: (CodexUsageWorktreeRef & { canonicalPath: string })[] +): Promise { + const processedFile = await getProcessedFileInfo(filePath) + const lines = createInterface({ + input: createReadStream(filePath, { encoding: 'utf-8' }), + crlfDelay: Infinity + }) + const events: CodexUsageAttributedEvent[] = [] + const context: CodexUsageParseContext = { + sessionId: basename(filePath, '.jsonl'), + sessionCwd: null, + currentCwd: null, + currentModel: null, + previousTotals: null + } + + for await (const line of lines) { + const parsed = parseCodexUsageRecord(line, context) + if (!parsed) { + continue + } + const attributed = await attributeCodexUsageEvent(parsed, worktrees) + if (attributed) { + events.push(attributed) + } + } + + return { + ...processedFile, + ...aggregateCodexUsage(events) + } +} + +export async function scanCodexUsageFiles( + worktrees: CodexUsageWorktreeRef[], + previousProcessedFiles: CodexUsagePersistedFile[] +): Promise<{ + processedFiles: CodexUsagePersistedFile[] + sessions: CodexUsageSession[] + dailyAggregates: CodexUsageDailyAggregate[] +}> { + const files = await listCodexSessionFiles() + const previousByPath = new Map(previousProcessedFiles.map((file) => [file.path, file])) + const processedFiles: CodexUsagePersistedFile[] = [] + const worktreesWithCanonicalPaths = await buildWorktreesWithCanonicalPaths(worktrees) + const sessionsById = new Map() + const dailyByKey = new Map() + + for (const [index, filePath] of files.entries()) { + const fileInfo = await getProcessedFileInfo(filePath) + const previous = previousByPath.get(filePath) + const canReuse = + previous && previous.mtimeMs === fileInfo.mtimeMs && previous.size === fileInfo.size + + const processed = canReuse + ? previous + : await parseCodexUsageFile(filePath, worktreesWithCanonicalPaths) + + processedFiles.push(processed) + mergeSessions(sessionsById, processed.sessions) + mergeDailyAggregates(dailyByKey, processed.dailyAggregates) + + // Why: Codex session history can grow large, and scans run on the Electron + // main process. Yield regularly so opening Settings does not stall while + // a background refresh walks old JSONL files. + if ((index + 1) % YIELD_EVERY_FILES === 0) { + await yieldToEventLoop() + } + } + + 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) + ) + } +} + +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 +} + +export function getDefaultWorktreeLabel(pathValue: string): string { + return basename(pathValue) +} + +export function getSessionProjectLabel(locationBreakdown: CodexUsageLocationBreakdown[]): string { + if (locationBreakdown.length === 0) { + return 'Unknown location' + } + if (locationBreakdown.length === 1) { + return locationBreakdown[0].projectLabel + } + return 'Multiple locations' +} diff --git a/src/main/codex-usage/store.test.ts b/src/main/codex-usage/store.test.ts new file mode 100644 index 000000000..5b9b0b0fa --- /dev/null +++ b/src/main/codex-usage/store.test.ts @@ -0,0 +1,494 @@ +/* eslint-disable max-lines */ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { CodexUsagePersistedState } from './types' + +const { getPathMock } = vi.hoisted(() => ({ + getPathMock: vi.fn(() => '/tmp/orca-test-userdata') +})) + +vi.mock('electron', () => ({ + app: { + getPath: getPathMock + } +})) + +import { CodexUsageStore, normalizePersistedState } from './store' + +function createStoreWithState(state: Partial): CodexUsageStore { + const store = new CodexUsageStore({ + getRepos: () => [], + getWorktreeMeta: () => undefined + } as never) + + ;(store as unknown as { state: CodexUsagePersistedState }).state = { + schemaVersion: 1, + worktreeFingerprint: null, + processedFiles: [], + sessions: [], + dailyAggregates: [], + scanState: { + enabled: false, + lastScanStartedAt: null, + lastScanCompletedAt: null, + lastScanError: null + }, + ...state + } + + return store +} + +describe('CodexUsageStore', () => { + beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(new Date('2026-04-10T12:00:00.000-04:00')) + }) + + it('reports no data for Orca scope when only non-Orca Codex usage exists', async () => { + const store = createStoreWithState({ + sessions: [ + { + sessionId: 'session-1', + firstTimestamp: '2026-04-09T10:00:00.000Z', + lastTimestamp: '2026-04-09T10:10:00.000Z', + primaryModel: 'gpt-5', + hasMixedModels: false, + primaryProjectLabel: 'outside/repo', + hasMixedLocations: false, + primaryWorktreeId: null, + primaryRepoId: null, + eventCount: 1, + totalInputTokens: 1000, + totalCachedInputTokens: 400, + totalOutputTokens: 250, + totalReasoningOutputTokens: 100, + totalTokens: 1250, + hasInferredPricing: false, + locationBreakdown: [ + { + locationKey: 'cwd:/outside/repo', + projectLabel: 'outside/repo', + repoId: null, + worktreeId: null, + eventCount: 1, + inputTokens: 1000, + cachedInputTokens: 400, + outputTokens: 250, + reasoningOutputTokens: 100, + totalTokens: 1250, + hasInferredPricing: false + } + ], + modelBreakdown: [ + { + modelKey: 'gpt-5', + modelLabel: 'gpt-5', + eventCount: 1, + inputTokens: 1000, + cachedInputTokens: 400, + outputTokens: 250, + reasoningOutputTokens: 100, + totalTokens: 1250, + hasInferredPricing: false + } + ], + locationModelBreakdown: [ + { + locationKey: 'cwd:/outside/repo', + modelKey: 'gpt-5', + modelLabel: 'gpt-5', + repoId: null, + worktreeId: null, + eventCount: 1, + inputTokens: 1000, + cachedInputTokens: 400, + outputTokens: 250, + reasoningOutputTokens: 100, + totalTokens: 1250, + hasInferredPricing: false + } + ] + } + ], + dailyAggregates: [ + { + day: '2026-04-09', + model: 'gpt-5', + projectKey: 'cwd:/outside/repo', + projectLabel: 'outside/repo', + repoId: null, + worktreeId: null, + eventCount: 1, + inputTokens: 1000, + cachedInputTokens: 400, + outputTokens: 250, + reasoningOutputTokens: 100, + totalTokens: 1250, + hasInferredPricing: false + } + ] + }) + + const summary = await store.getSummary('orca', '30d') + + expect(summary.hasAnyCodexData).toBe(false) + expect(summary.sessions).toBe(0) + expect(summary.events).toBe(0) + }) + + it('calculates cost from uncached input plus cached input without double billing', async () => { + const store = createStoreWithState({ + dailyAggregates: [ + { + day: '2026-04-09', + model: 'gpt-5', + projectKey: 'worktree:repo-1::/workspace/repo', + projectLabel: 'Repo', + repoId: 'repo-1', + worktreeId: 'repo-1::/workspace/repo', + eventCount: 2, + inputTokens: 1000, + cachedInputTokens: 400, + outputTokens: 250, + reasoningOutputTokens: 100, + totalTokens: 1250, + hasInferredPricing: false + } + ] + }) + + const summary = await store.getSummary('orca', '30d') + + expect(summary.estimatedCostUsd).toBeCloseTo(0.0014) + expect(summary.totalTokens).toBe(1250) + expect(summary.reasoningOutputTokens).toBe(100) + }) + + it('counts mixed-model sessions once for each real model row in the breakdown', async () => { + const store = createStoreWithState({ + sessions: [ + { + sessionId: 'session-1', + firstTimestamp: '2026-04-09T10:00:00.000Z', + lastTimestamp: '2026-04-09T10:10:00.000Z', + primaryModel: 'Mixed models', + hasMixedModels: true, + primaryProjectLabel: 'Repo', + hasMixedLocations: false, + primaryWorktreeId: 'repo-1::/workspace/repo', + primaryRepoId: 'repo-1', + eventCount: 2, + totalInputTokens: 300, + totalCachedInputTokens: 100, + totalOutputTokens: 90, + totalReasoningOutputTokens: 10, + totalTokens: 390, + hasInferredPricing: false, + locationBreakdown: [ + { + locationKey: 'worktree:repo-1::/workspace/repo', + projectLabel: 'Repo', + repoId: 'repo-1', + worktreeId: 'repo-1::/workspace/repo', + eventCount: 2, + inputTokens: 300, + cachedInputTokens: 100, + outputTokens: 90, + reasoningOutputTokens: 10, + totalTokens: 390, + hasInferredPricing: false + } + ], + modelBreakdown: [ + { + modelKey: 'gpt-5', + modelLabel: 'gpt-5', + eventCount: 1, + inputTokens: 100, + cachedInputTokens: 20, + outputTokens: 30, + reasoningOutputTokens: 5, + totalTokens: 130, + hasInferredPricing: false + }, + { + modelKey: 'gpt-5.2-codex', + modelLabel: 'gpt-5.2-codex', + eventCount: 1, + inputTokens: 200, + cachedInputTokens: 80, + outputTokens: 60, + reasoningOutputTokens: 5, + totalTokens: 260, + hasInferredPricing: false + } + ], + locationModelBreakdown: [ + { + locationKey: 'worktree:repo-1::/workspace/repo', + modelKey: 'gpt-5', + modelLabel: 'gpt-5', + repoId: 'repo-1', + worktreeId: 'repo-1::/workspace/repo', + eventCount: 1, + inputTokens: 100, + cachedInputTokens: 20, + outputTokens: 30, + reasoningOutputTokens: 5, + totalTokens: 130, + hasInferredPricing: false + }, + { + locationKey: 'worktree:repo-1::/workspace/repo', + modelKey: 'gpt-5.2-codex', + modelLabel: 'gpt-5.2-codex', + repoId: 'repo-1', + worktreeId: 'repo-1::/workspace/repo', + eventCount: 1, + inputTokens: 200, + cachedInputTokens: 80, + outputTokens: 60, + reasoningOutputTokens: 5, + totalTokens: 260, + hasInferredPricing: false + } + ] + } + ], + dailyAggregates: [ + { + day: '2026-04-09', + model: 'gpt-5', + projectKey: 'worktree:repo-1::/workspace/repo', + projectLabel: 'Repo', + repoId: 'repo-1', + worktreeId: 'repo-1::/workspace/repo', + eventCount: 1, + inputTokens: 100, + cachedInputTokens: 20, + outputTokens: 30, + reasoningOutputTokens: 5, + totalTokens: 130, + hasInferredPricing: false + }, + { + day: '2026-04-09', + model: 'gpt-5.2-codex', + projectKey: 'worktree:repo-1::/workspace/repo', + projectLabel: 'Repo', + repoId: 'repo-1', + worktreeId: 'repo-1::/workspace/repo', + eventCount: 1, + inputTokens: 200, + cachedInputTokens: 80, + outputTokens: 60, + reasoningOutputTokens: 5, + totalTokens: 260, + hasInferredPricing: false + } + ] + }) + + const breakdown = await store.getBreakdown('orca', '30d', 'model') + + expect(breakdown.find((row) => row.key === 'gpt-5')?.sessions).toBe(1) + expect(breakdown.find((row) => row.key === 'gpt-5.2-codex')?.sessions).toBe(1) + }) + + it('uses only Orca-scoped models when projecting mixed-scope sessions', async () => { + const store = createStoreWithState({ + sessions: [ + { + sessionId: 'session-1', + firstTimestamp: '2026-04-09T10:00:00.000Z', + lastTimestamp: '2026-04-09T10:10:00.000Z', + primaryModel: 'Mixed models', + hasMixedModels: true, + primaryProjectLabel: 'Multiple locations', + hasMixedLocations: true, + primaryWorktreeId: 'repo-1::/workspace/repo', + primaryRepoId: 'repo-1', + eventCount: 2, + totalInputTokens: 300, + totalCachedInputTokens: 60, + totalOutputTokens: 90, + totalReasoningOutputTokens: 10, + totalTokens: 390, + hasInferredPricing: false, + locationBreakdown: [ + { + locationKey: 'worktree:repo-1::/workspace/repo', + projectLabel: 'Repo', + repoId: 'repo-1', + worktreeId: 'repo-1::/workspace/repo', + eventCount: 1, + inputTokens: 100, + cachedInputTokens: 20, + outputTokens: 30, + reasoningOutputTokens: 5, + totalTokens: 130, + hasInferredPricing: false + }, + { + locationKey: 'cwd:/outside/repo', + projectLabel: 'outside/repo', + repoId: null, + worktreeId: null, + eventCount: 1, + inputTokens: 200, + cachedInputTokens: 40, + outputTokens: 60, + reasoningOutputTokens: 5, + totalTokens: 260, + hasInferredPricing: false + } + ], + modelBreakdown: [ + { + modelKey: 'gpt-5', + modelLabel: 'gpt-5', + eventCount: 1, + inputTokens: 100, + cachedInputTokens: 20, + outputTokens: 30, + reasoningOutputTokens: 5, + totalTokens: 130, + hasInferredPricing: false + }, + { + modelKey: 'gpt-5.2-codex', + modelLabel: 'gpt-5.2-codex', + eventCount: 1, + inputTokens: 200, + cachedInputTokens: 40, + outputTokens: 60, + reasoningOutputTokens: 5, + totalTokens: 260, + hasInferredPricing: false + } + ], + locationModelBreakdown: [ + { + locationKey: 'worktree:repo-1::/workspace/repo', + modelKey: 'gpt-5', + modelLabel: 'gpt-5', + repoId: 'repo-1', + worktreeId: 'repo-1::/workspace/repo', + eventCount: 1, + inputTokens: 100, + cachedInputTokens: 20, + outputTokens: 30, + reasoningOutputTokens: 5, + totalTokens: 130, + hasInferredPricing: false + }, + { + locationKey: 'cwd:/outside/repo', + modelKey: 'gpt-5.2-codex', + modelLabel: 'gpt-5.2-codex', + repoId: null, + worktreeId: null, + eventCount: 1, + inputTokens: 200, + cachedInputTokens: 40, + outputTokens: 60, + reasoningOutputTokens: 5, + totalTokens: 260, + hasInferredPricing: false + } + ] + } + ], + dailyAggregates: [ + { + day: '2026-04-09', + model: 'gpt-5', + projectKey: 'worktree:repo-1::/workspace/repo', + projectLabel: 'Repo', + repoId: 'repo-1', + worktreeId: 'repo-1::/workspace/repo', + eventCount: 1, + inputTokens: 100, + cachedInputTokens: 20, + outputTokens: 30, + reasoningOutputTokens: 5, + totalTokens: 130, + hasInferredPricing: false + }, + { + day: '2026-04-09', + model: 'gpt-5.2-codex', + projectKey: 'cwd:/outside/repo', + projectLabel: 'outside/repo', + repoId: null, + worktreeId: null, + eventCount: 1, + inputTokens: 200, + cachedInputTokens: 40, + outputTokens: 60, + reasoningOutputTokens: 5, + totalTokens: 260, + hasInferredPricing: false + } + ] + }) + + const breakdown = await store.getBreakdown('orca', '30d', 'model') + const recentSessions = await store.getRecentSessions('orca', '30d', 10) + + expect(breakdown.find((row) => row.key === 'gpt-5')?.sessions).toBe(1) + expect(breakdown.find((row) => row.key === 'gpt-5.2-codex')).toBeUndefined() + expect(recentSessions[0]?.projectLabel).toBe('Repo') + expect(recentSessions[0]?.model).toBe('gpt-5') + }) + + it('drops persisted caches from older schemas that lack scoped model breakdown data', () => { + const normalized = normalizePersistedState({ + schemaVersion: 1, + processedFiles: [], + sessions: [ + { + sessionId: 'legacy', + firstTimestamp: '2026-04-09T10:00:00.000Z', + lastTimestamp: '2026-04-09T10:10:00.000Z', + primaryModel: 'gpt-5', + hasMixedModels: false, + primaryProjectLabel: 'Repo', + hasMixedLocations: false, + primaryWorktreeId: 'repo-1::/workspace/repo', + primaryRepoId: 'repo-1', + eventCount: 1, + totalInputTokens: 1, + totalCachedInputTokens: 0, + totalOutputTokens: 1, + totalReasoningOutputTokens: 0, + totalTokens: 2, + hasInferredPricing: false, + locationBreakdown: [], + modelBreakdown: [] + } + ], + dailyAggregates: [], + scanState: { + enabled: true, + lastScanStartedAt: 1, + lastScanCompletedAt: 2, + lastScanError: null + } + } as unknown as CodexUsagePersistedState) + + expect(normalized).toEqual({ + schemaVersion: 2, + worktreeFingerprint: null, + processedFiles: [], + sessions: [], + dailyAggregates: [], + scanState: { + enabled: false, + lastScanStartedAt: null, + lastScanCompletedAt: null, + lastScanError: null + } + }) + }) +}) diff --git a/src/main/codex-usage/store.ts b/src/main/codex-usage/store.ts new file mode 100644 index 000000000..a2f98de2b --- /dev/null +++ b/src/main/codex-usage/store.ts @@ -0,0 +1,618 @@ +/* eslint-disable max-lines -- Why: this store owns Codex analytics persistence, scan policy, and renderer query semantics. Keeping them together prevents the Codex range/scope rules from drifting away from the scanner’s event model. */ +import { app } from 'electron' +import { dirname, join } from 'path' +import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'fs' +import type { Repo } from '../../shared/types' +import type { + CodexUsageBreakdownKind, + CodexUsageBreakdownRow, + CodexUsageDailyPoint, + CodexUsageRange, + CodexUsageScanState, + CodexUsageScope, + CodexUsageSessionRow, + CodexUsageSummary +} from '../../shared/codex-usage-types' +import { listRepoWorktrees } from '../repo-worktrees' +import type { Store } from '../persistence' +import { mergeWorktree } from '../ipc/worktree-logic' +import type { CodexUsagePersistedState } from './types' +import { createWorktreeRefs, getDefaultWorktreeLabel, scanCodexUsageFiles } from './scanner' + +const SCHEMA_VERSION = 2 +const STALE_MS = 5 * 60_000 + +let _codexUsageFile: string | null = null + +const MODEL_PRICING: Record = { + 'gpt-5': { input: 1.25, cachedInput: 0.125, output: 10 }, + 'gpt-5.2-codex': { input: 1.75, cachedInput: 0.175, output: 14 }, + 'gpt-5.3-codex': { input: 1.9, cachedInput: 0.19, output: 15 } +} + +function getDefaultState(): CodexUsagePersistedState { + return { + schemaVersion: SCHEMA_VERSION, + worktreeFingerprint: null, + processedFiles: [], + sessions: [], + dailyAggregates: [], + scanState: { + enabled: false, + lastScanStartedAt: null, + lastScanCompletedAt: null, + lastScanError: null + } + } +} + +export function normalizePersistedState(state: CodexUsagePersistedState): CodexUsagePersistedState { + if (state.schemaVersion !== SCHEMA_VERSION) { + // Why: Orca-scoped Codex projections now depend on locationModelBreakdown. + // Reusing an older cache would silently serve wrong model/session rows + // until the next forced rescan, so schema changes must invalidate stale + // persisted analytics instead of best-effort patching partial data. + return getDefaultState() + } + return { + ...state, + sessions: state.sessions.map((session) => ({ + ...session, + locationModelBreakdown: session.locationModelBreakdown ?? [] + })) + } +} + +export function initCodexUsagePath(): void { + _codexUsageFile = join(app.getPath('userData'), 'orca-codex-usage.json') +} + +function getCodexUsageFile(): string { + if (!_codexUsageFile) { + _codexUsageFile = join(app.getPath('userData'), 'orca-codex-usage.json') + } + return _codexUsageFile +} + +function normalizeModelForPricing(model: string | null): string | null { + if (!model) { + return null + } + + const lower = model.toLowerCase() + if (lower === 'gpt-5' || lower === 'gpt-5-codex' || lower.startsWith('gpt-5.4')) { + return 'gpt-5' + } + if (lower.startsWith('gpt-5.2-codex')) { + return 'gpt-5.2-codex' + } + if (lower.startsWith('gpt-5.3-codex')) { + return 'gpt-5.3-codex' + } + return null +} + +function estimateCostUsd( + model: string | null, + inputTokens: number, + cachedInputTokens: number, + outputTokens: number +): number | null { + const normalized = normalizeModelForPricing(model) + if (!normalized) { + return null + } + const pricing = MODEL_PRICING[normalized] + const clampedCached = Math.min(cachedInputTokens, inputTokens) + // Why: Codex cached tokens are part of the input bucket. Charge uncached + // input on (input-cached) so cached tokens are not billed once at full input + // price and again at cache-read price. + const nonCachedInputTokens = Math.max(inputTokens - clampedCached, 0) + return ( + (nonCachedInputTokens * pricing.input + + clampedCached * pricing.cachedInput + + outputTokens * pricing.output) / + 1_000_000 + ) +} + +function getRangeCutoff(range: CodexUsageRange): string | null { + if (range === 'all') { + return null + } + const days = range === '7d' ? 7 : range === '30d' ? 30 : 90 + const now = new Date() + now.setHours(0, 0, 0, 0) + now.setDate(now.getDate() - (days - 1)) + const year = now.getFullYear() + const month = String(now.getMonth() + 1).padStart(2, '0') + const day = String(now.getDate()).padStart(2, '0') + return `${year}-${month}-${day}` +} + +function getLocalDay(timestamp: string): string | null { + const parsed = new Date(timestamp) + if (Number.isNaN(parsed.getTime())) { + return null + } + const year = parsed.getFullYear() + const month = String(parsed.getMonth() + 1).padStart(2, '0') + const day = String(parsed.getDate()).padStart(2, '0') + return `${year}-${month}-${day}` +} + +type CodexUsageWorktree = { + worktreeId: string + path: string + displayName: string +} + +type ScopedCodexUsageModelRow = { + modelKey: string + modelLabel: string + hasInferredPricing: boolean + eventCount: number + inputTokens: number + cachedInputTokens: number + outputTokens: number + reasoningOutputTokens: number + totalTokens: number +} + +function getWorktreeFingerprint(worktreesByRepo: Map): string { + const rows = [...worktreesByRepo.entries()] + .flatMap(([repoId, worktrees]) => + worktrees.map((worktree) => + JSON.stringify({ + repoId, + worktreeId: worktree.worktreeId, + path: worktree.path, + displayName: worktree.displayName + }) + ) + ) + .sort() + return JSON.stringify(rows) +} + +export class CodexUsageStore { + private state: CodexUsagePersistedState + private readonly store: Store + private scanPromise: Promise | null = null + + constructor(store: Store) { + this.store = store + this.state = this.load() + } + + private load(): CodexUsagePersistedState { + try { + const usageFile = getCodexUsageFile() + if (!existsSync(usageFile)) { + return getDefaultState() + } + const parsed = JSON.parse(readFileSync(usageFile, 'utf-8')) as CodexUsagePersistedState + return normalizePersistedState({ + ...getDefaultState(), + ...parsed, + scanState: { + ...getDefaultState().scanState, + ...parsed.scanState + } + }) + } catch (error) { + console.error('[codex-usage] Failed to load persisted state, starting fresh:', error) + return getDefaultState() + } + } + + private writeToDisk(): void { + const usageFile = getCodexUsageFile() + const dir = dirname(usageFile) + if (!existsSync(dir)) { + mkdirSync(dir, { recursive: true }) + } + const tmpFile = `${usageFile}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp` + writeFileSync(tmpFile, JSON.stringify(this.state, null, 2), 'utf-8') + renameSync(tmpFile, usageFile) + } + + async setEnabled(enabled: boolean): Promise { + this.state.scanState.enabled = enabled + this.writeToDisk() + return this.getScanState() + } + + getScanState(): CodexUsageScanState { + return { + ...this.state.scanState, + isScanning: this.scanPromise !== null, + hasAnyCodexData: this.state.sessions.length > 0 || this.state.dailyAggregates.length > 0 + } + } + + async refresh(force = false): Promise { + if (!this.state.scanState.enabled) { + return this.getScanState() + } + const currentWorktreeFingerprint = await this.getCurrentWorktreeFingerprint() + if (!force && this.state.scanState.lastScanCompletedAt) { + const ageMs = Date.now() - this.state.scanState.lastScanCompletedAt + if (ageMs < STALE_MS && this.state.worktreeFingerprint === currentWorktreeFingerprint) { + return this.getScanState() + } + } + await this.runScan() + return this.getScanState() + } + + private async runScan(): Promise { + if (this.scanPromise) { + await this.scanPromise + return + } + + this.state.scanState.lastScanStartedAt = Date.now() + this.state.scanState.lastScanError = null + this.writeToDisk() + + this.scanPromise = (async () => { + try { + const repos = this.store.getRepos() + const worktreesByRepo = await this.loadWorktreesByRepo(repos) + const worktreeFingerprint = getWorktreeFingerprint(worktreesByRepo) + const result = await scanCodexUsageFiles( + createWorktreeRefs(repos, worktreesByRepo), + this.state.worktreeFingerprint === worktreeFingerprint ? this.state.processedFiles : [] + ) + this.state.processedFiles = result.processedFiles + this.state.sessions = result.sessions + this.state.dailyAggregates = result.dailyAggregates + this.state.worktreeFingerprint = worktreeFingerprint + this.state.scanState.lastScanCompletedAt = Date.now() + this.state.scanState.lastScanError = null + this.writeToDisk() + } catch (error) { + this.state.scanState.lastScanError = error instanceof Error ? error.message : String(error) + this.writeToDisk() + } finally { + this.scanPromise = null + } + })() + + await this.scanPromise + } + + async getSummary(scope: CodexUsageScope, range: CodexUsageRange): Promise { + await this.refresh(false) + const filteredDaily = this.getFilteredDaily(scope, range) + const filteredSessions = this.getFilteredSessions(scope, range) + + let inputTokens = 0 + let cachedInputTokens = 0 + let outputTokens = 0 + let reasoningOutputTokens = 0 + let totalTokens = 0 + let events = 0 + let estimatedCostUsd = 0 + let hasAnyBillableCost = false + const byModel = new Map() + const byProject = new Map() + + for (const row of filteredDaily) { + inputTokens += row.inputTokens + cachedInputTokens += row.cachedInputTokens + outputTokens += row.outputTokens + reasoningOutputTokens += row.reasoningOutputTokens + totalTokens += row.totalTokens + events += row.eventCount + byModel.set( + row.model ?? 'Unknown model', + (byModel.get(row.model ?? 'Unknown model') ?? 0) + row.totalTokens + ) + byProject.set(row.projectLabel, (byProject.get(row.projectLabel) ?? 0) + row.totalTokens) + const cost = estimateCostUsd( + row.model, + row.inputTokens, + row.cachedInputTokens, + row.outputTokens + ) + if (cost !== null) { + hasAnyBillableCost = true + estimatedCostUsd += cost + } + } + + const topModel = + [...byModel.entries()].sort((left, right) => right[1] - left[1])[0]?.[0] ?? null + const topProject = + [...byProject.entries()].sort((left, right) => right[1] - left[1])[0]?.[0] ?? null + + return { + scope, + range, + sessions: filteredSessions.length, + events, + inputTokens, + cachedInputTokens, + outputTokens, + reasoningOutputTokens, + totalTokens, + estimatedCostUsd: hasAnyBillableCost ? estimatedCostUsd : null, + topModel, + topProject, + hasAnyCodexData: filteredSessions.length > 0 || filteredDaily.length > 0 + } + } + + async getDaily(scope: CodexUsageScope, range: CodexUsageRange): Promise { + await this.refresh(false) + const byDay = new Map() + for (const row of this.getFilteredDaily(scope, range)) { + const existing = byDay.get(row.day) ?? { + day: row.day, + inputTokens: 0, + cachedInputTokens: 0, + outputTokens: 0, + reasoningOutputTokens: 0, + totalTokens: 0 + } + existing.inputTokens += row.inputTokens + existing.cachedInputTokens += row.cachedInputTokens + existing.outputTokens += row.outputTokens + existing.reasoningOutputTokens += row.reasoningOutputTokens + existing.totalTokens += row.totalTokens + byDay.set(row.day, existing) + } + return [...byDay.values()].sort((left, right) => left.day.localeCompare(right.day)) + } + + async getBreakdown( + scope: CodexUsageScope, + range: CodexUsageRange, + kind: CodexUsageBreakdownKind + ): Promise { + await this.refresh(false) + const rows = new Map() + const filteredDaily = this.getFilteredDaily(scope, range) + const filteredSessions = this.getFilteredSessions(scope, range) + + for (const daily of filteredDaily) { + const key = kind === 'model' ? (daily.model ?? 'unknown') : daily.projectKey + const label = kind === 'model' ? (daily.model ?? 'Unknown model') : daily.projectLabel + const existing = rows.get(key) ?? { + key, + label, + sessions: 0, + events: 0, + inputTokens: 0, + cachedInputTokens: 0, + outputTokens: 0, + reasoningOutputTokens: 0, + totalTokens: 0, + estimatedCostUsd: null, + hasInferredPricing: false + } + existing.events += daily.eventCount + existing.inputTokens += daily.inputTokens + existing.cachedInputTokens += daily.cachedInputTokens + existing.outputTokens += daily.outputTokens + existing.reasoningOutputTokens += daily.reasoningOutputTokens + existing.totalTokens += daily.totalTokens + existing.hasInferredPricing ||= daily.hasInferredPricing + rows.set(key, existing) + } + + for (const session of filteredSessions) { + if (kind === 'model') { + const seen = new Set() + for (const model of this.getScopedSessionModels(session, scope)) { + if (seen.has(model.modelKey)) { + continue + } + seen.add(model.modelKey) + const row = rows.get(model.modelKey) + if (row) { + row.sessions++ + } + } + continue + } + const matchingLocations = session.locationBreakdown.filter((entry) => + scope === 'all' ? true : entry.worktreeId !== null + ) + const seen = new Set() + for (const location of matchingLocations) { + if (seen.has(location.locationKey)) { + continue + } + seen.add(location.locationKey) + const row = rows.get(location.locationKey) + if (row) { + row.sessions++ + } + } + } + + for (const row of rows.values()) { + row.estimatedCostUsd = estimateCostUsd( + kind === 'model' ? row.key : null, + row.inputTokens, + row.cachedInputTokens, + row.outputTokens + ) + } + + return [...rows.values()].sort((left, right) => right.totalTokens - left.totalTokens) + } + + async getRecentSessions( + scope: CodexUsageScope, + range: CodexUsageRange, + limit = 12 + ): Promise { + await this.refresh(false) + return this.getFilteredSessions(scope, range) + .slice(0, limit) + .map((session) => { + const matchingLocations = session.locationBreakdown.filter((entry) => + scope === 'all' ? true : entry.worktreeId !== null + ) + const scopedLocations = + matchingLocations.length > 0 ? matchingLocations : session.locationBreakdown + const totals = scopedLocations.reduce( + (acc, entry) => { + acc.events += entry.eventCount + acc.inputTokens += entry.inputTokens + acc.cachedInputTokens += entry.cachedInputTokens + acc.outputTokens += entry.outputTokens + acc.reasoningOutputTokens += entry.reasoningOutputTokens + acc.totalTokens += entry.totalTokens + acc.hasInferredPricing ||= entry.hasInferredPricing + return acc + }, + { + events: 0, + inputTokens: 0, + cachedInputTokens: 0, + outputTokens: 0, + reasoningOutputTokens: 0, + totalTokens: 0, + hasInferredPricing: false + } + ) + const durationMinutes = Math.max( + 0, + Math.round( + (new Date(session.lastTimestamp).getTime() - + new Date(session.firstTimestamp).getTime()) / + 60_000 + ) + ) + return { + sessionId: session.sessionId, + lastActiveAt: session.lastTimestamp, + durationMinutes, + projectLabel: + scopedLocations.length > 1 + ? 'Multiple locations' + : (scopedLocations[0]?.projectLabel ?? session.primaryProjectLabel), + model: this.getScopedSessionPrimaryModel(session, scope), + events: totals.events, + inputTokens: totals.inputTokens, + cachedInputTokens: totals.cachedInputTokens, + outputTokens: totals.outputTokens, + reasoningOutputTokens: totals.reasoningOutputTokens, + totalTokens: totals.totalTokens, + hasInferredPricing: session.hasInferredPricing || totals.hasInferredPricing + } + }) + } + + private getFilteredDaily(scope: CodexUsageScope, range: CodexUsageRange) { + const cutoff = getRangeCutoff(range) + return this.state.dailyAggregates.filter((entry) => { + if (cutoff && entry.day < cutoff) { + return false + } + if (scope === 'orca' && entry.worktreeId === null) { + return false + } + return true + }) + } + + private getFilteredSessions(scope: CodexUsageScope, range: CodexUsageRange) { + const cutoff = getRangeCutoff(range) + return this.state.sessions.filter((session) => { + const day = getLocalDay(session.lastTimestamp) + if (!day) { + return false + } + if (cutoff && day < cutoff) { + return false + } + if (scope === 'orca') { + return session.locationBreakdown.some((entry) => entry.worktreeId !== null) + } + return true + }) + } + + private getScopedSessionModels( + session: CodexUsagePersistedState['sessions'][number], + scope: CodexUsageScope + ): ScopedCodexUsageModelRow[] { + if (scope === 'all' || session.locationModelBreakdown.length === 0) { + return session.modelBreakdown + } + + const rows = new Map() + for (const entry of session.locationModelBreakdown) { + if (entry.worktreeId === null) { + continue + } + const existing = rows.get(entry.modelKey) ?? { + modelKey: entry.modelKey, + modelLabel: entry.modelLabel, + hasInferredPricing: false, + eventCount: 0, + inputTokens: 0, + cachedInputTokens: 0, + outputTokens: 0, + reasoningOutputTokens: 0, + totalTokens: 0 + } + existing.hasInferredPricing ||= entry.hasInferredPricing + existing.eventCount += entry.eventCount + existing.inputTokens += entry.inputTokens + existing.cachedInputTokens += entry.cachedInputTokens + existing.outputTokens += entry.outputTokens + existing.reasoningOutputTokens += entry.reasoningOutputTokens + existing.totalTokens += entry.totalTokens + rows.set(entry.modelKey, existing) + } + return [...rows.values()].sort((left, right) => right.totalTokens - left.totalTokens) + } + + private getScopedSessionPrimaryModel( + session: CodexUsagePersistedState['sessions'][number], + scope: CodexUsageScope + ): string | null { + const scopedModels = this.getScopedSessionModels(session, scope) + if (scopedModels.length === 0) { + return session.primaryModel + } + if (scopedModels.length === 1) { + return scopedModels[0]?.modelLabel ?? null + } + return 'Mixed models' + } + + private async getCurrentWorktreeFingerprint(): Promise { + const repos = this.store.getRepos() + const worktreesByRepo = await this.loadWorktreesByRepo(repos) + return getWorktreeFingerprint(worktreesByRepo) + } + + private async loadWorktreesByRepo(repos: Repo[]): Promise> { + const worktreesByRepo = new Map() + + for (const repo of repos) { + const gitWorktrees = await listRepoWorktrees(repo) + const mapped = gitWorktrees.map((worktree) => { + const worktreeId = `${repo.id}::${worktree.path}` + const meta = this.store.getWorktreeMeta(worktreeId) + const merged = mergeWorktree(repo.id, worktree, meta, repo.displayName) + return { + worktreeId, + path: worktree.path, + displayName: merged.displayName || getDefaultWorktreeLabel(worktree.path) + } + }) + worktreesByRepo.set(repo.id, mapped) + } + + return worktreesByRepo + } +} diff --git a/src/main/codex-usage/types.ts b/src/main/codex-usage/types.ts new file mode 100644 index 000000000..4b54c6f6c --- /dev/null +++ b/src/main/codex-usage/types.ts @@ -0,0 +1,124 @@ +export type CodexUsageProcessedFile = { + path: string + mtimeMs: number + size: number +} + +export type CodexUsageLocationBreakdown = { + locationKey: string + projectLabel: string + repoId: string | null + worktreeId: string | null + eventCount: number + inputTokens: number + cachedInputTokens: number + outputTokens: number + reasoningOutputTokens: number + totalTokens: number + hasInferredPricing: boolean +} + +export type CodexUsageModelBreakdown = { + modelKey: string + modelLabel: string + hasInferredPricing: boolean + eventCount: number + inputTokens: number + cachedInputTokens: number + outputTokens: number + reasoningOutputTokens: number + totalTokens: number +} + +export type CodexUsageLocationModelBreakdown = { + locationKey: string + modelKey: string + modelLabel: string + repoId: string | null + worktreeId: string | null + eventCount: number + inputTokens: number + cachedInputTokens: number + outputTokens: number + reasoningOutputTokens: number + totalTokens: number + hasInferredPricing: boolean +} + +export type CodexUsageSession = { + 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 + hasInferredPricing: boolean + locationBreakdown: CodexUsageLocationBreakdown[] + modelBreakdown: CodexUsageModelBreakdown[] + locationModelBreakdown: CodexUsageLocationModelBreakdown[] +} + +export type CodexUsageDailyAggregate = { + 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 + hasInferredPricing: boolean +} + +export type CodexUsagePersistedFile = CodexUsageProcessedFile & { + sessions: CodexUsageSession[] + dailyAggregates: CodexUsageDailyAggregate[] +} + +export type CodexUsagePersistedState = { + schemaVersion: number + worktreeFingerprint: string | null + processedFiles: CodexUsagePersistedFile[] + sessions: CodexUsageSession[] + dailyAggregates: CodexUsageDailyAggregate[] + scanState: { + enabled: boolean + lastScanStartedAt: number | null + lastScanCompletedAt: number | null + lastScanError: string | null + } +} + +export type CodexUsageParsedEvent = { + sessionId: string + timestamp: string + model: string | null + cwd: string | null + hasInferredPricing: boolean + inputTokens: number + cachedInputTokens: number + outputTokens: number + reasoningOutputTokens: number + totalTokens: number +} + +export type CodexUsageAttributedEvent = CodexUsageParsedEvent & { + day: string + projectKey: string + projectLabel: string + repoId: string | null + worktreeId: string | null +} diff --git a/src/main/index.ts b/src/main/index.ts index 2f06f048e..a45448f9b 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -4,6 +4,7 @@ import devIcon from '../../resources/icon-dev.png?asset' import { Store, initDataPath } from './persistence' import { StatsCollector, initStatsPath } from './stats/collector' import { ClaudeUsageStore, initClaudeUsagePath } from './claude-usage/store' +import { CodexUsageStore, initCodexUsagePath } from './codex-usage/store' import { killAllPty } from './ipc/pty' import { registerCoreHandlers } from './ipc/register-core-handlers' import { triggerStartupNotificationRegistration } from './ipc/notifications' @@ -26,6 +27,7 @@ let mainWindow: BrowserWindow | null = null let store: Store | null = null let stats: StatsCollector | null = null let claudeUsage: ClaudeUsageStore | null = null +let codexUsage: CodexUsageStore | null = null let runtime: OrcaRuntimeService | null = null let runtimeRpc: OrcaRuntimeRpcServer | null = null @@ -42,6 +44,7 @@ initDataPath() // before app.setName changes it. See persistence.ts:20-28. initStatsPath() initClaudeUsagePath() +initCodexUsagePath() enableMainProcessGpuFeatures() function openMainWindow(): BrowserWindow { @@ -57,9 +60,12 @@ function openMainWindow(): BrowserWindow { if (!claudeUsage) { throw new Error('Claude usage store must be initialized before opening the main window') } + if (!codexUsage) { + throw new Error('Codex usage store must be initialized before opening the main window') + } const window = createMainWindow(store) - registerCoreHandlers(store, runtime, stats, claudeUsage, window.webContents.id) + registerCoreHandlers(store, runtime, stats, claudeUsage, codexUsage, window.webContents.id) attachMainWindowServices(window, store, runtime) window.on('closed', () => { if (mainWindow === window) { @@ -86,6 +92,7 @@ app.whenReady().then(async () => { store = new Store() stats = new StatsCollector() claudeUsage = new ClaudeUsageStore(store) + codexUsage = new CodexUsageStore(store) runtime = new OrcaRuntimeService(store, stats) nativeTheme.themeSource = store.getSettings().theme ?? 'system' diff --git a/src/main/ipc/codex-usage.ts b/src/main/ipc/codex-usage.ts new file mode 100644 index 000000000..d94c5af39 --- /dev/null +++ b/src/main/ipc/codex-usage.ts @@ -0,0 +1,39 @@ +import { ipcMain } from 'electron' +import type { CodexUsageStore } from '../codex-usage/store' +import type { + CodexUsageBreakdownKind, + CodexUsageRange, + CodexUsageScope +} from '../../shared/codex-usage-types' + +export function registerCodexUsageHandlers(codexUsage: CodexUsageStore): void { + ipcMain.handle('codexUsage:getScanState', () => codexUsage.getScanState()) + ipcMain.handle('codexUsage:setEnabled', (_event, args: { enabled: boolean }) => + codexUsage.setEnabled(args.enabled) + ) + ipcMain.handle('codexUsage:refresh', (_event, args?: { force?: boolean }) => + codexUsage.refresh(args?.force ?? false) + ) + ipcMain.handle( + 'codexUsage:getSummary', + (_event, args: { scope: CodexUsageScope; range: CodexUsageRange }) => + codexUsage.getSummary(args.scope, args.range) + ) + ipcMain.handle( + 'codexUsage:getDaily', + (_event, args: { scope: CodexUsageScope; range: CodexUsageRange }) => + codexUsage.getDaily(args.scope, args.range) + ) + ipcMain.handle( + 'codexUsage:getBreakdown', + ( + _event, + args: { scope: CodexUsageScope; range: CodexUsageRange; kind: CodexUsageBreakdownKind } + ) => codexUsage.getBreakdown(args.scope, args.range, args.kind) + ) + ipcMain.handle( + 'codexUsage:getRecentSessions', + (_event, args: { scope: CodexUsageScope; range: CodexUsageRange; limit?: number }) => + codexUsage.getRecentSessions(args.scope, args.range, args.limit) + ) +} diff --git a/src/main/ipc/register-core-handlers.test.ts b/src/main/ipc/register-core-handlers.test.ts index 0203331ad..9143f284d 100644 --- a/src/main/ipc/register-core-handlers.test.ts +++ b/src/main/ipc/register-core-handlers.test.ts @@ -4,6 +4,7 @@ const { registerCliHandlersMock, registerPreflightHandlersMock, registerClaudeUsageHandlersMock, + registerCodexUsageHandlersMock, registerGitHubHandlersMock, registerStatsHandlersMock, registerNotificationHandlersMock, @@ -21,6 +22,7 @@ const { registerCliHandlersMock: vi.fn(), registerPreflightHandlersMock: vi.fn(), registerClaudeUsageHandlersMock: vi.fn(), + registerCodexUsageHandlersMock: vi.fn(), registerGitHubHandlersMock: vi.fn(), registerStatsHandlersMock: vi.fn(), registerNotificationHandlersMock: vi.fn(), @@ -48,6 +50,10 @@ vi.mock('./claude-usage', () => ({ registerClaudeUsageHandlers: registerClaudeUsageHandlersMock })) +vi.mock('./codex-usage', () => ({ + registerCodexUsageHandlers: registerCodexUsageHandlersMock +})) + vi.mock('./github', () => ({ registerGitHubHandlers: registerGitHubHandlersMock })) @@ -101,6 +107,7 @@ describe('registerCoreHandlers', () => { registerCliHandlersMock.mockReset() registerPreflightHandlersMock.mockReset() registerClaudeUsageHandlersMock.mockReset() + registerCodexUsageHandlersMock.mockReset() registerGitHubHandlersMock.mockReset() registerStatsHandlersMock.mockReset() registerNotificationHandlersMock.mockReset() @@ -121,10 +128,18 @@ describe('registerCoreHandlers', () => { const runtime = { marker: 'runtime' } const stats = { marker: 'stats' } const claudeUsage = { marker: 'claudeUsage' } + const codexUsage = { marker: 'codexUsage' } - registerCoreHandlers(store as never, runtime as never, stats as never, claudeUsage as never) + registerCoreHandlers( + store as never, + runtime as never, + stats as never, + claudeUsage as never, + codexUsage as never + ) expect(registerClaudeUsageHandlersMock).toHaveBeenCalledWith(claudeUsage) + expect(registerCodexUsageHandlersMock).toHaveBeenCalledWith(codexUsage) expect(registerGitHubHandlersMock).toHaveBeenCalledWith(store, stats) expect(registerStatsHandlersMock).toHaveBeenCalledWith(stats) expect(registerNotificationHandlersMock).toHaveBeenCalledWith(store) diff --git a/src/main/ipc/register-core-handlers.ts b/src/main/ipc/register-core-handlers.ts index 7f5276226..d42f1e1b6 100644 --- a/src/main/ipc/register-core-handlers.ts +++ b/src/main/ipc/register-core-handlers.ts @@ -5,6 +5,7 @@ import type { OrcaRuntimeService } from '../runtime/orca-runtime' import type { StatsCollector } from '../stats/collector' import { registerFilesystemHandlers } from './filesystem' import { registerClaudeUsageHandlers } from './claude-usage' +import { registerCodexUsageHandlers } from './codex-usage' import { registerGitHubHandlers } from './github' import { registerStatsHandlers } from './stats' import { registerRuntimeHandlers } from './runtime' @@ -21,18 +22,21 @@ import { registerUpdaterHandlers } from '../window/attach-main-window-services' import type { ClaudeUsageStore } from '../claude-usage/store' +import type { CodexUsageStore } from '../codex-usage/store' export function registerCoreHandlers( store: Store, runtime: OrcaRuntimeService, stats: StatsCollector, claudeUsage: ClaudeUsageStore, + codexUsage: CodexUsageStore, mainWindowWebContentsId: number | null = null ): void { setTrustedBrowserRendererWebContentsId(mainWindowWebContentsId) registerCliHandlers() registerPreflightHandlers() registerClaudeUsageHandlers(claudeUsage) + registerCodexUsageHandlers(codexUsage) registerGitHubHandlers(store, stats) registerStatsHandlers(stats) registerNotificationHandlers(store) diff --git a/src/preload/api-types.d.ts b/src/preload/api-types.d.ts index c614d481b..8db49e63b 100644 --- a/src/preload/api-types.d.ts +++ b/src/preload/api-types.d.ts @@ -1,3 +1,4 @@ +/* eslint-disable max-lines -- Why: the preload contract is intentionally centralized in one declaration file so renderer and preload stay in lockstep when IPC surfaces change. */ import type { BrowserLoadError, CreateWorktreeResult, @@ -37,6 +38,16 @@ import type { ClaudeUsageSessionRow, ClaudeUsageSummary } from '../../shared/claude-usage-types' +import type { + CodexUsageBreakdownKind, + CodexUsageBreakdownRow, + CodexUsageDailyPoint, + CodexUsageRange, + CodexUsageScanState, + CodexUsageScope, + CodexUsageSessionRow, + CodexUsageSummary +} from '../../shared/codex-usage-types' export type BrowserApi = { registerGuest: (args: { browserTabId: string; webContentsId: number }) => Promise @@ -84,6 +95,30 @@ export type ClaudeUsageApi = { }) => Promise } +export type CodexUsageApi = { + getScanState: () => Promise + setEnabled: (args: { enabled: boolean }) => Promise + refresh: (args?: { force?: boolean }) => Promise + getSummary: (args: { + scope: CodexUsageScope + range: CodexUsageRange + }) => Promise + getDaily: (args: { + scope: CodexUsageScope + range: CodexUsageRange + }) => Promise + getBreakdown: (args: { + scope: CodexUsageScope + range: CodexUsageRange + kind: CodexUsageBreakdownKind + }) => Promise + getRecentSessions: (args: { + scope: CodexUsageScope + range: CodexUsageRange + limit?: number + }) => Promise +} + export type PreloadApi = { repos: { list: () => Promise @@ -217,6 +252,7 @@ export type PreloadApi = { } stats: StatsApi claudeUsage: ClaudeUsageApi + codexUsage: CodexUsageApi fs: { readDir: (args: { dirPath: string }) => Promise readFile: (args: { diff --git a/src/preload/index.ts b/src/preload/index.ts index 483371078..6f6e5d10a 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -590,6 +590,22 @@ const api = { ipcRenderer.invoke('claudeUsage:getRecentSessions', args) }, + codexUsage: { + getScanState: (): Promise => ipcRenderer.invoke('codexUsage:getScanState'), + setEnabled: (args: { enabled: boolean }): Promise => + ipcRenderer.invoke('codexUsage:setEnabled', args), + refresh: (args?: { force?: boolean }): Promise => + ipcRenderer.invoke('codexUsage:refresh', args), + getSummary: (args: { scope: string; range: string }): Promise => + ipcRenderer.invoke('codexUsage:getSummary', args), + getDaily: (args: { scope: string; range: string }): Promise => + ipcRenderer.invoke('codexUsage:getDaily', args), + getBreakdown: (args: { scope: string; range: string; kind: string }): Promise => + ipcRenderer.invoke('codexUsage:getBreakdown', args), + getRecentSessions: (args: { scope: string; range: string; limit?: number }): Promise => + ipcRenderer.invoke('codexUsage:getRecentSessions', args) + }, + runtime: { syncWindowGraph: (graph: RuntimeSyncWindowGraph): Promise => ipcRenderer.invoke('runtime:syncWindowGraph', graph), diff --git a/src/renderer/src/components/stats/ClaudeUsageLoadingState.tsx b/src/renderer/src/components/stats/ClaudeUsageLoadingState.tsx index 5a3ea1b4a..e459ab9c6 100644 --- a/src/renderer/src/components/stats/ClaudeUsageLoadingState.tsx +++ b/src/renderer/src/components/stats/ClaudeUsageLoadingState.tsx @@ -1,11 +1,21 @@ import { RefreshCw } from 'lucide-react' -export function ClaudeUsageLoadingState(): React.JSX.Element { +type ClaudeUsageLoadingStateProps = { + title?: string + summaryCardCount?: number + summaryGridClassName?: string +} + +export function ClaudeUsageLoadingState({ + title = 'Claude Usage Tracking', + summaryCardCount = 8, + summaryGridClassName = 'md:grid-cols-2 xl:grid-cols-4' +}: ClaudeUsageLoadingStateProps): React.JSX.Element { return (
-

Claude Usage Tracking

+

{title}

@@ -18,8 +28,8 @@ export function ClaudeUsageLoadingState(): React.JSX.Element {
-
- {Array.from({ length: 6 }, (_, index) => ( +
+ {Array.from({ length: summaryCardCount }, (_, index) => (
diff --git a/src/renderer/src/components/stats/ClaudeUsagePane.tsx b/src/renderer/src/components/stats/ClaudeUsagePane.tsx index 45980d12f..63f4779c1 100644 --- a/src/renderer/src/components/stats/ClaudeUsagePane.tsx +++ b/src/renderer/src/components/stats/ClaudeUsagePane.tsx @@ -102,7 +102,7 @@ export function ClaudeUsagePane(): React.JSX.Element {

Claude Usage Tracking

- Reads local Claude usage logs to show token, cache, model, and session stats. + Reads local Claude usage logs to show token, model, and session stats.

+
+
+ ) + } + + if (!summary && (scanState.isScanning || scanState.lastScanCompletedAt === null)) { + return ( + + ) + } + + const hasAnyData = summary?.hasAnyCodexData ?? scanState.hasAnyCodexData + + return ( +
+
+
+

Codex Usage Tracking

+

+ {formatUpdatedAt(scanState.lastScanCompletedAt)} + {scanState.lastScanError ? ` • Last scan error: ${scanState.lastScanError}` : ''} +

+
+
+ + + + + + + + + + Filters + + + + + Scope + void setCodexUsageScope(value as CodexUsageScope)} + > + {SCOPE_OPTIONS.map((option) => ( + + {option.label} + + ))} + + + Range + void setCodexUsageRange(value as CodexUsageRange)} + > + {RANGE_OPTIONS.map((option) => ( + + {RANGE_LABELS[option]} + + ))} + + + + + + + + + + Refresh + + + + +
+
+ +
+

+ {SCOPE_OPTIONS.find((option) => option.value === scope)?.label} • {RANGE_LABELS[range]} +

+
+ + {!hasAnyData ? ( +
+ No local Codex usage found yet for this scope. +
+ ) : ( + <> +
+ } + /> + } + /> + } + /> + } + /> + } + /> + } + /> +
+

+ Reasoning tokens are shown for visibility, but cost is calculated from uncached input, + cached input, and output only. +

+ + + +
+
+
+

By model

+

+ Top model: {summary?.topModel ?? 'n/a'} +

+
+
+ {modelBreakdown.slice(0, 5).map((row) => ( +
+
+ {row.label} + + {formatTokens(row.totalTokens)} + +
+
+ {row.sessions} sessions • {row.events} events + {row.hasInferredPricing ? ' • inferred pricing' : ''} +
+
+ ))} +
+
+ +
+
+

By project

+

+ Top project: {summary?.topProject ?? 'n/a'} +

+
+
+ {projectBreakdown.slice(0, 5).map((row) => ( +
+
+ {row.label} + + {formatTokens(row.totalTokens)} + +
+
+ {row.sessions} sessions • {row.events} events +
+
+ ))} +
+
+
+ +
+
+

Recent sessions

+

+ Most recent local Codex sessions in this scope. +

+
+
+ + + + + + + + + + + + + + {recentSessions.map((row) => ( + + + + + + + + + + ))} + +
Last activeProjectModelEventsInputOutputTotal
+ {formatSessionTime(row.lastActiveAt)} + {row.projectLabel} + {row.model ?? 'Unknown'} + {row.hasInferredPricing ? ' *' : ''} + {row.events} + {formatTokens(row.inputTokens)} + + {formatTokens(row.outputTokens)} + + {formatTokens(row.totalTokens)} +
+
+
+ + )} +
+ ) +} diff --git a/src/renderer/src/components/stats/StatsPane.tsx b/src/renderer/src/components/stats/StatsPane.tsx index 3e301ce9b..6722489a9 100644 --- a/src/renderer/src/components/stats/StatsPane.tsx +++ b/src/renderer/src/components/stats/StatsPane.tsx @@ -1,14 +1,17 @@ -import { useEffect } from 'react' +import { useEffect, useState } from 'react' import { Bot, Clock, GitPullRequest } from 'lucide-react' import { useAppStore } from '../../store' import { StatCard } from './StatCard' import { ClaudeUsagePane } from './ClaudeUsagePane' +import { CodexUsagePane } from './CodexUsagePane' import type { SettingsSearchEntry } from '../settings/settings-search' +import { cn } from '@/lib/utils' export const STATS_PANE_SEARCH_ENTRIES: SettingsSearchEntry[] = [ { title: 'Stats & Usage', - description: 'Orca stats plus Claude usage analytics, tokens, cache, and sessions.', + description: + 'Orca stats plus Claude and Codex usage analytics, tokens, cache, models, and sessions.', keywords: [ 'stats', 'usage', @@ -18,6 +21,7 @@ export const STATS_PANE_SEARCH_ENTRIES: SettingsSearchEntry[] = [ 'time', 'tracking', 'claude', + 'codex', 'tokens', 'cache' ] @@ -55,49 +59,81 @@ function formatTrackingSince(timestamp: number | null): string { export function StatsPane(): React.JSX.Element { const summary = useAppStore((s) => s.statsSummary) const fetchStatsSummary = useAppStore((s) => s.fetchStatsSummary) + const [activeUsageTab, setActiveUsageTab] = useState<'claude' | 'codex'>('claude') useEffect(() => { void fetchStatsSummary() }, [fetchStatsSummary]) - if (!summary) { - return - } - - const trackingSince = formatTrackingSince(summary.firstEventAt) - return (
-
- {summary.totalAgentsSpawned === 0 && summary.totalPRsCreated === 0 ? ( -
- Start your first agent to begin tracking -
- ) : ( - <> -
- } - /> - } - /> - } - /> + {summary ? ( +
+ {summary.totalAgentsSpawned === 0 && summary.totalPRsCreated === 0 ? ( +
+ Start your first agent to begin tracking
- {trackingSince &&

{trackingSince}

} - - )} -
+ ) : ( + <> +
+ } + /> + } + /> + } + /> +
+ {formatTrackingSince(summary.firstEventAt) && ( +

+ {formatTrackingSince(summary.firstEventAt)} +

+ )} + + )} +
+ ) : null} - +
+
+

Usage Analytics

+
+ {(['claude', 'codex'] as const).map((tab) => ( + + ))} +
+
+ + {/* Why: the Stats section lives inside the scroll-tracked settings page. Keeping only the + active panel mounted avoids hidden tab-content layout/focus churn that produced a visible + vertical jitter below the usage card when switching disabled providers. */} +
{activeUsageTab === 'claude' ? : }
+
) } diff --git a/src/renderer/src/store/index.ts b/src/renderer/src/store/index.ts index c1819f32b..79939a46c 100644 --- a/src/renderer/src/store/index.ts +++ b/src/renderer/src/store/index.ts @@ -10,6 +10,7 @@ import { createGitHubSlice } from './slices/github' import { createEditorSlice } from './slices/editor' import { createStatsSlice } from './slices/stats' import { createClaudeUsageSlice } from './slices/claude-usage' +import { createCodexUsageSlice } from './slices/codex-usage' import { createBrowserSlice } from './slices/browser' export const useAppStore = create()((...a) => ({ @@ -23,6 +24,7 @@ export const useAppStore = create()((...a) => ({ ...createEditorSlice(...a), ...createStatsSlice(...a), ...createClaudeUsageSlice(...a), + ...createCodexUsageSlice(...a), ...createBrowserSlice(...a) })) diff --git a/src/renderer/src/store/slices/codex-usage.ts b/src/renderer/src/store/slices/codex-usage.ts new file mode 100644 index 000000000..cdcd91396 --- /dev/null +++ b/src/renderer/src/store/slices/codex-usage.ts @@ -0,0 +1,154 @@ +import type { StateCreator } from 'zustand' +import type { + CodexUsageBreakdownRow, + CodexUsageDailyPoint, + CodexUsageRange, + CodexUsageScanState, + CodexUsageScope, + CodexUsageSessionRow, + CodexUsageSummary +} from '../../../../shared/codex-usage-types' +import type { AppState } from '../types' + +export type CodexUsageSlice = { + codexUsageScope: CodexUsageScope + codexUsageRange: CodexUsageRange + codexUsageScanState: CodexUsageScanState | null + codexUsageSummary: CodexUsageSummary | null + codexUsageDaily: CodexUsageDailyPoint[] + codexUsageModelBreakdown: CodexUsageBreakdownRow[] + codexUsageProjectBreakdown: CodexUsageBreakdownRow[] + codexUsageRecentSessions: CodexUsageSessionRow[] + setCodexUsageEnabled: (enabled: boolean) => Promise + setCodexUsageScope: (scope: CodexUsageScope) => Promise + setCodexUsageRange: (range: CodexUsageRange) => Promise + fetchCodexUsage: (opts?: { forceRefresh?: boolean }) => Promise + enableCodexUsage: () => Promise + refreshCodexUsage: () => Promise +} + +export const createCodexUsageSlice: StateCreator = ( + set, + get +) => ({ + codexUsageScope: 'orca', + codexUsageRange: '30d', + codexUsageScanState: null, + codexUsageSummary: null, + codexUsageDaily: [], + codexUsageModelBreakdown: [], + codexUsageProjectBreakdown: [], + codexUsageRecentSessions: [], + + setCodexUsageEnabled: async (enabled) => { + try { + const nextScanState = (await window.api.codexUsage.setEnabled({ + enabled + })) as CodexUsageScanState + set({ + codexUsageScanState: enabled + ? { + ...nextScanState, + isScanning: true, + lastScanCompletedAt: null, + lastScanError: null + } + : nextScanState, + codexUsageSummary: null, + codexUsageDaily: [], + codexUsageModelBreakdown: [], + codexUsageProjectBreakdown: [], + codexUsageRecentSessions: [] + }) + if (enabled) { + await get().fetchCodexUsage({ forceRefresh: true }) + } + } catch (error) { + console.error('Failed to update Codex usage setting:', error) + } + }, + + setCodexUsageScope: async (scope) => { + set({ codexUsageScope: scope }) + await get().fetchCodexUsage() + }, + + setCodexUsageRange: async (range) => { + set({ codexUsageRange: range }) + await get().fetchCodexUsage() + }, + + fetchCodexUsage: async (opts) => { + try { + const scanState = (await window.api.codexUsage.getScanState()) as CodexUsageScanState + const currentScanState = get().codexUsageScanState + const shouldPreserveLoadingState = + opts?.forceRefresh === true && + currentScanState?.enabled === true && + get().codexUsageSummary === null + set({ + codexUsageScanState: shouldPreserveLoadingState + ? { + ...scanState, + isScanning: true, + lastScanCompletedAt: null, + lastScanError: null + } + : scanState + }) + if (!scanState.enabled) { + return + } + + const nextScanState = (await window.api.codexUsage.refresh({ + force: opts?.forceRefresh ?? false + })) as CodexUsageScanState + const { codexUsageScope, codexUsageRange } = get() + + const [summary, daily, modelBreakdown, projectBreakdown, recentSessions] = await Promise.all([ + window.api.codexUsage.getSummary({ + scope: codexUsageScope, + range: codexUsageRange + }) as Promise, + window.api.codexUsage.getDaily({ + scope: codexUsageScope, + range: codexUsageRange + }) as Promise, + window.api.codexUsage.getBreakdown({ + scope: codexUsageScope, + range: codexUsageRange, + kind: 'model' + }) as Promise, + window.api.codexUsage.getBreakdown({ + scope: codexUsageScope, + range: codexUsageRange, + kind: 'project' + }) as Promise, + window.api.codexUsage.getRecentSessions({ + scope: codexUsageScope, + range: codexUsageRange, + limit: 10 + }) as Promise + ]) + + set({ + codexUsageScanState: nextScanState, + codexUsageSummary: summary, + codexUsageDaily: daily, + codexUsageModelBreakdown: modelBreakdown, + codexUsageProjectBreakdown: projectBreakdown, + codexUsageRecentSessions: recentSessions + }) + } catch (error) { + console.error('Failed to fetch Codex usage:', error) + } + }, + + enableCodexUsage: async () => { + await get().setCodexUsageEnabled(true) + }, + + refreshCodexUsage: async () => { + await get().fetchCodexUsage({ forceRefresh: true }) + } +}) diff --git a/src/renderer/src/store/slices/store-session-cascades.test.ts b/src/renderer/src/store/slices/store-session-cascades.test.ts index 138cc8d5f..c4d21c3f8 100644 --- a/src/renderer/src/store/slices/store-session-cascades.test.ts +++ b/src/renderer/src/store/slices/store-session-cascades.test.ts @@ -62,6 +62,22 @@ const mockApi = { getDaily: vi.fn().mockResolvedValue([]), getBreakdown: vi.fn().mockResolvedValue([]), getRecentSessions: vi.fn().mockResolvedValue([]) + }, + codexUsage: { + getScanState: vi.fn().mockResolvedValue({ + enabled: false, + isScanning: false, + lastScanStartedAt: null, + lastScanCompletedAt: null, + lastScanError: null, + hasAnyCodexData: false + }), + setEnabled: vi.fn().mockResolvedValue({}), + refresh: vi.fn().mockResolvedValue({}), + getSummary: vi.fn().mockResolvedValue(null), + getDaily: vi.fn().mockResolvedValue([]), + getBreakdown: vi.fn().mockResolvedValue([]), + getRecentSessions: vi.fn().mockResolvedValue([]) } } @@ -78,6 +94,7 @@ import { createGitHubSlice } from './github' import { createEditorSlice } from './editor' import { createStatsSlice } from './stats' import { createClaudeUsageSlice } from './claude-usage' +import { createCodexUsageSlice } from './codex-usage' import { createBrowserSlice } from './browser' function createTestStore() { @@ -92,6 +109,7 @@ function createTestStore() { ...createEditorSlice(...a), ...createStatsSlice(...a), ...createClaudeUsageSlice(...a), + ...createCodexUsageSlice(...a), ...createBrowserSlice(...a) })) } diff --git a/src/renderer/src/store/slices/store-test-helpers.ts b/src/renderer/src/store/slices/store-test-helpers.ts index 779938c4b..ada4371c9 100644 --- a/src/renderer/src/store/slices/store-test-helpers.ts +++ b/src/renderer/src/store/slices/store-test-helpers.ts @@ -18,6 +18,7 @@ import { createGitHubSlice } from './github' import { createEditorSlice } from './editor' import { createStatsSlice } from './stats' import { createClaudeUsageSlice } from './claude-usage' +import { createCodexUsageSlice } from './codex-usage' import { createBrowserSlice } from './browser' export const TEST_REPO = { @@ -40,6 +41,7 @@ export function createTestStore() { ...createEditorSlice(...a), ...createStatsSlice(...a), ...createClaudeUsageSlice(...a), + ...createCodexUsageSlice(...a), ...createBrowserSlice(...a) })) } diff --git a/src/renderer/src/store/slices/tabs.test.ts b/src/renderer/src/store/slices/tabs.test.ts index c15cf2971..b9f3a5cc6 100644 --- a/src/renderer/src/store/slices/tabs.test.ts +++ b/src/renderer/src/store/slices/tabs.test.ts @@ -57,6 +57,22 @@ const mockApi = { getDaily: vi.fn().mockResolvedValue([]), getBreakdown: vi.fn().mockResolvedValue([]), getRecentSessions: vi.fn().mockResolvedValue([]) + }, + codexUsage: { + getScanState: vi.fn().mockResolvedValue({ + enabled: false, + isScanning: false, + lastScanStartedAt: null, + lastScanCompletedAt: null, + lastScanError: null, + hasAnyCodexData: false + }), + setEnabled: vi.fn().mockResolvedValue({}), + refresh: vi.fn().mockResolvedValue({}), + getSummary: vi.fn().mockResolvedValue(null), + getDaily: vi.fn().mockResolvedValue([]), + getBreakdown: vi.fn().mockResolvedValue([]), + getRecentSessions: vi.fn().mockResolvedValue([]) } } @@ -73,6 +89,7 @@ import { createGitHubSlice } from './github' import { createEditorSlice } from './editor' import { createStatsSlice } from './stats' import { createClaudeUsageSlice } from './claude-usage' +import { createCodexUsageSlice } from './codex-usage' import { createBrowserSlice } from './browser' const WT = 'repo1::/tmp/feature' @@ -89,6 +106,7 @@ function createTestStore() { ...createEditorSlice(...a), ...createStatsSlice(...a), ...createClaudeUsageSlice(...a), + ...createCodexUsageSlice(...a), ...createBrowserSlice(...a) })) } diff --git a/src/renderer/src/store/types.ts b/src/renderer/src/store/types.ts index 1949bb6b6..41dd57a97 100644 --- a/src/renderer/src/store/types.ts +++ b/src/renderer/src/store/types.ts @@ -8,6 +8,7 @@ import type { GitHubSlice } from './slices/github' import type { EditorSlice } from './slices/editor' import type { StatsSlice } from './slices/stats' import type { ClaudeUsageSlice } from './slices/claude-usage' +import type { CodexUsageSlice } from './slices/codex-usage' import type { BrowserSlice } from './slices/browser' export type AppState = RepoSlice & @@ -20,4 +21,5 @@ export type AppState = RepoSlice & EditorSlice & StatsSlice & ClaudeUsageSlice & + CodexUsageSlice & BrowserSlice diff --git a/src/shared/codex-usage-types.ts b/src/shared/codex-usage-types.ts new file mode 100644 index 000000000..c91e2c70f --- /dev/null +++ b/src/shared/codex-usage-types.ts @@ -0,0 +1,66 @@ +export type CodexUsageScope = 'orca' | 'all' +export type CodexUsageRange = '7d' | '30d' | '90d' | 'all' +export type CodexUsageBreakdownKind = 'model' | 'project' + +export type CodexUsageScanState = { + enabled: boolean + isScanning: boolean + lastScanStartedAt: number | null + lastScanCompletedAt: number | null + lastScanError: string | null + hasAnyCodexData: boolean +} + +export type CodexUsageSummary = { + scope: CodexUsageScope + range: CodexUsageRange + sessions: number + events: number + inputTokens: number + cachedInputTokens: number + outputTokens: number + reasoningOutputTokens: number + totalTokens: number + estimatedCostUsd: number | null + topModel: string | null + topProject: string | null + hasAnyCodexData: boolean +} + +export type CodexUsageDailyPoint = { + day: string + inputTokens: number + cachedInputTokens: number + outputTokens: number + reasoningOutputTokens: number + totalTokens: number +} + +export type CodexUsageBreakdownRow = { + key: string + label: string + sessions: number + events: number + inputTokens: number + cachedInputTokens: number + outputTokens: number + reasoningOutputTokens: number + totalTokens: number + estimatedCostUsd: number | null + hasInferredPricing: boolean +} + +export type CodexUsageSessionRow = { + sessionId: string + lastActiveAt: string + durationMinutes: number + projectLabel: string + model: string | null + events: number + inputTokens: number + cachedInputTokens: number + outputTokens: number + reasoningOutputTokens: number + totalTokens: number + hasInferredPricing: boolean +}