mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-29 10:43:47 +00:00
Merge pull request #1319 from getagentseal/feat/spend-by-branch
Add Spend by branch & worktree lens (project x branch attribution)
This commit is contained in:
commit
003854c7f0
14 changed files with 1231 additions and 6 deletions
|
|
@ -47,6 +47,7 @@ const CHANNELS = [
|
|||
'codeburn:getCompare',
|
||||
'codeburn:getYield',
|
||||
'codeburn:getSpendFlow',
|
||||
'codeburn:getBranchSpend',
|
||||
'codeburn:getOptimizeReport',
|
||||
'codeburn:getDevices',
|
||||
'codeburn:getDevicesScan',
|
||||
|
|
@ -121,6 +122,8 @@ const ARGV_CASES: Array<{ channel: string; args: unknown[]; argv: string[] }> =
|
|||
{ channel: 'codeburn:getModels', args: ['week', 'claude', true, { from: '2026-07-01', to: '2026-07-11' }], argv: ['models', '--format', 'json', '--period', 'week', '--provider', 'claude', '--by-task', '--from', '2026-07-01', '--to', '2026-07-11'] },
|
||||
{ channel: 'codeburn:getYield', args: ['today', 'all', { from: '2026-07-01', to: '2026-07-11' }], argv: ['yield', '--format', 'json', '--period', 'today', '--from', '2026-07-01', '--to', '2026-07-11'] },
|
||||
{ channel: 'codeburn:getSpendFlow', args: ['month', 'all', { from: '2026-07-01', to: '2026-07-11' }], argv: ['spend', '--format', 'flow-json', '--period', 'month', '--from', '2026-07-01', '--to', '2026-07-11'] },
|
||||
{ channel: 'codeburn:getBranchSpend', args: ['month', 'openai'], argv: ['spend', '--format', 'branch-json', '--period', 'month', '--provider', 'openai'] },
|
||||
{ channel: 'codeburn:getBranchSpend', args: ['30days', 'all', { from: '2026-07-01', to: '2026-07-11' }], argv: ['spend', '--format', 'branch-json', '--period', '30days', '--from', '2026-07-01', '--to', '2026-07-11'] },
|
||||
{ channel: 'codeburn:getOptimizeReport', args: ['month', 'all', { from: '2026-07-01', to: '2026-07-11' }], argv: ['optimize', '--format', 'json', '--period', 'month', '--from', '2026-07-01', '--to', '2026-07-11'] },
|
||||
{ channel: 'codeburn:getDevices', args: ['week'], argv: ['devices', '--format', 'json', '--period', 'week'] },
|
||||
{ channel: 'codeburn:getDevicesScan', args: [], argv: ['devices', 'scan', '--format', 'json'] },
|
||||
|
|
@ -520,6 +523,7 @@ describe('createBridgeHandlers (cold-start warmup)', () => {
|
|||
['codeburn:getCompareModels', ['today', 'all', true]],
|
||||
['codeburn:getYield', ['today', 'all', undefined, true]],
|
||||
['codeburn:getSpendFlow', ['today', 'all', undefined, true]],
|
||||
['codeburn:getBranchSpend', ['today', 'all', undefined, true]],
|
||||
['codeburn:getOptimizeReport', ['today', 'all', undefined, true]],
|
||||
]
|
||||
|
||||
|
|
@ -829,6 +833,8 @@ describe('project filter', () => {
|
|||
expect(calls[0]).toEqual(['sessions', '--format', 'json', '--period', 'week', '--project=my-company', '--exclude=scratch'])
|
||||
await handlers['codeburn:getSessionsContributions']!('week', 'all')
|
||||
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'])
|
||||
})
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -573,6 +573,14 @@ export function createBridgeHandlers(deps: Deps = { spawnCli, spawnCliAction, re
|
|||
...projectArgs(),
|
||||
...rangeArgs(vRange(range)),
|
||||
], 3),
|
||||
// Spend "By branch" lens: spend per canonical project × branch (plus
|
||||
// coverage for sources without branch metadata).
|
||||
'codeburn:getBranchSpend': run((period: string, provider: string, range?: DateRange) => [
|
||||
'spend', '--format', 'branch-json', '--period', vPeriod(period),
|
||||
...providerArgs(vProvider(provider)),
|
||||
...projectArgs(),
|
||||
...rangeArgs(vRange(range)),
|
||||
], 3),
|
||||
'codeburn:getOptimizeReport': run((period: string, provider: string, range?: DateRange) => [
|
||||
'optimize', '--format', 'json', '--period', vPeriod(period),
|
||||
...providerArgs(vProvider(provider)),
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ const bridge = {
|
|||
getCompare: (period: string, provider: string, modelA: string, modelB: string) => invoke('codeburn:getCompare', period, provider, modelA, modelB),
|
||||
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),
|
||||
getOptimizeReport: (period: string, provider: string, range?: DateRange, background?: boolean) => invoke('codeburn:getOptimizeReport', period, provider, range, background),
|
||||
getDevices: (period: string) => invoke('codeburn:getDevices', period),
|
||||
getDevicesScan: () => invoke('codeburn:getDevicesScan'),
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import { sanitizeProps } from '../electron/telemetry'
|
|||
import { __resetPolledMemo, hasPolledMemo, primePolledMemo } from './hooks/usePolled'
|
||||
import { setActiveCurrency } from './lib/format'
|
||||
import { readOverviewHeadline, writeOverviewHeadline } from './lib/overviewSnapshot'
|
||||
import type { DateRange, MenubarPayload, ModelReportRow, OptimizeJsonReport, SpendFlow } from './lib/types'
|
||||
import type { BranchSpendReport, DateRange, MenubarPayload, ModelReportRow, OptimizeJsonReport, SpendFlow } from './lib/types'
|
||||
|
||||
const stored = new Map<string, string>()
|
||||
vi.stubGlobal('localStorage', {
|
||||
|
|
@ -22,6 +22,7 @@ vi.stubGlobal('localStorage', {
|
|||
const mocks = vi.hoisted(() => ({
|
||||
getOverview: vi.fn<(period: string, provider: string, range?: DateRange, configSource?: string | null, background?: boolean, scope?: string) => Promise<MenubarPayload>>(),
|
||||
getSpendFlow: vi.fn<(period: string, provider: string, range?: DateRange, background?: boolean) => Promise<SpendFlow>>(),
|
||||
getBranchSpend: vi.fn<(period: string, provider: string, range?: DateRange, background?: boolean) => Promise<BranchSpendReport>>(),
|
||||
getTimeline: vi.fn<(period: string, provider: string, range?: DateRange) => Promise<MenubarPayload>>(),
|
||||
getOptimizeReport: vi.fn<(period: string, provider: string, range?: DateRange, background?: boolean) => Promise<OptimizeJsonReport>>(),
|
||||
getModels: vi.fn(),
|
||||
|
|
@ -138,6 +139,11 @@ function installDefaultMocks() {
|
|||
mocks.getOverview.mockResolvedValue(overviewPayload())
|
||||
mocks.getTimeline.mockResolvedValue(overviewPayload())
|
||||
mocks.getSpendFlow.mockResolvedValue({ period: { label: 'Last 30 days', start: '', end: '' }, models: [], projects: [], links: [] })
|
||||
mocks.getBranchSpend.mockResolvedValue({
|
||||
period: { label: '', start: '', end: '' },
|
||||
projects: [],
|
||||
totals: { branchKnownCost: 0, branchUnknownCost: 0, noBranchDataCost: 0, noBranchDataSessions: 0, noBranchDataProviders: [], distinctSessions: 0 },
|
||||
})
|
||||
mocks.getOptimizeReport.mockResolvedValue({
|
||||
period: { label: 'Last 30 days', start: null, end: null },
|
||||
summary: {
|
||||
|
|
|
|||
168
app/renderer/components/BranchBreakdown.test.tsx
Normal file
168
app/renderer/components/BranchBreakdown.test.tsx
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
// @vitest-environment jsdom
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { BranchBreakdown } from './BranchBreakdown'
|
||||
import type { BranchSpendReport } from '../lib/types'
|
||||
|
||||
const { getBranchSpend } = vi.hoisted(() => ({
|
||||
getBranchSpend: vi.fn<(period: string, provider: string) => Promise<BranchSpendReport>>(),
|
||||
}))
|
||||
vi.mock('../lib/ipc', async orig => {
|
||||
const actual = await orig<typeof import('../lib/ipc')>()
|
||||
return { ...actual, codeburn: { getBranchSpend } }
|
||||
})
|
||||
|
||||
function report(overrides: Partial<BranchSpendReport> = {}): BranchSpendReport {
|
||||
return {
|
||||
period: { label: '2026-07-01 to 2026-07-02', start: '2026-07-01T00:00:00.000Z', end: '2026-07-02T00:00:00.000Z' },
|
||||
projects: [
|
||||
{
|
||||
id: '/code/alpha',
|
||||
label: 'alpha',
|
||||
totalCost: 8,
|
||||
branches: [
|
||||
{
|
||||
projectId: '/code/alpha', projectLabel: 'alpha', branch: 'feat/auth',
|
||||
cost: 3, calls: 4, sessions: 1,
|
||||
tokens: { inputTokens: 1200, outputTokens: 300, reasoningTokens: 100, cacheReadTokens: 9000, cacheWriteTokens: 50 },
|
||||
firstActive: '2026-07-01T08:00:00Z', lastActive: '2026-07-01T09:30:00Z',
|
||||
worktrees: [{ path: '/code/alpha', sessions: 1, cost: 3 }],
|
||||
sessionRows: [{
|
||||
sessionId: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee', title: 'Implement auth', provider: 'claude',
|
||||
workingDirectory: '/code/alpha', cost: 3, calls: 4,
|
||||
tokens: { inputTokens: 1200, outputTokens: 300, reasoningTokens: 100, cacheReadTokens: 9000, cacheWriteTokens: 50 },
|
||||
models: ['claude-sonnet'], firstActive: '2026-07-01T08:00:00Z', lastActive: '2026-07-01T09:30:00Z',
|
||||
}],
|
||||
},
|
||||
{
|
||||
projectId: '/code/alpha', projectLabel: 'alpha', branch: 'fix/parser',
|
||||
cost: 5, calls: 2, sessions: 1,
|
||||
tokens: { inputTokens: 400, outputTokens: 80, reasoningTokens: 0, cacheReadTokens: 2000, cacheWriteTokens: 0 },
|
||||
firstActive: '2026-07-01T10:00:00Z', lastActive: '2026-07-01T10:15:00Z',
|
||||
worktrees: [{ path: '/code/alpha-wt/task-42', sessions: 1, cost: 5 }],
|
||||
sessionRows: [{
|
||||
sessionId: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee', provider: 'claude',
|
||||
workingDirectory: '/code/alpha-wt/task-42', cost: 5, calls: 2,
|
||||
tokens: { inputTokens: 400, outputTokens: 80, reasoningTokens: 0, cacheReadTokens: 2000, cacheWriteTokens: 0 },
|
||||
models: ['claude-sonnet'], firstActive: '2026-07-01T10:00:00Z', lastActive: '2026-07-01T10:15:00Z',
|
||||
}],
|
||||
},
|
||||
{
|
||||
projectId: '/code/alpha', projectLabel: 'alpha', branch: null,
|
||||
cost: 2, calls: 1, sessions: 1,
|
||||
tokens: { inputTokens: 100, outputTokens: 10, reasoningTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 },
|
||||
firstActive: '2026-07-01T07:00:00Z', lastActive: '2026-07-01T07:05:00Z',
|
||||
worktrees: [],
|
||||
sessionRows: [],
|
||||
},
|
||||
],
|
||||
coverage: {
|
||||
branchKnownCost: 8, branchUnknownCost: 2, noBranchDataCost: 4,
|
||||
noBranchDataSessions: 1, noBranchDataProviders: ['codex'], distinctSessions: 2,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: '/code/beta',
|
||||
label: 'beta',
|
||||
totalCost: 6,
|
||||
branches: [{
|
||||
projectId: '/code/beta', projectLabel: 'beta', branch: 'main',
|
||||
cost: 6, calls: 3, sessions: 1,
|
||||
tokens: { inputTokens: 500, outputTokens: 50, reasoningTokens: 0, cacheReadTokens: 1000, cacheWriteTokens: 0 },
|
||||
firstActive: '2026-07-01T11:00:00Z', lastActive: '2026-07-01T11:20:00Z',
|
||||
worktrees: [], sessionRows: [{
|
||||
sessionId: 'ffffffff-1111-2222-3333-444444444444', provider: 'claude',
|
||||
cost: 6, calls: 3,
|
||||
tokens: { inputTokens: 500, outputTokens: 50, reasoningTokens: 0, cacheReadTokens: 1000, cacheWriteTokens: 0 },
|
||||
models: ['claude-sonnet'], firstActive: '2026-07-01T11:00:00Z', lastActive: '2026-07-01T11:20:00Z',
|
||||
}],
|
||||
}],
|
||||
coverage: {
|
||||
branchKnownCost: 6, branchUnknownCost: 0, noBranchDataCost: 0,
|
||||
noBranchDataSessions: 0, noBranchDataProviders: [], distinctSessions: 1,
|
||||
},
|
||||
},
|
||||
],
|
||||
totals: {
|
||||
branchKnownCost: 14, branchUnknownCost: 2, noBranchDataCost: 4,
|
||||
noBranchDataSessions: 1, noBranchDataProviders: ['codex'], distinctSessions: 3,
|
||||
},
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('BranchBreakdown', () => {
|
||||
beforeEach(() => {
|
||||
getBranchSpend.mockReset()
|
||||
getBranchSpend.mockResolvedValue(report())
|
||||
})
|
||||
|
||||
it('defaults to the top project and shows its branch rows with cost, sessions and calls', async () => {
|
||||
render(<BranchBreakdown period="30days" provider="all" />)
|
||||
await waitFor(() => expect(getBranchSpend).toHaveBeenCalledWith('30days', 'all'))
|
||||
// alpha is the top project: its rows show, beta's do not.
|
||||
expect(await screen.findByText('feat/auth')).toBeInTheDocument()
|
||||
expect(screen.getByText('fix/parser')).toBeInTheDocument()
|
||||
expect(screen.getByText('$3.00')).toBeInTheDocument()
|
||||
expect(screen.getByText('$5.00')).toBeInTheDocument()
|
||||
expect(screen.queryByText('beta / main')).not.toBeInTheDocument()
|
||||
// The Unknown bucket keeps its honest name (never relabeled as a branch).
|
||||
expect(screen.getByText('Unknown')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('expands a branch into tokens, worktree evidence and per-session contributions', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<BranchBreakdown period="30days" provider="all" />)
|
||||
await user.click(await screen.findByText('fix/parser'))
|
||||
expect(screen.getByText(/cacheR 2K/)).toBeInTheDocument()
|
||||
// Recorded worktree path: basename in the row, full path as tooltip.
|
||||
const wt = screen.getByText(/task-42 · 1 session · \$5.00/)
|
||||
expect(wt).toHaveAttribute('title', '/code/alpha-wt/task-42')
|
||||
// Session contribution shows the branch-sliced cost (5, not the session total 8).
|
||||
expect(screen.getByText('2 calls')).toBeInTheDocument()
|
||||
expect(screen.getByText('$5.00', { selector: '.sps-cost' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('inspects a session with real detail: id, provider, working directory, models', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<BranchBreakdown period="30days" provider="all" />)
|
||||
await user.click(await screen.findByText('feat/auth'))
|
||||
await user.click(screen.getByText('Implement auth'))
|
||||
const region = await screen.findByRole('region', { name: /Session aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee detail/ })
|
||||
expect(region).toHaveTextContent('aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee')
|
||||
expect(region).toHaveTextContent('claude')
|
||||
expect(region).toHaveTextContent('alpha')
|
||||
expect(region).toHaveTextContent('claude-sonnet')
|
||||
})
|
||||
|
||||
it('keeps same-named branches of different projects separate in the All projects view', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<BranchBreakdown period="30days" provider="all" />)
|
||||
await user.click(await screen.findByRole('button', { name: /Project for the By branch lens/i }))
|
||||
await user.click(screen.getByRole('option', { name: 'All projects' }))
|
||||
expect(await screen.findByText('alpha / feat/auth')).toBeInTheDocument()
|
||||
expect(screen.getByText('beta / main')).toBeInTheDocument()
|
||||
// Two projects, each with its own spend line, no merged "main" row.
|
||||
expect(screen.queryByText(/^main$/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the coverage note with known, unknown, no-branch-data and distinct sessions', async () => {
|
||||
render(<BranchBreakdown period="30days" provider="all" />)
|
||||
const note = await screen.findByRole('note', { name: 'Branch metadata coverage' })
|
||||
expect(note).toHaveTextContent('On branches $8.00')
|
||||
expect(note).toHaveTextContent('Unknown, before first branch $2.00')
|
||||
expect(note).toHaveTextContent('No branch data $4.00 (1 session: codex)')
|
||||
expect(note).toHaveTextContent('2 distinct sessions')
|
||||
})
|
||||
|
||||
it('renders the CLI error inside the panel when the report fails', async () => {
|
||||
// A provider no other test in this file fetched: earlier successes persist
|
||||
// as durable localStorage snapshots under their memo keys, and usePolled
|
||||
// keeps last-good data painted on an error for the SAME key.
|
||||
getBranchSpend.mockRejectedValue({ kind: 'nonzero', message: 'boom' })
|
||||
render(<BranchBreakdown period="30days" provider="grok" />)
|
||||
await waitFor(() => expect(screen.getByText(/boom/)).toBeInTheDocument())
|
||||
})
|
||||
})
|
||||
250
app/renderer/components/BranchBreakdown.tsx
Normal file
250
app/renderer/components/BranchBreakdown.tsx
Normal file
|
|
@ -0,0 +1,250 @@
|
|||
import { Fragment, useEffect, useState } from 'react'
|
||||
|
||||
import { CliErrorText } from './CliErrorPanel'
|
||||
import { EmptyNote } from './EmptyState'
|
||||
import { Dropdown } from './Dropdown'
|
||||
import { ListRow } from './ListRow'
|
||||
import { Panel } from './Panel'
|
||||
import { SectionSkeleton } from './Skeleton'
|
||||
import { usePolled } from '../hooks/usePolled'
|
||||
import { formatCompact, formatDayShort, formatUsd } from '../lib/format'
|
||||
import { codeburn } from '../lib/ipc'
|
||||
import { reportMemoKey } from '../lib/reportMemoKey'
|
||||
import type { BranchSpendProjectReport, BranchSpendReport, BranchSpendRow, BranchSpendSessionRow, BranchTokenSplit, DateRange, Period } from '../lib/types'
|
||||
|
||||
const ALL_PROJECTS = '__all__'
|
||||
|
||||
/// Row label for a session id, mirroring the CLI's shortSessionId conventions
|
||||
/// (src/sessions-report.ts): agent/codex prefixes and UUID head…tail trimming.
|
||||
/// A session id alone is not globally unique — it labels the row, the full id
|
||||
/// stays in the detail view and the tooltip.
|
||||
function shortSessionId(value: string): string {
|
||||
const id = value.trim()
|
||||
if (id.startsWith('agent-')) return `Agent ${id.slice(6, 14)}`
|
||||
if (id.startsWith('rollout-')) {
|
||||
const tail = id.match(/([0-9a-f]{8})-[0-9a-f-]{27,}$/i)?.[1]
|
||||
return `Codex ${tail ?? id.slice(-8)}`
|
||||
}
|
||||
if (/^[0-9a-f]{8}-[0-9a-f-]{27}$/i.test(id)) return `${id.slice(0, 8)}…${id.slice(-4)}`
|
||||
return id.length > 24 ? `${id.slice(0, 12)}…${id.slice(-6)}` : id || 'Unknown session'
|
||||
}
|
||||
|
||||
/** "Jul 3" from an ISO timestamp; local noon keeps the calendar day stable. */
|
||||
function activityDay(iso: string | null): string {
|
||||
if (!iso) return '—'
|
||||
const d = new Date(iso)
|
||||
if (Number.isNaN(d.getTime())) return '—'
|
||||
return formatDayShort(d.toISOString())
|
||||
}
|
||||
|
||||
/** One day collapses to its label, otherwise the two endpoints joined by "-". */
|
||||
function activitySpan(first: string | null, last: string | null): string {
|
||||
const a = activityDay(first)
|
||||
const b = activityDay(last)
|
||||
if (a === '—' && b === '—') return '—'
|
||||
return a === b ? a : `${a} - ${b}`
|
||||
}
|
||||
|
||||
function tokenSummary(tokens: BranchTokenSplit): string {
|
||||
return [
|
||||
`in ${formatCompact(tokens.inputTokens)}`,
|
||||
`out ${formatCompact(tokens.outputTokens)}`,
|
||||
...(tokens.reasoningTokens > 0 ? [`reason ${formatCompact(tokens.reasoningTokens)}`] : []),
|
||||
`cacheR ${formatCompact(tokens.cacheReadTokens)}`,
|
||||
...(tokens.cacheWriteTokens > 0 ? [`cacheW ${formatCompact(tokens.cacheWriteTokens)}`] : []),
|
||||
].join(' · ')
|
||||
}
|
||||
|
||||
/** The recorded historical working directory, shown under its display
|
||||
* conventions: basename in the row, full path on the tooltip. */
|
||||
function pathLabel(path: string): string {
|
||||
const parts = path.replace(/\\/g, '/').split('/').filter(Boolean)
|
||||
return parts.at(-1) || path
|
||||
}
|
||||
|
||||
function BranchSessionDetail({ session }: { session: BranchSpendSessionRow }) {
|
||||
return (
|
||||
<div className="spend-proj-detail branch-session-detail" role="region" aria-label={`Session ${session.sessionId} detail`}>
|
||||
<div className="branch-detail-line"><span>Session</span><code>{session.sessionId}</code></div>
|
||||
<div className="branch-detail-line"><span>Provider</span><span>{session.provider}{session.isSidechain ? ' (subagent)' : ''}</span></div>
|
||||
<div className="branch-detail-line"><span>Working directory</span><span title={session.workingDirectory}>{session.workingDirectory ? pathLabel(session.workingDirectory) : 'Not recorded'}</span></div>
|
||||
<div className="branch-detail-line"><span>Models</span><span>{session.models.length ? session.models.join(', ') : '—'}</span></div>
|
||||
<div className="branch-detail-line"><span>Tokens</span><span>{tokenSummary(session.tokens)}</span></div>
|
||||
<div className="branch-detail-line"><span>Activity</span><span>{activitySpan(session.firstActive, session.lastActive)} · {session.calls.toLocaleString('en-US')} calls</span></div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function BranchRowView({ row, index, showProject, expanded, onToggle }: {
|
||||
row: BranchSpendRow
|
||||
index: number
|
||||
showProject: boolean
|
||||
expanded: boolean
|
||||
onToggle: () => void
|
||||
}) {
|
||||
const [openSession, setOpenSession] = useState<string | null>(null)
|
||||
// An expansion must never survive onto different data: the session ids here
|
||||
// belong to this report snapshot.
|
||||
useEffect(() => { setOpenSession(null) }, [row.projectId, row.branch])
|
||||
const title = showProject ? `${row.projectLabel} / ${row.branch ?? 'Unknown'}` : (row.branch ?? 'Unknown')
|
||||
return (
|
||||
<Fragment key={`${row.projectId}|${row.branch ?? '__unknown__'}`}>
|
||||
<ListRow
|
||||
no={String(index + 1).padStart(2, '0')}
|
||||
title={title}
|
||||
sub={`${row.sessions.toLocaleString('en-US')} ${row.sessions === 1 ? 'session' : 'sessions'} · ${row.calls.toLocaleString('en-US')} calls · ${activitySpan(row.firstActive, row.lastActive)}`}
|
||||
value={formatUsd(row.cost)}
|
||||
expanded={expanded}
|
||||
onClick={onToggle}
|
||||
/>
|
||||
{expanded && (
|
||||
<div className="spend-proj-detail" role="region" aria-label={`${title} detail`}>
|
||||
<div className="branch-detail-line"><span>Tokens</span><span>{tokenSummary(row.tokens)}</span></div>
|
||||
{row.worktrees.map(wt => (
|
||||
<div className="branch-detail-line" key={wt.path}>
|
||||
<span>Worktree</span>
|
||||
<span title={wt.path}>{pathLabel(wt.path)} · {wt.sessions} {wt.sessions === 1 ? 'session' : 'sessions'} · {formatUsd(wt.cost)}</span>
|
||||
</div>
|
||||
))}
|
||||
{row.sessionRows.map(session => {
|
||||
const sessionKey = `${row.projectId}|${row.branch}|${session.sessionId}`
|
||||
const open = openSession === sessionKey
|
||||
return (
|
||||
<Fragment key={sessionKey}>
|
||||
<div
|
||||
className={open ? 'spend-proj-session li-clickable is-open-row' : 'spend-proj-session li-clickable'}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-expanded={open}
|
||||
aria-label={`Inspect session ${session.title ?? session.sessionId}`}
|
||||
onClick={() => setOpenSession(current => current === sessionKey ? null : sessionKey)}
|
||||
onKeyDown={event => {
|
||||
if (event.target !== event.currentTarget) return
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault()
|
||||
setOpenSession(current => current === sessionKey ? null : sessionKey)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span className="sps-date" title={session.sessionId}>{session.title ?? shortSessionId(session.sessionId)}</span>
|
||||
<span className="sps-model">{session.models[0] ?? session.provider}</span>
|
||||
<span className="sps-calls">{session.calls.toLocaleString('en-US')} calls</span>
|
||||
<span className="sps-cost">{formatUsd(session.cost)}</span>
|
||||
</div>
|
||||
{open && <BranchSessionDetail session={session} />}
|
||||
</Fragment>
|
||||
)
|
||||
})}
|
||||
{row.sessionRows.length === 0 && <div className="spend-proj-empty">No session detail for this branch.</div>}
|
||||
</div>
|
||||
)}
|
||||
</Fragment>
|
||||
)
|
||||
}
|
||||
|
||||
function CoverageNote({ scope }: { scope: BranchSpendProjectReport['coverage'] }) {
|
||||
const providers = scope.noBranchDataProviders
|
||||
return (
|
||||
<div className="branch-coverage" role="note" aria-label="Branch metadata coverage">
|
||||
<span>On branches {formatUsd(scope.branchKnownCost)}</span>
|
||||
<span>Unknown, before first branch {formatUsd(scope.branchUnknownCost)}</span>
|
||||
<span>
|
||||
No branch data {formatUsd(scope.noBranchDataCost)}
|
||||
{scope.noBranchDataSessions > 0 ? ` (${scope.noBranchDataSessions} ${scope.noBranchDataSessions === 1 ? 'session' : 'sessions'}${providers.length ? `: ${providers.join(', ')}` : ''})` : ''}
|
||||
</span>
|
||||
<span className="branch-coverage-note">
|
||||
{scope.distinctSessions.toLocaleString('en-US')} distinct {scope.distinctSessions === 1 ? 'session' : 'sessions'} — a session that switched branches appears on each one, so rows are not summed.
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function BranchPage({ report }: { report: BranchSpendReport }) {
|
||||
// `null` = auto (the top project by spend). The user's explicit choice —
|
||||
// including "All projects" — persists across refreshes and only falls back
|
||||
// when the chosen project no longer appears in a new report snapshot.
|
||||
const [selected, setSelected] = useState<string | null>(null)
|
||||
const [expandedKey, setExpandedKey] = useState<string | null>(null)
|
||||
const projectOptions = [
|
||||
{ value: ALL_PROJECTS, label: 'All projects' },
|
||||
...report.projects.map(p => ({ value: p.id, label: p.label })),
|
||||
]
|
||||
const chosen = selected !== null && selected !== ALL_PROJECTS
|
||||
? report.projects.find(p => p.id === selected)
|
||||
: undefined
|
||||
const effectiveId = selected === ALL_PROJECTS
|
||||
? ALL_PROJECTS
|
||||
: chosen ? chosen.id : report.projects[0]?.id ?? ALL_PROJECTS
|
||||
|
||||
const scope: BranchSpendProjectReport['coverage'] = effectiveId === ALL_PROJECTS
|
||||
? report.totals
|
||||
: report.projects.find(p => p.id === effectiveId)?.coverage ?? report.totals
|
||||
const rows: BranchSpendRow[] = effectiveId === ALL_PROJECTS
|
||||
? report.projects.flatMap(p => p.branches)
|
||||
: report.projects.find(p => p.id === effectiveId)?.branches ?? []
|
||||
const showProject = effectiveId === ALL_PROJECTS
|
||||
|
||||
// Reset any open expansion when the visible row set changes (project or
|
||||
// filter switch, refresh that alters the list): a stale expandedKey would
|
||||
// otherwise point at a row that is no longer present.
|
||||
useEffect(() => { setExpandedKey(null) }, [effectiveId, rows.map(r => `${r.projectId}|${r.branch}`).join('|')])
|
||||
|
||||
return (
|
||||
<Panel
|
||||
title="By branch"
|
||||
right="spend per project and branch"
|
||||
className="spend-scroll"
|
||||
>
|
||||
<div className="branch-picker">
|
||||
<Dropdown
|
||||
id="branch-project"
|
||||
ariaLabel="Project for the By branch lens"
|
||||
value={effectiveId}
|
||||
options={projectOptions}
|
||||
onChange={value => setSelected(value)}
|
||||
/>
|
||||
</div>
|
||||
{rows.length ? (
|
||||
rows.map((row, i) => {
|
||||
const rowKey = `${row.projectId}|${row.branch ?? '__unknown__'}`
|
||||
return (
|
||||
<BranchRowView
|
||||
key={rowKey}
|
||||
row={row}
|
||||
index={i}
|
||||
showProject={showProject}
|
||||
expanded={expandedKey === rowKey}
|
||||
onToggle={() => setExpandedKey(current => current === rowKey ? null : rowKey)}
|
||||
/>
|
||||
)
|
||||
})
|
||||
) : (
|
||||
<EmptyNote>No branch activity for this project in the selected range yet. Branch metadata is captured per turn (Claude transcripts carry it today); sources without it are listed in the coverage note.</EmptyNote>
|
||||
)}
|
||||
<CoverageNote scope={scope} />
|
||||
</Panel>
|
||||
)
|
||||
}
|
||||
|
||||
/** Spend "By branch" lens: canonical project × branch rows with per-session
|
||||
* contributions and recorded worktree evidence, filtered by the app-wide
|
||||
* period/provider/range controls (the CLI report computes the full filtered
|
||||
* population; this panel only narrows the display to the chosen project). */
|
||||
export function BranchBreakdown({ period, provider, range = null }: { period: Period; provider: string; range?: DateRange | null }) {
|
||||
const report = usePolled<BranchSpendReport>(
|
||||
() => range ? codeburn.getBranchSpend(period, provider, range) : codeburn.getBranchSpend(period, provider),
|
||||
[period, provider, range?.from, range?.to],
|
||||
{ memoKey: reportMemoKey('branchspend', period, provider, range) },
|
||||
)
|
||||
if (!report.data) {
|
||||
if (report.error) {
|
||||
return (
|
||||
<Panel title="By branch" className="spend-scroll">
|
||||
<CliErrorText error={report.error} />
|
||||
</Panel>
|
||||
)
|
||||
}
|
||||
return <SectionSkeleton label="Scanning branches…" rows={4} />
|
||||
}
|
||||
return <BranchPage report={report.data} />
|
||||
}
|
||||
|
|
@ -451,6 +451,74 @@ export type SpendFlow = {
|
|||
links: SpendFlowLink[]
|
||||
}
|
||||
|
||||
// ————— src/branch-spend.ts — Spend "By branch" lens (shared contract) —————
|
||||
|
||||
export type BranchTokenSplit = {
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
reasoningTokens: number
|
||||
cacheReadTokens: number
|
||||
cacheWriteTokens: number
|
||||
}
|
||||
|
||||
/** One session's contribution inside a single (project, branch) row; cost is
|
||||
* the branch-sliced portion. `workingDirectory` is the provider-recorded
|
||||
* historical cwd (the worktree path itself when the session ran in one). */
|
||||
export type BranchSpendSessionRow = {
|
||||
sessionId: string
|
||||
title?: string
|
||||
provider: string
|
||||
workingDirectory?: string
|
||||
isSidechain?: boolean
|
||||
cost: number
|
||||
calls: number
|
||||
tokens: BranchTokenSplit
|
||||
models: string[]
|
||||
firstActive: string | null
|
||||
lastActive: string | null
|
||||
}
|
||||
|
||||
export type BranchWorktreeRow = { path: string; sessions: number; cost: number }
|
||||
|
||||
export type BranchSpendRow = {
|
||||
projectId: string
|
||||
projectLabel: string
|
||||
/** `null` = Unknown: spend before the session's first observed branch. */
|
||||
branch: string | null
|
||||
cost: number
|
||||
calls: number
|
||||
sessions: number
|
||||
tokens: BranchTokenSplit
|
||||
firstActive: string | null
|
||||
lastActive: string | null
|
||||
worktrees: BranchWorktreeRow[]
|
||||
sessionRows: BranchSpendSessionRow[]
|
||||
}
|
||||
|
||||
export type BranchSpendCoverage = {
|
||||
branchKnownCost: number
|
||||
branchUnknownCost: number
|
||||
noBranchDataCost: number
|
||||
noBranchDataSessions: number
|
||||
noBranchDataProviders: string[]
|
||||
/** Identity-based; never the sum of row session counts (rows overlap). */
|
||||
distinctSessions: number
|
||||
}
|
||||
|
||||
export type BranchSpendProjectReport = {
|
||||
id: string
|
||||
label: string
|
||||
totalCost: number
|
||||
branches: BranchSpendRow[]
|
||||
coverage: BranchSpendCoverage
|
||||
}
|
||||
|
||||
export type BranchSpendReport = {
|
||||
period: { label: string; start: string; end: string }
|
||||
projects: BranchSpendProjectReport[]
|
||||
totals: BranchSpendCoverage
|
||||
}
|
||||
|
||||
// ————— src/optimize.ts —————
|
||||
|
||||
export type WasteAction =
|
||||
|
|
@ -824,6 +892,8 @@ export interface CodeburnBridge {
|
|||
getCompare(period: Period, provider: string, modelA: string, modelB: string): Promise<CompareJsonReport>
|
||||
getYield(period: Period, provider: string, range?: DateRange, background?: boolean): Promise<YieldJsonReport>
|
||||
getSpendFlow(period: Period, provider: string, range?: DateRange, background?: boolean): Promise<SpendFlow>
|
||||
/** Spend per canonical project × branch (`spend --format branch-json`). */
|
||||
getBranchSpend(period: Period, provider: string, range?: DateRange, background?: boolean): Promise<BranchSpendReport>
|
||||
getOptimizeReport(period: Period, provider: string, range?: DateRange, background?: boolean): Promise<OptimizeJsonReport>
|
||||
getDevices(period: Period): Promise<CombinedUsage>
|
||||
getDevicesScan(): Promise<DeviceScanResult>
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import userEvent from '@testing-library/user-event'
|
|||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import type { Polled } from '../hooks/usePolled'
|
||||
import type { MenubarPayload, SpendFlow } from '../lib/types'
|
||||
import type { BranchSpendReport, MenubarPayload, SpendFlow } from '../lib/types'
|
||||
import { Spend, SpendContent } from './Spend'
|
||||
|
||||
const ROOT_WEEK_OVERVIEW = JSON.parse(
|
||||
|
|
@ -19,16 +19,25 @@ function polled(data: MenubarPayload): Polled<MenubarPayload> {
|
|||
return { data, error: null, loading: false, switching: false, lastSuccessAt: Date.now(), refresh: vi.fn() }
|
||||
}
|
||||
|
||||
const { getOverview, getSpendFlow, getTimeline } = vi.hoisted(() => ({
|
||||
const { getOverview, getSpendFlow, getTimeline, getBranchSpend } = vi.hoisted(() => ({
|
||||
getOverview: vi.fn<(period: string, provider: string) => Promise<MenubarPayload>>(),
|
||||
getSpendFlow: vi.fn<(period: string, provider: string) => Promise<SpendFlow>>(),
|
||||
getTimeline: vi.fn<(period: string, provider: string) => Promise<MenubarPayload>>(),
|
||||
getBranchSpend: vi.fn<(period: string, provider: string) => Promise<BranchSpendReport>>(),
|
||||
}))
|
||||
vi.mock('../lib/ipc', async orig => {
|
||||
const actual = await orig<typeof import('../lib/ipc')>()
|
||||
return { ...actual, codeburn: { getOverview, getSpendFlow, getTimeline } }
|
||||
return { ...actual, codeburn: { getOverview, getSpendFlow, getTimeline, getBranchSpend } }
|
||||
})
|
||||
|
||||
function emptyBranchReport(): BranchSpendReport {
|
||||
return {
|
||||
period: { label: '', start: '', end: '' },
|
||||
projects: [],
|
||||
totals: { branchKnownCost: 0, branchUnknownCost: 0, noBranchDataCost: 0, noBranchDataSessions: 0, noBranchDataProviders: [], distinctSessions: 0 },
|
||||
}
|
||||
}
|
||||
|
||||
function daily(date: string, cost: number, models: Array<{ name: string; cost: number }>) {
|
||||
return {
|
||||
date,
|
||||
|
|
@ -144,6 +153,8 @@ describe('Spend', () => {
|
|||
vi.setSystemTime(new Date(2026, 6, 10, 12, 0, 0))
|
||||
getOverview.mockReset()
|
||||
getSpendFlow.mockReset()
|
||||
getBranchSpend.mockReset()
|
||||
getBranchSpend.mockResolvedValue(emptyBranchReport())
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { Fragment, useState } from 'react'
|
||||
|
||||
import { BranchBreakdown } from '../components/BranchBreakdown'
|
||||
import { CliErrorPanel, CliErrorText } from '../components/CliErrorPanel'
|
||||
import { EmptyNote } from '../components/EmptyState'
|
||||
import { ListRow } from '../components/ListRow'
|
||||
|
|
@ -191,6 +192,8 @@ function SpendPage({
|
|||
<ProjectBreakdown projects={projects} onInvestigate={onInvestigate} />
|
||||
</div>
|
||||
|
||||
<BranchBreakdown period={period} provider={provider} range={range} />
|
||||
|
||||
<Panel title="Cost flow · model → project" right="model → project flow for this range" className="scroll-x">
|
||||
{flow.data && flow.data.links.length ? (
|
||||
<Sankey flow={flow.data} />
|
||||
|
|
|
|||
|
|
@ -456,6 +456,17 @@ td:first-child { font-size: var(--fs-body); font-weight: var(--fw-body); }
|
|||
.spend-proj-session .sps-cost { color: var(--ink); font-family: var(--mono); }
|
||||
.spend-proj-empty { padding: 4px 0 8px 27px; font-size: 11px; color: var(--mut2); }
|
||||
|
||||
/* Spend: By branch lens (project picker, branch detail lines, coverage note). */
|
||||
.branch-picker { padding: 0 0 8px; }
|
||||
.branch-detail-line { display: grid; grid-template-columns: 110px minmax(0, 1fr); column-gap: 10px; padding: 3px 0; font-size: 11px; color: var(--mut); font-variant-numeric: tabular-nums; }
|
||||
.branch-detail-line > span:last-child { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--ink); }
|
||||
.branch-detail-line code { font-family: var(--mono); font-size: 10px; }
|
||||
.spend-proj-session.li-clickable { cursor: pointer; border-radius: 6px; }
|
||||
.spend-proj-session.li-clickable:hover .sps-model { text-decoration: underline; }
|
||||
.spend-proj-session.is-open-row .sps-model { text-decoration: underline; }
|
||||
.branch-coverage { display: flex; flex-wrap: wrap; column-gap: 16px; row-gap: 2px; padding: 8px 0 2px; border-top: 1px solid var(--line2); font-size: 10px; color: var(--mut2); font-variant-numeric: tabular-nums; }
|
||||
.branch-coverage-note { flex-basis: 100%; }
|
||||
|
||||
/* Models: token audit lens (fixed columns, scrolls inside its panel). */
|
||||
.audit-table { min-width: 720px; }
|
||||
.audit-table .mdot { width: 10px; height: 10px; border-radius: 3px; }
|
||||
|
|
|
|||
58
docs/by-branch.md
Normal file
58
docs/by-branch.md
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
# Spend by branch and worktree
|
||||
|
||||
The Spend view in CodeBurn Desktop has a **By branch** panel: pick a project and
|
||||
see where its AI spend went — per git branch, with the recorded worktrees and
|
||||
the individual sessions behind each branch.
|
||||
|
||||
## What each branch row shows
|
||||
|
||||
- **Cost** attributed turn by turn. A session that switched branches mid-way
|
||||
(for example `feat/auth` → `fix/parser`) contributes each turn's cost to the
|
||||
branch that was active when it happened — the same session appears on both
|
||||
rows with its own slice, never the whole cost twice.
|
||||
- **Calls** (behavioral requests) and **tokens per component** (input, output,
|
||||
reasoning, cache read, cache write) summed from the same turns.
|
||||
- **Distinct sessions** and the **activity window** (first–last attributed call
|
||||
in the selected range).
|
||||
- Expanding a row shows the **recorded worktrees** (from the session's
|
||||
provider-recorded working directory — the worktree path itself, not today's
|
||||
checkout) and each session's contribution. Click a session to inspect its
|
||||
real detail: id, provider, working directory, models, tokens, activity.
|
||||
|
||||
## Coverage (the fine print, kept visible)
|
||||
|
||||
Branch metadata is captured per turn and, today, only Claude transcripts carry
|
||||
it. The coverage note under the rows therefore splits the project's spend:
|
||||
|
||||
- **On branches** — spend attributed to named branches.
|
||||
- **Unknown, before first branch** — spend inside a branch-bearing session that
|
||||
happened before its first recorded branch. A branch set before the selected
|
||||
range still carries forward into the range; only spend that genuinely
|
||||
predates every recorded branch lands here. It is *Unknown*, never relabeled
|
||||
as `main`.
|
||||
- **No branch data** — spend from sessions that never recorded a branch
|
||||
(non-Claude sources). Listed with the providers and session count.
|
||||
|
||||
A session on several branch rows counts **once** in the distinct-session total
|
||||
(rows overlap; they are not summed). Costs do reconcile: known + unknown +
|
||||
no-branch-data equals the project's total in-range spend.
|
||||
|
||||
The lens always respects the period, provider, and calendar range selected at
|
||||
the top of the window; the project picker narrows the display (choose *All
|
||||
projects* to see every project's branches, labeled `project / branch`, so two
|
||||
projects that both have a `main` never merge).
|
||||
|
||||
## CLI
|
||||
|
||||
The same report is available from the terminal:
|
||||
|
||||
```bash
|
||||
codeburn spend --format branch-json # whole period default
|
||||
codeburn spend --format branch-json --period week --provider claude
|
||||
codeburn spend --format branch-json --from 2026-07-01 --to 2026-07-11 --project alpha
|
||||
```
|
||||
|
||||
The JSON carries `projects[]` (canonical project id, branch rows, per-session
|
||||
contributions, worktree evidence, coverage) and `totals` (identity-based
|
||||
distinct sessions plus the same coverage split). It reuses the `--project` /
|
||||
`--exclude` filtering introduced for the CLI in #1285.
|
||||
396
src/branch-spend.ts
Normal file
396
src/branch-spend.ts
Normal file
|
|
@ -0,0 +1,396 @@
|
|||
import { reportUnmatchedProjectPatterns } from './project-filter-warnings.js'
|
||||
import { cachedProjectIdentitiesForRange } from './daily-cache.js'
|
||||
import { toDateString } from './daily-cache.js'
|
||||
import { filterProjectsByName, parseAllSessions } from './parser.js'
|
||||
import { inferSessionProvider } from './session-output.js'
|
||||
import { behavioralCallCount } from './behavioral-weight.js'
|
||||
import { spendProjectIdentity } from './spend-flow.js'
|
||||
import type { DateRange, ProjectSummary, SessionSummary } from './types.js'
|
||||
|
||||
/// Per-branch-and-project spend, the Spend "By branch" lens. Extends the
|
||||
/// branch-name-only `aggregateByBranch` (sessions-report.ts) with the canonical
|
||||
/// project in the row key, so two projects that both have a `main` branch never
|
||||
/// merge, and with per-session contributions, worktree evidence, and coverage
|
||||
/// splits so every attributed dollar is explained.
|
||||
///
|
||||
/// The reuse rules are the same as `aggregateByBranch`:
|
||||
/// - The cache stores a turn's branch only when it CHANGES, so a report must
|
||||
/// reconstruct each turn's branch by carrying the last-seen value forward.
|
||||
/// (The parser already resolves this carry across a date-range boundary, so a
|
||||
/// turn active after a branch switch made before the window carries the right
|
||||
/// branch here; turns that genuinely precede the session's first-ever branch
|
||||
/// arrive with no branch and stay unknown.)
|
||||
/// - Only sessions that EVER observed a branch participate. A provider that
|
||||
/// never captures branch data (everything but Claude today) would otherwise
|
||||
/// pile all of its spend into one unknown bucket that dwarfs every real
|
||||
/// branch; those sessions are reported separately as coverage instead.
|
||||
/// - A session that switches branches contributes its turn-level cost to EACH
|
||||
/// branch it touched, so branch rows (and project totals over them) must
|
||||
/// never be summed into a distinct-session count. Distinct sessions are
|
||||
/// counted by identity, once, per project and overall.
|
||||
|
||||
export type BranchTokenSplit = {
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
reasoningTokens: number
|
||||
cacheReadTokens: number
|
||||
cacheWriteTokens: number
|
||||
}
|
||||
|
||||
/// One session's contribution inside a single (project, branch) row. The cost
|
||||
/// is the branch-sliced portion (a session in two branch rows shows each
|
||||
/// portion, not its whole total).
|
||||
export type BranchSpendSessionRow = {
|
||||
sessionId: string
|
||||
/// Human session title captured from the transcript. Absent when none.
|
||||
title?: string
|
||||
/// Inferred provider id (first turn's call provider, model-name fallback).
|
||||
provider: string
|
||||
/// The provider-recorded historical working directory, BEFORE git-worktree
|
||||
/// canonicalization — for a session that ran in a linked worktree this is
|
||||
/// the worktree path itself. Evidence-only: never resolved from today's
|
||||
/// checkout. Absent when the provider recorded none.
|
||||
workingDirectory?: string
|
||||
/// Claude Code only: this row is a subagent (sidechain) transcript.
|
||||
isSidechain?: boolean
|
||||
cost: number
|
||||
calls: number
|
||||
tokens: BranchTokenSplit
|
||||
/// Distinct models contributing cost in this branch, cost-descending.
|
||||
models: string[]
|
||||
/// First/last attributed call timestamps inside this branch (ISO strings).
|
||||
firstActive: string | null
|
||||
lastActive: string | null
|
||||
}
|
||||
|
||||
/// Recorded working-directory evidence for one branch row, grouped over the
|
||||
/// session contributions that carry it.
|
||||
export type BranchWorktreeRow = {
|
||||
path: string
|
||||
sessions: number
|
||||
cost: number
|
||||
}
|
||||
|
||||
export type BranchSpendRow = {
|
||||
/// Canonical project id (absolute projectPath, path-folded) and display
|
||||
/// label — the same identity the spend-flow and By project views use.
|
||||
projectId: string
|
||||
projectLabel: string
|
||||
/// The git branch active for the attributed turns. `null` means Unknown:
|
||||
/// spend inside a branch-bearing session that happened before its first
|
||||
/// observed branch. It is NOT "main" and must never be relabeled.
|
||||
branch: string | null
|
||||
cost: number
|
||||
/// Behavioral calls (supplementary accounting excluded), the app-wide
|
||||
/// request counter convention.
|
||||
calls: number
|
||||
/// Distinct sessions contributing to THIS row (by provider+project+session
|
||||
/// identity). A session that switched branches appears in several rows.
|
||||
sessions: number
|
||||
tokens: BranchTokenSplit
|
||||
firstActive: string | null
|
||||
lastActive: string | null
|
||||
/// Recorded worktree evidence (historical working directories) for the
|
||||
/// sessions in this row, cost-descending. Empty when no session recorded one.
|
||||
worktrees: BranchWorktreeRow[]
|
||||
/// Per-session contributions in this branch, cost-descending.
|
||||
sessionRows: BranchSpendSessionRow[]
|
||||
}
|
||||
|
||||
/// Where the in-range spend of one project stands relative to branch metadata.
|
||||
export type BranchSpendCoverage = {
|
||||
/// Cost attributed to named branches.
|
||||
branchKnownCost: number
|
||||
/// Cost inside branch-bearing sessions that predates their first observed
|
||||
/// branch (the `null` branch rows).
|
||||
branchUnknownCost: number
|
||||
/// Cost from sessions that never observed a branch anywhere in their
|
||||
/// transcript — sources without branch metadata. Unknown ≠ 0, and this cost
|
||||
/// is NOT relabeled or dropped.
|
||||
noBranchDataCost: number
|
||||
noBranchDataSessions: number
|
||||
/// Providers whose sessions carried no branch metadata, cost-descending.
|
||||
noBranchDataProviders: string[]
|
||||
/// Distinct sessions across ALL branch rows of the scope (identity-based;
|
||||
/// never the sum of row session counts).
|
||||
distinctSessions: number
|
||||
}
|
||||
|
||||
export type BranchSpendProjectReport = {
|
||||
id: string
|
||||
label: string
|
||||
/// The project's full in-range cost across all its sessions, including the
|
||||
/// no-branch-data share — the same number the By project view reports.
|
||||
totalCost: number
|
||||
/// Branch rows, named branches cost-descending, then the Unknown (`null`)
|
||||
/// row last.
|
||||
branches: BranchSpendRow[]
|
||||
coverage: BranchSpendCoverage
|
||||
}
|
||||
|
||||
export type BranchSpendReport = {
|
||||
period: { label: string; start: string; end: string }
|
||||
/// Every project with branch-relevant in-range spend, cost-descending. The
|
||||
/// full population for the filters — callers paginate only the display.
|
||||
projects: BranchSpendProjectReport[]
|
||||
totals: BranchSpendCoverage
|
||||
}
|
||||
|
||||
const NUL = String.fromCharCode(0)
|
||||
|
||||
/// Row-level distinct-session key, matching the by-PR convention: provider +
|
||||
/// project + sessionId, NUL-delimited so ids/names containing spaces or the
|
||||
/// separator never collide (a session id alone is not globally unique).
|
||||
function distinctSessionKey(session: SessionSummary): string {
|
||||
return `${linkageProvider(session)}${NUL}${session.project}${NUL}${session.sessionId}`
|
||||
}
|
||||
|
||||
function linkageProvider(session: SessionSummary): string {
|
||||
if (session.parentSessionId || session.agentSpawnLinks || session.spawnPrSets) return 'claude'
|
||||
return inferSessionProvider(session)
|
||||
}
|
||||
|
||||
function emptyTokens(): BranchTokenSplit {
|
||||
return { inputTokens: 0, outputTokens: 0, reasoningTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 }
|
||||
}
|
||||
|
||||
function addTokens(acc: BranchTokenSplit, usage: SessionSummary['turns'][number]['assistantCalls'][number]['usage']): void {
|
||||
acc.inputTokens += usage.inputTokens
|
||||
acc.outputTokens += usage.outputTokens
|
||||
acc.reasoningTokens += usage.reasoningTokens
|
||||
acc.cacheReadTokens += usage.cacheReadInputTokens
|
||||
acc.cacheWriteTokens += usage.cacheCreationInputTokens
|
||||
}
|
||||
|
||||
type SessionAccumulator = {
|
||||
key: string
|
||||
session: SessionSummary
|
||||
provider: string
|
||||
cost: number
|
||||
calls: number
|
||||
tokens: BranchTokenSplit
|
||||
models: Map<string, number>
|
||||
firstActive: string | null
|
||||
lastActive: string | null
|
||||
}
|
||||
|
||||
type BranchAccumulator = {
|
||||
branch: string | null
|
||||
cost: number
|
||||
calls: number
|
||||
tokens: BranchTokenSplit
|
||||
firstActive: string | null
|
||||
lastActive: string | null
|
||||
sessions: Map<string, SessionAccumulator>
|
||||
}
|
||||
|
||||
function firstTimestampOf(value: string | null, candidate: string | undefined): string | null {
|
||||
if (!candidate) return value
|
||||
if (value === null || Date.parse(candidate) < Date.parse(value)) return candidate
|
||||
return value
|
||||
}
|
||||
|
||||
function lastTimestampOf(value: string | null, candidate: string | undefined): string | null {
|
||||
if (!candidate) return value
|
||||
if (value === null || Date.parse(candidate) > Date.parse(value)) return candidate
|
||||
return value
|
||||
}
|
||||
|
||||
function projectBranches(project: ProjectSummary): {
|
||||
branches: BranchAccumulator[]
|
||||
noBranchCost: number
|
||||
noBranchSessions: Set<string>
|
||||
noBranchProviders: Map<string, number>
|
||||
totalCost: number
|
||||
} {
|
||||
const byBranch = new Map<string, BranchAccumulator>()
|
||||
let noBranchCost = 0
|
||||
const noBranchSessions = new Set<string>()
|
||||
const noBranchProviders = new Map<string, number>()
|
||||
let totalCost = 0
|
||||
|
||||
for (const session of project.sessions) {
|
||||
const participates = session.everHadBranch === true || session.turns.some(turn => !!turn.gitBranch)
|
||||
const sessionCallCost = session.turns.reduce(
|
||||
(sum, turn) => sum + turn.assistantCalls.reduce((s, call) => s + call.costUSD, 0), 0)
|
||||
totalCost += sessionCallCost
|
||||
|
||||
if (!participates) {
|
||||
// Source without branch metadata: keep its cost visible in coverage, not
|
||||
// in branch rows, so it can never be relabeled as a branch.
|
||||
noBranchCost += sessionCallCost
|
||||
noBranchSessions.add(distinctSessionKey(session))
|
||||
const provider = linkageProvider(session)
|
||||
noBranchProviders.set(provider, (noBranchProviders.get(provider) ?? 0) + sessionCallCost)
|
||||
continue
|
||||
}
|
||||
|
||||
const identity = distinctSessionKey(session)
|
||||
const provider = linkageProvider(session)
|
||||
// Carry the last-seen branch forward across turns (the cache stores it
|
||||
// only when it changes; the parser pre-resolves the range-boundary carry).
|
||||
let current: string | null = null
|
||||
for (const turn of session.turns) {
|
||||
if (turn.gitBranch) current = turn.gitBranch
|
||||
if (turn.assistantCalls.length === 0) continue
|
||||
let acc = byBranch.get(current ?? '')
|
||||
if (!acc) {
|
||||
acc = { branch: current, cost: 0, calls: 0, tokens: emptyTokens(), firstActive: null, lastActive: null, sessions: new Map() }
|
||||
byBranch.set(current ?? '', acc)
|
||||
}
|
||||
let sessionAcc = acc.sessions.get(identity)
|
||||
if (!sessionAcc) {
|
||||
sessionAcc = { key: identity, session, provider, cost: 0, calls: 0, tokens: emptyTokens(), models: new Map(), firstActive: null, lastActive: null }
|
||||
acc.sessions.set(identity, sessionAcc)
|
||||
}
|
||||
for (const call of turn.assistantCalls) {
|
||||
acc.cost += call.costUSD
|
||||
sessionAcc.cost += call.costUSD
|
||||
addTokens(acc.tokens, call.usage)
|
||||
addTokens(sessionAcc.tokens, call.usage)
|
||||
if (call.model && call.costUSD > 0) sessionAcc.models.set(call.model, (sessionAcc.models.get(call.model) ?? 0) + call.costUSD)
|
||||
acc.firstActive = firstTimestampOf(acc.firstActive, call.timestamp)
|
||||
acc.lastActive = lastTimestampOf(acc.lastActive, call.timestamp)
|
||||
sessionAcc.firstActive = firstTimestampOf(sessionAcc.firstActive, call.timestamp)
|
||||
sessionAcc.lastActive = lastTimestampOf(sessionAcc.lastActive, call.timestamp)
|
||||
}
|
||||
acc.calls += behavioralCallCount(turn.assistantCalls)
|
||||
sessionAcc.calls += behavioralCallCount(turn.assistantCalls)
|
||||
}
|
||||
}
|
||||
|
||||
return { branches: [...byBranch.values()], noBranchCost, noBranchSessions, noBranchProviders, totalCost }
|
||||
}
|
||||
|
||||
function toSessionRow(acc: SessionAccumulator): BranchSpendSessionRow {
|
||||
return {
|
||||
sessionId: acc.session.sessionId,
|
||||
...(acc.session.title ? { title: acc.session.title } : {}),
|
||||
provider: acc.provider,
|
||||
...(acc.session.workingDirectory ? { workingDirectory: acc.session.workingDirectory } : {}),
|
||||
...(acc.session.isSidechain ? { isSidechain: true } : {}),
|
||||
cost: acc.cost,
|
||||
calls: acc.calls,
|
||||
tokens: acc.tokens,
|
||||
models: [...acc.models.entries()].sort(([, a], [, b]) => b - a).map(([model]) => model),
|
||||
firstActive: acc.firstActive,
|
||||
lastActive: acc.lastActive,
|
||||
}
|
||||
}
|
||||
|
||||
function toRow(acc: BranchAccumulator, projectId: string, projectLabel: string): BranchSpendRow {
|
||||
const sessionRows = [...acc.sessions.values()].sort((a, b) => b.cost - a.cost)
|
||||
const worktreeMap = new Map<string, BranchWorktreeRow>()
|
||||
for (const s of sessionRows) {
|
||||
if (!s.session.workingDirectory) continue
|
||||
const existing = worktreeMap.get(s.session.workingDirectory)
|
||||
if (existing) {
|
||||
existing.sessions += 1
|
||||
existing.cost += s.cost
|
||||
} else {
|
||||
worktreeMap.set(s.session.workingDirectory, { path: s.session.workingDirectory, sessions: 1, cost: s.cost })
|
||||
}
|
||||
}
|
||||
return {
|
||||
projectId,
|
||||
projectLabel,
|
||||
branch: acc.branch,
|
||||
cost: acc.cost,
|
||||
calls: acc.calls,
|
||||
sessions: acc.sessions.size,
|
||||
tokens: acc.tokens,
|
||||
firstActive: acc.firstActive,
|
||||
lastActive: acc.lastActive,
|
||||
worktrees: [...worktreeMap.values()].sort((a, b) => b.cost - a.cost),
|
||||
sessionRows: sessionRows.map(toSessionRow),
|
||||
}
|
||||
}
|
||||
|
||||
function coverageOf(
|
||||
branches: BranchAccumulator[],
|
||||
noBranchCost: number,
|
||||
noBranchSessions: Set<string>,
|
||||
noBranchProviders: Map<string, number>,
|
||||
): BranchSpendCoverage {
|
||||
const distinct = new Set<string>()
|
||||
for (const acc of branches) for (const key of acc.sessions.keys()) distinct.add(key)
|
||||
return {
|
||||
branchKnownCost: branches.filter(acc => acc.branch !== null).reduce((sum, acc) => sum + acc.cost, 0),
|
||||
branchUnknownCost: branches.filter(acc => acc.branch === null).reduce((sum, acc) => sum + acc.cost, 0),
|
||||
noBranchDataCost: noBranchCost,
|
||||
noBranchDataSessions: noBranchSessions.size,
|
||||
noBranchDataProviders: [...noBranchProviders.entries()].sort(([, a], [, b]) => b - a).map(([provider]) => provider),
|
||||
distinctSessions: distinct.size,
|
||||
}
|
||||
}
|
||||
|
||||
/// Pure core over an already-parsed, already-filtered project list — unit-test
|
||||
/// surface for the fixtures with known outcomes.
|
||||
export function buildBranchSpendReport(projects: ProjectSummary[], range: DateRange): BranchSpendReport {
|
||||
const out: BranchSpendProjectReport[] = []
|
||||
const totalsDistinct = new Set<string>()
|
||||
let totalsKnown = 0
|
||||
let totalsUnknown = 0
|
||||
let totalsNoBranch = 0
|
||||
let totalsNoBranchSessions = 0
|
||||
const totalsNoBranchProviders = new Map<string, number>()
|
||||
|
||||
for (const project of projects) {
|
||||
const { id: projectId, label: projectLabel } = spendProjectIdentity(project)
|
||||
const { branches, noBranchCost, noBranchSessions, noBranchProviders, totalCost } = projectBranches(project)
|
||||
if (branches.length === 0 && noBranchCost <= 0) continue
|
||||
const sorted = [...branches].sort((a, b) => {
|
||||
// Named branches by cost first; the Unknown row sinks to the bottom of
|
||||
// its project rather than masquerading as the biggest branch.
|
||||
if (a.branch === null && b.branch !== null) return 1
|
||||
if (b.branch === null && a.branch !== null) return -1
|
||||
const byCost = b.cost - a.cost
|
||||
return byCost !== 0 ? byCost : (a.branch ?? '').localeCompare(b.branch ?? '')
|
||||
})
|
||||
const coverage = coverageOf(branches, noBranchCost, noBranchSessions, noBranchProviders)
|
||||
for (const key of noBranchSessions) totalsDistinct.add(key)
|
||||
for (const acc of branches) for (const key of acc.sessions.keys()) totalsDistinct.add(key)
|
||||
totalsKnown += coverage.branchKnownCost
|
||||
totalsUnknown += coverage.branchUnknownCost
|
||||
totalsNoBranch += coverage.noBranchDataCost
|
||||
totalsNoBranchSessions += coverage.noBranchDataSessions
|
||||
for (const [provider, cost] of noBranchProviders) {
|
||||
totalsNoBranchProviders.set(provider, (totalsNoBranchProviders.get(provider) ?? 0) + cost)
|
||||
}
|
||||
out.push({
|
||||
id: projectId,
|
||||
label: projectLabel,
|
||||
totalCost,
|
||||
branches: sorted.map(acc => toRow(acc, projectId, projectLabel)),
|
||||
coverage,
|
||||
})
|
||||
}
|
||||
|
||||
out.sort((a, b) => b.totalCost - a.totalCost)
|
||||
return {
|
||||
period: {
|
||||
label: `${toDateString(range.start)} to ${toDateString(range.end)}`,
|
||||
start: range.start.toISOString(),
|
||||
end: range.end.toISOString(),
|
||||
},
|
||||
projects: out,
|
||||
totals: {
|
||||
branchKnownCost: totalsKnown,
|
||||
branchUnknownCost: totalsUnknown,
|
||||
noBranchDataCost: totalsNoBranch,
|
||||
noBranchDataSessions: totalsNoBranchSessions,
|
||||
noBranchDataProviders: [...totalsNoBranchProviders.entries()].sort(([, a], [, b]) => b - a).map(([provider]) => provider),
|
||||
distinctSessions: totalsDistinct.size,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// CLI/IPC entry: parse the filtered population (range, provider, project
|
||||
/// patterns — the same flags and semantics as `spend --format flow-json`) and
|
||||
/// build the by-branch report over it.
|
||||
export async function computeBranchSpend(range: DateRange, provider: string, projectFilter?: string[], excludeFilter?: string[]): Promise<BranchSpendReport> {
|
||||
const parsed = await parseAllSessions(range, provider)
|
||||
await reportUnmatchedProjectPatterns(parsed, projectFilter, excludeFilter, () => cachedProjectIdentitiesForRange(range))
|
||||
const projects = filterProjectsByName(parsed, projectFilter, excludeFilter)
|
||||
return buildBranchSpendReport(projects, range)
|
||||
}
|
||||
11
src/main.ts
11
src/main.ts
|
|
@ -2589,11 +2589,11 @@ program
|
|||
.option('--from <date>', 'Custom range start (YYYY-MM-DD)')
|
||||
.option('--to <date>', 'Custom range end (YYYY-MM-DD)')
|
||||
.option('--provider <provider>', 'Filter by provider (e.g. claude, codex, cursor)', 'all')
|
||||
.option('--format <format>', 'Output format: flow-json', 'flow-json')
|
||||
.option('--format <format>', 'Output format: flow-json, branch-json', 'flow-json')
|
||||
.option('--project <name>', 'Show only projects matching name (repeatable)', collect, [])
|
||||
.option('--exclude <name>', 'Exclude projects matching name (repeatable)', collect, [])
|
||||
.action(async (opts) => {
|
||||
assertFormat(opts.format, ['flow-json'], 'spend')
|
||||
assertFormat(opts.format, ['flow-json', 'branch-json'], 'spend')
|
||||
assertProvider(opts.provider, 'spend')
|
||||
const { computeSpendFlow } = await import('./spend-flow.js')
|
||||
await loadPricing()
|
||||
|
|
@ -2611,6 +2611,13 @@ program
|
|||
range = getDateRange(opts.period).range
|
||||
}
|
||||
|
||||
if (opts.format === 'branch-json') {
|
||||
// Spend per canonical project x branch (the desktop "By branch" lens).
|
||||
const { computeBranchSpend } = await import('./branch-spend.js')
|
||||
console.log(JSON.stringify(await computeBranchSpend(range, opts.provider, opts.project, opts.exclude)))
|
||||
return
|
||||
}
|
||||
|
||||
console.log(JSON.stringify(await computeSpendFlow(range, opts.provider, opts.project, opts.exclude)))
|
||||
})
|
||||
|
||||
|
|
|
|||
230
tests/branch-spend.test.ts
Normal file
230
tests/branch-spend.test.ts
Normal file
|
|
@ -0,0 +1,230 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { buildBranchSpendReport } from '../src/branch-spend.js'
|
||||
import type { ClassifiedTurn, ParsedApiCall, ProjectSummary, SessionSummary, TokenUsage } from '../src/types.js'
|
||||
|
||||
// Fixtures with known outcomes for the Spend "By branch" report. Costs are
|
||||
// round numbers so the required splits (3+5, A/B mains, pre-branch spend,
|
||||
// worktree evidence) are checkable exactly.
|
||||
|
||||
const ZERO_USAGE: TokenUsage = {
|
||||
inputTokens: 0, outputTokens: 0, cacheCreationInputTokens: 0,
|
||||
cacheReadInputTokens: 0, cachedInputTokens: 0, reasoningTokens: 0, webSearchRequests: 0,
|
||||
}
|
||||
|
||||
let keySeq = 0
|
||||
function call(cost: number, overrides: Partial<ParsedApiCall> = {}): ParsedApiCall {
|
||||
return {
|
||||
provider: 'claude', model: 'claude-sonnet', usage: { ...ZERO_USAGE, inputTokens: 100, outputTokens: 20 }, costUSD: cost,
|
||||
tools: [], mcpTools: [], skills: [], subagentTypes: [],
|
||||
hasAgentSpawn: false, hasPlanMode: false, speed: 'standard',
|
||||
timestamp: '2026-07-01T10:00:00Z', bashCommands: [], deduplicationKey: `k${keySeq++}`,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function turn(cost: number, opts: { calls?: number; gitBranch?: string; at?: string; usage?: Partial<TokenUsage>; provider?: string } = {}): ClassifiedTurn {
|
||||
const { calls = 1, gitBranch, at = '2026-07-01T10:00:00Z', usage, provider = 'claude' } = opts
|
||||
return {
|
||||
userMessage: '',
|
||||
assistantCalls: Array.from({ length: calls }, () => call(cost / calls, { timestamp: at, provider, ...(usage ? { usage: { ...ZERO_USAGE, ...usage } } : {}) })),
|
||||
timestamp: at, sessionId: 's',
|
||||
category: 'coding', retries: 0, hasEdits: false,
|
||||
...(gitBranch ? { gitBranch } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
function session(id: string, turns: ClassifiedTurn[], overrides: Partial<SessionSummary> = {}): SessionSummary {
|
||||
return {
|
||||
sessionId: id, project: 'p',
|
||||
firstTimestamp: '2026-07-01T10:00:00Z', lastTimestamp: '2026-07-01T11:00:00Z',
|
||||
totalCostUSD: 0, totalSavingsUSD: 0, totalEstimatedCostUSD: 0,
|
||||
totalInputTokens: 0, totalOutputTokens: 0, totalReasoningTokens: 0,
|
||||
totalCacheReadTokens: 0, totalCacheWriteTokens: 0,
|
||||
apiCalls: 0, turns,
|
||||
modelBreakdown: {}, toolBreakdown: {}, mcpBreakdown: {}, bashBreakdown: {},
|
||||
categoryBreakdown: {} as SessionSummary['categoryBreakdown'],
|
||||
skillBreakdown: {} as SessionSummary['skillBreakdown'],
|
||||
subagentBreakdown: {} as SessionSummary['subagentBreakdown'],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
const RANGE = { start: new Date('2026-07-01T00:00:00Z'), end: new Date('2026-07-02T00:00:00Z') }
|
||||
|
||||
function report(projects: ProjectSummary[]) {
|
||||
return buildBranchSpendReport(projects, RANGE)
|
||||
}
|
||||
|
||||
function project(key: { project: string; projectPath: string }, sessions: SessionSummary[]): ProjectSummary {
|
||||
return {
|
||||
project: key.project, projectPath: key.projectPath, sessions,
|
||||
totalCostUSD: 0, totalSavingsUSD: 0, totalApiCalls: 0, totalProxiedCostUSD: 0,
|
||||
}
|
||||
}
|
||||
|
||||
describe('buildBranchSpendReport', () => {
|
||||
it('keeps identical branch names of different projects in separate rows', () => {
|
||||
const rep = report([
|
||||
project({ project: 'alpha', projectPath: '/code/alpha' }, [
|
||||
session('a1', [turn(4, { gitBranch: 'main' })]),
|
||||
]),
|
||||
project({ project: 'beta', projectPath: '/code/beta' }, [
|
||||
session('b1', [turn(7, { gitBranch: 'main' })]),
|
||||
]),
|
||||
])
|
||||
expect(rep.projects).toHaveLength(2)
|
||||
const alpha = rep.projects.find(p => p.label === 'alpha')!
|
||||
const beta = rep.projects.find(p => p.label === 'beta')!
|
||||
expect(alpha.branches.map(r => [r.branch, r.cost])).toEqual([['main', 4]])
|
||||
expect(beta.branches.map(r => [r.branch, r.cost])).toEqual([['main', 7]])
|
||||
expect(rep.totals.distinctSessions).toBe(2)
|
||||
})
|
||||
|
||||
it('splits a switching session per branch: 3 on feat/auth, 5 on fix/parser, one distinct session, 8 total', () => {
|
||||
const rep = report([
|
||||
project({ project: 'alpha', projectPath: '/code/alpha' }, [
|
||||
session('s1', [
|
||||
turn(3, { gitBranch: 'feat/auth' }),
|
||||
turn(5, { gitBranch: 'fix/parser' }),
|
||||
]),
|
||||
]),
|
||||
])
|
||||
const alpha = rep.projects[0]!
|
||||
expect(alpha.branches.map(r => [r.branch, r.cost])).toEqual([
|
||||
['fix/parser', 5], ['feat/auth', 3],
|
||||
])
|
||||
// Same session counts toward each row, but the identity-based count is one.
|
||||
expect(alpha.branches.every(r => r.sessions === 1)).toBe(true)
|
||||
expect(alpha.coverage.distinctSessions).toBe(1)
|
||||
expect(rep.totals.distinctSessions).toBe(1)
|
||||
// Branch rows overlap, so they are NOT summable into a distinct count —
|
||||
// but their costs are disjoint turn slices that reconcile to the source.
|
||||
expect(alpha.branches.reduce((sum, r) => sum + r.cost, 0)).toBeCloseTo(8, 6)
|
||||
expect(alpha.coverage.branchKnownCost).toBeCloseTo(8, 6)
|
||||
expect(alpha.coverage.branchUnknownCost).toBe(0)
|
||||
})
|
||||
|
||||
it('identifies a worktree from the recorded historical working directory', () => {
|
||||
const rep = report([
|
||||
project({ project: 'alpha', projectPath: '/code/alpha' }, [
|
||||
session('main-s', [turn(2, { gitBranch: 'main' })], { workingDirectory: '/code/alpha' }),
|
||||
session('wt-s', [turn(6, { gitBranch: 'feat/auth' })], { workingDirectory: '/code/alpha-worktrees/task-42' }),
|
||||
]),
|
||||
])
|
||||
const feat = rep.projects[0]!.branches.find(r => r.branch === 'feat/auth')!
|
||||
expect(feat.worktrees).toEqual([
|
||||
{ path: '/code/alpha-worktrees/task-42', sessions: 1, cost: 6 },
|
||||
])
|
||||
// The worktree session still belongs to the canonical project.
|
||||
expect(feat.projectId).toBe('/code/alpha')
|
||||
expect(rep.projects[0]!.coverage.distinctSessions).toBe(2)
|
||||
})
|
||||
|
||||
it('keeps in-range spend on the branch carried from before the range', () => {
|
||||
// The parser resolves the carry across the range boundary before slicing,
|
||||
// so an in-range turn active on `main` (set before the window) arrives
|
||||
// with gitBranch='main' and must NOT land in the Unknown bucket.
|
||||
const rep = report([
|
||||
project({ project: 'alpha', projectPath: '/code/alpha' }, [
|
||||
session('s1', [
|
||||
turn(9, { gitBranch: 'main', at: '2026-07-01T09:00:00Z' }),
|
||||
turn(1, { gitBranch: 'main', at: '2026-07-01T10:00:00Z' }),
|
||||
]),
|
||||
]),
|
||||
])
|
||||
expect(rep.projects[0]!.branches.map(r => [r.branch, r.cost])).toEqual([['main', 10]])
|
||||
expect(rep.projects[0]!.coverage.branchUnknownCost).toBe(0)
|
||||
})
|
||||
|
||||
it('attributes spend made before the first known branch to Unknown, never to a later branch', () => {
|
||||
const rep = report([
|
||||
project({ project: 'alpha', projectPath: '/code/alpha' }, [
|
||||
session('s1', [
|
||||
turn(2), // before any branch was observed
|
||||
turn(5, { gitBranch: 'feat/auth' }),
|
||||
]),
|
||||
]),
|
||||
])
|
||||
const alpha = rep.projects[0]!
|
||||
expect(alpha.branches.map(r => [r.branch, r.cost])).toEqual([
|
||||
['feat/auth', 5], [null, 2],
|
||||
])
|
||||
expect(alpha.coverage.branchKnownCost).toBeCloseTo(5, 6)
|
||||
expect(alpha.coverage.branchUnknownCost).toBeCloseTo(2, 6)
|
||||
// everHadBranch pre-filter evidence: a session whose only in-range turns
|
||||
// precede its first branch still participates via the Unknown bucket.
|
||||
const anchored = report([
|
||||
project({ project: 'alpha', projectPath: '/code/alpha' }, [
|
||||
session('s2', [turn(2)], { everHadBranch: true }),
|
||||
]),
|
||||
])
|
||||
expect(anchored.projects[0]!.branches).toHaveLength(1)
|
||||
expect(anchored.projects[0]!.branches[0]!.branch).toBeNull()
|
||||
})
|
||||
|
||||
it('reports provider-sources without branch metadata as coverage, not as a branch', () => {
|
||||
const rep = report([
|
||||
project({ project: 'alpha', projectPath: '/code/alpha' }, [
|
||||
session('claude-s', [turn(5, { gitBranch: 'main' })]),
|
||||
session('codex-s', [turn(7, { provider: 'codex' })]),
|
||||
]),
|
||||
])
|
||||
const alpha = rep.projects[0]!
|
||||
expect(alpha.branches.map(r => r.branch)).toEqual(['main'])
|
||||
expect(alpha.coverage.noBranchDataCost).toBeCloseTo(7, 6)
|
||||
expect(alpha.coverage.noBranchDataSessions).toBe(1)
|
||||
expect(alpha.coverage.noBranchDataProviders).toEqual(['codex'])
|
||||
// Reconciliation: known + unknown + no-metadata covers the full spend.
|
||||
expect(
|
||||
alpha.coverage.branchKnownCost + alpha.coverage.branchUnknownCost + alpha.coverage.noBranchDataCost,
|
||||
).toBeCloseTo(alpha.totalCost, 6)
|
||||
})
|
||||
|
||||
it('sums token components per branch from the contributing calls', () => {
|
||||
const rep = report([
|
||||
project({ project: 'alpha', projectPath: '/code/alpha' }, [
|
||||
session('s1', [
|
||||
turn(1, { gitBranch: 'main', usage: { inputTokens: 300, outputTokens: 50, reasoningTokens: 25, cacheReadInputTokens: 900, cacheCreationInputTokens: 40 } }),
|
||||
turn(1, { gitBranch: 'main', usage: { inputTokens: 100, outputTokens: 10 } }),
|
||||
]),
|
||||
]),
|
||||
])
|
||||
const tokens = rep.projects[0]!.branches[0]!.tokens
|
||||
expect(tokens.inputTokens).toBe(400)
|
||||
expect(tokens.outputTokens).toBe(60)
|
||||
expect(tokens.reasoningTokens).toBe(25)
|
||||
expect(tokens.cacheReadTokens).toBe(900)
|
||||
expect(tokens.cacheWriteTokens).toBe(40)
|
||||
})
|
||||
|
||||
it('tracks activity windows and per-session contributions inside a branch', () => {
|
||||
const rep = report([
|
||||
project({ project: 'alpha', projectPath: '/code/alpha' }, [
|
||||
session('s1', [
|
||||
turn(3, { gitBranch: 'feat/auth', at: '2026-07-01T08:00:00Z' }),
|
||||
turn(2, { gitBranch: 'feat/auth', at: '2026-07-01T09:30:00Z' }),
|
||||
], { title: 'Implement auth' }),
|
||||
session('s2', [turn(4, { gitBranch: 'feat/auth', at: '2026-07-01T10:15:00Z' })]),
|
||||
]),
|
||||
])
|
||||
const feat = rep.projects[0]!.branches.find(r => r.branch === 'feat/auth')!
|
||||
expect(feat.firstActive).toBe('2026-07-01T08:00:00Z')
|
||||
expect(feat.lastActive).toBe('2026-07-01T10:15:00Z')
|
||||
expect(feat.sessions).toBe(2)
|
||||
expect(feat.sessionRows.map(s => [s.sessionId, s.cost])).toEqual([['s1', 5], ['s2', 4]])
|
||||
expect(feat.sessionRows[0]!.title).toBe('Implement auth')
|
||||
expect(feat.sessionRows[0]!.firstActive).toBe('2026-07-01T08:00:00Z')
|
||||
expect(feat.sessionRows[0]!.lastActive).toBe('2026-07-01T09:30:00Z')
|
||||
})
|
||||
|
||||
it('omits projects with neither branch rows nor no-branch spend', () => {
|
||||
const rep = report([
|
||||
project({ project: 'alpha', projectPath: '/code/alpha' }, [
|
||||
session('s1', [turn(5, { gitBranch: 'main' })]),
|
||||
]),
|
||||
project({ project: 'empty', projectPath: '/code/empty' }, []),
|
||||
])
|
||||
expect(rep.projects.map(p => p.label)).toEqual(['alpha'])
|
||||
})
|
||||
})
|
||||
Loading…
Add table
Add a link
Reference in a new issue