Skip to content

Commit 70ba92c

Browse files
committed
fix(ccusage): address adapter review findings
1 parent 1c4d94d commit 70ba92c

14 files changed

Lines changed: 210 additions & 80 deletions

File tree

‎apps/ccusage/scripts/compare-pr-performance.ts‎

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -487,17 +487,9 @@ const command = define({
487487
const sections = [
488488
await compareFixture({
489489
...options,
490-
commands: [
491-
'daily',
492-
'session',
493-
'blocks',
494-
'claude',
495-
'claude session',
496-
'codex',
497-
'codex session',
498-
],
490+
commands: ['claude daily', 'claude session', 'codex daily', 'codex session'],
499491
description:
500-
'Committed small fixtures for stable PR-to-PR feedback, output-shape regressions, and explicit Claude/Codex command coverage.',
492+
'Committed small fixtures for stable PR-to-PR feedback and explicit Claude/Codex command coverage.',
501493
title: 'Committed fixture performance',
502494
}),
503495
];

‎apps/ccusage/scripts/generate-large-fixture.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#!/usr/bin/env bun
22

3-
import { join, resolve } from 'node:path';
3+
import path, { join, resolve } from 'node:path';
4+
import process from 'node:process';
45
import { cli, define } from 'gunshi';
56

67
const DEFAULT_SIZE_MIB = 1024;
@@ -96,6 +97,13 @@ function contentPadding(length: number): string {
9697
return PADDING_SOURCE.slice(0, length);
9798
}
9899

100+
export function assertSafeDeletionTarget(directory: string, flagName: string): void {
101+
const resolved = resolve(directory);
102+
if (resolved === path.parse(resolved).root || resolved === process.cwd() || resolved.length < 5) {
103+
throw new Error(`Refusing to delete unsafe ${flagName} path: ${resolved}`);
104+
}
105+
}
106+
99107
/**
100108
* Creates one deterministic usage row that stays on ccusage's normal fast parser path.
101109
*
@@ -141,6 +149,7 @@ async function generateClaudeFixture(
141149
outputDir: string,
142150
sizeMib: number,
143151
): Promise<{ fileCount: number; lineCount: number; totalBytes: number }> {
152+
assertSafeDeletionTarget(outputDir, '--output-dir');
144153
const targetBytes = sizeMib * 1024 * 1024;
145154
const fileSizeTargets = createFileSizeTargets(targetBytes);
146155

@@ -196,6 +205,7 @@ export async function generateCodexFixture(
196205
outputDir: string,
197206
sizeMib: number,
198207
): Promise<{ fileCount: number; lineCount: number; totalBytes: number }> {
208+
assertSafeDeletionTarget(outputDir, '--codex-output-dir');
199209
const targetBytes = sizeMib * 1024 * 1024;
200210
const fileSizeTargets = createFileSizeTargets(targetBytes);
201211

‎apps/ccusage/src/_consts.ts‎

Lines changed: 1 addition & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -42,31 +42,7 @@ export const USER_HOME_DIR = homedir();
4242
* XDG config directory path
4343
* Uses XDG_CONFIG_HOME if set, otherwise falls back to ~/.config
4444
*/
45-
const XDG_CONFIG_DIR = xdgConfig ?? path.join(USER_HOME_DIR, '.config');
46-
47-
/**
48-
* Default Claude data directory path (~/.claude)
49-
* Used as base path for loading usage data from JSONL files
50-
*/
51-
export const DEFAULT_CLAUDE_CODE_PATH = '.claude';
52-
53-
/**
54-
* Default Claude data directory path using XDG config directory
55-
* Uses XDG_CONFIG_HOME if set, otherwise falls back to ~/.config/claude
56-
*/
57-
export const DEFAULT_CLAUDE_CONFIG_PATH = path.join(XDG_CONFIG_DIR, 'claude');
58-
59-
/**
60-
* Environment variable for specifying multiple Claude data directories
61-
* Supports comma-separated paths for multiple locations
62-
*/
63-
export const CLAUDE_CONFIG_DIR_ENV = 'CLAUDE_CONFIG_DIR';
64-
65-
/**
66-
* Claude projects directory name within the data directory
67-
* Contains subdirectories for each project with usage data
68-
*/
69-
export const CLAUDE_PROJECTS_DIR_NAME = 'projects';
45+
export const XDG_CONFIG_DIR = xdgConfig ?? path.join(USER_HOME_DIR, '.config');
7046

7147
/**
7248
* JSONL file glob pattern for finding usage data files
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import path from 'node:path';
2+
import { XDG_CONFIG_DIR } from '../../_consts.ts';
3+
4+
export const DEFAULT_CLAUDE_CODE_PATH = '.claude';
5+
export const DEFAULT_CLAUDE_CONFIG_PATH = path.join(XDG_CONFIG_DIR, 'claude');
6+
export const CLAUDE_CONFIG_DIR_ENV = 'CLAUDE_CONFIG_DIR';
7+
export const CLAUDE_PROJECTS_DIR_NAME = 'projects';

‎apps/ccusage/src/adapter/claude/index.ts‎

Lines changed: 1 addition & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,8 @@
11
import type { AdapterOptions, AgentUsageRow, ReportKind } from '../types.ts';
2-
import path from 'node:path';
3-
import process from 'node:process';
42
import { collectFilesRecursive } from '@ccusage/internal/fs';
5-
import {
6-
CLAUDE_CONFIG_DIR_ENV,
7-
CLAUDE_PROJECTS_DIR_NAME,
8-
DEFAULT_CLAUDE_CODE_PATH,
9-
DEFAULT_CLAUDE_CONFIG_PATH,
10-
USER_HOME_DIR,
11-
} from '../../_consts.ts';
123
import { loadDailyUsageData, loadMonthlyUsageData, loadSessionData } from '../../data-loader.ts';
134
import { normalizeDateFilter, toCompactDate } from '../shared.ts';
14-
15-
function getClaudeProjectPaths(): string[] {
16-
const envPaths = (process.env[CLAUDE_CONFIG_DIR_ENV] ?? '').trim();
17-
const basePaths =
18-
envPaths === ''
19-
? [DEFAULT_CLAUDE_CONFIG_PATH, path.join(USER_HOME_DIR, DEFAULT_CLAUDE_CODE_PATH)]
20-
: envPaths
21-
.split(',')
22-
.map((entry) => path.resolve(entry.trim()))
23-
.filter((entry) => entry !== '');
24-
return basePaths.map((basePath) => path.join(basePath, CLAUDE_PROJECTS_DIR_NAME));
25-
}
5+
import { getClaudeProjectPaths } from './paths.ts';
266

277
async function hasFiles(root: string, extension: `.${string}`): Promise<boolean> {
288
return (await collectFilesRecursive(root, { extension })).length > 0;
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import path from 'node:path';
2+
import process from 'node:process';
3+
import { USER_HOME_DIR } from '../../_consts.ts';
4+
import {
5+
CLAUDE_CONFIG_DIR_ENV,
6+
CLAUDE_PROJECTS_DIR_NAME,
7+
DEFAULT_CLAUDE_CODE_PATH,
8+
DEFAULT_CLAUDE_CONFIG_PATH,
9+
} from './constants.ts';
10+
11+
export function getClaudeProjectPaths(): string[] {
12+
const envPaths = (process.env[CLAUDE_CONFIG_DIR_ENV] ?? '').trim();
13+
const basePaths =
14+
envPaths === ''
15+
? [DEFAULT_CLAUDE_CONFIG_PATH, path.join(USER_HOME_DIR, DEFAULT_CLAUDE_CODE_PATH)]
16+
: envPaths
17+
.split(',')
18+
.map((entry) => entry.trim())
19+
.filter((entry) => entry !== '')
20+
.map((entry) => path.resolve(entry));
21+
return basePaths.map((basePath) => path.join(basePath, CLAUDE_PROJECTS_DIR_NAME));
22+
}
23+
24+
if (import.meta.vitest != null) {
25+
describe('getClaudeProjectPaths', () => {
26+
afterEach(() => {
27+
vi.unstubAllEnvs();
28+
});
29+
30+
it('ignores empty CLAUDE_CONFIG_DIR entries before resolving paths so cwd is never added accidentally', () => {
31+
vi.stubEnv(CLAUDE_CONFIG_DIR_ENV, '/tmp/claude-a, ,/tmp/claude-b,');
32+
33+
expect(getClaudeProjectPaths()).toEqual([
34+
path.join('/tmp/claude-a', CLAUDE_PROJECTS_DIR_NAME),
35+
path.join('/tmp/claude-b', CLAUDE_PROJECTS_DIR_NAME),
36+
]);
37+
});
38+
});
39+
}

‎apps/ccusage/src/adapter/opencode/loader.ts‎

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,10 +53,7 @@ function hasBillableTokenUsage(tokens: OpenCodeTokens): boolean {
5353

5454
function shouldLoadOpenCodeMessage(message: OpenCodeMessage): boolean {
5555
return (
56-
message.tokens?.input != null &&
57-
message.tokens.output != null &&
58-
message.tokens.cache?.read != null &&
59-
message.tokens.cache.write != null &&
56+
message.tokens != null &&
6057
hasBillableTokenUsage(message.tokens) &&
6158
message.providerID != null &&
6259
message.modelID != null
@@ -305,6 +302,41 @@ if (import.meta.vitest != null) {
305302
]);
306303
});
307304

305+
it('loads billable OpenCode messages without cache token fields', async () => {
306+
await using fixture = await createFixture({
307+
storage: {
308+
message: {
309+
'message.json': JSON.stringify({
310+
id: 'msg-1',
311+
sessionID: 'session-a',
312+
providerID: 'openai',
313+
modelID: 'gpt-5',
314+
time: { created: Date.UTC(2026, 4, 1, 1, 2, 3) },
315+
tokens: {
316+
input: 100,
317+
output: 50,
318+
},
319+
}),
320+
},
321+
},
322+
});
323+
vi.stubEnv('OPENCODE_DATA_DIR', fixture.path);
324+
325+
await expect(loadOpenCodeMessages()).resolves.toMatchObject([
326+
{
327+
sessionID: 'session-a',
328+
model: 'gpt-5',
329+
providerID: 'openai',
330+
usage: {
331+
inputTokens: 100,
332+
outputTokens: 50,
333+
cacheCreationInputTokens: 0,
334+
cacheReadInputTokens: 0,
335+
},
336+
},
337+
]);
338+
});
339+
308340
it('ignores non-billable OpenCode message files', async () => {
309341
await using fixture = await createFixture({
310342
storage: {

‎apps/ccusage/src/adapter/opencode/pricing.ts‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ function normalizeOpenCodeModelName(modelName: string): string {
2424
function createModelCandidates(entry: OpenCodeUsageEntry): string[] {
2525
const resolved = resolveModelName(entry.model);
2626
const normalized = normalizeOpenCodeModelName(resolved);
27-
const baseCandidates = normalized === resolved ? [resolved] : [normalized];
27+
const baseCandidates = normalized === resolved ? [resolved] : [resolved, normalized];
2828
const candidates = [...baseCandidates];
2929
if (entry.providerID !== 'unknown') {
3030
const providerPrefix = normalizeOpenCodeProviderID(entry.providerID);
@@ -33,6 +33,33 @@ function createModelCandidates(entry: OpenCodeUsageEntry): string[] {
3333
return Array.from(new Set(candidates));
3434
}
3535

36+
if (import.meta.vitest != null) {
37+
describe('createModelCandidates', () => {
38+
it('keeps both original and normalized model names before provider-prefixed candidates', () => {
39+
expect(
40+
createModelCandidates({
41+
timestamp: new Date('2026-05-01T00:00:00.000Z'),
42+
sessionID: 'session-a',
43+
usage: {
44+
inputTokens: 1,
45+
outputTokens: 1,
46+
cacheCreationInputTokens: 0,
47+
cacheReadInputTokens: 0,
48+
},
49+
model: 'claude-sonnet-4.5',
50+
providerID: 'anthropic',
51+
costUSD: null,
52+
}),
53+
).toEqual([
54+
'claude-sonnet-4.5',
55+
'claude-sonnet-4-5',
56+
'anthropic/claude-sonnet-4.5',
57+
'anthropic/claude-sonnet-4-5',
58+
]);
59+
});
60+
});
61+
}
62+
3663
export async function calculateOpenCodeCost(
3764
entry: OpenCodeUsageEntry,
3865
fetcher: LiteLLMPricingFetcher,

‎apps/ccusage/src/adapter/pi/parser.ts‎

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,19 @@ export async function loadPiUsageEntries(piPath?: string): Promise<PiUsageEntry[
144144

145145
for (const fileEntries of fileResults) {
146146
for (const entry of fileEntries) {
147-
const hash = `pi:${entry.project}:${entry.sessionId}:${entry.timestamp}:${entry.tokenTotal}`;
147+
const hash = [
148+
'pi',
149+
entry.project,
150+
entry.sessionId,
151+
entry.timestamp,
152+
entry.model,
153+
entry.inputTokens,
154+
entry.outputTokens,
155+
entry.cacheCreationTokens,
156+
entry.cacheReadTokens,
157+
entry.cost,
158+
entry.tokenTotal,
159+
].join(':');
148160
if (processedHashes.has(hash)) {
149161
continue;
150162
}
@@ -262,6 +274,49 @@ if (import.meta.vitest != null) {
262274
await expect(loadPiUsageEntries(fixture.getPath('sessions'))).resolves.toHaveLength(1);
263275
});
264276

277+
it('keeps distinct pi usage records that share timestamp and total tokens but differ in token breakdown', async () => {
278+
const base = {
279+
type: 'message',
280+
timestamp: '2026-04-22T01:02:04.000Z',
281+
message: {
282+
role: 'assistant',
283+
model: 'gpt-5.4',
284+
},
285+
};
286+
await using fixture = await createFixture({
287+
sessions: {
288+
project: {
289+
'session-id.jsonl': [
290+
JSON.stringify({
291+
...base,
292+
message: {
293+
...base.message,
294+
usage: {
295+
input: 100,
296+
output: 50,
297+
totalTokens: 150,
298+
},
299+
},
300+
}),
301+
JSON.stringify({
302+
...base,
303+
message: {
304+
...base.message,
305+
usage: {
306+
input: 90,
307+
output: 60,
308+
totalTokens: 150,
309+
},
310+
},
311+
}),
312+
].join('\n'),
313+
},
314+
},
315+
});
316+
317+
await expect(loadPiUsageEntries(fixture.getPath('sessions'))).resolves.toHaveLength(2);
318+
});
319+
265320
it.skipIf(getPiAgentPaths().length === 0)(
266321
'loads local pi-agent usage data when the user has a sessions directory',
267322
async () => {

‎apps/ccusage/src/adapter/types.ts‎

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type { LiteLLMPricingFetcher } from '@ccusage/internal/pricing';
22

3-
export type AgentId = 'claude' | 'codex' | 'opencode' | 'amp' | 'pi';
3+
export const agentIds = ['claude', 'codex', 'opencode', 'amp', 'pi'] as const;
4+
export type AgentId = (typeof agentIds)[number];
45
export type ReportKind = 'daily' | 'weekly' | 'monthly' | 'session';
56

67
export type AdapterOptions = {
@@ -41,13 +42,6 @@ export type AdapterContext = {
4142
progress?: AdapterProgress;
4243
};
4344

44-
export const agentIds = [
45-
'claude',
46-
'codex',
47-
'opencode',
48-
'amp',
49-
'pi',
50-
] as const satisfies readonly AgentId[];
5145
export const agentLabels = {
5246
all: 'All',
5347
claude: 'Claude',

0 commit comments

Comments
 (0)