Skip to content

Commit 95329b9

Browse files
committed
feat(opencode): support date range filters
1 parent 9f4129c commit 95329b9

7 files changed

Lines changed: 235 additions & 13 deletions

File tree

‎apps/opencode/src/_shared-args.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import type { Args } from 'gunshi';
2+
import * as v from 'valibot';
3+
4+
const filterDateRegex = /^\d{8}$/;
5+
const filterDateSchema = v.pipe(
6+
v.string(),
7+
v.regex(filterDateRegex, 'Date must be in YYYYMMDD format'),
8+
);
9+
10+
function parseDateArg(value: string): string {
11+
return v.parse(filterDateSchema, value);
12+
}
13+
14+
export const dateFilterArgs = {
15+
since: {
16+
type: 'custom',
17+
short: 's',
18+
description: 'Filter from date (YYYYMMDD format)',
19+
parse: parseDateArg,
20+
},
21+
until: {
22+
type: 'custom',
23+
short: 'u',
24+
description: 'Filter until date (YYYYMMDD format)',
25+
parse: parseDateArg,
26+
},
27+
} as const satisfies Args;

‎apps/opencode/src/commands/daily.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
import { groupBy } from 'es-toolkit';
1111
import { define } from 'gunshi';
1212
import pc from 'picocolors';
13+
import { dateFilterArgs } from '../_shared-args.ts';
1314
import { calculateCostForEntry } from '../cost-utils.ts';
1415
import { loadOpenCodeMessages } from '../data-loader.ts';
1516
import { logger } from '../logger.ts';
@@ -20,6 +21,7 @@ export const dailyCommand = define({
2021
name: 'daily',
2122
description: 'Show OpenCode token usage grouped by day',
2223
args: {
24+
...dateFilterArgs,
2325
json: {
2426
type: 'boolean',
2527
short: 'j',
@@ -33,7 +35,10 @@ export const dailyCommand = define({
3335
async run(ctx) {
3436
const jsonOutput = Boolean(ctx.values.json);
3537

36-
const entries = await loadOpenCodeMessages();
38+
const entries = await loadOpenCodeMessages({
39+
since: ctx.values.since,
40+
until: ctx.values.until,
41+
});
3742

3843
if (entries.length === 0) {
3944
const output = jsonOutput
Lines changed: 46 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,46 @@
1-
export { dailyCommand } from './daily';
2-
export { monthlyCommand } from './monthly';
3-
export { sessionCommand } from './session';
4-
export { weeklyCommand } from './weekly';
1+
import { dailyCommand } from './daily.ts';
2+
import { monthlyCommand } from './monthly.ts';
3+
import { sessionCommand } from './session.ts';
4+
import { weeklyCommand } from './weekly.ts';
5+
6+
export { dailyCommand } from './daily.ts';
7+
export { monthlyCommand } from './monthly.ts';
8+
export { sessionCommand } from './session.ts';
9+
export { weeklyCommand } from './weekly.ts';
10+
11+
if (import.meta.vitest != null) {
12+
const { describe, expect, it } = import.meta.vitest;
13+
14+
type DateArg = {
15+
short: string;
16+
description: string;
17+
parse: (value: string) => string;
18+
};
19+
type CommandWithDateArgs = {
20+
args: {
21+
since?: DateArg;
22+
until?: DateArg;
23+
};
24+
};
25+
26+
describe('OpenCode command date filter arguments', () => {
27+
it.each([
28+
['daily', dailyCommand],
29+
['weekly', weeklyCommand],
30+
['monthly', monthlyCommand],
31+
['session', sessionCommand],
32+
])('should expose main-mode compatible since and until args for %s', (_name, command) => {
33+
const args = (command as CommandWithDateArgs).args;
34+
35+
expect(args.since?.short).toBe('s');
36+
expect(args.since?.description).toBe('Filter from date (YYYYMMDD format)');
37+
expect(args.since?.parse('20240102')).toBe('20240102');
38+
expect(() => args.since?.parse('2024-01-02')).toThrow('Date must be in YYYYMMDD format');
39+
40+
expect(args.until?.short).toBe('u');
41+
expect(args.until?.description).toBe('Filter until date (YYYYMMDD format)');
42+
expect(args.until?.parse('20240103')).toBe('20240103');
43+
expect(() => args.until?.parse('2024-01-03')).toThrow('Date must be in YYYYMMDD format');
44+
});
45+
});
46+
}

‎apps/opencode/src/commands/monthly.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
import { groupBy } from 'es-toolkit';
1111
import { define } from 'gunshi';
1212
import pc from 'picocolors';
13+
import { dateFilterArgs } from '../_shared-args.ts';
1314
import { calculateCostForEntry } from '../cost-utils.ts';
1415
import { loadOpenCodeMessages } from '../data-loader.ts';
1516
import { logger } from '../logger.ts';
@@ -20,6 +21,7 @@ export const monthlyCommand = define({
2021
name: 'monthly',
2122
description: 'Show OpenCode token usage grouped by month',
2223
args: {
24+
...dateFilterArgs,
2325
json: {
2426
type: 'boolean',
2527
short: 'j',
@@ -33,7 +35,10 @@ export const monthlyCommand = define({
3335
async run(ctx) {
3436
const jsonOutput = Boolean(ctx.values.json);
3537

36-
const entries = await loadOpenCodeMessages();
38+
const entries = await loadOpenCodeMessages({
39+
since: ctx.values.since,
40+
until: ctx.values.until,
41+
});
3742

3843
if (entries.length === 0) {
3944
const output = jsonOutput

‎apps/opencode/src/commands/session.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
import { groupBy } from 'es-toolkit';
1111
import { define } from 'gunshi';
1212
import pc from 'picocolors';
13+
import { dateFilterArgs } from '../_shared-args.ts';
1314
import { calculateCostForEntry } from '../cost-utils.ts';
1415
import { loadOpenCodeMessages, loadOpenCodeSessions } from '../data-loader.ts';
1516
import { logger } from '../logger.ts';
@@ -20,6 +21,7 @@ export const sessionCommand = define({
2021
name: 'session',
2122
description: 'Show OpenCode token usage grouped by session',
2223
args: {
24+
...dateFilterArgs,
2325
json: {
2426
type: 'boolean',
2527
short: 'j',
@@ -34,7 +36,10 @@ export const sessionCommand = define({
3436
const jsonOutput = Boolean(ctx.values.json);
3537

3638
const [entries, sessionMetadataMap] = await Promise.all([
37-
loadOpenCodeMessages(),
39+
loadOpenCodeMessages({
40+
since: ctx.values.since,
41+
until: ctx.values.until,
42+
}),
3843
loadOpenCodeSessions(),
3944
]);
4045

‎apps/opencode/src/commands/weekly.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
import { groupBy } from 'es-toolkit';
1111
import { define } from 'gunshi';
1212
import pc from 'picocolors';
13+
import { dateFilterArgs } from '../_shared-args.ts';
1314
import { calculateCostForEntry } from '../cost-utils.ts';
1415
import { loadOpenCodeMessages } from '../data-loader.ts';
1516
import { logger } from '../logger.ts';
@@ -45,6 +46,7 @@ export const weeklyCommand = define({
4546
name: 'weekly',
4647
description: 'Show OpenCode token usage grouped by week (ISO week format)',
4748
args: {
49+
...dateFilterArgs,
4850
json: {
4951
type: 'boolean',
5052
short: 'j',
@@ -58,7 +60,10 @@ export const weeklyCommand = define({
5860
async run(ctx) {
5961
const jsonOutput = Boolean(ctx.values.json);
6062

61-
const entries = await loadOpenCodeMessages();
63+
const entries = await loadOpenCodeMessages({
64+
since: ctx.values.since,
65+
until: ctx.values.until,
66+
});
6267

6368
if (entries.length === 0) {
6469
const output = jsonOutput

‎apps/opencode/src/data-loader.ts‎

Lines changed: 138 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@
88
* @module data-loader
99
*/
1010

11-
import { readFile } from 'node:fs/promises';
12-
import { homedir } from 'node:os';
11+
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
12+
import { homedir, tmpdir } from 'node:os';
1313
import path from 'node:path';
1414
import process from 'node:process';
1515
import { isDirectorySync } from 'path-type';
@@ -123,6 +123,11 @@ export type LoadedSessionMetadata = {
123123
directory: string;
124124
};
125125

126+
export type LoadOpenCodeMessagesOptions = {
127+
since?: string;
128+
until?: string;
129+
};
130+
126131
/**
127132
* Get OpenCode data directory
128133
* @returns Path to OpenCode data directory, or null if not found
@@ -187,6 +192,26 @@ function convertOpenCodeMessageToUsageEntry(
187192
};
188193
}
189194

195+
function filterOpenCodeMessagesByDateRange(
196+
entries: LoadedUsageEntry[],
197+
options?: LoadOpenCodeMessagesOptions,
198+
): LoadedUsageEntry[] {
199+
if (options?.since == null && options?.until == null) {
200+
return entries;
201+
}
202+
203+
return entries.filter((entry) => {
204+
const dateStr = entry.timestamp.toISOString().substring(0, 10).replace(/-/g, '');
205+
if (options.since != null && dateStr < options.since) {
206+
return false;
207+
}
208+
if (options.until != null && dateStr > options.until) {
209+
return false;
210+
}
211+
return true;
212+
});
213+
}
214+
190215
async function loadOpenCodeSession(
191216
filePath: string,
192217
): Promise<v.InferOutput<typeof openCodeSessionSchema> | null> {
@@ -252,7 +277,9 @@ export async function loadOpenCodeSessions(): Promise<Map<string, LoadedSessionM
252277
* Load all OpenCode messages
253278
* @returns Array of LoadedUsageEntry for aggregation
254279
*/
255-
export async function loadOpenCodeMessages(): Promise<LoadedUsageEntry[]> {
280+
export async function loadOpenCodeMessages(
281+
options?: LoadOpenCodeMessagesOptions,
282+
): Promise<LoadedUsageEntry[]> {
256283
const openCodePath = getOpenCodePath();
257284
if (openCodePath == null) {
258285
return [];
@@ -305,11 +332,54 @@ export async function loadOpenCodeMessages(): Promise<LoadedUsageEntry[]> {
305332
entries.push(entry);
306333
}
307334

308-
return entries;
335+
return filterOpenCodeMessagesByDateRange(entries, options);
309336
}
310337

311338
if (import.meta.vitest != null) {
312-
const { describe, it, expect } = import.meta.vitest;
339+
const { describe, it, expect, afterEach, vi } = import.meta.vitest;
340+
341+
afterEach(() => {
342+
vi.unstubAllEnvs();
343+
});
344+
345+
async function createOpenCodeMessageFixture(
346+
messages: Array<v.InferOutput<typeof openCodeMessageSchema>>,
347+
): Promise<string> {
348+
const root = await mkdtemp(path.join(tmpdir(), 'opencode-data-'));
349+
const messagesDir = path.join(root, 'storage', 'message');
350+
await mkdir(messagesDir, { recursive: true });
351+
352+
await Promise.all(
353+
messages.map(async (message) =>
354+
writeFile(path.join(messagesDir, `${message.id}.json`), JSON.stringify(message)),
355+
),
356+
);
357+
358+
return root;
359+
}
360+
361+
function createTestMessage(
362+
id: string,
363+
timestamp: string,
364+
): v.InferOutput<typeof openCodeMessageSchema> {
365+
return {
366+
id,
367+
sessionID: 'session-test' as v.InferOutput<typeof sessionIdSchema>,
368+
providerID: 'anthropic',
369+
modelID: 'claude-sonnet-4-5' as v.InferOutput<typeof modelNameSchema>,
370+
time: {
371+
created: Date.parse(timestamp),
372+
},
373+
tokens: {
374+
input: 100,
375+
output: 50,
376+
},
377+
};
378+
}
379+
380+
function getSortedIsoTimestamps(entries: LoadedUsageEntry[]): string[] {
381+
return entries.map((entry) => entry.timestamp.toISOString()).sort();
382+
}
313383

314384
describe('data-loader', () => {
315385
it('should convert OpenCode message to LoadedUsageEntry', () => {
@@ -366,5 +436,68 @@ if (import.meta.vitest != null) {
366436
expect(entry.usage.cacheCreationInputTokens).toBe(0);
367437
expect(entry.costUSD).toBe(null);
368438
});
439+
440+
it('should filter OpenCode messages by since date', async () => {
441+
const root = await createOpenCodeMessageFixture([
442+
createTestMessage('msg_20240101', '2024-01-01T12:00:00.000Z'),
443+
createTestMessage('msg_20240102', '2024-01-02T12:00:00.000Z'),
444+
createTestMessage('msg_20240103', '2024-01-03T12:00:00.000Z'),
445+
]);
446+
447+
try {
448+
vi.stubEnv(OPENCODE_CONFIG_DIR_ENV, root);
449+
450+
const entries = await loadOpenCodeMessages({ since: '20240102' });
451+
452+
expect(getSortedIsoTimestamps(entries)).toEqual([
453+
'2024-01-02T12:00:00.000Z',
454+
'2024-01-03T12:00:00.000Z',
455+
]);
456+
} finally {
457+
await rm(root, { recursive: true, force: true });
458+
}
459+
});
460+
461+
it('should filter OpenCode messages by until date', async () => {
462+
const root = await createOpenCodeMessageFixture([
463+
createTestMessage('msg_20240101', '2024-01-01T12:00:00.000Z'),
464+
createTestMessage('msg_20240102', '2024-01-02T12:00:00.000Z'),
465+
createTestMessage('msg_20240103', '2024-01-03T12:00:00.000Z'),
466+
]);
467+
468+
try {
469+
vi.stubEnv(OPENCODE_CONFIG_DIR_ENV, root);
470+
471+
const entries = await loadOpenCodeMessages({ until: '20240102' });
472+
473+
expect(getSortedIsoTimestamps(entries)).toEqual([
474+
'2024-01-01T12:00:00.000Z',
475+
'2024-01-02T12:00:00.000Z',
476+
]);
477+
} finally {
478+
await rm(root, { recursive: true, force: true });
479+
}
480+
});
481+
482+
it('should filter OpenCode messages by since and until dates', async () => {
483+
const root = await createOpenCodeMessageFixture([
484+
createTestMessage('msg_20240101', '2024-01-01T12:00:00.000Z'),
485+
createTestMessage('msg_20240102', '2024-01-02T12:00:00.000Z'),
486+
createTestMessage('msg_20240103', '2024-01-03T12:00:00.000Z'),
487+
]);
488+
489+
try {
490+
vi.stubEnv(OPENCODE_CONFIG_DIR_ENV, root);
491+
492+
const entries = await loadOpenCodeMessages({
493+
since: '20240102',
494+
until: '20240102',
495+
});
496+
497+
expect(getSortedIsoTimestamps(entries)).toEqual(['2024-01-02T12:00:00.000Z']);
498+
} finally {
499+
await rm(root, { recursive: true, force: true });
500+
}
501+
});
369502
});
370503
}

0 commit comments

Comments
 (0)