From 4d235fee471a4c335f917d267d37310dabad5eb4 Mon Sep 17 00:00:00 2001 From: ozymandiashh <234437643+ozymandiashh@users.noreply.github.com> Date: Sat, 12 Sep 2026 12:12:55 +0300 Subject: [PATCH 1/5] Add spend-by-branch report (spend --format branch-json) Spend per canonical project x branch, keyed by the project identity the spend-flow and By project views already use, so identical branch names in different projects never merge. Reuses the aggregateByBranch rules: last-seen branch carried forward across turns (the parser resolves the carry across a range boundary from pre-range evidence), only ever-branched sessions participate, and turns before a session's first branch stay an explicit Unknown row. Rows carry cost, behavioral calls, token components, distinct sessions (identity-based, rows overlap), activity window, per-session contributions, recorded worktree evidence (historical working directory, never today's checkout), and a coverage split: known / Unknown / no-branch-data sources. Same --period/--provider/--from/--to/--project/--exclude semantics as spend --format flow-json. docs/by-branch.md documents the lens. --- docs/by-branch.md | 58 ++++++ src/branch-spend.ts | 396 +++++++++++++++++++++++++++++++++++++ src/main.ts | 11 +- tests/branch-spend.test.ts | 230 +++++++++++++++++++++ 4 files changed, 693 insertions(+), 2 deletions(-) create mode 100644 docs/by-branch.md create mode 100644 src/branch-spend.ts create mode 100644 tests/branch-spend.test.ts diff --git a/docs/by-branch.md b/docs/by-branch.md new file mode 100644 index 00000000..f2d9c86b --- /dev/null +++ b/docs/by-branch.md @@ -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. diff --git a/src/branch-spend.ts b/src/branch-spend.ts new file mode 100644 index 00000000..a9d5a0aa --- /dev/null +++ b/src/branch-spend.ts @@ -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 + 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 +} + +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 + noBranchProviders: Map + totalCost: number +} { + const byBranch = new Map() + let noBranchCost = 0 + const noBranchSessions = new Set() + const noBranchProviders = new Map() + 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() + 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, + noBranchProviders: Map, +): BranchSpendCoverage { + const distinct = new Set() + 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() + let totalsKnown = 0 + let totalsUnknown = 0 + let totalsNoBranch = 0 + let totalsNoBranchSessions = 0 + const totalsNoBranchProviders = new Map() + + 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 { + const parsed = await parseAllSessions(range, provider) + await reportUnmatchedProjectPatterns(parsed, projectFilter, excludeFilter, () => cachedProjectIdentitiesForRange(range)) + const projects = filterProjectsByName(parsed, projectFilter, excludeFilter) + return buildBranchSpendReport(projects, range) +} diff --git a/src/main.ts b/src/main.ts index cd063f46..431d31da 100644 --- a/src/main.ts +++ b/src/main.ts @@ -2589,11 +2589,11 @@ program .option('--from ', 'Custom range start (YYYY-MM-DD)') .option('--to ', 'Custom range end (YYYY-MM-DD)') .option('--provider ', 'Filter by provider (e.g. claude, codex, cursor)', 'all') - .option('--format ', 'Output format: flow-json', 'flow-json') + .option('--format ', 'Output format: flow-json, branch-json', 'flow-json') .option('--project ', 'Show only projects matching name (repeatable)', collect, []) .option('--exclude ', '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))) }) diff --git a/tests/branch-spend.test.ts b/tests/branch-spend.test.ts new file mode 100644 index 00000000..766d7138 --- /dev/null +++ b/tests/branch-spend.test.ts @@ -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 { + 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; 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 { + 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']) + }) +}) From 28120c313fb410c1e3f2d9e68ae8422b08e29080 Mon Sep 17 00:00:00 2001 From: ozymandiashh <234437643+ozymandiashh@users.noreply.github.com> Date: Sat, 12 Sep 2026 12:13:04 +0300 Subject: [PATCH 2/5] Add Spend By branch lens (renderer -> IPC -> branch-json report) New getBranchSpend bridge channel (codeburn:getBranchSpend) spawning 'spend --format branch-json' with the same period/provider/range flags and validation as the other first-click reports, plus background-priority prefetch handling. The renderer keeps the typed contract in lib/types.ts. BranchBreakdown panel: project picker (auto top project, explicit All projects view labeled project/branch), expandable branch rows with token components, worktree evidence and per-session contributions, a real session inspect detail, and the coverage note (known / Unknown / no-branch-data, identity-based distinct sessions). Reuses ListRow/Panel/Dropdown/stale-safe usePolled memo keys; selection is derived so a refresh or a vanished project falls back instead of mixing data. --- app/electron/main.test.ts | 4 + app/electron/main.ts | 5 + app/electron/preload.ts | 1 + app/renderer/App.test.tsx | 8 +- .../components/BranchBreakdown.test.tsx | 168 ++++++++++++ app/renderer/components/BranchBreakdown.tsx | 250 ++++++++++++++++++ app/renderer/lib/types.ts | 70 +++++ app/renderer/sections/Spend.test.tsx | 17 +- app/renderer/sections/Spend.tsx | 3 + app/renderer/styles/plain.css | 11 + 10 files changed, 533 insertions(+), 4 deletions(-) create mode 100644 app/renderer/components/BranchBreakdown.test.tsx create mode 100644 app/renderer/components/BranchBreakdown.tsx diff --git a/app/electron/main.test.ts b/app/electron/main.test.ts index 9b3b7880..8e4d1eee 100644 --- a/app/electron/main.test.ts +++ b/app/electron/main.test.ts @@ -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]], ] diff --git a/app/electron/main.ts b/app/electron/main.ts index 31bdd0b8..610f59d8 100644 --- a/app/electron/main.ts +++ b/app/electron/main.ts @@ -573,6 +573,11 @@ 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)), ...rangeArgs(vRange(range)), + ], 3), 'codeburn:getOptimizeReport': run((period: string, provider: string, range?: DateRange) => [ 'optimize', '--format', 'json', '--period', vPeriod(period), ...providerArgs(vProvider(provider)), diff --git a/app/electron/preload.ts b/app/electron/preload.ts index b91a3b0c..8e44bad7 100644 --- a/app/electron/preload.ts +++ b/app/electron/preload.ts @@ -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'), diff --git a/app/renderer/App.test.tsx b/app/renderer/App.test.tsx index dffb6fe4..0eece1eb 100644 --- a/app/renderer/App.test.tsx +++ b/app/renderer/App.test.tsx @@ -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() 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>(), getSpendFlow: vi.fn<(period: string, provider: string, range?: DateRange, background?: boolean) => Promise>(), + getBranchSpend: vi.fn<(period: string, provider: string, range?: DateRange, background?: boolean) => Promise>(), getTimeline: vi.fn<(period: string, provider: string, range?: DateRange) => Promise>(), getOptimizeReport: vi.fn<(period: string, provider: string, range?: DateRange, background?: boolean) => Promise>(), 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: { diff --git a/app/renderer/components/BranchBreakdown.test.tsx b/app/renderer/components/BranchBreakdown.test.tsx new file mode 100644 index 00000000..908aea19 --- /dev/null +++ b/app/renderer/components/BranchBreakdown.test.tsx @@ -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>(), +})) +vi.mock('../lib/ipc', async orig => { + const actual = await orig() + return { ...actual, codeburn: { getBranchSpend } } +}) + +function report(overrides: Partial = {}): 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() + 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() + 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() + 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() + 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() + 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() + await waitFor(() => expect(screen.getByText(/boom/)).toBeInTheDocument()) + }) +}) diff --git a/app/renderer/components/BranchBreakdown.tsx b/app/renderer/components/BranchBreakdown.tsx new file mode 100644 index 00000000..eacd5cda --- /dev/null +++ b/app/renderer/components/BranchBreakdown.tsx @@ -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 ( +
+
Session{session.sessionId}
+
Provider{session.provider}{session.isSidechain ? ' (subagent)' : ''}
+
Working directory{session.workingDirectory ? pathLabel(session.workingDirectory) : 'Not recorded'}
+
Models{session.models.length ? session.models.join(', ') : '—'}
+
Tokens{tokenSummary(session.tokens)}
+
Activity{activitySpan(session.firstActive, session.lastActive)} · {session.calls.toLocaleString('en-US')} calls
+
+ ) +} + +function BranchRowView({ row, index, showProject, expanded, onToggle }: { + row: BranchSpendRow + index: number + showProject: boolean + expanded: boolean + onToggle: () => void +}) { + const [openSession, setOpenSession] = useState(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 ( + + + {expanded && ( +
+
Tokens{tokenSummary(row.tokens)}
+ {row.worktrees.map(wt => ( +
+ Worktree + {pathLabel(wt.path)} · {wt.sessions} {wt.sessions === 1 ? 'session' : 'sessions'} · {formatUsd(wt.cost)} +
+ ))} + {row.sessionRows.map(session => { + const sessionKey = `${row.projectId}|${row.branch}|${session.sessionId}` + const open = openSession === sessionKey + return ( + +
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) + } + }} + > + {session.title ?? shortSessionId(session.sessionId)} + {session.models[0] ?? session.provider} + {session.calls.toLocaleString('en-US')} calls + {formatUsd(session.cost)} +
+ {open && } +
+ ) + })} + {row.sessionRows.length === 0 &&
No session detail for this branch.
} +
+ )} +
+ ) +} + +function CoverageNote({ scope }: { scope: BranchSpendProjectReport['coverage'] }) { + const providers = scope.noBranchDataProviders + return ( +
+ On branches {formatUsd(scope.branchKnownCost)} + Unknown, before first branch {formatUsd(scope.branchUnknownCost)} + + No branch data {formatUsd(scope.noBranchDataCost)} + {scope.noBranchDataSessions > 0 ? ` (${scope.noBranchDataSessions} ${scope.noBranchDataSessions === 1 ? 'session' : 'sessions'}${providers.length ? `: ${providers.join(', ')}` : ''})` : ''} + + + {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. + +
+ ) +} + +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(null) + const [expandedKey, setExpandedKey] = useState(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 ( + +
+ setSelected(value)} + /> +
+ {rows.length ? ( + rows.map((row, i) => { + const rowKey = `${row.projectId}|${row.branch ?? '__unknown__'}` + return ( + setExpandedKey(current => current === rowKey ? null : rowKey)} + /> + ) + }) + ) : ( + 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. + )} + +
+ ) +} + +/** 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( + () => 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 ( + + + + ) + } + return + } + return +} diff --git a/app/renderer/lib/types.ts b/app/renderer/lib/types.ts index c5dcaa35..5786d4bc 100644 --- a/app/renderer/lib/types.ts +++ b/app/renderer/lib/types.ts @@ -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 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`). */ + getBranchSpend(period: Period, provider: string, range?: DateRange, background?: boolean): Promise getOptimizeReport(period: Period, provider: string, range?: DateRange, background?: boolean): Promise getDevices(period: Period): Promise getDevicesScan(): Promise diff --git a/app/renderer/sections/Spend.test.tsx b/app/renderer/sections/Spend.test.tsx index c0cf81fa..6e340d2f 100644 --- a/app/renderer/sections/Spend.test.tsx +++ b/app/renderer/sections/Spend.test.tsx @@ -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 { 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>(), getSpendFlow: vi.fn<(period: string, provider: string) => Promise>(), getTimeline: vi.fn<(period: string, provider: string) => Promise>(), + getBranchSpend: vi.fn<(period: string, provider: string) => Promise>(), })) vi.mock('../lib/ipc', async orig => { const actual = await orig() - 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(() => { diff --git a/app/renderer/sections/Spend.tsx b/app/renderer/sections/Spend.tsx index 5e70b1db..538e4ca0 100644 --- a/app/renderer/sections/Spend.tsx +++ b/app/renderer/sections/Spend.tsx @@ -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({ + + {flow.data && flow.data.links.length ? ( diff --git a/app/renderer/styles/plain.css b/app/renderer/styles/plain.css index bdf26bc3..99fba45a 100644 --- a/app/renderer/styles/plain.css +++ b/app/renderer/styles/plain.css @@ -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; } From 810d91169ab491bcffaa994290687a2610bde41a Mon Sep 17 00:00:00 2001 From: ozymandiashh <234437643+ozymandiashh@users.noreply.github.com> Date: Sat, 12 Sep 2026 12:13:20 +0300 Subject: [PATCH 3/5] Move desktop dev server to port 5720 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The default 5173 collides with parallel CodeBurn worktree sessions sharing one machine. strictPort stays on so a busy port fails loudly instead of silently drifting; VITE_DEV_SERVER_URL follows the same port in the dev script. Note the port does NOT isolate the Electron userData profile — parallel sessions must still run the app one at a time. --- app/package.json | 2 +- app/vite.config.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/package.json b/app/package.json index 73a2b27c..3a839200 100644 --- a/app/package.json +++ b/app/package.json @@ -8,7 +8,7 @@ "build:electron": "tsc -p tsconfig.electron.json", "build:renderer": "vite build", "build": "npm run build:electron && npm run build:renderer", - "dev": "npm run build:electron && concurrently -k -n vite,electron -c cyan,magenta \"vite\" \"wait-on tcp:127.0.0.1:5173 && cross-env VITE_DEV_SERVER_URL=http://127.0.0.1:5173 electron .\"", + "dev": "npm run build:electron && concurrently -k -n vite,electron -c cyan,magenta \"vite\" \"wait-on tcp:127.0.0.1:5720 && cross-env VITE_DEV_SERVER_URL=http://127.0.0.1:5720 electron .\"", "test": "vitest run", "typecheck": "tsc --noEmit -p tsconfig.json", "stage-cli": "npm --prefix .. run build:cli && node scripts/stage-cli.mjs", diff --git a/app/vite.config.ts b/app/vite.config.ts index 5504c923..6ee5ee48 100644 --- a/app/vite.config.ts +++ b/app/vite.config.ts @@ -45,6 +45,6 @@ export default defineConfig({ __BUILD_SHA__: JSON.stringify(stamp.sha), __BUILD_DATE__: JSON.stringify(stamp.date), }, - server: { host: '127.0.0.1', port: 5173, strictPort: true }, + server: { host: '127.0.0.1', port: 5720, strictPort: true }, build: { outDir: '../dist/renderer', emptyOutDir: true }, }) From bb6a67b52172b7af0870ef85a96e515153448f71 Mon Sep 17 00:00:00 2001 From: ozymandiashh <234437643+ozymandiashh@users.noreply.github.com> Date: Sat, 12 Sep 2026 13:25:15 +0300 Subject: [PATCH 4/5] Restore the standard desktop development port --- app/package.json | 2 +- app/vite.config.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/package.json b/app/package.json index 3a839200..73a2b27c 100644 --- a/app/package.json +++ b/app/package.json @@ -8,7 +8,7 @@ "build:electron": "tsc -p tsconfig.electron.json", "build:renderer": "vite build", "build": "npm run build:electron && npm run build:renderer", - "dev": "npm run build:electron && concurrently -k -n vite,electron -c cyan,magenta \"vite\" \"wait-on tcp:127.0.0.1:5720 && cross-env VITE_DEV_SERVER_URL=http://127.0.0.1:5720 electron .\"", + "dev": "npm run build:electron && concurrently -k -n vite,electron -c cyan,magenta \"vite\" \"wait-on tcp:127.0.0.1:5173 && cross-env VITE_DEV_SERVER_URL=http://127.0.0.1:5173 electron .\"", "test": "vitest run", "typecheck": "tsc --noEmit -p tsconfig.json", "stage-cli": "npm --prefix .. run build:cli && node scripts/stage-cli.mjs", diff --git a/app/vite.config.ts b/app/vite.config.ts index 6ee5ee48..5504c923 100644 --- a/app/vite.config.ts +++ b/app/vite.config.ts @@ -45,6 +45,6 @@ export default defineConfig({ __BUILD_SHA__: JSON.stringify(stamp.sha), __BUILD_DATE__: JSON.stringify(stamp.date), }, - server: { host: '127.0.0.1', port: 5720, strictPort: true }, + server: { host: '127.0.0.1', port: 5173, strictPort: true }, build: { outDir: '../dist/renderer', emptyOutDir: true }, }) From dc8583fde8b15b38fe4cc79454ee24b4758c70fe Mon Sep 17 00:00:00 2001 From: iamtoruk Date: Sat, 12 Sep 2026 13:25:15 -0700 Subject: [PATCH 5/5] Scope the By branch fetch by the app project filter getBranchSpend was the only data fetch in createBridgeHandlers without projectArgs(), so a project hidden by the Projects pane filter still showed its branches in the Spend > By branch lens. Extends the existing "scopes every fetch" test to cover the channel. --- app/electron/main.test.ts | 2 ++ app/electron/main.ts | 5 ++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/app/electron/main.test.ts b/app/electron/main.test.ts index 8e4d1eee..8413b9d6 100644 --- a/app/electron/main.test.ts +++ b/app/electron/main.test.ts @@ -833,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']) }) }) diff --git a/app/electron/main.ts b/app/electron/main.ts index 610f59d8..b009f5bd 100644 --- a/app/electron/main.ts +++ b/app/electron/main.ts @@ -576,7 +576,10 @@ export function createBridgeHandlers(deps: Deps = { spawnCli, spawnCliAction, re // 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)), ...rangeArgs(vRange(range)), + '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),