diff --git a/app/electron/main.test.ts b/app/electron/main.test.ts index 8413b9d6..9a7111f1 100644 --- a/app/electron/main.test.ts +++ b/app/electron/main.test.ts @@ -45,6 +45,8 @@ const CHANNELS = [ 'codeburn:getSessionsContributions', 'codeburn:getCompareModels', 'codeburn:getCompare', + 'codeburn:getPeriodCompare', + 'codeburn:getPeriodCompareSessions', 'codeburn:getYield', 'codeburn:getSpendFlow', 'codeburn:getBranchSpend', @@ -106,6 +108,12 @@ const ARGV_CASES: Array<{ channel: string; args: unknown[]; argv: string[] }> = { channel: 'codeburn:getSessionsContributions', args: ['30days', 'claude', { from: '2026-07-01', to: '2026-07-11' }], argv: ['sessions', '--format', 'json', '--contributions', '--period', '30days', '--provider', 'claude', '--from', '2026-07-01', '--to', '2026-07-11'] }, { channel: 'codeburn:getCompareModels', args: ['month', 'codex'], argv: ['compare', '--format', 'json', '--period', 'month', '--provider', 'codex'] }, { channel: 'codeburn:getCompare', args: ['month', 'all', 'model-a', 'model-b'], argv: ['compare', '--format', 'json', '--period', 'month', '--model-a', 'model-a', '--model-b', 'model-b'] }, + { channel: 'codeburn:getPeriodCompare', args: [{ from: '2026-07-01', to: '2026-07-07' }, { from: '2026-07-08', to: '2026-07-14' }, 'claude'], argv: ['compare-periods', '--format', 'json', '--from-a', '2026-07-01', '--to-a', '2026-07-07', '--from-b', '2026-07-08', '--to-b', '2026-07-14', '--provider', 'claude'] }, + { channel: 'codeburn:getPeriodCompare', args: [{ from: '2026-07-01', to: '2026-07-07' }, { from: '2026-07-08', to: '2026-07-14' }, 'all'], argv: ['compare-periods', '--format', 'json', '--from-a', '2026-07-01', '--to-a', '2026-07-07', '--from-b', '2026-07-08', '--to-b', '2026-07-14'] }, + { channel: 'codeburn:getPeriodCompareSessions', args: [{ from: '2026-07-01', to: '2026-07-07' }, { from: '2026-07-08', to: '2026-07-14' }, 'all', 'project', '/work/app'], argv: ['compare-periods', '--format', 'sessions', '--from-a', '2026-07-01', '--to-a', '2026-07-07', '--from-b', '2026-07-08', '--to-b', '2026-07-14', '--dimension', 'project', '--key', '/work/app'] }, + // Claude sanitizes project paths to dash-leading slugs; the key rides in the + // VALUE position of --key, so a dash-leading key must survive validation. + { channel: 'codeburn:getPeriodCompareSessions', args: [{ from: '2026-07-01', to: '2026-07-07' }, { from: '2026-07-08', to: '2026-07-14' }, 'all', 'project', '-work-pricing'], argv: ['compare-periods', '--format', 'sessions', '--from-a', '2026-07-01', '--to-a', '2026-07-07', '--from-b', '2026-07-08', '--to-b', '2026-07-14', '--dimension', 'project', '--key', '-work-pricing'] }, { channel: 'codeburn:getYield', args: ['today', 'all'], argv: ['yield', '--format', 'json', '--period', 'today'] }, { channel: 'codeburn:getYield', args: ['today', 'claude'], argv: ['yield', '--format', 'json', '--period', 'today', '--provider', 'claude'] }, { channel: 'codeburn:getSpendFlow', args: ['month', 'openai'], argv: ['spend', '--format', 'flow-json', '--period', 'month', '--provider', 'openai'] }, @@ -835,6 +843,14 @@ describe('project filter', () => { expect(calls[1]).toEqual(['sessions', '--format', 'json', '--contributions', '--period', 'week', '--project=my-company', '--exclude=scratch']) await handlers['codeburn:getBranchSpend']!('week', 'all') expect(calls[2]).toEqual(['spend', '--format', 'branch-json', '--period', 'week', '--project=my-company', '--exclude=scratch']) + const rangeA = { from: '2026-07-01', to: '2026-07-07' } + const rangeB = { from: '2026-07-08', to: '2026-07-14' } + await handlers['codeburn:getPeriodCompare']!(rangeA, rangeB, 'all') + expect(calls[3]).toEqual(['compare-periods', '--format', 'json', '--from-a', '2026-07-01', '--to-a', '2026-07-07', '--from-b', '2026-07-08', '--to-b', '2026-07-14', '--project=my-company', '--exclude=scratch']) + // The drill-down too: a filtered-out project must not surface behind a + // contribution row either. + await handlers['codeburn:getPeriodCompareSessions']!(rangeA, rangeB, 'all', 'model', 'sonnet') + expect(calls[4]).toEqual(['compare-periods', '--format', 'sessions', '--from-a', '2026-07-01', '--to-a', '2026-07-07', '--from-b', '2026-07-08', '--to-b', '2026-07-14', '--project=my-company', '--exclude=scratch', '--dimension', 'model', '--key', 'sonnet']) }) }) diff --git a/app/electron/main.ts b/app/electron/main.ts index b009f5bd..b73a63bc 100644 --- a/app/electron/main.ts +++ b/app/electron/main.ts @@ -286,6 +286,25 @@ function vRange(range: DateRange | undefined): DateRange | undefined { } return range } +/** + * Drill-down contribution key (canonical project path or model id). Unlike + * vToken, a leading '-' is legal here: Claude sanitizes project paths by + * replacing separators with '-' (e.g. `/work/pricing` → `-work-pricing`), and + * the key is only ever emitted in the VALUE position of `--key`/`--dimension` + * pairs, where Commander binds the next token as the value — a dash-leading + * value cannot inject a flag through the argv array (no shell involved). + * Empty and NUL are still rejected. + */ +function vContributionKey(value: string): string { + if (!value || value.includes('\0')) throw new CliError('bad-args', 'invalid contribution key') + return value +} +/** vRange for channels where the range is REQUIRED (compare periods). */ +function vRequiredRange(range: DateRange | undefined, name: string): DateRange { + const v = vRange(range) + if (!v) throw new CliError('bad-args', `missing ${name} date range`) + return v +} function vCurrency(code: string): string { if (!/^[A-Z]{3}$/.test(code)) throw new CliError('bad-args', 'invalid currency code') return code @@ -561,6 +580,26 @@ export function createBridgeHandlers(deps: Deps = { spawnCli, spawnCliAction, re ...projectArgs(), '--model-a', vToken(modelA), '--model-b', vToken(modelB), ]), + // Compare periods (B minus A). Both ranges are REQUIRED local YYYY-MM-DD + // key pairs; the renderer computes the 7v7 default so argv stays explicit. + 'codeburn:getPeriodCompare': run((rangeA: DateRange, rangeB: DateRange, provider: string, background?: boolean) => [ + 'compare-periods', '--format', 'json', + '--from-a', vRequiredRange(rangeA, 'A').from, '--to-a', vRequiredRange(rangeA, 'A').to, + '--from-b', vRequiredRange(rangeB, 'B').from, '--to-b', vRequiredRange(rangeB, 'B').to, + ...providerArgs(vProvider(provider)), + ...projectArgs(), + ], 3), + 'codeburn:getPeriodCompareSessions': run((rangeA: DateRange, rangeB: DateRange, provider: string, dimension: string, key: string) => { + if (dimension !== 'project' && dimension !== 'model') throw new CliError('bad-args', 'invalid drill-down dimension') + return [ + 'compare-periods', '--format', 'sessions', + '--from-a', vRequiredRange(rangeA, 'A').from, '--to-a', vRequiredRange(rangeA, 'A').to, + '--from-b', vRequiredRange(rangeB, 'B').from, '--to-b', vRequiredRange(rangeB, 'B').to, + ...providerArgs(vProvider(provider)), + ...projectArgs(), + '--dimension', dimension, '--key', vContributionKey(key), + ] + }), 'codeburn:getYield': run((period: string, provider: string, range?: DateRange) => [ 'yield', '--format', 'json', '--period', vPeriod(period), ...providerArgs(vProvider(provider)), diff --git a/app/electron/preload.ts b/app/electron/preload.ts index 8e44bad7..32a4a927 100644 --- a/app/electron/preload.ts +++ b/app/electron/preload.ts @@ -29,6 +29,8 @@ const bridge = { getSessionsContributions: (period: string, provider: string, range?: DateRange, background?: boolean) => invoke('codeburn:getSessionsContributions', period, provider, range, background), getCompareModels: (period: string, provider: string, background?: boolean) => invoke('codeburn:getCompareModels', period, provider, background), getCompare: (period: string, provider: string, modelA: string, modelB: string) => invoke('codeburn:getCompare', period, provider, modelA, modelB), + getPeriodCompare: (rangeA: DateRange, rangeB: DateRange, provider: string, background?: boolean) => invoke('codeburn:getPeriodCompare', rangeA, rangeB, provider, background), + getPeriodCompareSessions: (rangeA: DateRange, rangeB: DateRange, provider: string, dimension: string, key: string) => invoke('codeburn:getPeriodCompareSessions', rangeA, rangeB, provider, dimension, key), getYield: (period: string, provider: string, range?: DateRange, background?: boolean) => invoke('codeburn:getYield', period, provider, range, background), getSpendFlow: (period: string, provider: string, range?: DateRange, background?: boolean) => invoke('codeburn:getSpendFlow', period, provider, range, background), getBranchSpend: (period: string, provider: string, range?: DateRange, background?: boolean) => invoke('codeburn:getBranchSpend', period, provider, range, background), diff --git a/app/renderer/App.test.tsx b/app/renderer/App.test.tsx index 0eece1eb..e06e0d9e 100644 --- a/app/renderer/App.test.tsx +++ b/app/renderer/App.test.tsx @@ -402,7 +402,7 @@ describe('App shortcuts', () => { render() expect(await screen.findByText('Most expensive sessions')).toBeInTheDocument() - expect(screen.getByText(`${mod}1-8`)).toBeInTheDocument() + expect(screen.getByText(`${mod}1-8,9`)).toBeInTheDocument() expect(screen.getAllByText(`${mod},`).length).toBeGreaterThan(0) expect(screen.getByText(`${mod}R`)).toBeInTheDocument() expect(screen.queryByText('Command')).not.toBeInTheDocument() diff --git a/app/renderer/App.tsx b/app/renderer/App.tsx index 26728cf0..c58a4ecf 100644 --- a/app/renderer/App.tsx +++ b/app/renderer/App.tsx @@ -19,6 +19,8 @@ import { formatCompact, formatUsd, setActiveCurrency } from './lib/format' import { EMPTY_FILTERS, filtersActive, + modelFilters, + projectFilters, unionFilters, type InvestigationFilters, } from './lib/investigation' @@ -47,6 +49,7 @@ import { Models } from './sections/Models' import { INITIAL_VISIBLE, Sessions, type SessionSort } from './sections/Sessions' import { PullRequestsContent } from './sections/PullRequests' import { Compare } from './sections/Compare' +import { PeriodCompare } from './sections/PeriodCompare' import { Plans } from './sections/Plans' import { Settings, type SettingsPane } from './sections/Settings' import { SpendContent } from './sections/Spend' @@ -141,6 +144,7 @@ const SECTION_TITLES: Record = { optimize: 'Optimize', models: 'Models', compare: 'Compare', + periods: 'Compare periods', plans: 'Plans', settings: 'Settings', plugins: 'Plugins', @@ -728,6 +732,20 @@ function AppMain() { trackEvent('section_view', { section: next }) }, [commitNav]) + /** Compare periods' contribution drill-down: the same Sessions destination + * every other drill-through lands on, scoped to the clicked side's range + * and filtered to the contribution's own key. Not a union: the range moves, + * so any previous selection no longer describes this population. */ + const inspectContribution = useCallback((range: DateRange, dimension: 'project' | 'model', key: string) => { + commitNav({ + section: 'sessions', + range, + filters: dimension === 'project' ? projectFilters(key) : modelFilters([key]), + sessionId: null, + visibleCount: INITIAL_VISIBLE, + }) + }, [commitNav]) + useEffect(() => { const onKeyDown = (event: KeyboardEvent) => { // Back/Forward in app history: the platform navigation chords (Cmd+[ / @@ -764,6 +782,7 @@ function AppMain() { else if (key === '5') navigate('optimize') else if (key === '6') navigate('models') else if (key === '7') navigate('compare') + else if (key === '9') navigate('periods') else if (key === '8') navigate('plans') else if (key === ',') navigate('settings') else if (key === 'r') refreshVisible() @@ -925,6 +944,8 @@ function AppMain() { ) : section === 'compare' ? ( + ) : section === 'periods' ? ( + ) : ( )} @@ -935,7 +956,7 @@ function AppMain() { {section !== 'settings' && ( { render( {}} />) const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') const labels = screen.getAllByRole('button').map(item => item.textContent?.replace(/(⌘|Ctrl\+)[\d,.]/, '')) - expect(labels).toEqual(['Overview', 'Sessions', 'Pull requests', 'Spend', 'Optimize', 'Models', 'Compare', 'Plans', 'Settings', 'Plugins']) + expect(labels).toEqual(['Overview', 'Sessions', 'Pull requests', 'Spend', 'Optimize', 'Models', 'Compare', 'Compare periods', 'Plans', 'Settings', 'Plugins']) expect(screen.getByRole('button', { name: new RegExp(`Sessions.*${esc(mod)}2`) })).toBeInTheDocument() expect(screen.getByRole('button', { name: new RegExp(`Pull requests.*${esc(mod)}3`) })).toBeInTheDocument() expect(screen.getByRole('button', { name: new RegExp(`Compare.*${esc(mod)}7`) })).toBeInTheDocument() diff --git a/app/renderer/components/Sidebar.tsx b/app/renderer/components/Sidebar.tsx index 0986c8dc..c1a3b414 100644 --- a/app/renderer/components/Sidebar.tsx +++ b/app/renderer/components/Sidebar.tsx @@ -6,7 +6,7 @@ import type { CompanionStatus } from '../lib/types' import { AboutModal, SOCIALS } from './AboutModal' import { FlameMark } from './FlameMark' -export type Section = 'overview' | 'sessions' | 'pullRequests' | 'spend' | 'optimize' | 'models' | 'compare' | 'plans' | 'settings' | 'plugins' +export type Section = 'overview' | 'sessions' | 'pullRequests' | 'spend' | 'optimize' | 'models' | 'compare' | 'periods' | 'plans' | 'settings' | 'plugins' export const NAV_ITEMS: Array<{ id: Section; label: string; key: string; icon: ReactNode }> = [ { id: 'overview', label: 'Overview', key: '1', icon: ( @@ -30,6 +30,9 @@ export const NAV_ITEMS: Array<{ id: Section; label: string; key: string; icon: R { id: 'compare', label: 'Compare', key: '7', icon: ( ) }, + { id: 'periods', label: 'Compare periods', key: '9', icon: ( + + ) }, { id: 'plans', label: 'Plans', key: '8', icon: ( ) }, diff --git a/app/renderer/lib/types.ts b/app/renderer/lib/types.ts index 5786d4bc..58f5411d 100644 --- a/app/renderer/lib/types.ts +++ b/app/renderer/lib/types.ts @@ -723,6 +723,99 @@ export type CompareJsonReport = { workingStyle: WorkingStyleRow[] } +// ---- Compare periods (period-diff; B minus A, A is the reference) ---- +// Mirrors the JSON emitted by `codeburn compare-periods --format json` +// (src/period-diff.ts). Raw (unrounded) numbers; the UI formats. + +export type PeriodRangeInfo = { from: string; to: string; days: number } + +export type PeriodContribution = { + key: string + costA: number + costB: number + diff: number + /** diff / |costA| x 100; null when costA is 0 (the row is `new`). */ + pct: number | null + status: 'new' | 'gone' | 'up' | 'down' | 'flat' + callsA: number + callsB: number +} + +export type PeriodTotalsRow = { + cost: number + calls: number + sessions: number + inputTokens: number + outputTokens: number + cacheReadTokens: number + cacheWriteTokens: number + savingsUSD: number + estimatedCostUSD: number +} + +export type PeriodTotalsDiff = { + A: PeriodTotalsRow + B: PeriodTotalsRow + diff: PeriodTotalsRow + pct: Record +} + +export type NormalizedMetric = { a: number | null; b: number | null; diff: number | null; pct: number | null } + +export type AggregateDayRow = { date: string; historyCost: number; detailCost: number; aggregateOnly: number } + +export type PeriodHistoryBasis = { + historyCost: { A: number; B: number } + detailCost: { A: number; B: number } + days: { A: AggregateDayRow[]; B: AggregateDayRow[] } + aggregateOnly: { A: number; B: number } + basis: string +} + +export type PeriodDiffReport = { + schema: 1 + provider: string + rangeA: PeriodRangeInfo + rangeB: PeriodRangeInfo + overlapDays: number + durationDeltaDays: number + totals: PeriodTotalsDiff + projects: PeriodContribution[] + models: PeriodContribution[] + normalized: { + perDay: NormalizedMetric + per100Calls: NormalizedMetric + denominators: { perDay: string; per100Calls: string } + } + coverage: { + unpricedModelsA: Array<{ model: string; calls: number }> + unpricedModelsB: Array<{ model: string; calls: number }> + pricingCoverageA: number | null + pricingCoverageB: number | null + } + history?: PeriodHistoryBasis +} + +export type PeriodSessionDiff = { + dimension: 'project' | 'model' + key: string + provider: string + rangeA: PeriodRangeInfo + rangeB: PeriodRangeInfo + sessions: Array<{ + identity: string + provider: string + sessionId: string + project: string + title?: string + costA: number + costB: number + diff: number + callsA: number + callsB: number + }> +} + // ————— src/models.ts + src/audit-report.ts (audit --format json) ————— /** Per-token rates used for pricing (src/models.ts ModelCosts). */ @@ -890,6 +983,10 @@ export interface CodeburnBridge { getSessionsContributions(period: Period, provider: string, range?: DateRange, background?: boolean): Promise getCompareModels(period: Period, provider: string, background?: boolean): Promise getCompare(period: Period, provider: string, modelA: string, modelB: string): Promise + /** Compare periods (B minus A). Both ranges are required local YYYY-MM-DD keys. */ + getPeriodCompare(rangeA: DateRange, rangeB: DateRange, provider: string, background?: boolean): Promise + /** Sessions behind one project/model contribution, joined across A and B. */ + getPeriodCompareSessions(rangeA: DateRange, rangeB: DateRange, provider: string, dimension: 'project' | 'model', key: string): Promise getYield(period: Period, provider: string, range?: DateRange, background?: boolean): Promise getSpendFlow(period: Period, provider: string, range?: DateRange, background?: boolean): Promise /** Spend per canonical project × branch (`spend --format branch-json`). */ diff --git a/app/renderer/sections/Overview.tsx b/app/renderer/sections/Overview.tsx index 7bba0e09..705bfd15 100644 --- a/app/renderer/sections/Overview.tsx +++ b/app/renderer/sections/Overview.tsx @@ -736,7 +736,7 @@ export function OverviewContent({ provider?: string range?: DateRange | null overview: Polled - onNavigate?: (section: 'optimize' | 'sessions') => void + onNavigate?: (section: 'optimize' | 'sessions' | 'periods') => void /** Drill-through entries: day bars, expensive sessions, models, categories. */ onInvestigate?: (request: InvestigateRequest) => void ready?: boolean @@ -922,6 +922,11 @@ export function OverviewContent({ +
+
Compare periods

Pick two ranges and see exactly what drove the change — projects, models, and the sessions behind them.

+ +
+
diff --git a/app/renderer/sections/PeriodCompare.test.tsx b/app/renderer/sections/PeriodCompare.test.tsx new file mode 100644 index 00000000..7afc0565 --- /dev/null +++ b/app/renderer/sections/PeriodCompare.test.tsx @@ -0,0 +1,215 @@ +// @vitest-environment jsdom +import { render, screen, waitFor, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +import type { PeriodDiffReport, PeriodSessionDiff } from '../lib/types' +import { __resetPolledMemo } from '../hooks/usePolled' +import { PeriodCompare, defaultSevenRanges } from './PeriodCompare' + +const mocks = vi.hoisted(() => ({ + getPeriodCompare: vi.fn<(a: { from: string; to: string }, b: { from: string; to: string }, provider: string) => Promise>(), + getPeriodCompareSessions: vi.fn<(a: { from: string; to: string }, b: { from: string; to: string }, provider: string, dimension: string, key: string) => Promise>(), + telemetryTrack: vi.fn<(name: string, props?: Record) => Promise>(), +})) +vi.mock('../lib/ipc', async orig => { + const actual = await orig() + return { ...actual, codeburn: mocks } +}) + +const RANGE_A = { from: '2026-03-02', to: '2026-03-08' } +const RANGE_B = { from: '2026-03-09', to: '2026-03-15' } + +const report: PeriodDiffReport = { + schema: 1, + provider: 'all', + rangeA: { ...RANGE_A, days: 7 }, + rangeB: { ...RANGE_B, days: 7 }, + overlapDays: 0, + durationDeltaDays: 0, + totals: { + A: { cost: 100, calls: 10, sessions: 3, inputTokens: 1000, outputTokens: 500, cacheReadTokens: 200, cacheWriteTokens: 100, savingsUSD: 0, estimatedCostUSD: 0 }, + B: { cost: 160, calls: 16, sessions: 4, inputTokens: 1800, outputTokens: 700, cacheReadTokens: 300, cacheWriteTokens: 120, savingsUSD: 0, estimatedCostUSD: 0 }, + diff: { cost: 60, calls: 6, sessions: 1, inputTokens: 800, outputTokens: 200, cacheReadTokens: 100, cacheWriteTokens: 20, savingsUSD: 0, estimatedCostUSD: 0 }, + pct: { cost: 60, calls: 60, sessions: 100 / 3, inputTokens: 80, outputTokens: 40, cacheReadTokens: 50, cacheWriteTokens: 20, savingsUSD: null, estimatedCostUSD: null }, + }, + projects: [ + { key: '/work/eff', costA: 10, costB: 20, diff: 10, pct: 100, status: 'up', callsA: 10, callsB: 1000 }, + { key: '/work/new', costA: 0, costB: 5, diff: 5, pct: null, status: 'new', callsA: 0, callsB: 50 }, + { key: '/work/gone', costA: 30, costB: 0, diff: -30, pct: -100, status: 'gone', callsA: 3, callsB: 0 }, + ], + models: [ + { key: 'claude-sonnet-4-5', costA: 40, costB: 160, diff: 120, pct: 300, status: 'up', callsA: 10, callsB: 16 }, + ], + normalized: { + perDay: { a: 100 / 7, b: 160 / 7, diff: 60 / 7, pct: 60 }, + per100Calls: { a: 1000, b: 1000, diff: 0, pct: 0 }, + denominators: { perDay: 'calendar days in the range (A: 7, B: 7)', per100Calls: 'API calls × 100 (A: 10, B: 16)' }, + }, + coverage: { + unpricedModelsA: [{ model: 'mystery-model', calls: 4 }], + unpricedModelsB: [], + pricingCoverageA: 0.9, + pricingCoverageB: 1, + }, + history: { + historyCost: { A: 112, B: 0 }, + detailCost: { A: 100, B: 160 }, + days: { A: [{ date: '2026-03-05', historyCost: 12, detailCost: 0, aggregateOnly: 12 }], B: [] }, + aggregateOnly: { A: 12, B: 0 }, + basis: 'Totals come from parsed session transcripts.', + }, +} + +const sessionsReport: PeriodSessionDiff = { + dimension: 'project', + key: '/work/eff', + provider: 'all', + rangeA: { ...RANGE_A, days: 7 }, + rangeB: { ...RANGE_B, days: 7 }, + sessions: [ + { identity: 'claude\0/work/eff\0s1', provider: 'claude', sessionId: 's1', project: '/work/eff', title: 'long run', costA: 10, costB: 20, diff: 10, callsA: 10, callsB: 1000 }, + ], +} + +beforeEach(() => { + globalThis.localStorage?.clear() + __resetPolledMemo() + // Start from explicit custom ranges so assertions are independent of the + // runner's today (the default preset is covered by its own test). + globalThis.localStorage?.setItem('codeburn.periodCompare.v1', JSON.stringify({ + preset: 'custom', rangeA: RANGE_A, rangeB: RANGE_B, lens: 'projects', view: 'raw', + })) + mocks.getPeriodCompare.mockReset().mockResolvedValue(report) + mocks.getPeriodCompareSessions.mockReset().mockResolvedValue(sessionsReport) + mocks.telemetryTrack.mockReset().mockResolvedValue(true) +}) + +describe('PeriodCompare', () => { + it('recomputes percentages and direction for daily averages with unequal lengths', async () => { + const unequal: PeriodDiffReport = { ...report, rangeA: { ...report.rangeA, days: 1 }, rangeB: { ...report.rangeB, days: 10 }, + projects: [{ key: '/work/eff', costA: 100, costB: 160, diff: 60, pct: 60, status: 'up', callsA: 10, callsB: 10 }] } + mocks.getPeriodCompare.mockResolvedValue(unequal) + render() + await screen.findByText('Contributions by project') + await userEvent.setup().click(screen.getByRole('tab', { name: 'Per day' })) + const row = screen.getByRole('button', { name: /\/work\/eff:.*Down/ }) + expect(row).toHaveTextContent('$100.00') + expect(row).toHaveTextContent('$16.00') + expect(row).toHaveTextContent('−$84.00') + expect(row).toHaveTextContent('−84.0%') + expect(row).not.toHaveTextContent('+60.0%') + }) + + it('does not reuse session details from a different B range after remount', async () => { + const user = userEvent.setup() + const first = render() + await user.click(await screen.findByRole('button', { name: /\/work\/eff/ })) + expect(await screen.findByLabelText('Sessions behind /work/eff')).toHaveTextContent('$20.00') + expect(mocks.getPeriodCompareSessions).toHaveBeenCalledTimes(1) + first.unmount() + const rangeB = { from: RANGE_B.from, to: '2026-03-18' } + localStorage.setItem('codeburn.periodCompare.v1', JSON.stringify({ preset: 'custom', rangeA: RANGE_A, rangeB, lens: 'projects', view: 'raw' })) + mocks.getPeriodCompare.mockResolvedValue({ ...report, rangeB: { ...rangeB, days: 10 } }) + mocks.getPeriodCompareSessions.mockResolvedValue({ ...sessionsReport, rangeB: { ...rangeB, days: 10 }, sessions: [{ ...sessionsReport.sessions[0], costB: 250, diff: 240 }] }) + render() + await user.click(await screen.findByRole('button', { name: /\/work\/eff/ })) + await waitFor(() => expect(mocks.getPeriodCompareSessions).toHaveBeenCalledTimes(2)) + expect(screen.getByLabelText('Sessions behind /work/eff')).toHaveTextContent('$250.00') + }) + + it('renders both ranges, the totals difference, and the coverage notes', async () => { + render() + expect(await screen.findByText('Totals')).toBeInTheDocument() + expect(screen.getByRole('status')).toHaveTextContent('A spans 7 days') + expect(screen.getByLabelText('Totals difference')).toHaveTextContent('API-equivalent cost') + // The global diff (B − A) is on screen, not just the two columns. + const totals = screen.getByLabelText('Totals difference') + expect(totals).toHaveTextContent('+$60.00') + expect(totals).toHaveTextContent('+60.0%') + // Aggregate-only carried history is reported separately, never folded in. + expect(screen.getByText(/Aggregate history without session detail/)).toBeInTheDocument() + expect(screen.getByText(/Missing pricing \(unknown, not zero\)/)).toBeInTheDocument() + }) + + it('labels a zero-A contribution New without a percentage, and Gone for a disappeared one', async () => { + const user = userEvent.setup() + render() + await screen.findByText('Contributions by project') + expect(screen.getByText('New')).toBeInTheDocument() + expect(screen.getByText('Gone')).toBeInTheDocument() + const newKey = screen.getByRole('button', { name: /\/work\/new/ }) + expect(newKey).toHaveTextContent('New') + expect(newKey).not.toHaveTextContent('%') + // Gone carries its −100%. + expect(screen.getByRole('button', { name: /\/work\/gone/ })).toHaveTextContent('Gone') + expect(screen.getByRole('button', { name: /\/work\/gone/ })).toHaveTextContent('−100%') + + // Clicking a contribution opens the session drill-down for it. + await user.click(screen.getByRole('button', { name: /\/work\/eff/ })) + expect(await screen.findByLabelText('Sessions behind /work/eff')).toBeInTheDocument() + expect(mocks.getPeriodCompareSessions).toHaveBeenCalledWith(RANGE_A, RANGE_B, 'all', 'project', '/work/eff') + expect(screen.getByText('long run')).toBeInTheDocument() + }) + + it('drills into sessions with the clicked side\'s range AND the contribution key', async () => { + const user = userEvent.setup() + const onInspectContribution = vi.fn() + render() + await user.click(await screen.findByRole('button', { name: /\/work\/eff/ })) + const drill = await screen.findByLabelText('Sessions behind /work/eff') + await user.click(within(drill).getByRole('button', { name: 'Open A in Sessions →' })) + expect(onInspectContribution).toHaveBeenCalledWith(RANGE_A, 'project', '/work/eff') + await user.click(within(drill).getByRole('button', { name: 'Open B in Sessions →' })) + expect(onInspectContribution).toHaveBeenCalledWith(RANGE_B, 'project', '/work/eff') + }) + + it('per-100-calls view recomputes honestly: cheaper per call is Down, zero calls is —', async () => { + const user = userEvent.setup() + render() + await screen.findByText('Contributions by project') + // Raw: /work/eff is Up (+100%). + expect(screen.getByRole('button', { name: /\/work\/eff/ })).toHaveTextContent('+100%') + await user.click(screen.getByRole('tab', { name: 'Per 100 calls' })) + // Raw cost doubled, but per call it fell $100 → $2 per 100 calls: Down, not Up. + const eff = screen.getByRole('button', { name: /\/work\/eff/ }) + expect(eff).toHaveTextContent('−98.0%') + // Zero calls in A: no cost per call exists — em dash, and still New. + const fresh = screen.getByRole('button', { name: /\/work\/new/ }) + expect(fresh).toHaveTextContent('—') + expect(fresh).toHaveTextContent('New') + }) + + it('switches to the model lens and drills by model', async () => { + const user = userEvent.setup() + render() + await screen.findByText('Contributions by project') + await user.click(screen.getByRole('tab', { name: 'Models' })) + expect(await screen.findByText('Contributions by model')).toBeInTheDocument() + await user.click(screen.getByRole('button', { name: /claude-sonnet-4-5/ })) + await waitFor(() => expect(mocks.getPeriodCompareSessions).toHaveBeenCalledWith(RANGE_A, RANGE_B, 'all', 'model', 'claude-sonnet-4-5')) + }) + + it('persists the A/B selection so returning to the section keeps it', async () => { + const user = userEvent.setup() + const { unmount } = render() + await screen.findByText('Totals') + await user.click(screen.getByRole('button', { name: 'Swap A and B' })) + // The swap re-fetches with the ranges exchanged. + await waitFor(() => expect(mocks.getPeriodCompare).toHaveBeenCalledWith(RANGE_B, RANGE_A, 'all')) + unmount() + + // Returning to the section (fresh component, no refetch needed) restores + // the swapped selection from storage: A shows B's old dates. + render() + await screen.findByText('Totals') + expect(screen.getByLabelText('A · reference: 2026-03-09 to 2026-03-15')).toBeInTheDocument() + expect(screen.getByLabelText('B · analyzed: 2026-03-02 to 2026-03-08')).toBeInTheDocument() + }) + + it('computes the default preset as the last seven complete days vs the seven before', () => { + const ranges = defaultSevenRanges(new Date(2026, 2, 15, 12, 0, 0)) + expect(ranges.rangeB).toEqual({ from: '2026-03-08', to: '2026-03-14' }) + expect(ranges.rangeA).toEqual({ from: '2026-03-01', to: '2026-03-07' }) + }) +}) diff --git a/app/renderer/sections/PeriodCompare.tsx b/app/renderer/sections/PeriodCompare.tsx new file mode 100644 index 00000000..01d6ef7e --- /dev/null +++ b/app/renderer/sections/PeriodCompare.tsx @@ -0,0 +1,618 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { CliErrorPanel } from '../components/CliErrorPanel' +import { EmptyNote } from '../components/EmptyState' +import { SectionSkeleton } from '../components/Skeleton' +import { SegTabs } from '../components/SegTabs' +import { SwitchingBanner } from '../components/SwitchingBanner' +import { RangeCalendar } from '../components/RangeCalendar' +import { usePolled } from '../hooks/usePolled' +import { formatCompact, formatUsd } from '../lib/format' +import { codeburn } from '../lib/ipc' +import { reportMemoKey } from '../lib/reportMemoKey' +import { trackEvent } from '../lib/track' +import type { DateRange, PeriodContribution, PeriodDiffReport, PeriodRangeInfo, PeriodSessionDiff } from '../lib/types' + +// Compare periods: two ranges, one deterministic difference. A is the +// reference, B the analyzed period; every difference on screen is B − A, +// straight from `codeburn compare-periods` (src/period-diff.ts). Nothing here +// recomputes usage — the renderer never reads logs or aggregates sessions. + +type Lens = 'projects' | 'models' +type View = 'raw' | 'perDay' | 'per100Calls' + +type Persisted = { preset: 'last7' | 'custom'; rangeA: DateRange; rangeB: DateRange; lens: Lens; view: View } + +const STORAGE_KEY = 'codeburn.periodCompare.v1' + +function readPersisted(): Persisted | null { + try { + const raw = globalThis.localStorage?.getItem(STORAGE_KEY) + if (!raw) return null + const parsed = JSON.parse(raw) as Partial + if (!parsed?.rangeA?.from || !parsed?.rangeB?.from) return null + return { + preset: parsed.preset === 'custom' ? 'custom' : 'last7', + rangeA: { from: parsed.rangeA.from, to: parsed.rangeA.to }, + rangeB: { from: parsed.rangeB.from, to: parsed.rangeB.to }, + lens: parsed.lens === 'models' ? 'models' : 'projects', + view: parsed.view === 'perDay' || parsed.view === 'per100Calls' ? parsed.view : 'raw', + } + } catch { return null } +} + +function persist(state: Persisted): void { + try { globalThis.localStorage?.setItem(STORAGE_KEY, JSON.stringify(state)) } catch { /* storage can be unavailable */ } +} + +/// Mirror of the CLI default (src/period-diff.ts defaultSevenDayRanges): +/// B = the last seven COMPLETE local calendar days (today is never complete), +/// A = the seven before that. Local time only — never UTC. +export function defaultSevenRanges(now = new Date()): { rangeA: DateRange; rangeB: DateRange } { + const key = (offset: number): string => { + const d = new Date(now.getFullYear(), now.getMonth(), now.getDate() + offset) + return localKey(d) + } + return { + rangeB: { from: key(-7), to: key(-1) }, + rangeA: { from: key(-14), to: key(-8) }, + } +} + +function localKey(d: Date): string { + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}` +} + +function formatDayShort(key: string): string { + const [y, m, d] = key.split('-').map(Number) + return new Date(y, m - 1, d).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) +} + +function signedUsd(value: number): string { + const body = formatUsd(Math.abs(value)) + if (value > 0) return `+${body}` + if (value < 0) return `−${body}` + return body +} + +function signedPct(value: number | null): string { + if (value === null) return '—' + const body = `${Math.abs(value) >= 100 ? Math.round(Math.abs(value)) : Math.abs(value).toFixed(1)}%` + return value > 0 ? `+${body}` : value < 0 ? `−${body}` : '0%' +} + +const STATUS_LABEL: Record = { + new: 'New', + gone: 'Gone', + up: 'Up', + down: 'Down', + flat: 'Flat', +} + +/// One lens row under a normalization view. Raw rows come straight from the +/// report; normalized views recompute differences, percentages and direction +/// from each side's own denominator — a +/// zero-call side has NO cost-per-call, never zero. +function normalizeRow(row: PeriodContribution, view: View, daysA: number, daysB: number): { a: number | null; b: number | null; diff: number | null; pct: number | null; status: PeriodContribution['status'] } { + if (view === 'raw') return { a: row.costA, b: row.costB, diff: row.diff, pct: row.pct, status: row.status } + const a = view === 'perDay' + ? (daysA > 0 ? row.costA / daysA : null) + : (row.callsA > 0 ? row.costA * 100 / row.callsA : null) + const b = view === 'perDay' + ? (daysB > 0 ? row.costB / daysB : null) + : (row.callsB > 0 ? row.costB * 100 / row.callsB : null) + let status: PeriodContribution['status'] + if ((a === null || a === 0) && b !== null && b !== 0) status = 'new' + else if ((b === null || b === 0) && a !== null && a !== 0) status = 'gone' + else if (a === null && b === null) status = 'flat' + else if (b! > a!) status = 'up' + else if (b! < a!) status = 'down' + else status = 'flat' + const diff = a !== null && b !== null ? b - a : null + const pct = a !== null && Math.abs(a) > 0 && diff !== null ? (diff / Math.abs(a)) * 100 : null + return { a, b, diff, pct, status } +} + +export function PeriodCompare({ + provider, + refreshToken = 0, + ready = true, + onInspectContribution, +}: { + provider: string + refreshToken?: number + ready?: boolean + /** Navigation adapter (until the goal-8 navigation lands): open the existing + * Sessions section scoped to one of the compared ranges. */ + onInspectContribution?: (range: DateRange, dimension: 'project' | 'model', key: string) => void +}) { + const saved = useMemo(readPersisted, []) + const defaults = useMemo(() => defaultSevenRanges(), []) + const [preset, setPreset] = useState(saved?.preset ?? 'last7') + const [rangeA, setRangeA] = useState(saved?.rangeA ?? defaults.rangeA) + const [rangeB, setRangeB] = useState(saved?.rangeB ?? defaults.rangeB) + const [lens, setLens] = useState(saved?.lens ?? 'projects') + const [view, setView] = useState(saved?.view ?? 'raw') + const [drill, setDrill] = useState<{ dimension: 'project' | 'model'; key: string } | null>(null) + + useEffect(() => { + persist({ preset, rangeA, rangeB, lens, view }) + }, [preset, rangeA, rangeB, lens, view]) + + const report = usePolled( + () => codeburn.getPeriodCompare(rangeA, rangeB, provider), + [rangeA.from, rangeA.to, rangeB.from, rangeB.to, provider, refreshToken], + { enabled: ready, memoKey: reportMemoKey('periodcompare-v2', 'week', provider, rangeA, `${rangeB.from}..${rangeB.to}`) }, + ) + + // One event per distinct (lens, view) actually put on screen, not per + // keystroke. Enum values only. + const trackedConfig = useRef(null) + useEffect(() => { + if (!report.data) return + const config = `${lens}|${view}` + if (trackedConfig.current === config) return + trackedConfig.current = config + trackEvent('period_compare_view', { lens, view }) + }, [report.data, lens, view]) + + const swap = useCallback(() => { + setRangeA(rangeB) + setRangeB(rangeA) + }, [rangeA, rangeB]) + + const pickPreset = useCallback((value: string) => { + if (value === 'last7') { + const next = defaultSevenRanges() + setPreset('last7') + setRangeA(next.rangeA) + setRangeB(next.rangeB) + } else { + setPreset('custom') + } + }, []) + + return ( +
+ {report.switching && } +
+
+ + +
+
+ + +
+ +
+ + {!report.data + ? report.error + ? + : + : ( + <> + + + + + + )} +
+ ) +} + +function RangeField({ label, value, onChange }: { label: string; value: DateRange; onChange: (range: DateRange) => void }) { + const [open, setOpen] = useState(false) + const wrapRef = useRef(null) + useEffect(() => { + if (!open) return + const onPointerDown = (event: MouseEvent) => { + if (!wrapRef.current?.contains(event.target as Node)) setOpen(false) + } + const onKeyDown = (event: KeyboardEvent) => { + if (event.key === 'Escape') setOpen(false) + } + document.addEventListener('mousedown', onPointerDown) + document.addEventListener('keydown', onKeyDown) + return () => { + document.removeEventListener('mousedown', onPointerDown) + document.removeEventListener('keydown', onKeyDown) + } + }, [open]) + + return ( +
+ {label} + + {open && ( +
+ { + onChange(range) + setOpen(false) + }} + /> +
+ )} +
+ ) +} + +function RangeMeta({ rangeA, rangeB }: { rangeA: DateRange; rangeB: DateRange }) { + const days = (range: DateRange): number => { + // Local midnight walk — same arithmetic as the engine (src/period-diff.ts). + const [fy, fm, fd] = range.from.split('-').map(Number) + const [ty, tm, td] = range.to.split('-').map(Number) + const cursor = new Date(fy, fm - 1, fd) + const end = new Date(ty, tm - 1, td) + if (cursor > end) return 0 + let count = 0 + while (cursor <= end) { count++; cursor.setDate(cursor.getDate() + 1) } + return count + } + const daysA = days(rangeA) + const daysB = days(rangeB) + const overlapStart = rangeA.from > rangeB.from ? rangeA.from : rangeB.from + const overlapEnd = rangeA.to < rangeB.to ? rangeA.to : rangeB.to + const overlap = overlapStart <= overlapEnd ? days({ from: overlapStart, to: overlapEnd }) : 0 + const delta = daysB - daysA + return ( +

+ A spans {daysA} {daysA === 1 ? 'day' : 'days'} · B spans {daysB} {daysB === 1 ? 'day' : 'days'} + {delta !== 0 && <> · duration differs by {delta > 0 ? '+' : ''}{delta} {Math.abs(delta) === 1 ? 'day' : 'days'}} + {overlap > 0 && <> · the ranges overlap on {overlap} {overlap === 1 ? 'day' : 'days'} — overlapping days count in BOTH sides} + · all differences are B − A +

+ ) +} + +function TotalsCard({ report }: { report: PeriodDiffReport }) { + const rows: Array<{ label: string; get: (t: PeriodDiffReport['totals']['A']) => number }> = [ + { label: 'API-equivalent cost', get: t => t.cost }, + { label: 'API calls', get: t => t.calls }, + { label: 'Sessions', get: t => t.sessions }, + { label: 'Input tokens', get: t => t.inputTokens }, + { label: 'Output tokens', get: t => t.outputTokens }, + { label: 'Cache read tokens', get: t => t.cacheReadTokens }, + { label: 'Cache write tokens', get: t => t.cacheWriteTokens }, + { label: 'Local-model savings', get: t => t.savingsUSD }, + { label: 'Estimated-price cost', get: t => t.estimatedCostUSD }, + ] + const fmt = (label: string, value: number): string => { + if (label.includes('cost') || label.includes('savings')) return formatUsd(value) + if (label.includes('tokens')) return formatCompact(value) + return value.toLocaleString('en-US') + } + // A range whose sources aged off disk is explained by the durable daily + // history alone, which carries no session detail. That cost is real and it is + // NOT in these totals, so say so where the totals are read — not only in the + // Coverage card at the bottom of the page. + const carriedA = report.history?.aggregateOnly.A ?? 0 + const carriedB = report.history?.aggregateOnly.B ?? 0 + return ( +
+

Totals

B − A · API-equivalent cost is not a subscription bill
+ {(carriedA > 0 || carriedB > 0) && ( +

+ Session detail only. A further {formatUsd(carriedA)} (A) and {formatUsd(carriedB)} (B) of daily history + has no session detail behind it and is NOT in these totals — see Coverage & basis. +

+ )} +
+
+ MetricABDiff% +
+ {rows.map(row => { + const a = row.get(report.totals.A) + const b = row.get(report.totals.B) + const diff = row.get(report.totals.diff) + const pct = report.totals.pct[rowLabelKey(row.label)] + return ( +
+ {row.label} + {fmt(row.label, a)} + {fmt(row.label, b)} + {signed(row, diff)} + {signedPct(pct)} +
+ ) + })} +
+
+ ) +} + +function signed(row: { label: string }, diff: number): string { + if (row.label.includes('cost') || row.label.includes('savings')) return signedUsd(diff) + if (row.label.includes('tokens')) return signedCompact(diff) + const body = Math.abs(diff).toLocaleString('en-US') + return diff > 0 ? `+${body}` : diff < 0 ? `−${body}` : body +} + +function signedCompact(value: number): string { + const body = formatCompact(Math.abs(value)) + return value > 0 ? `+${body}` : value < 0 ? `−${body}` : body +} + +function diffClass(value: number, label: string): string { + if (!label.includes('cost')) return '' + if (value > 0) return 'pcmp-up' + if (value < 0) return 'pcmp-down' + return '' +} + +// The totals diff table keys its percent column by display label; map back to +// the PeriodTotalsRow keys the report uses. +const PCT_KEY_BY_LABEL: Record = { + 'API-equivalent cost': 'cost', + 'API calls': 'calls', + 'Sessions': 'sessions', + 'Input tokens': 'inputTokens', + 'Output tokens': 'outputTokens', + 'Cache read tokens': 'cacheReadTokens', + 'Cache write tokens': 'cacheWriteTokens', + 'Local-model savings': 'savingsUSD', + 'Estimated-price cost': 'estimatedCostUSD', +} + +function rowLabelKey(label: string): keyof PeriodDiffReport['totals']['pct'] { + return PCT_KEY_BY_LABEL[label] ?? 'cost' +} + +function NormalizedCard({ report }: { report: PeriodDiffReport }) { + const metric = (label: string, m: { a: number | null; b: number | null; diff: number | null; pct: number | null }) => ( +
+ {label} + {m.a === null ? '—' : formatUsd(m.a)} + {m.b === null ? '—' : formatUsd(m.b)} + {m.diff === null ? '—' : signedUsd(m.diff)} + {signedPct(m.pct)} +
+ ) + return ( +
+

Normalized

— means the denominator is zero or unknown, not zero
+
+
+ ViewABDiff% +
+ {metric('Cost / day', report.normalized.perDay)} + {metric('Cost / 100 calls', report.normalized.per100Calls)} +
+

+ Denominators: {report.normalized.denominators.perDay}; {report.normalized.denominators.per100Calls}. +

+
+ ) +} + +function LensCard({ + report, + lens, + view, + onLens, + onView, + drill, + onDrill, + onInspectContribution, + provider, + refreshToken, +}: { + report: PeriodDiffReport + lens: Lens + view: View + onLens: (lens: Lens) => void + onView: (view: View) => void + drill: { dimension: 'project' | 'model'; key: string } | null + onDrill: (drill: { dimension: 'project' | 'model'; key: string } | null) => void + onInspectContribution?: (range: DateRange, dimension: 'project' | 'model', key: string) => void + provider: string + refreshToken: number +}) { + const rows = lens === 'projects' ? report.projects : report.models + return ( +
+
+

{lens === 'projects' ? 'Contributions by project' : 'Contributions by model'}

+ {view === 'raw' ? 'Raw' : view === 'perDay' ? 'Per day' : 'Per 100 calls'} +
+
+
+ { onLens(value as Lens); onDrill(null) }} + /> +
+
+ onView(value as View)} + /> +
+
+ {view === 'perDay' && ( +

Each side's cost divided by its own calendar days (A: {report.rangeA.days}, B: {report.rangeB.days}) — differences and percentages compare these daily averages.

+ )} + {view === 'per100Calls' && ( +

Each side's cost per 100 of its OWN API calls — efficiency, not scale. A side with zero calls has no cost per call: shown as —.

+ )} +
+
+ {lens === 'projects' ? 'Project' : 'Model'}ABDiff% +
+ {rows.length === 0 && ( +
No usage in either range.
+ )} + {rows.map(row => { + const norm = normalizeRow(row, view, report.rangeA.days, report.rangeB.days) + const dimension = lens === 'projects' ? 'project' : 'model' + const selected = drill?.dimension === dimension && drill.key === row.key + return ( + + ) + })} +
+ {report.rangeA.days !== report.rangeB.days && ( +

Different range lengths — per-day rows compare daily averages, not totals.

+ )} + {drill && ( + onDrill(null)} + /> + )} +

