Add Codex usage tracking (#444)

This commit is contained in:
Jinwoo Hong
2026-04-10 10:04:57 -07:00
committed by GitHub
parent 386bd17fb1
commit 1b3719cb4c
23 changed files with 3239 additions and 43 deletions
+203
View File
@@ -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()
})
})
+845
View File
@@ -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<string, unknown>
}
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<string> {
try {
const resolved = await realpath(pathValue)
return normalizeFsPath(resolved)
} catch {
return normalizeFsPath(pathValue)
}
}
async function yieldToEventLoop(): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 0))
}
async function walkJsonlFiles(dirPath: string): Promise<string[]> {
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<string[]> {
try {
return (await walkJsonlFiles(getCodexSessionsDirectory())).sort()
} catch {
return []
}
}
export async function getProcessedFileInfo(filePath: string): Promise<CodexUsageProcessedFile> {
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<string, unknown>
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<string, unknown>
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<string, unknown>
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<string, unknown>
const metadataModel = extractString(metadata.model)
if (metadataModel) {
return metadataModel
}
}
}
if (record.metadata && typeof record.metadata === 'object') {
const metadata = record.metadata as Record<string, unknown>
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<CodexUsageAttributedEvent | null> {
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<string, CodexUsageSession>()
const dailyByKey = new Map<string, CodexUsageDailyAggregate>()
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<string, CodexUsageSession>): 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<string, CodexUsageSession>,
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<string, CodexUsageDailyAggregate>,
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<string, unknown>
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<CodexUsagePersistedFile> {
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<string, CodexUsageSession>()
const dailyByKey = new Map<string, CodexUsageDailyAggregate>()
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<string, { path: string; worktreeId: string; displayName: string }[]>
): 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'
}
+494
View File
@@ -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<CodexUsagePersistedState>): 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
}
})
})
})
+618
View File
@@ -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<string, { input: number; cachedInput: number; output: number }> = {
'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, CodexUsageWorktree[]>): 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<void> | 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<CodexUsageScanState> {
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<CodexUsageScanState> {
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<void> {
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<CodexUsageSummary> {
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<string, number>()
const byProject = new Map<string, number>()
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<CodexUsageDailyPoint[]> {
await this.refresh(false)
const byDay = new Map<string, CodexUsageDailyPoint>()
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<CodexUsageBreakdownRow[]> {
await this.refresh(false)
const rows = new Map<string, CodexUsageBreakdownRow>()
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<string>()
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<string>()
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<CodexUsageSessionRow[]> {
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<string, ScopedCodexUsageModelRow>()
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<string> {
const repos = this.store.getRepos()
const worktreesByRepo = await this.loadWorktreesByRepo(repos)
return getWorktreeFingerprint(worktreesByRepo)
}
private async loadWorktreesByRepo(repos: Repo[]): Promise<Map<string, CodexUsageWorktree[]>> {
const worktreesByRepo = new Map<string, CodexUsageWorktree[]>()
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
}
}
+124
View File
@@ -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
}
+8 -1
View File
@@ -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'
+39
View File
@@ -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)
)
}
+16 -1
View File
@@ -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)
+4
View File
@@ -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)
+36
View File
@@ -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<void>
@@ -84,6 +95,30 @@ export type ClaudeUsageApi = {
}) => Promise<ClaudeUsageSessionRow[]>
}
export type CodexUsageApi = {
getScanState: () => Promise<CodexUsageScanState>
setEnabled: (args: { enabled: boolean }) => Promise<CodexUsageScanState>
refresh: (args?: { force?: boolean }) => Promise<CodexUsageScanState>
getSummary: (args: {
scope: CodexUsageScope
range: CodexUsageRange
}) => Promise<CodexUsageSummary>
getDaily: (args: {
scope: CodexUsageScope
range: CodexUsageRange
}) => Promise<CodexUsageDailyPoint[]>
getBreakdown: (args: {
scope: CodexUsageScope
range: CodexUsageRange
kind: CodexUsageBreakdownKind
}) => Promise<CodexUsageBreakdownRow[]>
getRecentSessions: (args: {
scope: CodexUsageScope
range: CodexUsageRange
limit?: number
}) => Promise<CodexUsageSessionRow[]>
}
export type PreloadApi = {
repos: {
list: () => Promise<Repo[]>
@@ -217,6 +252,7 @@ export type PreloadApi = {
}
stats: StatsApi
claudeUsage: ClaudeUsageApi
codexUsage: CodexUsageApi
fs: {
readDir: (args: { dirPath: string }) => Promise<DirEntry[]>
readFile: (args: {
+16
View File
@@ -590,6 +590,22 @@ const api = {
ipcRenderer.invoke('claudeUsage:getRecentSessions', args)
},
codexUsage: {
getScanState: (): Promise<unknown> => ipcRenderer.invoke('codexUsage:getScanState'),
setEnabled: (args: { enabled: boolean }): Promise<unknown> =>
ipcRenderer.invoke('codexUsage:setEnabled', args),
refresh: (args?: { force?: boolean }): Promise<unknown> =>
ipcRenderer.invoke('codexUsage:refresh', args),
getSummary: (args: { scope: string; range: string }): Promise<unknown> =>
ipcRenderer.invoke('codexUsage:getSummary', args),
getDaily: (args: { scope: string; range: string }): Promise<unknown> =>
ipcRenderer.invoke('codexUsage:getDaily', args),
getBreakdown: (args: { scope: string; range: string; kind: string }): Promise<unknown> =>
ipcRenderer.invoke('codexUsage:getBreakdown', args),
getRecentSessions: (args: { scope: string; range: string; limit?: number }): Promise<unknown> =>
ipcRenderer.invoke('codexUsage:getRecentSessions', args)
},
runtime: {
syncWindowGraph: (graph: RuntimeSyncWindowGraph): Promise<RuntimeStatus> =>
ipcRenderer.invoke('runtime:syncWindowGraph', graph),
@@ -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 (
<div className="space-y-4 rounded-lg border border-border/60 bg-card/30 p-4">
<div className="flex items-start justify-between gap-4">
<div className="min-w-0 flex-1">
<h3 className="text-sm font-semibold text-foreground">Claude Usage Tracking</h3>
<h3 className="text-sm font-semibold text-foreground">{title}</h3>
<div className="mt-2 h-3 w-40 animate-pulse rounded bg-muted/70" />
</div>
<div className="flex shrink-0 items-center gap-2 self-start">
@@ -18,8 +28,8 @@ export function ClaudeUsageLoadingState(): React.JSX.Element {
<div className="h-3 w-48 animate-pulse rounded bg-muted/60" />
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
{Array.from({ length: 6 }, (_, index) => (
<div className={`grid gap-3 ${summaryGridClassName}`}>
{Array.from({ length: summaryCardCount }, (_, index) => (
<div key={index} className="space-y-3 rounded-lg border border-border/60 bg-card/40 p-4">
<div className="h-3 w-24 animate-pulse rounded bg-muted/70" />
<div className="h-7 w-20 animate-pulse rounded bg-muted/60" />
@@ -102,7 +102,7 @@ export function ClaudeUsagePane(): React.JSX.Element {
<div className="space-y-2">
<h3 className="text-sm font-semibold text-foreground">Claude Usage Tracking</h3>
<p className="text-sm text-muted-foreground">
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.
</p>
</div>
<button
@@ -0,0 +1,117 @@
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../ui/tooltip'
import type { CodexUsageDailyPoint } from '../../../../shared/codex-usage-types'
function formatTokens(value: number): string {
if (value >= 1_000_000) {
return `${(value / 1_000_000).toFixed(1)}M`
}
if (value >= 1_000) {
return `${(value / 1_000).toFixed(1)}k`
}
return value.toLocaleString()
}
type CodexUsageDailyChartProps = {
daily: CodexUsageDailyPoint[]
}
export function CodexUsageDailyChart({ daily }: CodexUsageDailyChartProps): React.JSX.Element {
const maxDailyTotal = Math.max(1, ...daily.map((entry) => entry.totalTokens))
return (
<section className="rounded-lg border border-border/60 bg-card/40 p-4">
<div className="mb-3">
<h4 className="text-sm font-semibold text-foreground">Daily usage</h4>
<p className="text-xs text-muted-foreground">
Input, cached input, output, and reasoning totals by day.
</p>
</div>
<div className="grid h-56 grid-cols-10 items-end gap-3">
{daily.slice(-10).map((entry) => {
const segments = [
{
key: 'input',
label: 'Input',
value: entry.inputTokens,
className: 'bg-sky-500/80'
},
{
key: 'output',
label: 'Output',
value: entry.outputTokens,
className: 'bg-emerald-500/80'
},
{
key: 'cached-input',
label: 'Cached input',
value: entry.cachedInputTokens,
className: 'bg-amber-500/70'
},
{
key: 'reasoning',
label: 'Reasoning',
value: entry.reasoningOutputTokens,
className: 'bg-fuchsia-500/70'
}
]
return (
<div key={entry.day} className="flex h-full min-w-0 flex-col justify-end gap-2">
<span className="text-center text-[11px] text-muted-foreground">
{formatTokens(entry.totalTokens)}
</span>
<div className="flex min-h-0 flex-1 items-end justify-center">
<div className="flex h-full w-full max-w-12 overflow-hidden rounded-t-sm bg-muted/60">
<div className="flex h-full w-full flex-col justify-end">
{segments.map((segment) =>
segment.value > 0 ? (
<TooltipProvider key={segment.key} delayDuration={120}>
<Tooltip>
<TooltipTrigger asChild>
<div
className={segment.className}
style={{ height: `${(segment.value / maxDailyTotal) * 100}%` }}
/>
</TooltipTrigger>
<TooltipContent side="top" sideOffset={8}>
<div className="text-xs">
<div>{entry.day}</div>
<div>
{segment.label}: {segment.value.toLocaleString()} tokens
</div>
</div>
</TooltipContent>
</Tooltip>
</TooltipProvider>
) : null
)}
</div>
</div>
</div>
<span className="text-center text-[11px] text-muted-foreground">
{entry.day.slice(5)}
</span>
</div>
)
})}
</div>
<div className="mt-3 flex flex-wrap gap-4 text-xs text-muted-foreground">
<span className="inline-flex items-center gap-2">
<span className="size-2 rounded-full bg-sky-500/80" />
Input
</span>
<span className="inline-flex items-center gap-2">
<span className="size-2 rounded-full bg-emerald-500/80" />
Output
</span>
<span className="inline-flex items-center gap-2">
<span className="size-2 rounded-full bg-amber-500/70" />
Cached input
</span>
<span className="inline-flex items-center gap-2">
<span className="size-2 rounded-full bg-fuchsia-500/70" />
Reasoning
</span>
</div>
</section>
)
}
@@ -0,0 +1,370 @@
import { useEffect } from 'react'
import {
Activity,
Brain,
Coins,
DatabaseZap,
FolderKanban,
RefreshCw,
SlidersHorizontal,
Sparkles
} from 'lucide-react'
import type { CodexUsageRange, CodexUsageScope } from '../../../../shared/codex-usage-types'
import { useAppStore } from '../../store'
import { Button } from '../ui/button'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuLabel,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuTrigger
} from '../ui/dropdown-menu'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../ui/tooltip'
import { ClaudeUsageLoadingState } from './ClaudeUsageLoadingState'
import { CodexUsageDailyChart } from './CodexUsageDailyChart'
import { StatCard } from './StatCard'
const RANGE_OPTIONS: CodexUsageRange[] = ['7d', '30d', '90d', 'all']
const SCOPE_OPTIONS: { value: CodexUsageScope; label: string }[] = [
{ value: 'orca', label: 'Orca worktrees only' },
{ value: 'all', label: 'All local Codex usage' }
]
const RANGE_LABELS: Record<CodexUsageRange, string> = {
'7d': 'Last 7 days',
'30d': 'Last 30 days',
'90d': 'Last 90 days',
all: 'All time'
}
function formatTokens(value: number): string {
if (value >= 1_000_000) {
return `${(value / 1_000_000).toFixed(1)}M`
}
if (value >= 1_000) {
return `${(value / 1_000).toFixed(1)}k`
}
return value.toLocaleString()
}
function formatCost(value: number | null): string {
if (value === null) {
return 'n/a'
}
return value < 0.01 ? `$${value.toFixed(4)}` : `$${value.toFixed(2)}`
}
function formatUpdatedAt(timestamp: number | null): string {
if (!timestamp) {
return 'Not scanned yet'
}
return `Updated ${new Date(timestamp).toLocaleString()}`
}
function formatSessionTime(timestamp: string): string {
const parsed = new Date(timestamp)
if (Number.isNaN(parsed.getTime())) {
return timestamp
}
return parsed.toLocaleString(undefined, {
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: '2-digit'
})
}
export function CodexUsagePane(): React.JSX.Element {
const scanState = useAppStore((state) => state.codexUsageScanState)
const summary = useAppStore((state) => state.codexUsageSummary)
const daily = useAppStore((state) => state.codexUsageDaily)
const modelBreakdown = useAppStore((state) => state.codexUsageModelBreakdown)
const projectBreakdown = useAppStore((state) => state.codexUsageProjectBreakdown)
const recentSessions = useAppStore((state) => state.codexUsageRecentSessions)
const scope = useAppStore((state) => state.codexUsageScope)
const range = useAppStore((state) => state.codexUsageRange)
const fetchCodexUsage = useAppStore((state) => state.fetchCodexUsage)
const setCodexUsageEnabled = useAppStore((state) => state.setCodexUsageEnabled)
const refreshCodexUsage = useAppStore((state) => state.refreshCodexUsage)
const setCodexUsageScope = useAppStore((state) => state.setCodexUsageScope)
const setCodexUsageRange = useAppStore((state) => state.setCodexUsageRange)
useEffect(() => {
void fetchCodexUsage()
}, [fetchCodexUsage])
if (!scanState?.enabled) {
return (
<div className="rounded-lg border border-border/60 bg-card/40 p-4">
<div className="flex items-start justify-between gap-4">
<div className="space-y-2">
<h3 className="text-sm font-semibold text-foreground">Codex Usage Tracking</h3>
<p className="text-sm text-muted-foreground">
Reads local Codex usage logs to show token, model, and session stats.
</p>
</div>
<button
type="button"
role="switch"
aria-checked={false}
aria-label="Enable Codex usage analytics"
onClick={() => void setCodexUsageEnabled(true)}
className="relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border border-transparent bg-muted-foreground/30 transition-colors"
>
<span className="pointer-events-none block size-3.5 translate-x-0.5 rounded-full bg-background shadow-sm transition-transform" />
</button>
</div>
</div>
)
}
if (!summary && (scanState.isScanning || scanState.lastScanCompletedAt === null)) {
return (
<ClaudeUsageLoadingState
title="Codex Usage Tracking"
summaryCardCount={6}
summaryGridClassName="md:grid-cols-3"
/>
)
}
const hasAnyData = summary?.hasAnyCodexData ?? scanState.hasAnyCodexData
return (
<div className="space-y-4 rounded-lg border border-border/60 bg-card/30 p-4">
<div className="flex items-start justify-between gap-4">
<div className="min-w-0 flex-1">
<h3 className="text-sm font-semibold text-foreground">Codex Usage Tracking</h3>
<p className="mt-1 text-xs text-muted-foreground">
{formatUpdatedAt(scanState.lastScanCompletedAt)}
{scanState.lastScanError ? ` • Last scan error: ${scanState.lastScanError}` : ''}
</p>
</div>
<div className="flex shrink-0 items-center gap-2 self-start">
<DropdownMenu>
<TooltipProvider delayDuration={250}>
<Tooltip>
<TooltipTrigger asChild>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon-xs" aria-label="Codex usage options">
<SlidersHorizontal className="size-3.5" />
</Button>
</DropdownMenuTrigger>
</TooltipTrigger>
<TooltipContent side="bottom" sideOffset={6}>
Filters
</TooltipContent>
</Tooltip>
</TooltipProvider>
<DropdownMenuContent align="end" className="w-60">
<DropdownMenuLabel>Scope</DropdownMenuLabel>
<DropdownMenuRadioGroup
value={scope}
onValueChange={(value) => void setCodexUsageScope(value as CodexUsageScope)}
>
{SCOPE_OPTIONS.map((option) => (
<DropdownMenuRadioItem key={option.value} value={option.value}>
{option.label}
</DropdownMenuRadioItem>
))}
</DropdownMenuRadioGroup>
<DropdownMenuSeparator />
<DropdownMenuLabel>Range</DropdownMenuLabel>
<DropdownMenuRadioGroup
value={range}
onValueChange={(value) => void setCodexUsageRange(value as CodexUsageRange)}
>
{RANGE_OPTIONS.map((option) => (
<DropdownMenuRadioItem key={option} value={option}>
{RANGE_LABELS[option]}
</DropdownMenuRadioItem>
))}
</DropdownMenuRadioGroup>
</DropdownMenuContent>
</DropdownMenu>
<TooltipProvider delayDuration={250}>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon-xs"
onClick={() => void refreshCodexUsage()}
disabled={scanState.isScanning}
aria-label="Refresh Codex usage"
>
<RefreshCw className={`size-3.5 ${scanState.isScanning ? 'animate-spin' : ''}`} />
</Button>
</TooltipTrigger>
<TooltipContent side="bottom" sideOffset={6}>
Refresh
</TooltipContent>
</Tooltip>
</TooltipProvider>
<button
type="button"
role="switch"
aria-checked={true}
aria-label="Enable Codex usage analytics"
onClick={() => void setCodexUsageEnabled(false)}
className="relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border border-transparent bg-foreground transition-colors"
>
<span className="pointer-events-none block size-3.5 translate-x-4 rounded-full bg-background shadow-sm transition-transform" />
</button>
</div>
</div>
<div className="flex items-center justify-between gap-3">
<p className="text-xs text-muted-foreground">
{SCOPE_OPTIONS.find((option) => option.value === scope)?.label} • {RANGE_LABELS[range]}
</p>
</div>
{!hasAnyData ? (
<div className="rounded-lg border border-dashed border-border/60 bg-card/30 px-4 py-6 text-sm text-muted-foreground">
No local Codex usage found yet for this scope.
</div>
) : (
<>
<div className="grid gap-3 md:grid-cols-3">
<StatCard
label="Input tokens"
value={formatTokens(summary?.inputTokens ?? 0)}
icon={<Sparkles className="size-4" />}
/>
<StatCard
label="Output tokens"
value={formatTokens(summary?.outputTokens ?? 0)}
icon={<Activity className="size-4" />}
/>
<StatCard
label="Cached input"
value={formatTokens(summary?.cachedInputTokens ?? 0)}
icon={<DatabaseZap className="size-4" />}
/>
<StatCard
label="Reasoning output"
value={formatTokens(summary?.reasoningOutputTokens ?? 0)}
icon={<Brain className="size-4" />}
/>
<StatCard
label="Sessions / Events"
value={`${(summary?.sessions ?? 0).toLocaleString()} / ${(summary?.events ?? 0).toLocaleString()}`}
icon={<FolderKanban className="size-4" />}
/>
<StatCard
label="Est. API-equivalent cost"
value={formatCost(summary?.estimatedCostUsd ?? null)}
icon={<Coins className="size-4" />}
/>
</div>
<p className="px-1 text-xs text-muted-foreground">
Reasoning tokens are shown for visibility, but cost is calculated from uncached input,
cached input, and output only.
</p>
<CodexUsageDailyChart daily={daily} />
<div className="grid gap-4 xl:grid-cols-2">
<section className="rounded-lg border border-border/60 bg-card/40 p-4">
<div className="mb-3">
<h4 className="text-sm font-semibold text-foreground">By model</h4>
<p className="text-xs text-muted-foreground">
Top model: {summary?.topModel ?? 'n/a'}
</p>
</div>
<div className="space-y-3">
{modelBreakdown.slice(0, 5).map((row) => (
<div key={row.key} className="space-y-1">
<div className="flex items-center justify-between gap-3 text-sm">
<span className="truncate text-foreground">{row.label}</span>
<span className="shrink-0 text-muted-foreground">
{formatTokens(row.totalTokens)}
</span>
</div>
<div className="text-xs text-muted-foreground">
{row.sessions} sessions • {row.events} events
{row.hasInferredPricing ? ' • inferred pricing' : ''}
</div>
</div>
))}
</div>
</section>
<section className="rounded-lg border border-border/60 bg-card/40 p-4">
<div className="mb-3">
<h4 className="text-sm font-semibold text-foreground">By project</h4>
<p className="text-xs text-muted-foreground">
Top project: {summary?.topProject ?? 'n/a'}
</p>
</div>
<div className="space-y-3">
{projectBreakdown.slice(0, 5).map((row) => (
<div key={row.key} className="space-y-1">
<div className="flex items-center justify-between gap-3 text-sm">
<span className="truncate text-foreground">{row.label}</span>
<span className="shrink-0 text-muted-foreground">
{formatTokens(row.totalTokens)}
</span>
</div>
<div className="text-xs text-muted-foreground">
{row.sessions} sessions • {row.events} events
</div>
</div>
))}
</div>
</section>
</div>
<section className="rounded-lg border border-border/60 bg-card/40 p-4">
<div className="mb-3">
<h4 className="text-sm font-semibold text-foreground">Recent sessions</h4>
<p className="text-xs text-muted-foreground">
Most recent local Codex sessions in this scope.
</p>
</div>
<div className="overflow-x-auto">
<table className="min-w-full text-sm">
<thead>
<tr className="border-b border-border/60 text-left text-xs text-muted-foreground">
<th className="px-2 py-2 font-medium">Last active</th>
<th className="px-2 py-2 font-medium">Project</th>
<th className="px-2 py-2 font-medium">Model</th>
<th className="px-2 py-2 font-medium">Events</th>
<th className="px-2 py-2 font-medium">Input</th>
<th className="px-2 py-2 font-medium">Output</th>
<th className="px-2 py-2 font-medium">Total</th>
</tr>
</thead>
<tbody>
{recentSessions.map((row) => (
<tr key={row.sessionId} className="border-b border-border/40 last:border-b-0">
<td className="px-2 py-2 text-muted-foreground">
{formatSessionTime(row.lastActiveAt)}
</td>
<td className="px-2 py-2 text-foreground">{row.projectLabel}</td>
<td className="px-2 py-2 text-muted-foreground">
{row.model ?? 'Unknown'}
{row.hasInferredPricing ? ' *' : ''}
</td>
<td className="px-2 py-2 text-muted-foreground">{row.events}</td>
<td className="px-2 py-2 text-muted-foreground">
{formatTokens(row.inputTokens)}
</td>
<td className="px-2 py-2 text-muted-foreground">
{formatTokens(row.outputTokens)}
</td>
<td className="px-2 py-2 text-muted-foreground">
{formatTokens(row.totalTokens)}
</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
</>
)}
</div>
)
}
+72 -36
View File
@@ -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 <ClaudeUsagePane />
}
const trackingSince = formatTrackingSince(summary.firstEventAt)
return (
<div className="space-y-5">
<div className="space-y-3">
{summary.totalAgentsSpawned === 0 && summary.totalPRsCreated === 0 ? (
<div className="flex min-h-[8rem] items-center justify-center rounded-lg border border-dashed border-border/60 bg-card/30 text-sm text-muted-foreground">
Start your first agent to begin tracking
</div>
) : (
<>
<div className="grid grid-cols-3 gap-3">
<StatCard
label="Agents spawned"
value={summary.totalAgentsSpawned.toLocaleString()}
icon={<Bot className="size-4" />}
/>
<StatCard
label="Time agents worked"
value={formatDuration(summary.totalAgentTimeMs)}
icon={<Clock className="size-4" />}
/>
<StatCard
label="PRs created"
value={summary.totalPRsCreated.toLocaleString()}
icon={<GitPullRequest className="size-4" />}
/>
{summary ? (
<div className="space-y-3">
{summary.totalAgentsSpawned === 0 && summary.totalPRsCreated === 0 ? (
<div className="flex min-h-[8rem] items-center justify-center rounded-lg border border-dashed border-border/60 bg-card/30 text-sm text-muted-foreground">
Start your first agent to begin tracking
</div>
{trackingSince && <p className="px-1 text-xs text-muted-foreground">{trackingSince}</p>}
</>
)}
</div>
) : (
<>
<div className="grid grid-cols-3 gap-3">
<StatCard
label="Agents spawned"
value={summary.totalAgentsSpawned.toLocaleString()}
icon={<Bot className="size-4" />}
/>
<StatCard
label="Time agents worked"
value={formatDuration(summary.totalAgentTimeMs)}
icon={<Clock className="size-4" />}
/>
<StatCard
label="PRs created"
value={summary.totalPRsCreated.toLocaleString()}
icon={<GitPullRequest className="size-4" />}
/>
</div>
{formatTrackingSince(summary.firstEventAt) && (
<p className="px-1 text-xs text-muted-foreground">
{formatTrackingSince(summary.firstEventAt)}
</p>
)}
</>
)}
</div>
) : null}
<ClaudeUsagePane />
<div className="space-y-4">
<div className="flex items-center justify-between gap-3">
<h3 className="text-sm font-semibold text-foreground">Usage Analytics</h3>
<div
role="group"
aria-label="Usage analytics provider"
className="inline-flex w-fit items-center justify-center rounded-lg bg-muted p-[3px] text-muted-foreground"
>
{(['claude', 'codex'] as const).map((tab) => (
<button
key={tab}
type="button"
aria-pressed={activeUsageTab === tab}
onClick={() => setActiveUsageTab(tab)}
className={cn(
'inline-flex h-8 items-center justify-center rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-all',
activeUsageTab === tab
? 'bg-background text-foreground shadow-sm dark:border-input dark:bg-input/30'
: 'text-foreground/60 hover:text-foreground dark:text-muted-foreground dark:hover:text-foreground'
)}
>
{tab === 'claude' ? 'Claude' : 'Codex'}
</button>
))}
</div>
</div>
{/* 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. */}
<div>{activeUsageTab === 'claude' ? <ClaudeUsagePane /> : <CodexUsagePane />}</div>
</div>
</div>
)
}
+2
View File
@@ -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<AppState>()((...a) => ({
@@ -23,6 +24,7 @@ export const useAppStore = create<AppState>()((...a) => ({
...createEditorSlice(...a),
...createStatsSlice(...a),
...createClaudeUsageSlice(...a),
...createCodexUsageSlice(...a),
...createBrowserSlice(...a)
}))
@@ -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<void>
setCodexUsageScope: (scope: CodexUsageScope) => Promise<void>
setCodexUsageRange: (range: CodexUsageRange) => Promise<void>
fetchCodexUsage: (opts?: { forceRefresh?: boolean }) => Promise<void>
enableCodexUsage: () => Promise<void>
refreshCodexUsage: () => Promise<void>
}
export const createCodexUsageSlice: StateCreator<AppState, [], [], CodexUsageSlice> = (
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<CodexUsageSummary>,
window.api.codexUsage.getDaily({
scope: codexUsageScope,
range: codexUsageRange
}) as Promise<CodexUsageDailyPoint[]>,
window.api.codexUsage.getBreakdown({
scope: codexUsageScope,
range: codexUsageRange,
kind: 'model'
}) as Promise<CodexUsageBreakdownRow[]>,
window.api.codexUsage.getBreakdown({
scope: codexUsageScope,
range: codexUsageRange,
kind: 'project'
}) as Promise<CodexUsageBreakdownRow[]>,
window.api.codexUsage.getRecentSessions({
scope: codexUsageScope,
range: codexUsageRange,
limit: 10
}) as Promise<CodexUsageSessionRow[]>
])
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 })
}
})
@@ -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)
}))
}
@@ -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)
}))
}
@@ -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)
}))
}
+2
View File
@@ -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
+66
View File
@@ -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
}