Click a row to inspect the sessions behind it. The project and model lenses describe the SAME global difference from two perspectives — never add them together.

+
+ ) +} + +function DrillPanel({ + rangeA, + rangeB, + provider, + refreshToken, + dimension, + drillKey, + onInspectContribution, + onClose, +}: { + rangeA: PeriodRangeInfo + rangeB: PeriodRangeInfo + provider: string + refreshToken: number + dimension: 'project' | 'model' + drillKey: string + onInspectContribution?: (range: DateRange, dimension: 'project' | 'model', key: string) => void + onClose: () => void +}) { + const report = usePolled( + () => codeburn.getPeriodCompareSessions( + { from: rangeA.from, to: rangeA.to }, + { from: rangeB.from, to: rangeB.to }, + provider, + dimension, + drillKey, + ), + [rangeA.from, rangeA.to, rangeB.from, rangeB.to, provider, dimension, drillKey, refreshToken], + { memoKey: reportMemoKey('periodcomparesessions-v2', 'week', provider, { from: rangeA.from, to: rangeA.to }, JSON.stringify([rangeB.from, rangeB.to, dimension, drillKey])) }, + ) + if (!report.data) { + if (report.error) return + return + } + const sessions = report.data.sessions + return ( +
+
+ {dimension === 'project' ? 'Project' : 'Model'}: {drillKey} + + + + + +
+
+
+ SessionProviderABDiff +
+ {sessions.length === 0 && ( +
No sessions behind this contribution in either range.
+ )} + {sessions.map(session => ( +
+ + {session.title ?? session.sessionId} + {session.project} + + {session.provider} + {session.costA > 0 ? formatUsd(session.costA) : '—'} + {session.costB > 0 ? formatUsd(session.costB) : '—'} + {signedUsd(session.diff)} +
+ ))} +
+

A session active on both sides of the boundary appears once with its in-range cost on each side — attribution follows each call's own timestamp.

+
+ ) +} + +function CoverageCard({ report }: { report: PeriodDiffReport }) { + const unpriced = [...report.coverage.unpricedModelsA.map(m => ({ ...m, side: 'A' as const })), ...report.coverage.unpricedModelsB.map(m => ({ ...m, side: 'B' as const }))] + const carried = report.history + const aggregateOnly = carried ? carried.aggregateOnly.A + carried.aggregateOnly.B : 0 + return ( +
+

Coverage & basis

+
    +
  • Pricing coverage — A: {report.coverage.pricingCoverageA === null ? 'unknown' : `${Math.round(report.coverage.pricingCoverageA * 100)}%`}, B: {report.coverage.pricingCoverageB === null ? 'unknown' : `${Math.round(report.coverage.pricingCoverageB * 100)}%`}.
  • + {unpriced.length > 0 && ( +
  • + Missing pricing (unknown, not zero):{' '} + {unpriced.map(m => `${m.model} (${m.side}, ${m.calls.toLocaleString('en-US')} calls)`).join('; ')}. +
  • + )} + {carried && carried.days.A.length === 0 && carried.days.B.length === 0 && ( +
  • {carried.basis} No aggregate-only days in either range.
  • + )} + {carried && (carried.days.A.length > 0 || carried.days.B.length > 0) && ( +
  • + Aggregate history without session detail — A: {formatUsd(carried.aggregateOnly.A)} ({carried.days.A.map(d => `${d.date}: ${formatUsd(d.aggregateOnly)}`).join(', ')}),{' '} + B: {formatUsd(carried.aggregateOnly.B)} ({carried.days.B.map(d => `${d.date}: ${formatUsd(d.aggregateOnly)}`).join(', ')}). This cost survives only as daily history; it is reported separately and is NOT in the totals or the lenses. +
  • + )} +
  • All differences are deterministic calculations (B − A) over the full population of each range — no sampled top-N, no generated explanation.
  • +
+
+ ) +} diff --git a/app/renderer/styles/plain.css b/app/renderer/styles/plain.css index 99fba45a..09cf367e 100644 --- a/app/renderer/styles/plain.css +++ b/app/renderer/styles/plain.css @@ -1238,3 +1238,36 @@ html.page-hidden *::after { /* Drill affordances inside expanded report rows. */ .spend-proj-drill, .pr-drill { margin-bottom: 8px; } +/* ---- Compare periods (sections/PeriodCompare.tsx) ---- */ +.pcmp { display: flex; flex-direction: column; gap: 12px; } +.pcmp-controls { display: flex; flex-direction: column; gap: 10px; } +.pcmp-controls-row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; } +.pcmp-swap { align-self: center; } +.pcmp-ranges { display: flex; gap: 10px; flex-wrap: wrap; } +.pcmp-range { position: relative; display: flex; align-items: center; gap: 6px; } +.pcmp-range-label { font-size: 10.5px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.04em; color: var(--mut2); } +.pcmp-range-trigger { min-height: 29px; padding: 6px 10px; font-size: 11.5px; border-radius: 7px; border: 1px solid var(--line, rgba(128,128,128,0.25)); background: transparent; color: inherit; cursor: pointer; } +.pcmp-range-trigger:hover { border-color: var(--acc, currentColor); } +.pcmp-meta { margin: 0; font-size: 11px; color: var(--mut); } +.pcmp-table { display: flex; flex-direction: column; font-size: 12px; } +.pcmp-tr { display: grid; grid-template-columns: minmax(140px, 2fr) repeat(4, minmax(64px, 1fr)); gap: 8px; align-items: center; padding: 5px 6px; border-radius: 6px; text-align: left; } +.pcmp-th { font-size: 10.5px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.04em; color: var(--mut2); } +.pcmp-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +button.pcmp-row { width: 100%; background: none; border: 0; color: inherit; font: inherit; cursor: pointer; } +button.pcmp-row:hover { background: rgba(128, 128, 128, 0.12); } +button.pcmp-row-on { background: rgba(128, 128, 128, 0.18); } +.pcmp-key { font-family: var(--mono, ui-monospace, monospace); font-size: 11px; } +.pcmp-sub { display: block; font-size: 10px; color: var(--mut2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.pcmp-up { color: var(--warn, #e08a4e); } +.pcmp-down { color: var(--ok, #5aab6e); } +.pcmp-badge { display: inline-block; padding: 1px 6px; border-radius: 999px; font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.04em; } +.pcmp-badge.new { background: rgba(90, 171, 110, 0.18); color: var(--ok, #5aab6e); } +.pcmp-badge.gone { background: rgba(224, 138, 78, 0.18); color: var(--warn, #e08a4e); } +.pcmp-caption { margin: 8px 0 0; font-size: 11px; color: var(--mut); } +.pcmp-drill { margin-top: 10px; border-top: 1px solid rgba(128, 128, 128, 0.2); padding-top: 10px; display: flex; flex-direction: column; gap: 8px; } +.pcmp-drill-head { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; flex-wrap: wrap; } +.pcmp-drill-actions { display: flex; gap: 12px; } +.pcmp-coverage { margin: 0; padding-left: 16px; display: flex; flex-direction: column; gap: 6px; font-size: 11.5px; color: var(--mut); } +@media (max-width: 860px) { + .pcmp-tr { grid-template-columns: minmax(110px, 2fr) repeat(4, minmax(52px, 1fr)); } +} diff --git a/docs/compare-periods.md b/docs/compare-periods.md new file mode 100644 index 00000000..953c7cfd --- /dev/null +++ b/docs/compare-periods.md @@ -0,0 +1,91 @@ +# Compare periods + +Compare two date ranges side by side and see exactly what drove the change in +usage and cost. CodeBurn computes every difference deterministically as +**B − A**: A is the *reference* period, B is the *analyzed* one. + +## Where to find it + +- **Overview → "Compare periods" card → Compare →**, or +- the **Compare periods** item in the sidebar (shortcut `9`). + +The classic model-vs-model comparison in **Compare** is unchanged; period +comparison is its own screen. + +## Choosing the two ranges + +- **Last 7 vs prior 7** (default): B is the last seven *complete* calendar + days (today is never complete), A is the seven before that. +- **Custom**: pick A and B independently from the calendar controls. Dates are + local calendar days (the same `YYYY-MM-DD` convention every other CodeBurn + range uses). **⇄ Swap** exchanges A and B. + +The header always shows how many days each range spans, whether the durations +differ, and whether the ranges overlap (overlapping days count on **both** +sides). Your selection is remembered when you leave the screen and come back. + +## Reading the report + +**Totals** — API-equivalent cost, calls, sessions, every token component, and +estimated-price cost, each with its absolute (B − A) and relative difference. +Where a percentage is undefined (the A component is zero) the cell shows `—` +rather than an invented number. API-equivalent cost is what the same usage +would have cost at API rates; it is **not** a subscription invoice. + +**Normalized** — the same difference per calendar day and per 100 API calls. +The denominators are printed under the table (A and B use *their own* day and +call counts). A zero or unknown denominator renders as `—`, never as zero. + +**Contributions by project / by model** — the largest increases and decreases +in each dimension, sorted by absolute movement. The two lenses are two +*perspectives on the same global difference*; each complete lens alone sums to +the total difference. Never add the lenses together. + +- A project or model that exists only in B is labeled **New** (no infinite + percentage). One that exists only in A is **Gone**. +- Click any row to inspect the sessions behind it: each session shows its cost + in A and in B. A session that straddles the boundary appears once, with the + part of its activity that falls inside each range — attribution follows each + API call's own timestamp, not the session's start date. +- **Open A / B in Sessions** jumps to the Sessions screen scoped to that range + and filtered to that contribution's project or model, so the drill-through + lands on exactly the population the row describes. +- The **Raw / Per day / Per 100 calls** switch rescales the lens. Per-100-calls + recomputes honestly: a period with zero calls has *no* cost per call (shown + as `—`), and a period that spent more in total but less per call shows as a + decrease. + +**Coverage & basis** — what the numbers are made of: + +- Pricing coverage per range, and any models with usage but no price data + ("unknown", not zero). +- **Aggregate history without session detail**: when a day's session sources + have aged off disk, its cost survives only in the durable daily history. + Those days are listed here with their unexplained amount and are *not* + folded into the totals or the lenses. The Totals card says so inline when + either range has such a day, because on a machine with aged-off history the + detail-only total can be far below what `codeburn report` shows for the same + range (`report` and `status` read the durable daily history; `compare-periods` + matches `sessions`, `models` and `spend`, which read session transcripts). + +Every difference is a deterministic calculation over the full population of +both ranges (not a top-N sample). Nothing is AI-generated: a rise or drop can +always be traced from the totals to a lens row to the sessions behind it. + +## CLI + +The desktop feature is backed by the same engine the CLI exposes: + +```bash +codeburn compare-periods --format json # last 7 complete days vs prior 7 +codeburn compare-periods --format json \ + --from-a 2026-03-01 --to-a 2026-03-07 \ + --from-b 2026-03-08 --to-b 2026-03-14 +codeburn compare-periods --format sessions \ + --dimension project --key /work/my-app \ + --from-a 2026-03-01 --to-a 2026-03-07 \ + --from-b 2026-03-08 --to-b 2026-03-14 +``` + +`--provider`, `--project`, and `--exclude` filter both ranges the same way +they filter every other command. diff --git a/scripts/perf/compare-periods-demo-fixture.mjs b/scripts/perf/compare-periods-demo-fixture.mjs new file mode 100644 index 00000000..ed7e2b0a --- /dev/null +++ b/scripts/perf/compare-periods-demo-fixture.mjs @@ -0,0 +1,89 @@ +#!/usr/bin/env node +// Goal-1 demo fixture: an isolated Claude config dir + cache dir with usage in +// the two default compare windows (A = Aug 29 - Sep 4, B = Sep 5 - Sep 11, +// relative to today 2026-09-12 local) so the desktop Compare periods screen +// has a known story to show. Read-only fixture; nothing touches real logs. +import { mkdir, writeFile, rm } from 'node:fs/promises' +import { join } from 'node:path' + +const root = process.argv[2] +if (!root) { console.error('usage: node gen-fixture.mjs '); process.exit(1) } +await rm(root, { recursive: true, force: true }) + +const day = (month, date, hour, minute = 0) => new Date(2026, month - 1, date, hour, minute, 0).toISOString() + +function assistant(sessionId, ts, model, input, output, msgId) { + return JSON.stringify({ + type: 'assistant', + sessionId, + timestamp: ts, + message: { + id: msgId, + type: 'message', + role: 'assistant', + model, + content: [{ type: 'text', text: 'ok' }], + usage: { input_tokens: input, output_tokens: output }, + }, + }) +} +function user(sessionId, ts) { + return JSON.stringify({ type: 'user', sessionId, timestamp: ts, message: { role: 'user', content: 'work on the feature' } }) +} + +const MODEL = 'claude-sonnet-4-5' +const MYSTERY = 'mystery-model-9' // no pricing anywhere: coverage must flag it + +const sessions = { + // /work/pricing: active in both windows, MUCH heavier in B (Up), plus a + // session straddling the A/B boundary (Sep 4 22:00 + Sep 5 08:00). + 'pricing-a1': [ + ['u', day(8, 30, 9)], ['a', day(8, 30, 9, 1), MODEL, 2000, 300], + ['u', day(9, 2, 10)], ['a', day(9, 2, 10, 1), MODEL, 2500, 400], + ], + 'pricing-straddle': [ + ['u', day(9, 4, 22)], ['a', day(9, 4, 22, 1), MODEL, 3000, 300], + ['u', day(9, 5, 8)], ['a', day(9, 5, 8, 1), MODEL, 4000, 400], + ], + 'pricing-b1': [ + ['u', day(9, 9, 11)], ['a', day(9, 9, 11, 1), MODEL, 12000, 900], + ['u', day(9, 10, 15)], ['a', day(9, 10, 15, 1), MODEL, 9000, 700], + ], + // /work/website: only in A (Gone). + 'website-a1': [ + ['u', day(8, 31, 14)], ['a', day(8, 31, 14, 1), MODEL, 4000, 500], + ], + // /work/mobile: only in B (New) — one priced call plus one call on the + // unpriced model (coverage must flag the unpriced one as unknown, not zero). + 'mobile-b1': [ + ['u', day(9, 8, 9)], ['a', day(9, 8, 9, 1), MYSTERY, 6000, 800], + ], + 'mobile-b2': [ + ['u', day(9, 7, 16)], ['a', day(9, 7, 16, 1), MODEL, 2000, 300], + ], +} + +const projects = { + 'pricing': 'pricing-a1', + 'pricing2': 'pricing-straddle', + 'pricing3': 'pricing-b1', + 'website': 'website-a1', + 'mobile': 'mobile-b1', +} + +const slug = name => name.replaceAll('/', '-') +for (const [dir, prefix] of Object.entries({ '-work-pricing': ['pricing-a1', 'pricing-straddle', 'pricing-b1'], '-work-website': ['website-a1'], '-work-mobile': ['mobile-b1', 'mobile-b2'] })) { + const dirPath = join(root, 'claude', 'projects', dir) + await mkdir(dirPath, { recursive: true }) + let seq = 0 + for (const sessionId of prefix) { + const lines = sessions[sessionId].map(spec => { + const [kind, ts, model, input, output] = spec + if (kind === 'u') return user(sessionId, ts) + seq += 1 + return assistant(sessionId, ts, model, input, output, `msg-${sessionId}-${seq}`) + }) + await writeFile(join(dirPath, `${sessionId}.jsonl`), lines.join('\n') + '\n', 'utf-8') + } +} +console.log(`fixture written under ${root}`) diff --git a/src/main.ts b/src/main.ts index 431d31da..79e57225 100644 --- a/src/main.ts +++ b/src/main.ts @@ -19,7 +19,9 @@ import { isBehavioralCall } from './behavioral-weight.js' import { CATEGORY_LABELS, type DateRange, type ProjectSummary, type TaskCategory } from './types.js' import type { AppliedFix } from './act/types.js' import { aggregateModelEfficiency } from './model-efficiency.js' -import { buildPeriodData, buildMenubarPayloadForRange, buildDurablePeriod, type DurablePeriod } from './usage-aggregator.js' +import { buildPeriodData, buildMenubarPayloadForRange, buildDurablePeriod, getDailyCacheConfigHash, type DurablePeriod } from './usage-aggregator.js' +import { aggregateProjectsIntoDays } from './day-aggregator.js' +import { buildPeriodDiffReport, defaultSevenDayRanges, diffSessions, dayKeyToRange, historyBasis, localRangeInfo } from './period-diff.js' import { loadStatusSnapshot, saveStatusSnapshot } from './session-cache.js' import { renderDashboard } from './dashboard.js' import { renderOverview } from './overview.js' @@ -2289,6 +2291,128 @@ program await renderCompare(range, opts.provider, opts.modelA, opts.modelB, opts.project, opts.exclude) }) +program + .command('compare-periods') + .description('Compare usage and cost between two periods (B minus A: B is analyzed, A is the reference)') + .option('--from-a ', 'Reference period A start (YYYY-MM-DD)') + .option('--to-a ', 'Reference period A end (YYYY-MM-DD)') + .option('--from-b ', 'Analyzed period B start (YYYY-MM-DD)') + .option('--to-b ', 'Analyzed period B end (YYYY-MM-DD)') + .option('--provider ', 'Filter by provider (e.g. claude, codex, cursor)', 'all') + .option('--format ', 'Output format: json, sessions', 'json') + .option('--dimension ', 'Drill-down dimension for --format sessions: project, model') + .option('--key ', 'Canonical contribution key for --format sessions (project path or model id from the report)') + .option('--project ', 'Show only projects matching name (repeatable)', collect, []) + .option('--exclude ', 'Exclude projects matching name (repeatable)', collect, []) + .option('--no-with-history', 'Skip the durable daily-history cross-check (aggregate-only carried days)') + .action(async (opts) => { + assertProvider(opts.provider, 'compare-periods') + assertFormat(opts.format, ['json', 'sessions'], 'compare-periods') + + // Explicit ranges must come as two complete pairs; otherwise the default + // horizon is the last seven complete local days (B) vs the seven before + // (A). Same local-date conventions as --from/--to everywhere else. + const flagsGiven = [opts.fromA, opts.toA, opts.fromB, opts.toB].filter(v => v !== undefined) + let keyRangeA: DateRange + let keyRangeB: DateRange + if (flagsGiven.length > 0) { + if (flagsGiven.length !== 4) { + process.stderr.write('codeburn compare-periods: --from-a/--to-a/--from-b/--to-b must be provided together.\n') + process.exit(1) + } + // parseDateRangeFlags THROWS on a bad date (it never returns null for a + // provided pair), so the same try/catch every other date-flag command + // uses is what turns that into one clean line instead of a stack trace. + try { + keyRangeA = parseDateRangeFlags(opts.fromA, opts.toA)! + keyRangeB = parseDateRangeFlags(opts.fromB, opts.toB)! + } catch (err) { + console.error(`\n Error: ${err instanceof Error ? err.message : String(err)}\n`) + process.exit(1) + } + } else { + const defaults = defaultSevenDayRanges() + keyRangeA = dayKeyToRange(defaults.A.from, defaults.A.to) + keyRangeB = dayKeyToRange(defaults.B.from, defaults.B.to) + } + + if (opts.format === 'sessions') { + const dimension = opts.dimension + if (dimension !== 'project' && dimension !== 'model') { + process.stderr.write('codeburn compare-periods: --dimension must be "project" or "model" for --format sessions.\n') + process.exit(1) + } + if (!opts.key) { + process.stderr.write('codeburn compare-periods: --key is required for --format sessions.\n') + process.exit(1) + } + await loadPricing() + const [parsedSessionsA, parsedSessionsB] = await Promise.all([ + parseAllSessions(keyRangeA, opts.provider), + parseAllSessions(keyRangeB, opts.provider), + ]) + // Same project filter as the report: a drill-down must never surface a + // session from a project the active filter hides. + const projectsA = filterProjectsByName(parsedSessionsA, opts.project, opts.exclude) + const projectsB = filterProjectsByName(parsedSessionsB, opts.project, opts.exclude) + process.stdout.write(JSON.stringify({ + dimension, + key: opts.key, + provider: opts.provider, + rangeA: localRangeInfo(keyRangeA), + rangeB: localRangeInfo(keyRangeB), + sessions: diffSessions(projectsA, projectsB, dimension, opts.key), + }, null, 2) + '\n') + return + } + + await loadPricing() + const [parsedA, parsedB] = await Promise.all([ + parseAllSessions(keyRangeA, opts.provider), + parseAllSessions(keyRangeB, opts.provider), + ]) + await reportUnmatchedProjectPatterns([...parsedA, ...parsedB], opts.project, opts.exclude, () => cachedProjectIdentitiesForRange(keyRangeB)) + const projectsA = filterProjectsByName(parsedA, opts.project, opts.exclude) + const projectsB = filterProjectsByName(parsedB, opts.project, opts.exclude) + + // Cross-check the durable daily history so usage whose sources aged off + // disk (aggregate-only carried days) is visible instead of silently + // missing from a transcript-based report. Best-effort: an unavailable + // daily cache degrades to the report's explicit "detail only" basis note. + let history + if (opts.withHistory) { + try { + const { ensureCacheHydrated } = await import('./daily-cache.js') + const cache = await ensureCacheHydrated( + range => parseAllSessions(range, 'all'), + aggregateProjectsIntoDays, + getDailyCacheConfigHash(), + isSessionHydrationComplete, + ) + history = historyBasis( + cache, + localRangeInfo(keyRangeA), + localRangeInfo(keyRangeB), + opts.provider, + aggregateProjectsIntoDays(projectsA), + aggregateProjectsIntoDays(projectsB), + ) + } catch (err) { + process.stderr.write(`codeburn compare-periods: daily history check skipped (${err instanceof Error ? err.message : String(err)}).\n`) + } + } + + const report = buildPeriodDiffReport({ + provider: opts.provider, + rangeA: localRangeInfo(keyRangeA), + rangeB: localRangeInfo(keyRangeB), + projectsA, + projectsB, + history, + }) + process.stdout.write(JSON.stringify(report, null, 2) + '\n') + }) + program .command('audit') .description("Token audit: raw provider token fields vs codeburn's displayed totals and cost derivation") diff --git a/src/period-diff.ts b/src/period-diff.ts new file mode 100644 index 00000000..22a51edd --- /dev/null +++ b/src/period-diff.ts @@ -0,0 +1,556 @@ +import { getDaysInRange, type DailyCache, type DailyEntry } from './daily-cache.js' +import type { DateRange, ProjectSummary } from './types.js' +import { buildPeriodData, canonicalSessionCountKey } from './usage-aggregator.js' +import { inferSessionProvider } from './session-output.js' +import { spendProjectIdentity } from './spend-flow.js' + +/// Period-vs-period difference engine (Compare periods). Pure functions only: +/// no clock reads, no filesystem, no parsing. The caller parses each range with +/// `parseAllSessions(range, provider)` — which slices at CALL granularity +/// (src/parser.ts `callsInRange`, issue #852) — and hands the sliced +/// ProjectSummary[] trees in. A session that straddles the A/B boundary is +/// therefore split across both ranges at the same granularity every other +/// CodeBurn report uses; nothing here re-derives attribution from session start +/// dates. All differences are B − A. A is the reference period, B the analyzed +/// one. + +export type PeriodRangeKey = { from: string; to: string } + +export type PeriodRangeInfo = { + from: string + to: string + /// Inclusive count of local calendar days, counted by walking local + /// midnights (never millisecond division, which DST breaks). + days: number +} + +export type ContributionStatus = 'new' | 'gone' | 'up' | 'down' | 'flat' + +export type Contribution = { + /// Canonical project path or canonical model id (the keys every other + /// report uses — never a display title or short name). + key: string + costA: number + costB: number + diff: number + /// diff / |costA| × 100. Null when costA is exactly 0 — the row is labeled + /// `new` instead of inventing an infinite percentage. + pct: number | null + status: ContributionStatus + callsA: number + callsB: number +} + +export type PeriodTotals = { + cost: number + calls: number + sessions: number + inputTokens: number + outputTokens: number + cacheReadTokens: number + cacheWriteTokens: number + savingsUSD: number + estimatedCostUSD: number +} + +export type TotalsDiff = { + A: PeriodTotals + B: PeriodTotals + /// B − A for every component, unrounded. + diff: PeriodTotals + /// Per-component B−A percent, null where the A component is 0. + pct: Record, number | null> & { sessions: number | null } +} + +export type NormalizedMetric = { + a: number | null + b: number | null + diff: number | null + pct: number | null +} + +export type NormalizedView = { + /// Cost per calendar day of each range. + perDay: NormalizedMetric + /// Cost per 100 (behavioral) API calls of each range. + per100Calls: NormalizedMetric + /// What each denominator counts, so a normalized number can always be + /// checked against the raw totals on screen. + denominators: { + perDay: string + per100Calls: string + } +} + +export type CoverageBlock = { + /// Models with calls but no price data — "unknown", never zero — per range, + /// straight from the shared buildPeriodData rules. + unpricedModelsA: Array<{ model: string; calls: number }> + unpricedModelsB: Array<{ model: string; calls: number }> + pricingCoverageA: number | null + pricingCoverageB: number | null +} + +export type AggregateDayRow = { + date: string + /// Cost the durable daily history holds for that day (all providers, or the + /// selected provider's slice when a provider filter is active). + historyCost: number + /// Cost the session-detail basis explains for that day. + detailCost: number + /// historyCost − detailCost when the durable history holds more than the + /// session detail can explain: usage whose sources aged off disk and survives + /// only as the aggregate carried history. Shown separately, never folded into + /// the totals or the contribution lenses. + aggregateOnly: number +} + +export type HistoryBasis = { + historyCost: { A: number; B: number } + detailCost: { A: number; B: number } + /// Days in each range whose durable history exceeds what the session detail + /// explains, sorted by date. Empty arrays when everything reconciles. + days: { A: AggregateDayRow[]; B: AggregateDayRow[] } + aggregateOnly: { A: number; B: number } + /// One-line explanation of the basis, rendered verbatim in the UI/report. + basis: string +} + +export type PeriodDiffReport = { + schema: 1 + provider: string + rangeA: PeriodRangeInfo + rangeB: PeriodRangeInfo + /// Inclusive local-day overlap of A and B, 0 when disjoint. + overlapDays: number + /// days(B) − days(A); 0 when the ranges are equally long. + durationDeltaDays: number + totals: TotalsDiff + /// Same global difference seen per project. Lenses are never summed together: + /// each one alone reconciles the global diff (before display rounding). + projects: Contribution[] + /// Separate lens: the same global difference seen per model. + models: Contribution[] + normalized: NormalizedView + coverage: CoverageBlock + history?: HistoryBasis +} + +export type SessionDiffRow = { + /// `provider\0projectPath\0sessionId` — the canonical session identity. A + /// bare sessionId is not globally unique and is never used as the key. + identity: string + provider: string + sessionId: string + project: string + title?: string + costA: number + costB: number + diff: number + callsA: number + callsB: number +} + +const EPSILON = 1e-9 + +function localDateKey(date: Date): string { + return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}` +} + +function localDayStart(date: Date): Date { + return new Date(date.getFullYear(), date.getMonth(), date.getDate()) +} + +/// Count inclusive local calendar days from `from` to `to` by walking local +/// midnights. Millisecond division would miscount across a DST transition; a +/// calendar walk does not, in any timezone. +export function countLocalDays(from: string, to: string): number { + const [fy, fm, fd] = from.split('-').map(Number) as [number, number, number] + const [ty, tm, td] = to.split('-').map(Number) as [number, number, number] + const cursor = localDayStart(new Date(fy, fm - 1, fd)) + const end = localDayStart(new Date(ty, tm - 1, td)) + if (cursor > end) return 0 + let days = 0 + while (cursor <= end) { + days++ + cursor.setDate(cursor.getDate() + 1) + } + return days +} + +export function rangeInfo(range: PeriodRangeKey): PeriodRangeInfo { + return { ...range, days: countLocalDays(range.from, range.to) } +} + +/// Key a parser DateRange (local start/end Dates, end inclusive at 23:59:59.999) +/// into from/to strings plus its inclusive local-day count. +export function localRangeInfo(range: DateRange): PeriodRangeInfo { + return rangeInfo({ from: localDateKey(range.start), to: localDateKey(range.end) }) +} + +/// Local 'YYYY-MM-DD' day keys (inclusive) back into the parser DateRange +/// shape: [from 00:00:00.000, to 23:59:59.999] in LOCAL time — the same +/// convention `--from/--to` uses everywhere else in the CLI. +export function dayKeyToRange(from: string, to: string): DateRange { + const [fy, fm, fd] = from.split('-').map(Number) as [number, number, number] + const [ty, tm, td] = to.split('-').map(Number) as [number, number, number] + return { start: new Date(fy, fm - 1, fd), end: new Date(ty, tm - 1, td, 23, 59, 59, 999) } +} + +/// The default horizon: B = the last seven COMPLETE local calendar days +/// (today is never complete), A = the seven before that. All local time — +/// never UTC. +export function defaultSevenDayRanges(now = new Date()): { A: PeriodRangeKey; B: PeriodRangeKey } { + const day = (offset: number): string => { + const d = localDayStart(now) + d.setDate(d.getDate() + offset) + return localDateKey(d) + } + return { + A: { from: day(-14), to: day(-8) }, + B: { from: day(-7), to: day(-1) }, + } +} + +/// Inclusive local-day overlap between two [from..to] key ranges. +export function overlapDays(a: PeriodRangeKey, b: PeriodRangeKey): number { + const start = a.from > b.from ? a.from : b.from + const end = a.to < b.to ? a.to : b.to + if (start > end) return 0 + return countLocalDays(start, end) +} + +function pct(diff: number, base: number): number | null { + if (Math.abs(base) < EPSILON) return null + return (diff / Math.abs(base)) * 100 +} + +function statusOf(costA: number, costB: number): ContributionStatus { + if (Math.abs(costA) < EPSILON && Math.abs(costB) >= EPSILON) return 'new' + if (Math.abs(costB) < EPSILON && Math.abs(costA) >= EPSILON) return 'gone' + if (costB > costA) return 'up' + if (costB < costA) return 'down' + return 'flat' +} + +/// Deterministic order: largest absolute movement first, then B size, then key. +function byMovement(a: Contribution, b: Contribution): number { + const delta = Math.abs(b.diff) - Math.abs(a.diff) + if (delta !== 0) return delta + if (b.costB !== a.costB) return b.costB - a.costB + return a.key.localeCompare(b.key) +} + +function contribution(key: string, costA: number, costB: number, callsA: number, callsB: number): Contribution { + const diff = costB - costA + return { key, costA, costB, diff, pct: pct(diff, costA), status: statusOf(costA, costB), callsA, callsB } +} + +function totalsOf(projects: ProjectSummary[], label: string): { totals: PeriodTotals; unpriced: Array<{ model: string; calls: number }>; pricingCoverage: number | null } { + const data = buildPeriodData(label, projects) + return { + totals: { + cost: data.cost, + calls: data.calls, + sessions: data.sessions, + inputTokens: data.inputTokens, + outputTokens: data.outputTokens, + cacheReadTokens: data.cacheReadTokens, + cacheWriteTokens: data.cacheWriteTokens, + savingsUSD: data.savingsUSD, + estimatedCostUSD: data.estimatedCostUSD ?? 0, + }, + unpriced: (data.unpricedModels ?? []).map(m => ({ model: m.model, calls: m.calls })), + pricingCoverage: data.pricingCoverage ?? null, + } +} + +function diffTotals(a: PeriodTotals, b: PeriodTotals): TotalsDiff { + const diff: PeriodTotals = { + cost: b.cost - a.cost, + calls: b.calls - a.calls, + sessions: b.sessions - a.sessions, + inputTokens: b.inputTokens - a.inputTokens, + outputTokens: b.outputTokens - a.outputTokens, + cacheReadTokens: b.cacheReadTokens - a.cacheReadTokens, + cacheWriteTokens: b.cacheWriteTokens - a.cacheWriteTokens, + savingsUSD: b.savingsUSD - a.savingsUSD, + estimatedCostUSD: b.estimatedCostUSD - a.estimatedCostUSD, + } + const pctRow = (fn: (t: PeriodTotals) => number): number | null => { + const va = fn(a) + return pct(fn(diff), va) + } + return { + A: a, + B: b, + diff, + pct: { + cost: pctRow(t => t.cost), + calls: pctRow(t => t.calls), + sessions: pctRow(t => t.sessions), + inputTokens: pctRow(t => t.inputTokens), + outputTokens: pctRow(t => t.outputTokens), + cacheReadTokens: pctRow(t => t.cacheReadTokens), + cacheWriteTokens: pctRow(t => t.cacheWriteTokens), + savingsUSD: pctRow(t => t.savingsUSD), + estimatedCostUSD: pctRow(t => t.estimatedCostUSD), + }, + } +} + +function normalize(numeratorA: number, numeratorB: number, denominatorA: number, denominatorB: number): NormalizedMetric { + // Denominator 0 or unknown → unavailable (null), never an invented value. + const a = denominatorA > 0 ? numeratorA / denominatorA : null + const b = denominatorB > 0 ? numeratorB / denominatorB : null + if (a === null || b === null) return { a, b, diff: null, pct: null } + const delta = b - a + return { a, b, diff: delta, pct: pct(delta, a) } +} + +function normalizedView(totalsA: PeriodTotals, totalsB: PeriodTotals, rangeA: PeriodRangeInfo, rangeB: PeriodRangeInfo): NormalizedView { + return { + perDay: normalize(totalsA.cost, totalsB.cost, rangeA.days, rangeB.days), + per100Calls: normalize(totalsA.cost * 100, totalsB.cost * 100, totalsA.calls, totalsB.calls), + denominators: { + perDay: `calendar days in the range (A: ${rangeA.days}, B: ${rangeB.days})`, + per100Calls: `API calls × 100 (A: ${totalsA.calls.toLocaleString('en-US')}, B: ${totalsB.calls.toLocaleString('en-US')})`, + }, + } +} + +function projectContributions(projectsA: ProjectSummary[], projectsB: ProjectSummary[]): Contribution[] { + const fold = (projects: ProjectSummary[]) => { + const totals = new Map() + for (const project of projects) { + const { id } = spendProjectIdentity(project) + const value = totals.get(id) ?? { cost: 0, calls: 0 } + value.cost += project.totalCostUSD + value.calls += project.totalApiCalls + totals.set(id, value) + } + return totals + } + const costsA = fold(projectsA) + const costsB = fold(projectsB) + const keys = new Set([...costsA.keys(), ...costsB.keys()]) + const rows: Contribution[] = [] + for (const key of keys) { + const a = costsA.get(key) + const b = costsB.get(key) + const costA = a?.cost ?? 0 + const costB = b?.cost ?? 0 + if (Math.abs(costA) < EPSILON && Math.abs(costB) < EPSILON) continue + rows.push(contribution(key, costA, costB, a?.calls ?? 0, b?.calls ?? 0)) + } + return rows.sort(byMovement) +} + +function modelContributions(projectsA: ProjectSummary[], projectsB: ProjectSummary[]): Contribution[] { + const fold = (projects: ProjectSummary[]): Map => { + const map = new Map() + for (const p of projects) { + for (const sess of p.sessions) { + for (const [model, d] of Object.entries(sess.modelBreakdown)) { + const acc = map.get(model) ?? { cost: 0, calls: 0 } + acc.cost += d.costUSD + acc.calls += d.calls + map.set(model, acc) + } + } + } + return map + } + const costsA = fold(projectsA) + const costsB = fold(projectsB) + const keys = new Set([...costsA.keys(), ...costsB.keys()]) + const rows: Contribution[] = [] + for (const key of keys) { + const a = costsA.get(key) + const b = costsB.get(key) + const costA = a?.cost ?? 0 + const costB = b?.cost ?? 0 + if (Math.abs(costA) < EPSILON && Math.abs(costB) < EPSILON) continue + rows.push(contribution(key, costA, costB, a?.calls ?? 0, b?.calls ?? 0)) + } + return rows.sort(byMovement) +} + +/// Cross-check the session-detail totals against the durable daily history +/// (the ONLY record of days whose sources aged off disk, flagged `carried`). +/// Days where the history holds more than the detail explains are listed with +/// their aggregate-only amount so a reader can always see how much of the +/// picture has no session detail behind it. The aggregate-only amount is +/// reported separately and is NEVER folded into totals or lenses. +export function historyBasis( + cache: DailyCache, + rangeA: PeriodRangeKey, + rangeB: PeriodRangeKey, + provider: string, + freshDaysA: DailyEntry[], + freshDaysB: DailyEntry[], +): HistoryBasis { + const dayCost = (entry: DailyEntry): number => { + if (provider === 'all' || provider === '') return entry.cost + return entry.providers[provider]?.cost ?? 0 + } + const detailByDay = (days: DailyEntry[]): Map => + new Map(days.map(day => [day.date, day.cost])) + + const build = (range: PeriodRangeKey, fresh: DailyEntry[]) => { + const detail = detailByDay(fresh) + const rows: AggregateDayRow[] = [] + let historyCost = 0 + let detailCost = 0 + let aggregateOnly = 0 + for (const entry of getDaysInRange(cache, range.from, range.to)) { + const history = dayCost(entry) + const explained = detail.get(entry.date) ?? 0 + historyCost += history + detailCost += explained + // Only a POSITIVE unexplained remainder is aggregate history. A negative + // one (detail exceeds history) means the durable cache is simply behind, + // not that detail is wrong — never clamp it into a fake carried number. + if (history > explained + EPSILON) { + const unexplained = history - explained + aggregateOnly += unexplained + rows.push({ date: entry.date, historyCost: history, detailCost: explained, aggregateOnly: unexplained }) + } + } + return { rows, historyCost, detailCost, aggregateOnly } + } + + const a = build(rangeA, freshDaysA) + const b = build(rangeB, freshDaysB) + return { + historyCost: { A: a.historyCost, B: b.historyCost }, + detailCost: { A: a.detailCost, B: b.detailCost }, + days: { A: a.rows, B: b.rows }, + aggregateOnly: { A: a.aggregateOnly, B: b.aggregateOnly }, + basis: 'Totals come from parsed session transcripts. Days whose sources no longer exist survive only as aggregate daily history; their unexplained cost is listed here, not folded into the totals.', + } +} + +// getDaysInRange is imported at the top of this module. +function emptyHistoryBasis(): HistoryBasis { + return { + historyCost: { A: 0, B: 0 }, + detailCost: { A: 0, B: 0 }, + days: { A: [], B: [] }, + aggregateOnly: { A: 0, B: 0 }, + basis: 'Daily history unavailable in this run; totals reflect parsed session detail only.', + } +} + +export function buildPeriodDiffReport(args: { + provider: string + rangeA: PeriodRangeKey + rangeB: PeriodRangeKey + projectsA: ProjectSummary[] + projectsB: ProjectSummary[] + history?: HistoryBasis +}): PeriodDiffReport { + const infoA = rangeInfo(args.rangeA) + const infoB = rangeInfo(args.rangeB) + const labelA = `${infoA.from} to ${infoA.to}` + const labelB = `${infoB.from} to ${infoB.to}` + const sideA = totalsOf(args.projectsA, labelA) + const sideB = totalsOf(args.projectsB, labelB) + const totalsA = sideA.totals + const totalsB = sideB.totals + return { + schema: 1, + provider: args.provider, + rangeA: infoA, + rangeB: infoB, + overlapDays: overlapDays(args.rangeA, args.rangeB), + durationDeltaDays: infoB.days - infoA.days, + totals: diffTotals(totalsA, totalsB), + projects: projectContributions(args.projectsA, args.projectsB), + models: modelContributions(args.projectsA, args.projectsB), + normalized: normalizedView(totalsA, totalsB, infoA, infoB), + coverage: { + unpricedModelsA: sideA.unpriced, + unpricedModelsB: sideB.unpriced, + pricingCoverageA: sideA.pricingCoverage, + pricingCoverageB: sideB.pricingCoverage, + }, + history: args.history ?? emptyHistoryBasis(), + } +} + +/// Sessions behind one contribution, joined across A and B on the canonical +/// session identity (provider + project path + sessionId). Costs are each +/// range's post-slice session totals, so a session with activity on both sides +/// of the boundary appears once with a cost in each column. +export function diffSessions( + projectsA: ProjectSummary[], + projectsB: ProjectSummary[], + dimension: 'project' | 'model', + key: string, +): SessionDiffRow[] { + type Acc = { provider: string; sessionId: string; project: string; title?: string; costA: number; costB: number; callsA: number; callsB: number } + const accs = new Map() + + const fold = (projects: ProjectSummary[], side: 'A' | 'B') => { + for (const project of projects) { + for (const session of project.sessions) { + // Model lens: attribute the MODEL's slice of the session (its + // modelBreakdown entry), never the whole session cost — a session can + // use several models and its total belongs to no single one of them. + const modelEntry = dimension === 'model' ? session.modelBreakdown[key] : undefined + if (dimension === 'model' && !modelEntry) continue + if (dimension === 'project' && spendProjectIdentity(project).id !== key) continue + const cost = dimension === 'model' ? modelEntry!.costUSD : session.totalCostUSD + const calls = dimension === 'model' ? modelEntry!.calls : session.apiCalls + const identity = canonicalSessionCountKey(session, project.projectPath) + const acc = accs.get(identity) ?? { + provider: inferSessionProvider(session), + sessionId: session.sessionId, + project: project.project, + title: session.title, + costA: 0, + costB: 0, + callsA: 0, + callsB: 0, + } + if (side === 'A') { + acc.costA += cost + acc.callsA += calls + } else { + acc.costB += cost + acc.callsB += calls + } + if (!acc.title && session.title) acc.title = session.title + accs.set(identity, acc) + } + } + } + fold(projectsA, 'A') + fold(projectsB, 'B') + + const rows: SessionDiffRow[] = [] + for (const [identity, acc] of accs) { + if (Math.abs(acc.costA) < EPSILON && Math.abs(acc.costB) < EPSILON) continue + rows.push({ + identity, + provider: acc.provider, + sessionId: acc.sessionId, + project: acc.project, + ...(acc.title ? { title: acc.title } : {}), + costA: acc.costA, + costB: acc.costB, + diff: acc.costB - acc.costA, + callsA: acc.callsA, + callsB: acc.callsB, + }) + } + return rows.sort(byMovementLikeSessions) +} + +function byMovementLikeSessions(a: SessionDiffRow, b: SessionDiffRow): number { + const delta = Math.abs(b.diff) - Math.abs(a.diff) + if (delta !== 0) return delta + if (b.costB !== a.costB) return b.costB - a.costB + return a.identity.localeCompare(b.identity) +} diff --git a/tests/compare-periods-cli.test.ts b/tests/compare-periods-cli.test.ts new file mode 100644 index 00000000..c082b606 --- /dev/null +++ b/tests/compare-periods-cli.test.ts @@ -0,0 +1,187 @@ +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { spawnSync } from 'node:child_process' + +import { describe, expect, it } from 'vitest' + +function runCli(args: string[], home: string) { + return spawnSync(process.execPath, ['--import', 'tsx', 'src/cli.ts', ...args], { + cwd: process.cwd(), + env: { + ...process.env, + CLAUDE_CONFIG_DIR: join(home, '.claude'), + CODEBURN_CACHE_DIR: join(home, '.cache', 'codeburn'), + HOME: home, USERPROFILE: home, + TZ: 'UTC', + }, + encoding: 'utf-8', + }) +} + +function userLine(sessionId: string, timestamp: string): string { + return JSON.stringify({ + type: 'user', + sessionId, + timestamp, + message: { role: 'user', content: 'add feature' }, + }) +} + +function assistantLine(sessionId: string, timestamp: string, messageId: string, inputTokens: number): string { + return JSON.stringify({ + type: 'assistant', + sessionId, + timestamp, + message: { + id: messageId, + type: 'message', + role: 'assistant', + model: 'claude-sonnet-4-5', + content: [{ type: 'text', text: 'done' }], + usage: { input_tokens: inputTokens, output_tokens: 100 }, + }, + }) +} + +// Two sessions on two consecutive local days (UTC runner): 'a-side' on +// 2026-04-16, 'b-side' on 2026-04-17. Session 'straddle' has one call on +// EACH day, proving the drill-down joins its two sliced halves. +async function writeFixture(home: string): Promise { + const projectDir = join(home, '.claude', 'projects', 'work') + await mkdir(projectDir, { recursive: true }) + await writeFile( + join(projectDir, 'a-side.jsonl'), + [ + userLine('a-side', '2026-04-16T10:00:00Z'), + assistantLine('a-side', '2026-04-16T10:01:00Z', 'msg-a', 1000), + ].join('\n'), + ) + await writeFile( + join(projectDir, 'b-side.jsonl'), + [ + userLine('b-side', '2026-04-17T10:00:00Z'), + assistantLine('b-side', '2026-04-17T10:01:00Z', 'msg-b', 3000), + ].join('\n'), + ) + await writeFile( + join(projectDir, 'straddle.jsonl'), + [ + userLine('straddle', '2026-04-16T20:00:00Z'), + assistantLine('straddle', '2026-04-16T20:01:00Z', 'msg-s1', 1000), + userLine('straddle', '2026-04-17T09:00:00Z'), + assistantLine('straddle', '2026-04-17T09:01:00Z', 'msg-s2', 2000), + ].join('\n'), + ) +} + +const ARGS_A = ['--from-a', '2026-04-16', '--to-a', '2026-04-16', '--from-b', '2026-04-17', '--to-b', '2026-04-17'] + +describe('codeburn compare-periods (CLI)', () => { + it('reports the B − A difference with reconciling lenses on a real fixture', async () => { + const home = await mkdtemp(join(tmpdir(), 'codeburn-cli-periods-')) + try { + await writeFixture(home) + const run = runCli(['compare-periods', '--format', 'json', ...ARGS_A], home) + expect(run.status).toBe(0) + const report = JSON.parse(run.stdout) + + expect(report.schema).toBe(1) + expect(report.rangeA).toMatchObject({ from: '2026-04-16', to: '2026-04-16', days: 1 }) + expect(report.rangeB).toMatchObject({ from: '2026-04-17', to: '2026-04-17', days: 1 }) + + const totalA = report.totals.A.cost + const totalB = report.totals.B.cost + expect(totalA).toBeGreaterThan(0) + expect(totalB).toBeGreaterThan(totalA) + expect(report.totals.diff.cost).toBeCloseTo(totalB - totalA, 10) + + const lensSum = (rows: Array<{ diff: number }>) => rows.reduce((s, r) => s + r.diff, 0) + expect(report.projects).toHaveLength(1) + expect(report.projects[0].key.endsWith('work') || report.projects[0].key.includes('work')).toBe(true) + expect(lensSum(report.projects)).toBeCloseTo(report.totals.diff.cost, 10) + expect(lensSum(report.models)).toBeCloseTo(report.totals.diff.cost, 10) + + // The boundary-straddling session must be visible in the drill-down + // with a cost on BOTH sides, joined into one canonical row. + const drill = runCli( + ['compare-periods', '--format', 'sessions', '--dimension', 'project', '--key', report.projects[0].key, ...ARGS_A], + home, + ) + expect(drill.status).toBe(0) + const sessions = JSON.parse(drill.stdout) + const straddle = sessions.sessions.find((s: { sessionId: string }) => s.sessionId === 'straddle') + expect(straddle).toBeDefined() + expect(straddle.costA).toBeGreaterThan(0) + expect(straddle.costB).toBeGreaterThan(0) + // Same-session drill rows must not duplicate the straddler. + expect(sessions.sessions.filter((s: { sessionId: string }) => s.sessionId === 'straddle')).toHaveLength(1) + } finally { + await rm(home, { recursive: true, force: true }) + } + }) + + it('defaults to the last seven complete days vs the seven before', async () => { + const home = await mkdtemp(join(tmpdir(), 'codeburn-cli-periods-default-')) + try { + await writeFixture(home) + const run = runCli(['compare-periods', '--format', 'json'], home) + expect(run.status).toBe(0) + const report = JSON.parse(run.stdout) + expect(report.rangeB.days).toBe(7) + expect(report.rangeA.days).toBe(7) + // Today (Apr 18 in the fixture's world, but really the runner's today) + // must not be inside either range: both are complete days only. + const today = new Date() + const todayKey = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}` + expect(report.rangeB.to).not.toBe(todayKey) + expect(report.rangeB.to < todayKey).toBe(true) + expect(report.rangeA.to < report.rangeB.from).toBe(true) + } finally { + await rm(home, { recursive: true, force: true }) + } + }) + + it('rejects partial explicit ranges loudly', async () => { + const home = await mkdtemp(join(tmpdir(), 'codeburn-cli-periods-bad-')) + try { + await writeFixture(home) + const run = runCli(['compare-periods', '--from-a', '2026-04-16'], home) + expect(run.status).not.toBe(0) + expect(run.stderr).toContain('must be provided together') + } finally { + await rm(home, { recursive: true, force: true }) + } + }) + + it('rejects an impossible date instead of rolling it forward', async () => { + const home = await mkdtemp(join(tmpdir(), 'codeburn-cli-periods-bad2-')) + try { + await writeFixture(home) + const run = runCli(['compare-periods', '--from-a', '2026-02-31', '--to-a', '2026-03-05', '--from-b', '2026-04-16', '--to-b', '2026-04-17'], home) + expect(run.status).not.toBe(0) + // One readable line, like every other date-flag command — not a stack trace. + expect(run.stderr).toContain('is not a real calendar date') + expect(run.stderr).not.toContain('at parseLocalDate') + } finally { + await rm(home, { recursive: true, force: true }) + } + }) + + it('honours the project filter in the session drill-down, not only in the report', async () => { + const home = await mkdtemp(join(tmpdir(), 'codeburn-cli-periods-filter-')) + try { + await writeFixture(home) + const report = JSON.parse(runCli(['compare-periods', '--format', 'json', ...ARGS_A], home).stdout) + const key = report.projects[0].key + const unfiltered = runCli(['compare-periods', '--format', 'sessions', '--dimension', 'project', '--key', key, ...ARGS_A], home) + expect(JSON.parse(unfiltered.stdout).sessions.length).toBeGreaterThan(0) + // An excluded project must not surface behind a contribution either. + const filtered = runCli(['compare-periods', '--format', 'sessions', '--dimension', 'project', '--key', key, '--exclude', 'work', ...ARGS_A], home) + expect(filtered.status).toBe(0) + expect(JSON.parse(filtered.stdout).sessions).toEqual([]) + } finally { + await rm(home, { recursive: true, force: true }) + } + }) +}) diff --git a/tests/period-diff-boundary-parse.test.ts b/tests/period-diff-boundary-parse.test.ts new file mode 100644 index 00000000..e724f617 --- /dev/null +++ b/tests/period-diff-boundary-parse.test.ts @@ -0,0 +1,106 @@ +import { mkdtemp, mkdir, rm, writeFile } from 'fs/promises' +import { tmpdir } from 'os' +import { join } from 'path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' + +import { loadPricing } from '../src/models.js' +import { parseAllSessions, clearSessionCache } from '../src/parser.js' +import { buildPeriodDiffReport, diffSessions } from '../src/period-diff.js' +import type { DateRange } from '../src/types.js' + +// End-to-end proof that a session with activity on BOTH sides of the A/B +// boundary is attributed at the parser's real granularity (per call, issue +// #852), and that the period-diff engine joins the two halves into one row. + +let base: string + +beforeEach(async () => { + base = await mkdtemp(join(tmpdir(), 'codeburn-period-diff-')) + process.env['CLAUDE_CONFIG_DIR'] = base + await loadPricing() +}) + +afterEach(async () => { + delete process.env['CLAUDE_CONFIG_DIR'] + clearSessionCache() + await rm(base, { recursive: true, force: true }) +}) + +function line(timestamp: string, messageId: string, inputTokens: number): string { + return JSON.stringify({ + type: 'assistant', + sessionId: 'straddle', + timestamp, + message: { + id: messageId, + type: 'message', + role: 'assistant', + model: 'claude-sonnet-4-5', + content: [{ type: 'text', text: 'ok' }], + usage: { input_tokens: inputTokens, output_tokens: 100 }, + }, + }) +} + +// One session, two turns: local Apr 16 10:00 (side A) and Apr 17 10:00 (side B). +async function writeStraddlingSession(): Promise { + const projectDir = join(base, 'projects', 'work') + await mkdir(projectDir, { recursive: true }) + const tsA = new Date(2026, 3, 16, 10, 0, 0).toISOString() + const tsB = new Date(2026, 3, 17, 10, 0, 0).toISOString() + await writeFile( + join(projectDir, 'straddle.jsonl'), + [line(tsA, 'msg-a', 1000), line(tsB, 'msg-b', 3000)].join('\n') + '\n', + 'utf-8', + ) +} + +function dayRange(y: number, m: number, d: number): DateRange { + return { start: new Date(y, m, d), end: new Date(y, m, d, 23, 59, 59, 999) } +} + +describe('period diff over a real parse', () => { + it('splits a boundary-straddling session by call and reconciles the diff', async () => { + await writeStraddlingSession() + const rangeA = dayRange(2026, 3, 16) + const rangeB = dayRange(2026, 3, 17) + + const projectsA = await parseAllSessions(rangeA, 'all') + const projectsB = await parseAllSessions(rangeB, 'all') + + // Each range holds the SAME session with only ITS calls (post-slice). + const sessionA = projectsA[0]!.sessions[0]! + const sessionB = projectsB[0]!.sessions[0]! + expect(sessionA.sessionId).toBe('straddle') + expect(sessionB.sessionId).toBe('straddle') + const costA = sessionA.totalCostUSD + const costB = sessionB.totalCostUSD + expect(costA).toBeGreaterThan(0) + expect(costB).toBeGreaterThan(costA) // Apr 17's call carries more input tokens. + + const report = buildPeriodDiffReport({ + provider: 'all', + rangeA: { from: '2026-04-16', to: '2026-04-16' }, + rangeB: { from: '2026-04-17', to: '2026-04-17' }, + projectsA, + projectsB, + }) + // Same canonical project on both sides → one contribution row, diff = B − A. + expect(report.projects).toHaveLength(1) + expect(report.projects[0]!.costA).toBeCloseTo(costA, 10) + expect(report.projects[0]!.costB).toBeCloseTo(costB, 10) + expect(report.totals.diff.cost).toBeCloseTo(costB - costA, 10) + expect(lensSum(report.projects)).toBeCloseTo(report.totals.diff.cost, 10) + + // Drill-down: ONE row for the straddling session, cost on both sides. + const rows = diffSessions(projectsA, projectsB, 'project', projectsA[0]!.project) + expect(rows).toHaveLength(1) + expect(rows[0]!.sessionId).toBe('straddle') + expect(rows[0]!.costA).toBeCloseTo(costA, 10) + expect(rows[0]!.costB).toBeCloseTo(costB, 10) + }) +}) + +function lensSum(rows: Array<{ diff: number }>): number { + return rows.reduce((s, row) => s + row.diff, 0) +} diff --git a/tests/period-diff.test.ts b/tests/period-diff.test.ts new file mode 100644 index 00000000..20ff7647 --- /dev/null +++ b/tests/period-diff.test.ts @@ -0,0 +1,396 @@ +import { describe, expect, it } from 'vitest' + +import { + buildPeriodDiffReport, + countLocalDays, + defaultSevenDayRanges, + diffSessions, + historyBasis, + localRangeInfo, + overlapDays, + rangeInfo, +} from '../src/period-diff.js' +import type { DailyCache, DailyEntry } from '../src/daily-cache.js' +import type { ProjectSummary, SessionSummary } from '../src/types.js' + +// Minimal but arithmetically consistent session/project fixtures: the same +// fields buildPeriodData, the session-count key, and the model lens read. + +type SessionSpec = { + sessionId: string + provider?: string + model?: string + modelCosts?: Record + costUSD: number + calls: number + inputTokens?: number + outputTokens?: number + cacheReadTokens?: number + cacheWriteTokens?: number + title?: string + firstTimestamp?: string +} + +function makeSession(spec: SessionSpec): SessionSummary { + const modelBreakdown: SessionSummary['modelBreakdown'] = {} + const models = spec.modelCosts ?? { [spec.model ?? 'test-model']: { costUSD: spec.costUSD, calls: spec.calls } } + let totalCost = 0 + let totalCalls = 0 + for (const [model, d] of Object.entries(models)) { + modelBreakdown[model] = { + calls: d.calls, + costUSD: d.costUSD, + savingsUSD: 0, + tokens: { inputTokens: 0, outputTokens: 0, cacheCreationInputTokens: 0, cacheReadInputTokens: 0, cachedInputTokens: 0, reasoningTokens: 0, webSearchRequests: 0 }, + } + totalCost += d.costUSD + totalCalls += d.calls + } + const costUSD = spec.modelCosts ? totalCost : spec.costUSD + const calls = spec.modelCosts ? totalCalls : spec.calls + return { + sessionId: spec.sessionId, + project: 'proj', + firstTimestamp: spec.firstTimestamp ?? '2026-03-10T10:00:00.000Z', + lastTimestamp: spec.firstTimestamp ?? '2026-03-10T11:00:00.000Z', + totalCostUSD: costUSD, + totalSavingsUSD: 0, + totalInputTokens: spec.inputTokens ?? 0, + totalOutputTokens: spec.outputTokens ?? 0, + totalReasoningTokens: 0, + totalCacheReadTokens: spec.cacheReadTokens ?? 0, + totalCacheWriteTokens: spec.cacheWriteTokens ?? 0, + apiCalls: calls, + turns: [], + modelBreakdown, + toolBreakdown: {}, + mcpBreakdown: {}, + bashBreakdown: {}, + categoryBreakdown: {} as SessionSummary['categoryBreakdown'], + skillBreakdown: {}, + subagentBreakdown: {}, + } as SessionSummary +} + +function makeProject(project: string, sessions: SessionSummary[]): ProjectSummary { + const totalCostUSD = sessions.reduce((s, sess) => s + sess.totalCostUSD, 0) + return { + project, + projectPath: project, + sessions, + totalCostUSD, + totalSavingsUSD: 0, + totalApiCalls: sessions.reduce((s, sess) => s + sess.apiCalls, 0), + totalProxiedCostUSD: 0, + } +} + +const RANGE_A = { from: '2026-03-02', to: '2026-03-08' } +const RANGE_B = { from: '2026-03-09', to: '2026-03-15' } + +// The acceptance fixture: A: X=70, Y=30 → 100. B: X=90, Z=70 → 160. +// Differences X=+20, Y=−30, Z=+70, total=+60. Every complete lens must +// reconcile the global difference before display rounding. +function acceptanceFixture(): { projectsA: ProjectSummary[]; projectsB: ProjectSummary[] } { + return { + projectsA: [ + makeProject('/work/x', [makeSession({ sessionId: 'x1', model: 'model-x', costUSD: 70, calls: 7 })]), + makeProject('/work/y', [makeSession({ sessionId: 'y1', model: 'model-y', costUSD: 30, calls: 3 })]), + ], + projectsB: [ + makeProject('/work/x', [makeSession({ sessionId: 'x1', model: 'model-x', costUSD: 90, calls: 9 })]), + makeProject('/work/z', [makeSession({ sessionId: 'z1', model: 'model-z', costUSD: 70, calls: 7 })]), + ], + } +} + +function lensSum(rows: Array<{ diff: number }>): number { + return rows.reduce((s, row) => s + row.diff, 0) +} + +describe('buildPeriodDiffReport — acceptance fixture', () => { + it('keeps same-label projects separate by canonical path through drill-down', () => { + const one = { ...makeProject('app', [makeSession({ sessionId: 'shared', costUSD: 3, calls: 1 })]), projectPath: '/work/a/app' } + const two = { ...makeProject('app', [makeSession({ sessionId: 'shared', costUSD: 5, calls: 1 })]), projectPath: '/work/b/app' } + const report = buildPeriodDiffReport({ provider: 'all', rangeA: RANGE_A, rangeB: RANGE_B, projectsA: [], projectsB: [one, two] }) + expect(report.projects.map(p => [p.key, p.costB])).toEqual([['/work/b/app', 5], ['/work/a/app', 3]]) + expect(lensSum(report.projects)).toBe(report.totals.diff.cost) + expect(diffSessions([], [one, two], 'project', '/work/a/app')).toMatchObject([{ costB: 3 }]) + expect(diffSessions([], [one, two], 'project', '/work/b/app')).toMatchObject([{ costB: 5 }]) + expect(diffSessions([], [one, two], 'project', 'app')).toEqual([]) + }) + + it('adds multiple summaries of the same canonical project instead of overwriting', () => { + const one = makeProject('/work/app', [makeSession({ sessionId: 'one', costUSD: 3, calls: 1 })]) + const two = makeProject('/work/app', [makeSession({ sessionId: 'two', costUSD: 5, calls: 1 })]) + const report = buildPeriodDiffReport({ provider: 'all', rangeA: RANGE_A, rangeB: RANGE_B, projectsA: [], projectsB: [one, two] }) + expect(report.projects).toMatchObject([{ key: '/work/app', costB: 8, callsB: 2 }]) + }) + + const { projectsA, projectsB } = acceptanceFixture() + const report = buildPeriodDiffReport({ provider: 'all', rangeA: RANGE_A, rangeB: RANGE_B, projectsA, projectsB }) + + it('reports the global difference B − A', () => { + expect(report.totals.A.cost).toBe(100) + expect(report.totals.B.cost).toBe(160) + expect(report.totals.diff.cost).toBe(60) + expect(report.totals.pct.cost).toBeCloseTo(60, 10) + }) + + it('reconciles the project lens with the global difference', () => { + const x = report.projects.find(row => row.key === '/work/x') + const y = report.projects.find(row => row.key === '/work/y') + const z = report.projects.find(row => row.key === '/work/z') + expect(x).toMatchObject({ costA: 70, costB: 90, diff: 20, status: 'up' }) + expect(y).toMatchObject({ costA: 30, costB: 0, diff: -30, status: 'gone' }) + expect(z).toMatchObject({ costA: 0, costB: 70, diff: 70, status: 'new' }) + expect(y!.pct).toBeCloseTo(-100, 10) + expect(z!.pct).toBeNull() // New: no infinite percentage. + expect(lensSum(report.projects)).toBeCloseTo(report.totals.diff.cost, 10) + }) + + it('reconciles the separate model lens with the same global difference', () => { + const byKey = new Map(report.models.map(row => [row.key, row])) + expect(byKey.get('model-x')!.diff).toBe(20) + expect(byKey.get('model-y')!.diff).toBe(-30) + expect(byKey.get('model-z')!.diff).toBe(70) + expect(lensSum(report.models)).toBeCloseTo(report.totals.diff.cost, 10) + // Lenses are perspectives, not partitions to be summed together — the + // report carries them separately and nothing adds projects + models. + }) + + it('shows both ranges, their duration, and disjointness', () => { + expect(report.rangeA).toMatchObject({ from: '2026-03-02', to: '2026-03-08', days: 7 }) + expect(report.rangeB).toMatchObject({ from: '2026-03-09', to: '2026-03-15', days: 7 }) + expect(report.durationDeltaDays).toBe(0) + expect(report.overlapDays).toBe(0) + }) + + it('normalizes per day and per 100 calls with explicit denominators', () => { + // A: $100 over 10 calls → $10/call → $1000 per 100 calls; B: $160/16 calls. + expect(report.normalized.perDay).toMatchObject({ a: 100 / 7, b: 160 / 7 }) + expect(report.normalized.per100Calls).toMatchObject({ a: 1000, b: 1000, diff: 0 }) + expect(report.normalized.denominators.perDay).toContain('A: 7') + expect(report.normalized.denominators.per100Calls).toContain('calls × 100') + }) +}) + +describe('edge cases', () => { + it('A = 0: every row is New, no percentage is invented, per-100-calls is unavailable', () => { + const report = buildPeriodDiffReport({ + provider: 'all', + rangeA: RANGE_A, + rangeB: RANGE_B, + projectsA: [], + projectsB: [makeProject('/work/z', [makeSession({ sessionId: 'z1', model: 'model-z', costUSD: 70, calls: 7 })])], + }) + expect(report.totals.A.cost).toBe(0) + expect(report.totals.diff.cost).toBe(70) + expect(report.projects).toHaveLength(1) + expect(report.projects[0]).toMatchObject({ status: 'new', pct: null, diff: 70 }) + expect(report.models[0]).toMatchObject({ status: 'new', pct: null }) + // No calls in A → cost per 100 calls is unavailable, not zero and not ∞. + expect(report.normalized.per100Calls.a).toBeNull() + expect(report.normalized.per100Calls.diff).toBeNull() + // Per-day still works: 0 days with data is a zero denominator too. + expect(report.normalized.perDay.a).toBe(0) + }) + + it('B = 0: every row is Gone, the difference is −A', () => { + const report = buildPeriodDiffReport({ + provider: 'all', + rangeA: RANGE_A, + rangeB: RANGE_B, + projectsA: [makeProject('/work/y', [makeSession({ sessionId: 'y1', model: 'model-y', costUSD: 30, calls: 3 })])], + projectsB: [], + }) + expect(report.totals.diff.cost).toBe(-30) + expect(report.projects[0]).toMatchObject({ status: 'gone', diff: -30 }) + expect(report.projects[0]!.pct).toBeCloseTo(-100, 10) + expect(report.normalized.per100Calls.b).toBeNull() + }) + + it('ranges of different lengths normalize honestly and report the duration delta', () => { + const report = buildPeriodDiffReport({ + provider: 'all', + rangeA: { from: '2026-03-02', to: '2026-03-08' }, // 7 days + rangeB: { from: '2026-03-09', to: '2026-03-22' }, // 14 days + projectsA: [makeProject('/w', [makeSession({ sessionId: 'a', costUSD: 70, calls: 7 })])], + projectsB: [makeProject('/w', [makeSession({ sessionId: 'b', costUSD: 140, calls: 14 })])], + }) + expect(report.durationDeltaDays).toBe(7) + expect(report.normalized.perDay).toMatchObject({ a: 10, b: 10, diff: 0 }) + // Raw totals doubled, normalized per day did not — the view must show both. + expect(report.totals.diff.cost).toBe(70) + }) + + it('overlapping ranges report their overlap in days', () => { + const report = buildPeriodDiffReport({ + provider: 'all', + rangeA: { from: '2026-03-05', to: '2026-03-11' }, + rangeB: { from: '2026-03-09', to: '2026-03-15' }, + projectsA: [makeProject('/w', [makeSession({ sessionId: 'a', costUSD: 1, calls: 1 })])], + projectsB: [makeProject('/w', [makeSession({ sessionId: 'b', costUSD: 2, calls: 1 })])], + }) + expect(report.overlapDays).toBe(3) // Mar 9, 10, 11. + }) + + it('unpriced models and estimated cost are surfaced as coverage, not hidden', () => { + // 'mystery-model' has calls but no price → cost 0 and it lands in + // unpricedModels via the shared buildPeriodData rules. + const report = buildPeriodDiffReport({ + provider: 'all', + rangeA: RANGE_A, + rangeB: RANGE_B, + projectsA: [makeProject('/w', [makeSession({ sessionId: 'a', model: 'mystery-model', costUSD: 0, calls: 4 })])], + projectsB: [makeProject('/w', [makeSession({ sessionId: 'b', model: 'claude-sonnet-4-5', costUSD: 5, calls: 4 })])], + }) + expect(report.coverage.unpricedModelsA.map(m => m.model)).toContain('mystery-model') + expect(report.coverage.pricingCoverageA).toBeLessThan(1) + }) +}) + +describe('calendar arithmetic', () => { + it('counts days across a month boundary by walking local midnights', () => { + expect(countLocalDays('2026-02-27', '2026-03-03')).toBe(5) + expect(countLocalDays('2026-01-31', '2026-02-01')).toBe(2) + }) + + it('counts days across DST transitions without millisecond math', () => { + // US DST starts 2026-03-08; EU DST starts 2026-10-25 and ends 2026-03-29. + // Whatever the runner's timezone, a calendar walk counts calendar days. + expect(countLocalDays('2026-03-07', '2026-03-09')).toBe(3) + expect(countLocalDays('2026-10-24', '2026-10-26')).toBe(3) + expect(countLocalDays('2026-03-28', '2026-03-30')).toBe(3) + }) + + it('defaults to the last seven complete days vs the seven before', () => { + const ranges = defaultSevenDayRanges(new Date(2026, 2, 15, 12, 0, 0)) // Mar 15 2026, noon local + expect(ranges.B).toEqual({ from: '2026-03-08', to: '2026-03-14' }) + expect(ranges.A).toEqual({ from: '2026-03-01', to: '2026-03-07' }) + expect(rangeInfo(ranges.A).days).toBe(7) + expect(rangeInfo(ranges.B).days).toBe(7) + // Today (Mar 15) is deliberately outside both ranges: it is not complete. + }) + + it('rejects inverted ranges as zero days', () => { + expect(countLocalDays('2026-03-10', '2026-03-01')).toBe(0) + }) + + it('round-trips a DateRange through localRangeInfo', () => { + const info = localRangeInfo({ start: new Date(2026, 2, 9), end: new Date(2026, 2, 15, 23, 59, 59, 999) }) + expect(info).toEqual({ from: '2026-03-09', to: '2026-03-15', days: 7 }) + }) +}) + +describe('sessions spanning the A/B boundary', () => { + // The parser hands each range a post-slice tree: the same session carries + // only its in-range calls on each side. The drill-down must join the two + // halves into ONE row keyed by the canonical identity — never two sessions. + it('joins both halves of a boundary-straddling session', () => { + const session = (cost: number, calls: number): SessionSummary => + makeSession({ sessionId: 'straddle-1', model: 'model-x', costUSD: cost, calls, title: 'long run' }) + const report = buildPeriodDiffReport({ + provider: 'all', + rangeA: RANGE_A, + rangeB: RANGE_B, + projectsA: [makeProject('/work/x', [session(30, 3)])], + projectsB: [makeProject('/work/x', [session(40, 4)])], + }) + expect(report.projects).toHaveLength(1) + expect(report.projects[0]).toMatchObject({ costA: 30, costB: 40, diff: 10 }) + + const rows = diffSessions( + [makeProject('/work/x', [session(30, 3)])], + [makeProject('/work/x', [session(40, 4)])], + 'project', + '/work/x', + ) + expect(rows).toHaveLength(1) + expect(rows[0]).toMatchObject({ sessionId: 'straddle-1', costA: 30, costB: 40, diff: 10, callsA: 3, callsB: 4 }) + expect(rows[0]!.identity).toContain('straddle-1') + }) + + it('drills by model across projects and by project across models', () => { + const a = [makeProject('/w1', [makeSession({ sessionId: 's1', modelCosts: { 'm-a': { costUSD: 10, calls: 1 }, 'm-b': { costUSD: 5, calls: 1 } } })])] + const b = [makeProject('/w2', [makeSession({ sessionId: 's2', modelCosts: { 'm-a': { costUSD: 25, calls: 2 } } })])] + // Two DIFFERENT sessions (a bare sessionId is not globally unique — the + // identity includes the project path), so the model lens yields two rows. + const byModel = diffSessions(a, b, 'model', 'm-a') + expect(byModel).toHaveLength(2) + const pairA = byModel.find(row => row.costA === 10) + const pairB = byModel.find(row => row.costB === 25) + expect(pairA).toMatchObject({ costB: 0, diff: -10 }) + expect(pairB).toMatchObject({ costA: 0, diff: 25 }) + expect(lensSum(byModel)).toBe(15) + // m-b exists only in A → its own row, status via negative diff. + const goneModel = diffSessions(a, b, 'model', 'm-b') + expect(goneModel).toHaveLength(1) + expect(goneModel[0]).toMatchObject({ costA: 5, costB: 0, diff: -5 }) + const byProject = diffSessions(a, b, 'project', '/w2') + expect(byProject).toHaveLength(1) + expect(byProject[0]).toMatchObject({ costA: 0, costB: 25 }) + }) +}) + +function day(date: string, cost: number, carried?: true): DailyEntry { + return { + date, + cost, + savingsUSD: 0, + calls: 1, + sessions: 1, + inputTokens: 0, + outputTokens: 0, + cacheReadTokens: 0, + cacheWriteTokens: 0, + editTurns: 0, + oneShotTurns: 0, + models: {}, + categories: {}, + providers: {}, + ...(carried ? { carried: true as const } : {}), + } +} + +describe('history basis (aggregate-only carried history)', () => { + const cache: DailyCache = { + version: 21, + savingsConfigHash: '', + lastComputedDate: '2026-03-15', + days: [ + day('2026-03-03', 10), // fully explained by detail + day('2026-03-05', 12, true), // sources gone: 12 in history, 0 in detail + day('2026-03-11', 4), // explained + day('2026-03-13', 9, true), // sources gone on the B side + ], + } + + it('lists only the days history holds that session detail cannot explain', () => { + const freshA = [day('2026-03-03', 10)] + const freshB = [day('2026-03-11', 4)] + const basis = historyBasis(cache, RANGE_A, RANGE_B, 'all', freshA, freshB) + expect(basis.aggregateOnly.A).toBeCloseTo(12, 10) + expect(basis.aggregateOnly.B).toBeCloseTo(9, 10) + expect(basis.days.A.map(row => row.date)).toEqual(['2026-03-05']) + expect(basis.days.B.map(row => row.date)).toEqual(['2026-03-13']) + // The totals NEVER include the aggregate-only amount: the detail basis + // stays reconciled with its own lenses. + expect(basis.detailCost.A).toBe(10) + expect(basis.historyCost.A).toBe(22) + }) + + it('never reports a negative unexplained remainder when detail leads history', () => { + const plainCache: DailyCache = { ...cache, days: [day('2026-03-03', 10)] } + const basis = historyBasis(plainCache, RANGE_A, RANGE_B, 'all', [day('2026-03-03', 15)], []) + expect(basis.aggregateOnly.A).toBe(0) + expect(basis.days.A).toHaveLength(0) + }) +}) + +describe('overlap helper', () => { + it('handles disjoint and identical ranges', () => { + expect(overlapDays({ from: '2026-03-01', to: '2026-03-07' }, { from: '2026-03-09', to: '2026-03-15' })).toBe(0) + expect(overlapDays(RANGE_A, RANGE_A)).toBe(7) + }) +})