diff --git a/app/renderer/components/RootDeepProjectLabels.test.tsx b/app/renderer/components/RootDeepProjectLabels.test.tsx new file mode 100644 index 00000000..836770ae --- /dev/null +++ b/app/renderer/components/RootDeepProjectLabels.test.tsx @@ -0,0 +1,13 @@ +import { describe, it, expect } from 'vitest' +import { renderToStaticMarkup } from 'react-dom/server' +import { Sankey } from './Sankey' + +describe('root distinguishing canonical project labels', () => { + it('does not discard the parent segment that distinguishes deep cwd siblings', () => { + const flow = {period:{label:'Today',start:'2026-09-07',end:'2026-09-07'}, models:[{id:'m',label:'m',cost:5}], projects:[{id:'/left/a/x/vault',label:'left/a/x/vault',cost:2},{id:'/right/a/x/vault',label:'right/a/x/vault',cost:3}], links:[{model:'m',project:'/left/a/x/vault',cost:2},{model:'m',project:'/right/a/x/vault',cost:3}]} + const html=renderToStaticMarkup(); + console.log('ROOT_VISIBLE_AX', [...html.matchAll(/aria-label="([^"]+)"/g)].map(m=>m[1])); + expect(html).toContain('left/a/x/vault ·'); + expect(html).toContain('right/a/x/vault ·'); + }); +}); diff --git a/app/renderer/components/Sankey.tsx b/app/renderer/components/Sankey.tsx index 1dd7b4de..5f0abcdf 100644 --- a/app/renderer/components/Sankey.tsx +++ b/app/renderer/components/Sankey.tsx @@ -8,6 +8,7 @@ type LayoutNode = SpendFlowNode & { h: number fill: string displayLabel: string + axLabel: string } const VIEW_W = 760 @@ -103,9 +104,18 @@ export function Sankey({ flow }: { flow: SpendFlow }) { ))} {projects.map(node => ( - - {node.displayLabel} · {formatUsd(node.cost)} - + + {node.id} + + {node.displayLabel} · {formatUsd(node.cost)} + + ))} ) @@ -125,8 +135,10 @@ function layoutNodes(nodes: SpendFlowNode[], x: number, modelSide: boolean): Lay const h = Math.max(2, inflated[i] * scale) const neutral = isOtherNode(node.id) || isOtherNode(node.label) const fill = modelSide && !neutral ? seriesColorForModel(node.label || node.id) : neutral ? 'var(--s-other)' : 'var(--mut2)' - const displayLabel = modelSide ? modelDisplayLabel(node.label || node.id) : projectDisplayLabel(node.label || node.id) - const laidOut = { ...node, x, y, h, fill, displayLabel } + const source = node.label || node.id + const axLabel = modelSide ? modelDisplayLabel(source) : projectCanonicalLabel(source) + const displayLabel = modelSide ? axLabel : ellipsize(axLabel, 24) + const laidOut = { ...node, x, y, h, fill, displayLabel, axLabel } y += h + GAP return laidOut }) @@ -149,10 +161,14 @@ function modelDisplayLabel(raw: string): string { return ellipsize(shortenId(value), 18) } -function projectDisplayLabel(raw: string): string { +function projectCanonicalLabel(raw: string): string { const value = raw.trim() if (isOtherNode(value)) return 'Other' - return ellipsize(shortenProjectPath(value), 24) + // Abs cwd still sent as the label (older payloads) may shorten. Canonical + // CLI labels already include the parent context that distinguishes collisions + // — do not drop it with a 3-segment tail. + if (value.startsWith('/') || /^[a-zA-Z]:[\\/]/.test(value)) return shortenProjectPath(value) + return value } function shortenId(value: string): string { diff --git a/app/renderer/lib/session-count-label.ts b/app/renderer/lib/session-count-label.ts new file mode 100644 index 00000000..5f9ee36f --- /dev/null +++ b/app/renderer/lib/session-count-label.ts @@ -0,0 +1,31 @@ +/// Display copy for period session counts. Keep in lockstep with +/// `src/session-count-label.ts` (renderer does not import `src/`). +export type SessionCountBasis = 'identity' | 'partial' + +export const SESSION_COUNT_HELP = 'Older session logs may be unavailable.' +export const COMBINED_SESSION_COUNT_HELP = 'Session identities are unavailable across devices.' +export const COMBINED_SESSION_COUNT_LABEL = 'Session count unavailable' + +export function sessionCountIsExact(basis: SessionCountBasis | undefined): boolean { + return basis === 'identity' +} + +export function formatSessionCount( + sessions: number, + basis: SessionCountBasis | undefined, +): string { + if (!sessionCountIsExact(basis)) { + if (sessions <= 0) return 'Session count unavailable' + return sessions === 1 ? 'At least 1 session' : `At least ${sessions.toLocaleString('en-US')} sessions` + } + if (sessions === 1) return '1 session' + return `${sessions.toLocaleString('en-US')} sessions` +} + +export function formatSessionAveragePlaceholder(): string { + return '—' +} + +export function formatCombinedSessionCount(): string { + return COMBINED_SESSION_COUNT_LABEL +} diff --git a/app/renderer/lib/types.ts b/app/renderer/lib/types.ts index ed8b3800..0aabb691 100644 --- a/app/renderer/lib/types.ts +++ b/app/renderer/lib/types.ts @@ -152,6 +152,7 @@ export type MenubarPayload = { cost: number calls: number sessions: number + sessionCountBasis?: 'identity' | 'partial' oneShotRate: number | null inputTokens: number outputTokens: number @@ -179,13 +180,15 @@ export type MenubarPayload = { // Optional: older CLIs omit it. `id` is the internal provider name (round-trips // as --provider), `label` the display name. `hasUsage` distinguishes active $0 // providers from detected-but-idle providers when present. - providerDetails?: Array<{ id: string; label: string; cost: number; calls?: number; hasUsage?: boolean }> + providerDetails?: Array<{ id: string; label: string; cost: number; calls?: number; hasUsage?: boolean; sessions?: number; sessionCountBasis?: 'identity' | 'partial' }> topProjects: Array<{ + id?: string name: string cost: number savingsUSD: number sessions: number - avgCostPerSession: number + avgCostPerSession?: number + sessionCountBasis?: 'identity' | 'partial' sessionDetails: Array<{ cost: number savingsUSD: number diff --git a/app/renderer/sections/Overview.test.tsx b/app/renderer/sections/Overview.test.tsx index ddf9146c..0d2e2eec 100644 --- a/app/renderer/sections/Overview.test.tsx +++ b/app/renderer/sections/Overview.test.tsx @@ -543,6 +543,20 @@ describe('Overview', () => { expect(container.querySelectorAll('.ov-sessions-widget .mdot')).toHaveLength(0) }) + it('uses singular call copy for a one-call expensive session', async () => { + const now = new Date() + const payload = makePayload(now) + payload.current.topSessions = [ + { project: 'tiny', cost: 0.02, savingsUSD: 0, calls: 1, date: '2026-07-08' }, + ] + getOverview.mockResolvedValue(payload) + + render() + + expect(await screen.findByText('Jul 8 · 1 call')).toBeInTheDocument() + expect(screen.queryByText(/1 calls/)).not.toBeInTheDocument() + }) + it('disambiguates two same-project/same-day/same-calls sessions by cost', async () => { const now = new Date() const base = makePayload(now) @@ -682,13 +696,77 @@ describe('Overview', () => { const kpis = container.querySelector('.ov-hero-main') as HTMLElement // Hero cost is the combined $500, not the local $312.40. expect(within(kpis).getByText('$500.00')).toBeInTheDocument() - expect(within(kpis).getByText(/6,300 calls · 128 sessions/)).toBeInTheDocument() + expect(within(kpis).getByText(/6,300 calls · Session count unavailable/)).toBeInTheDocument() + expect(within(kpis).queryByText(/128 sessions/)).not.toBeInTheDocument() + expect(within(kpis).queryByText(/At least/)).not.toBeInTheDocument() expect(within(kpis).getByText('Combined · Last 30 days')).toBeInTheDocument() expect(within(kpis).getByText('2 of 2 devices')).toBeInTheDocument() expect(within(kpis).getByText('workstation')).toBeInTheDocument() expect(within(kpis).getByText('laptop · this device')).toBeInTheDocument() // Combined mode hides the local savings lines (they are device-specific). expect(within(kpis).queryByText('Saved via local models')).not.toBeInTheDocument() + expect(within(kpis).getByTitle('Session identities are unavailable across devices.')).toBeInTheDocument() + }) + + it('combined zero, missing basis, and replicated device counts all stay unavailable', async () => { + const now = new Date() + const cases: Array<{ name: string, combined: NonNullable }> = [ + { + name: 'zero', + combined: { + perDevice: [{ id: 'local', name: 'laptop', local: true, cost: 0, calls: 0, sessions: 0, inputTokens: 0, outputTokens: 0, cacheCreateTokens: 0, cacheReadTokens: 0, totalTokens: 0 }], + combined: { cost: 0, calls: 0, sessions: 0, inputTokens: 0, outputTokens: 0, cacheCreateTokens: 0, cacheReadTokens: 0, totalTokens: 0, deviceCount: 1, reachableCount: 1 }, + }, + }, + { + name: 'missing-basis', + combined: { + perDevice: [{ id: 'local', name: 'laptop', local: true, cost: 10, calls: 4, sessions: 2, inputTokens: 0, outputTokens: 0, cacheCreateTokens: 0, cacheReadTokens: 0, totalTokens: 0 }], + combined: { cost: 10, calls: 4, sessions: 2, inputTokens: 0, outputTokens: 0, cacheCreateTokens: 0, cacheReadTokens: 0, totalTokens: 0, deviceCount: 1, reachableCount: 1 }, + }, + }, + { + name: 'replicated', + combined: { + perDevice: [ + { id: 'a', name: 'one', local: true, cost: 1, calls: 1, sessions: 1, inputTokens: 0, outputTokens: 0, cacheCreateTokens: 0, cacheReadTokens: 0, totalTokens: 0 }, + { id: 'b', name: 'two', local: false, cost: 1, calls: 1, sessions: 1, inputTokens: 0, outputTokens: 0, cacheCreateTokens: 0, cacheReadTokens: 0, totalTokens: 0 }, + ], + combined: { cost: 2, calls: 2, sessions: 2, inputTokens: 0, outputTokens: 0, cacheCreateTokens: 0, cacheReadTokens: 0, totalTokens: 0, deviceCount: 2, reachableCount: 2 }, + }, + }, + ] + for (const entry of cases) { + const payload = makePayload(now) + delete payload.current.sessionCountBasis + payload.combined = entry.combined + const { container, unmount } = render() + const kpis = container.querySelector('.ov-hero-main') as HTMLElement + expect(within(kpis).getByText(/Session count unavailable/), entry.name).toBeInTheDocument() + expect(within(kpis).queryByText(/At least/), entry.name).not.toBeInTheDocument() + expect(within(kpis).getByTitle('Session identities are unavailable across devices.'), entry.name).toBeInTheDocument() + unmount() + } + }) + + it('local source-only exact zero and partial counts still work', async () => { + const now = new Date() + const zero = makePayload(now) + zero.current.cost = 0 + zero.current.calls = 0 + zero.current.sessions = 0 + zero.current.sessionCountBasis = 'identity' + const { container, unmount } = render() + expect(within(container.querySelector('.ov-hero-main') as HTMLElement).getByText(/0 sessions/)).toBeInTheDocument() + unmount() + + const partial = makePayload(now) + partial.current.sessions = 3 + partial.current.sessionCountBasis = 'partial' + render() + const kpis = document.querySelector('.ov-hero-main') as HTMLElement + expect(within(kpis).getByText(/At least 3 sessions/)).toBeInTheDocument() + expect(within(kpis).getByTitle('Older session logs may be unavailable.')).toBeInTheDocument() }) it('keeps local hero totals when scope is local even if a combined payload is present', async () => { diff --git a/app/renderer/sections/Overview.tsx b/app/renderer/sections/Overview.tsx index f2ac8753..27054c23 100644 --- a/app/renderer/sections/Overview.tsx +++ b/app/renderer/sections/Overview.tsx @@ -25,6 +25,7 @@ import type { YieldJsonReport, } from '../lib/types' import type { OverviewHeadlineSnapshot } from '../lib/overviewSnapshot' +import { formatCombinedSessionCount, formatSessionCount, sessionCountIsExact, COMBINED_SESSION_COUNT_HELP, SESSION_COUNT_HELP } from '../lib/session-count-label' export { localDateKey } from '../lib/period' @@ -766,6 +767,12 @@ export function OverviewContent({ const heroCost = combined ? combined.combined.cost : data.current.cost const heroCalls = combined ? combined.combined.calls : data.current.calls const heroSessions = combined ? combined.combined.sessions : data.current.sessions + const heroSessionLabel = combined + ? formatCombinedSessionCount() + : formatSessionCount(heroSessions, data.current.sessionCountBasis) + const heroSessionHelp = combined + ? COMBINED_SESSION_COUNT_HELP + : (sessionCountIsExact(data.current.sessionCountBasis) ? undefined : SESSION_COUNT_HELP) const animateKey = heroSelectionKey const stats = deriveStats(data, now) const periodDaily = sliceDailyToPeriod(data.history.daily, period, now) @@ -806,7 +813,7 @@ export function OverviewContent({ Replaying the live hero from $0 on handoff makes that exact value appear to collapse and recover; snap to the revalidated total. */} -
{heroCalls.toLocaleString('en-US')} calls · {heroSessions.toLocaleString('en-US')} sessions
+
{heroCalls.toLocaleString('en-US')} calls · {heroSessionLabel}
{combined ? : ( @@ -869,7 +876,7 @@ export function OverviewContent({
{data.current.topSessions.length ? data.current.topSessions.map((session, index) => { const model = modelIndex.get(sessionModelKey(session.project, session.date, session.calls, session.cost)) - const sub = [formatChartDate(session.date), model, `${session.calls} calls`].filter(Boolean).join(' · ') + const sub = [formatChartDate(session.date), model, `${session.calls} ${session.calls === 1 ? 'call' : 'calls'}`].filter(Boolean).join(' · ') return onNavigate?.('sessions')} /> }) : No sessions in this range.}
diff --git a/app/renderer/sections/Spend.test.tsx b/app/renderer/sections/Spend.test.tsx index 114d01e5..f9fc6a77 100644 --- a/app/renderer/sections/Spend.test.tsx +++ b/app/renderer/sections/Spend.test.tsx @@ -1,10 +1,23 @@ // @vitest-environment jsdom +import { readFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' + import { render, screen, within } from '@testing-library/react' 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 { Spend } from './Spend' +import { Spend, SpendContent } from './Spend' + +const ROOT_WEEK_OVERVIEW = JSON.parse( + readFileSync(join(dirname(fileURLToPath(import.meta.url)), '../test/fixtures/overview-week-all.json'), 'utf8'), +) as MenubarPayload + +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(() => ({ getOverview: vi.fn<(period: string, provider: string) => Promise>(), @@ -328,8 +341,9 @@ describe('Spend', () => { expect(screen.getByText(/gpt-5.5-codex/)).toBeInTheDocument() expect(screen.queryByText(/Opus 4.8/)).not.toBeInTheDocument() expect(screen.queryByText(/GPT-5.5 Codex/)).not.toBeInTheDocument() - expect(screen.getByText(/src\/mobile-app/)).toBeInTheDocument() - expect(screen.queryByText(/Users\/me\/src\/mobile-app/)).not.toBeInTheDocument() + const visibleProjectText = [...container.querySelectorAll('svg text')].map(el => el.textContent ?? '').join('\n') + expect(visibleProjectText).toMatch(/src\/mobile-app/) + expect(visibleProjectText).not.toMatch(/Users\/me\/src\/mobile-app/) const opusRibbon = container.querySelector('[data-testid="sankey-ribbon"][data-model="claude-opus-4-20260701"]') expect(opusRibbon?.getAttribute('stroke')).toBe('url(#sankey-claude-opus-4-20260701)') @@ -339,6 +353,37 @@ describe('Spend', () => { expect(otherNode?.getAttribute('fill')).toBe('var(--s-other)') }) + it('shows distinct same-basename hyphenated cwd labels on the cost-flow chart', async () => { + getOverview.mockResolvedValue(makePayload(new Date())) + getSpendFlow.mockResolvedValue({ + period: { label: 'Today', start: '2026-09-07', end: '2026-09-07' }, + models: [ + { id: 'Opus 4.6', label: 'Opus 4.6', cost: 0.45 }, + { id: 'Sonnet 4.5', label: 'Sonnet 4.5', cost: 0.018 }, + ], + projects: [ + { id: '/tmp/shared-vault', label: 'tmp/shared-vault', cost: 0.46891 }, + { id: '/tmp/alt/shared-vault', label: 'alt/shared-vault', cost: 0.018 }, + ], + links: [ + { model: 'Opus 4.6', project: '/tmp/shared-vault', cost: 0.45 }, + { model: 'Sonnet 4.5', project: '/tmp/alt/shared-vault', cost: 0.018 }, + ], + }) + getTimeline.mockResolvedValue(makePayload(new Date())) + + const { container } = render() + + expect(await screen.findByLabelText(/tmp\/shared-vault/)).toBeInTheDocument() + expect(screen.getByLabelText(/alt\/shared-vault/)).toBeInTheDocument() + const visibleProjectText = [...container.querySelectorAll('svg text')].map(el => el.textContent ?? '').join('\n') + expect(visibleProjectText).toMatch(/tmp\/shared-vault/) + expect(visibleProjectText).toMatch(/alt\/shared-vault/) + expect(visibleProjectText).not.toMatch(/shared\/vault/) + const svgTitles = [...container.querySelectorAll('svg title')].map(el => el.textContent) + expect(svgTitles).toEqual(expect.arrayContaining(['/tmp/shared-vault', '/tmp/alt/shared-vault'])) + }) + it('expands a project row inline to reveal its sessions, one open row at a time', async () => { const user = userEvent.setup() const payload = makePayload(new Date()) @@ -393,4 +438,191 @@ describe('Spend', () => { expect(second).toHaveAttribute('aria-expanded', 'false') expect(screen.queryByRole('region', { name: 'agentseal-dash sessions' })).not.toBeInTheDocument() }) + + it('expands same-basename projects independently when ids differ', async () => { + const user = userEvent.setup() + const payload = makePayload(new Date()) + payload.current.topProjects = [ + { + id: '/tmp/shared-vault', + name: 'shared-vault', + cost: 0.47, + savingsUSD: 0, + sessions: 2, + avgCostPerSession: 0.235, + sessionDetails: [{ + cost: 0.45, savingsUSD: 0, calls: 3, inputTokens: 0, outputTokens: 0, date: '2026-09-07', + models: [{ name: 'Opus 4.6', cost: 0.45, savingsUSD: 0 }], + }], + }, + { + id: '/tmp/other-vault', + name: 'other-vault', + cost: 0.02, + savingsUSD: 0, + sessions: 1, + avgCostPerSession: 0.02, + sessionDetails: [{ + cost: 0.02, savingsUSD: 0, calls: 1, inputTokens: 0, outputTokens: 0, date: '2026-09-07', + models: [{ name: 'Haiku 4.5', cost: 0.02, savingsUSD: 0 }], + }], + }, + { + id: '/var/shared-vault', + name: 'shared-vault', + cost: 0.01, + savingsUSD: 0, + sessions: 1, + avgCostPerSession: 0.01, + sessionDetails: [{ + cost: 0.01, savingsUSD: 0, calls: 1, inputTokens: 0, outputTokens: 0, date: '2026-09-07', + models: [{ name: 'Sonnet 4.5', cost: 0.01, savingsUSD: 0 }], + }], + }, + ] + getOverview.mockResolvedValue(payload) + getSpendFlow.mockResolvedValue(makeFlow()) + getTimeline.mockResolvedValue(makePayload(new Date())) + + render() + + const sharedRows = await screen.findAllByRole('button', { name: /shared-vault/ }) + expect(sharedRows).toHaveLength(2) + const firstShared = sharedRows[0]! + const secondShared = sharedRows[1]! + + await user.click(firstShared) + expect(firstShared).toHaveAttribute('aria-expanded', 'true') + expect(secondShared).toHaveAttribute('aria-expanded', 'false') + expect(screen.getByText('Opus 4.6')).toBeInTheDocument() + expect(screen.queryByText('Sonnet 4.5')).not.toBeInTheDocument() + expect(screen.queryByText('No session detail for this project.')).not.toBeInTheDocument() + + await user.click(secondShared) + expect(firstShared).toHaveAttribute('aria-expanded', 'false') + expect(secondShared).toHaveAttribute('aria-expanded', 'true') + expect(screen.queryByText('Opus 4.6')).not.toBeInTheDocument() + expect(screen.getByText('Sonnet 4.5')).toBeInTheDocument() + }) + + it('shows a lower-bound session phrase and help, not an unqualified count', async () => { + const payload = makePayload(new Date()) + payload.current.sessionCountBasis = 'partial' + payload.current.topProjects = [{ + id: '/tmp/count-boundary', + name: 'vault', + cost: 4, + savingsUSD: 0, + sessions: 3, + sessionCountBasis: 'partial', + sessionDetails: [], + }] + getOverview.mockResolvedValue(payload) + getSpendFlow.mockResolvedValue(makeFlow()) + getTimeline.mockResolvedValue(payload) + + render() + + const row = await screen.findByRole('button', { name: /At least 3 sessions/ }) + expect(row).toHaveAccessibleName(/At least 3 sessions/) + expect(screen.getByText('At least 3 sessions')).toBeInTheDocument() + expect(screen.getByTitle('Older session logs may be unavailable.')).toBeInTheDocument() + expect(screen.queryByText(/^3 sessions$/)).not.toBeInTheDocument() + }) + + it('keeps an exact source-only count unqualified', async () => { + const payload = makePayload(new Date()) + payload.current.sessionCountBasis = 'identity' + payload.current.topProjects = [{ + id: '/tmp/only', + name: 'vault', + cost: 0.012, + savingsUSD: 0, + sessions: 1, + avgCostPerSession: 0.012, + sessionCountBasis: 'identity', + sessionDetails: [], + }] + getOverview.mockResolvedValue(payload) + getSpendFlow.mockResolvedValue(makeFlow()) + getTimeline.mockResolvedValue(payload) + + render() + + expect(await screen.findByText('1 session')).toBeInTheDocument() + expect(screen.queryByText(/At least/)).not.toBeInTheDocument() + }) + + it('replaces legacy duplicate-name rows without leaving a ghost after current ids arrive', () => { + const current = structuredClone(ROOT_WEEK_OVERVIEW) + const ids = current.current.topProjects.map(row => row.id) + expect(new Set(ids).size).toBe(5) + expect(ids).toHaveLength(5) + + const legacy = structuredClone(current) + legacy.current.topProjects.splice(1, 0, { ...structuredClone(legacy.current.topProjects[0]!), name: 'shared-vault' }) + legacy.current.topProjects[0]!.name = 'shared-vault' + for (const row of legacy.current.topProjects) delete row.id + + const { rerender, container } = render( + , + ) + expect(container.querySelectorAll('.spend-scroll [role=button]')).toHaveLength(6) + + rerender() + expect(screen.getByText('top 5')).toBeTruthy() + expect(container.querySelectorAll('.spend-scroll [role=button]')).toHaveLength(5) + expect(screen.queryByText('shared-vault')).toBeNull() + }) + + it('expands legacy same-name rows independently when ids are absent', async () => { + const user = userEvent.setup() + const payload = makePayload(new Date()) + payload.current.topProjects = [ + { + name: 'shared-vault', + cost: 0.45, + savingsUSD: 0, + sessions: 1, + avgCostPerSession: 0.45, + sessionDetails: [{ + cost: 0.45, savingsUSD: 0, calls: 3, inputTokens: 0, outputTokens: 0, date: '2026-09-07', + models: [{ name: 'Opus 4.6', cost: 0.45, savingsUSD: 0 }], + }], + }, + { + name: 'shared-vault', + cost: 0.01, + savingsUSD: 0, + sessions: 1, + avgCostPerSession: 0.01, + sessionDetails: [{ + cost: 0.01, savingsUSD: 0, calls: 1, inputTokens: 0, outputTokens: 0, date: '2026-09-07', + models: [{ name: 'Sonnet 4.5', cost: 0.01, savingsUSD: 0 }], + }], + }, + ] + getOverview.mockResolvedValue(payload) + getSpendFlow.mockResolvedValue(makeFlow()) + getTimeline.mockResolvedValue(makePayload(new Date())) + + render() + + const sharedRows = await screen.findAllByRole('button', { name: /shared-vault/ }) + expect(sharedRows).toHaveLength(2) + const firstShared = sharedRows[0]! + const secondShared = sharedRows[1]! + + await user.click(firstShared) + expect(firstShared).toHaveAttribute('aria-expanded', 'true') + expect(secondShared).toHaveAttribute('aria-expanded', 'false') + expect(screen.getByText('Opus 4.6')).toBeInTheDocument() + expect(screen.queryByText('Sonnet 4.5')).not.toBeInTheDocument() + + await user.click(secondShared) + expect(firstShared).toHaveAttribute('aria-expanded', 'false') + expect(secondShared).toHaveAttribute('aria-expanded', 'true') + expect(screen.queryByText('Opus 4.6')).not.toBeInTheDocument() + expect(screen.getByText('Sonnet 4.5')).toBeInTheDocument() + }) }) diff --git a/app/renderer/sections/Spend.tsx b/app/renderer/sections/Spend.tsx index ba673097..934164a9 100644 --- a/app/renderer/sections/Spend.tsx +++ b/app/renderer/sections/Spend.tsx @@ -15,10 +15,15 @@ import { formatUsd } from '../lib/format' import { codeburn } from '../lib/ipc' import { contiguousDailyWindow, dataStartKey, localDateKey } from '../lib/period' import { reportMemoKey } from '../lib/reportMemoKey' +import { formatSessionCount, SESSION_COUNT_HELP } from '../lib/session-count-label' import type { CliError, DateRange, MenubarPayload, Period, SpendFlow } from '../lib/types' type Project = MenubarPayload['current']['topProjects'][number] +function projectRowKey(project: Project, index: number): string { + return project.id || `legacy:${index}:${project.name}` +} + /** Date-only CLI strings ("2026-07-11") formatted at local noon so the calendar day never rolls across time zones. */ function formatProjectDay(date: string): string { const d = new Date(`${date}T12:00:00`) @@ -209,16 +214,17 @@ function ProjectBreakdown({ projects }: { projects: Project[] }) { {projects.length ? ( projects.map((project, i) => { - const open = expanded === project.name + const rowKey = projectRowKey(project, i) + const open = expanded === rowKey return ( - + {formatSessionCount(project.sessions, project.sessionCountBasis)}} value={formatUsd(project.cost)} expanded={open} - onClick={() => setExpanded(current => current === project.name ? null : project.name)} + onClick={() => setExpanded(current => current === rowKey ? null : rowKey)} /> {open && (
diff --git a/app/renderer/test/fixtures/overview-week-all.json b/app/renderer/test/fixtures/overview-week-all.json new file mode 100644 index 00000000..3e00eb88 --- /dev/null +++ b/app/renderer/test/fixtures/overview-week-all.json @@ -0,0 +1,622 @@ +{ + "generated": "2026-09-07T14:22:51.049Z", + "current": { + "label": "Last 7 Days", + "cost": 0.540615, + "calls": 11, + "sessions": 7, + "sessionCountBasis": "partial", + "oneShotRate": null, + "inputTokens": 33800, + "outputTokens": 4710, + "cacheReadTokens": 900000, + "cacheWriteTokens": 0, + "cacheHitPercent": 96.38038123795245, + "codexCredits": 0, + "estimatedCostUSD": 0, + "topActivities": [ + { + "name": "Conversation", + "cost": 0.540615, + "savingsUSD": 0, + "turns": 10, + "oneShotRate": null + } + ], + "topModels": [ + { + "name": "Opus 4.6", + "cost": 0.44999999999999996, + "calls": 1, + "savingsUSD": 0, + "savingsBaselineModel": "", + "estimatedCostUSD": 0, + "inputTokens": 0, + "outputTokens": 0, + "cacheReadTokens": 900000, + "cacheWriteTokens": 0 + }, + { + "name": "Sonnet 4.5", + "cost": 0.07425000000000001, + "calls": 5, + "savingsUSD": 0, + "savingsBaselineModel": "", + "estimatedCostUSD": 0, + "inputTokens": 16500, + "outputTokens": 1650, + "cacheReadTokens": 0, + "cacheWriteTokens": 0 + }, + { + "name": "Haiku 4.5", + "cost": 0.015, + "calls": 1, + "savingsUSD": 0, + "savingsBaselineModel": "", + "estimatedCostUSD": 0, + "inputTokens": 10000, + "outputTokens": 1000, + "cacheReadTokens": 0, + "cacheWriteTokens": 0 + }, + { + "name": "GPT-5.3 Codex", + "cost": 0.001365, + "calls": 3, + "savingsUSD": 0, + "savingsBaselineModel": "", + "estimatedCostUSD": 0, + "inputTokens": 300, + "outputTokens": 60, + "cacheReadTokens": 0, + "cacheWriteTokens": 0 + }, + { + "name": "totally-unknown-model-xyz", + "cost": 0, + "calls": 1, + "savingsUSD": 0, + "savingsBaselineModel": "", + "estimatedCostUSD": 0, + "inputTokens": 7000, + "outputTokens": 2000, + "cacheReadTokens": 0, + "cacheWriteTokens": 0 + } + ], + "unpricedModels": [ + { + "model": "totally-unknown-model-xyz", + "calls": 1, + "tokens": 9000 + } + ], + "localModelSavings": { + "totalUSD": 0, + "calls": 0, + "byModel": [], + "byProvider": [] + }, + "providers": { + "claude": 0.53925, + "codex": 0.001365 + }, + "providerDetails": [ + { + "id": "claude", + "label": "Claude", + "cost": 0.53925, + "calls": 8, + "hasUsage": true, + "inputTokens": 33500, + "outputTokens": 4650, + "sessions": 5, + "sessionCountBasis": "partial", + "cacheReadTokens": 900000 + }, + { + "id": "codex", + "label": "Codex", + "cost": 0.001365, + "calls": 3, + "hasUsage": true, + "inputTokens": 300, + "outputTokens": 60, + "sessions": 2, + "sessionCountBasis": "partial", + "cacheReadTokens": 0 + } + ], + "topProjects": [ + { + "id": "/tmp/shared-vault", + "name": "tmp/shared-vault", + "cost": 0.47161499999999995, + "savingsUSD": 0, + "sessions": 3, + "sessionCountBasis": "partial", + "sessionDetails": [ + { + "cost": 0.47024999999999995, + "savingsUSD": 0, + "calls": 4, + "inputTokens": 11500, + "outputTokens": 2450, + "date": "2026-09-02", + "models": [ + { + "name": "Opus 4.6", + "cost": 0.44999999999999996, + "savingsUSD": 0 + }, + { + "name": "Sonnet 4.5", + "cost": 0.020250000000000004, + "savingsUSD": 0 + }, + { + "name": "totally-unknown-model-xyz", + "cost": 0, + "savingsUSD": 0 + } + ] + }, + { + "cost": 0.00091, + "savingsUSD": 0, + "calls": 2, + "inputTokens": 200, + "outputTokens": 40, + "date": "2026-09-07", + "models": [ + { + "name": "GPT-5.3 Codex", + "cost": 0.00091, + "savingsUSD": 0 + } + ] + }, + { + "cost": 0.000455, + "savingsUSD": 0, + "calls": 1, + "inputTokens": 100, + "outputTokens": 20, + "date": "2026-09-02", + "models": [ + { + "name": "GPT-5.3 Codex", + "cost": 0.000455, + "savingsUSD": 0 + } + ] + } + ] + }, + { + "id": "/tmp/alt/shared-vault", + "name": "alt/shared-vault", + "cost": 0.018000000000000002, + "savingsUSD": 0, + "sessions": 1, + "sessionCountBasis": "partial", + "sessionDetails": [ + { + "cost": 0.018000000000000002, + "savingsUSD": 0, + "calls": 1, + "inputTokens": 4000, + "outputTokens": 400, + "date": "2026-09-07", + "models": [ + { + "name": "Sonnet 4.5", + "cost": 0.018000000000000002, + "savingsUSD": 0 + } + ] + } + ] + }, + { + "id": "/tmp/CaseVault", + "name": "CaseVault", + "cost": 0.018000000000000002, + "savingsUSD": 0, + "sessions": 1, + "sessionCountBasis": "partial", + "sessionDetails": [ + { + "cost": 0.018000000000000002, + "savingsUSD": 0, + "calls": 1, + "inputTokens": 4000, + "outputTokens": 400, + "date": "2026-09-07", + "models": [ + { + "name": "Sonnet 4.5", + "cost": 0.018000000000000002, + "savingsUSD": 0 + } + ] + } + ] + }, + { + "id": "/tmp/casevault", + "name": "casevault", + "cost": 0.018000000000000002, + "savingsUSD": 0, + "sessions": 1, + "sessionCountBasis": "partial", + "sessionDetails": [ + { + "cost": 0.018000000000000002, + "savingsUSD": 0, + "calls": 1, + "inputTokens": 4000, + "outputTokens": 400, + "date": "2026-09-07", + "models": [ + { + "name": "Sonnet 4.5", + "cost": 0.018000000000000002, + "savingsUSD": 0 + } + ] + } + ] + }, + { + "id": "/tmp/other-vault", + "name": "other-vault", + "cost": 0.015, + "savingsUSD": 0, + "sessions": 1, + "sessionCountBasis": "partial", + "sessionDetails": [ + { + "cost": 0.015, + "savingsUSD": 0, + "calls": 1, + "inputTokens": 10000, + "outputTokens": 1000, + "date": "2026-09-07", + "models": [ + { + "name": "Haiku 4.5", + "cost": 0.015, + "savingsUSD": 0 + } + ] + } + ] + } + ], + "modelEfficiency": [], + "topSessions": [ + { + "project": "shared-vault", + "cost": 0.47024999999999995, + "savingsUSD": 0, + "calls": 4, + "date": "2026-09-02" + }, + { + "project": "shared-vault", + "cost": 0.018000000000000002, + "savingsUSD": 0, + "calls": 1, + "date": "2026-09-07" + }, + { + "project": "CaseVault", + "cost": 0.018000000000000002, + "savingsUSD": 0, + "calls": 1, + "date": "2026-09-07" + } + ], + "workflow": { + "corrections": 0, + "correctionRate": 0, + "medianTimeToFirstEditMs": null + }, + "topReworkedFiles": [], + "pricingCoverage": 0.9090909090909091, + "retryTax": { + "totalUSD": 0, + "retries": 0, + "editTurns": 0, + "byModel": [] + }, + "routingWaste": { + "totalSavingsUSD": 0, + "baselineModel": "", + "baselineCostPerEdit": 0, + "byModel": [] + }, + "tools": [], + "skills": [], + "subagents": [], + "mcpServers": [] + }, + "optimize": { + "findingCount": 2, + "savingsUSD": 0.027760215517241376, + "topFindings": [ + { + "title": "Shrink bash output limit", + "impact": "medium", + "savingsUSD": 0.0015197198275862067 + }, + { + "title": "1 context-heavy session", + "impact": "low", + "savingsUSD": 0.02624049568965517 + } + ] + }, + "history": { + "daily": [ + { + "date": "2026-09-02", + "cost": 0.0027050000000000004, + "savingsUSD": 0, + "calls": 2, + "inputTokens": 600, + "outputTokens": 70, + "cacheReadTokens": 0, + "cacheWriteTokens": 0, + "topModels": [ + { + "name": "Sonnet 4.5", + "cost": 0.0022500000000000003, + "savingsUSD": 0, + "calls": 1, + "inputTokens": 500, + "outputTokens": 50 + }, + { + "name": "GPT-5.3 Codex", + "cost": 0.000455, + "savingsUSD": 0, + "calls": 1, + "inputTokens": 100, + "outputTokens": 20 + } + ] + }, + { + "date": "2026-09-07", + "cost": 0.53791, + "savingsUSD": 0, + "calls": 9, + "inputTokens": 33200, + "outputTokens": 4640, + "cacheReadTokens": 900000, + "cacheWriteTokens": 0, + "topModels": [ + { + "name": "Opus 4.6", + "cost": 0.44999999999999996, + "savingsUSD": 0, + "calls": 1, + "inputTokens": 0, + "outputTokens": 0 + }, + { + "name": "Sonnet 4.5", + "cost": 0.07200000000000001, + "savingsUSD": 0, + "calls": 4, + "inputTokens": 16000, + "outputTokens": 1600 + }, + { + "name": "Haiku 4.5", + "cost": 0.015, + "savingsUSD": 0, + "calls": 1, + "inputTokens": 10000, + "outputTokens": 1000 + }, + { + "name": "GPT-5.3 Codex", + "cost": 0.00091, + "savingsUSD": 0, + "calls": 2, + "inputTokens": 200, + "outputTokens": 40 + }, + { + "name": "totally-unknown-model-xyz", + "cost": 0, + "savingsUSD": 0, + "calls": 1, + "inputTokens": 7000, + "outputTokens": 2000 + } + ] + } + ] + }, + "currency": { + "code": "USD", + "symbol": "$", + "rate": 1 + }, + "telemetrySnapshot": { + "schema": 2, + "period": "Last 7 Days", + "providerCount": 2, + "costBucket": "<1", + "models": [ + { + "name": "Opus 4.6", + "costBucket": "<1", + "turnBucket": "1-10", + "oneShotRate": -1, + "tasks": [ + { + "name": "Conversation", + "turnBucket": "1-10", + "share": 1 + } + ] + }, + { + "name": "Sonnet 4.5", + "costBucket": "<1", + "turnBucket": "1-10", + "oneShotRate": -1, + "tasks": [ + { + "name": "Conversation", + "turnBucket": "1-10", + "share": 1 + } + ] + }, + { + "name": "Haiku 4.5", + "costBucket": "<1", + "turnBucket": "1-10", + "oneShotRate": -1, + "tasks": [ + { + "name": "Conversation", + "turnBucket": "1-10", + "share": 1 + } + ] + }, + { + "name": "GPT-5.3 Codex", + "costBucket": "<1", + "turnBucket": "1-10", + "oneShotRate": -1, + "tasks": [ + { + "name": "Conversation", + "turnBucket": "1-10", + "share": 1 + } + ] + }, + { + "name": "totally-unknown-model-xyz", + "costBucket": "<1", + "turnBucket": "1-10", + "oneShotRate": -1, + "tasks": [ + { + "name": "Conversation", + "turnBucket": "1-10", + "share": 1 + } + ] + } + ], + "categories": [ + { + "name": "Conversation", + "turnBucket": "10-100", + "oneShotRate": -1, + "topModels": [ + "Sonnet 4.5", + "GPT-5.3 Codex", + "Opus 4.6" + ] + } + ], + "providers": [ + { + "name": "claude", + "costBucket": "<1" + }, + { + "name": "codex", + "costBucket": "<1" + } + ], + "mcpServers": [], + "skills": [], + "tools": [], + "sessions": { + "countBucket": "1-10", + "medianMinutesBucket": "<5" + }, + "efficiency": { + "cacheHitRate": 0.96, + "retryTaxShare": 0 + } + }, + "liveSessions": { + "windowSeconds": 600, + "sessions": [ + { + "id": "shared-sonnet", + "provider": "claude", + "project": "shared-vault", + "branch": null, + "model": "Sonnet 4.5", + "contextTokens": 550, + "contextWindow": 200000, + "startedAt": "2026-09-07T14:22:45.597Z", + "lastActivityAt": "2026-09-07T14:22:45.597Z", + "idleSeconds": 5 + }, + { + "id": "other-haiku", + "provider": "claude", + "project": "other-vault", + "branch": null, + "model": "Haiku 4.5", + "contextTokens": 11000, + "contextWindow": 200000, + "startedAt": "2026-09-07T14:22:45.597Z", + "lastActivityAt": "2026-09-07T14:22:45.597Z", + "idleSeconds": 5 + }, + { + "id": "case-1", + "provider": "claude", + "project": "casevault", + "branch": null, + "model": "Sonnet 4.5", + "contextTokens": 4400, + "contextWindow": 200000, + "startedAt": "2026-09-07T14:22:45.597Z", + "lastActivityAt": "2026-09-07T14:22:45.597Z", + "idleSeconds": 5 + }, + { + "id": "case-0", + "provider": "claude", + "project": "CaseVault", + "branch": null, + "model": "Sonnet 4.5", + "contextTokens": 4400, + "contextWindow": 200000, + "startedAt": "2026-09-07T14:22:45.597Z", + "lastActivityAt": "2026-09-07T14:22:45.597Z", + "idleSeconds": 5 + }, + { + "id": "alt-sonnet", + "provider": "claude", + "project": "shared-vault", + "branch": null, + "model": "Sonnet 4.5", + "contextTokens": 4400, + "contextWindow": 200000, + "startedAt": "2026-09-07T14:22:45.597Z", + "lastActivityAt": "2026-09-07T14:22:45.597Z", + "idleSeconds": 5 + } + ] + } +} diff --git a/dash/src/App.tsx b/dash/src/App.tsx index 14f4e7c3..abe1483d 100644 --- a/dash/src/App.tsx +++ b/dash/src/App.tsx @@ -12,7 +12,7 @@ import { type Payload, type Period, } from '@/lib/api' -import { cn, fmtNum, fmtTokens, usd } from '@/lib/utils' +import { cn, fmtNum, fmtTokens, formatSessionCount, usd } from '@/lib/utils' import { Card } from '@/components/ui/card' import { Skeleton } from '@/components/ui/skeleton' import { MetricCard } from '@/components/MetricCard' @@ -118,7 +118,7 @@ function DeviceView({ payload, isRemote, unit }: { payload?: Payload; isRemote:
- {c ? `${fmtNum(c.calls)} calls · ${fmtNum(c.sessions)} sessions` : ' '} + {c ? `${fmtNum(c.calls)} calls · ${formatSessionCount(c.sessions, c.sessionCountBasis)}` : ' '}
{c ? (unit === 'tokens' ? fmtTokens(c.inputTokens + c.outputTokens) : usd(c.cost)) : } @@ -142,7 +142,7 @@ function DeviceView({ payload, isRemote, unit }: { payload?: Payload; isRemote: sub={`in ${fmtTokens(c.inputTokens)} / out ${fmtTokens(c.outputTokens)}`} /> - + @@ -221,8 +221,8 @@ function DeviceView({ payload, isRemote, unit }: { payload?: Payload; isRemote: rows={(c?.topProjects ?? []).slice(0, 10).map((p) => ({ name: p.name, cost: usd(p.cost), - sessions: fmtNum(p.sessions), - avgCost: usd(p.avgCostPerSession), + sessions: formatSessionCount(p.sessions, p.sessionCountBasis), + avgCost: p.sessionCountBasis === 'identity' && p.avgCostPerSession != null ? usd(p.avgCostPerSession) : '—', }))} /> )} diff --git a/dash/src/lib/api.ts b/dash/src/lib/api.ts index f8da59e8..5d19514e 100644 --- a/dash/src/lib/api.ts +++ b/dash/src/lib/api.ts @@ -40,6 +40,7 @@ export type Current = { cost: number calls: number sessions: number + sessionCountBasis?: 'identity' | 'partial' oneShotRate: number | null inputTokens: number outputTokens: number @@ -50,7 +51,7 @@ export type Current = { topActivities: Array<{ name: string; cost: number; turns: number; oneShotRate: number | null }> topModels: Array<{ name: string; cost: number; calls: number; savingsUSD: number }> providers: Record - topProjects: Array<{ name: string; cost: number; sessions: number; avgCostPerSession: number }> + topProjects: Array<{ name: string; cost: number; sessions: number; avgCostPerSession?: number; sessionCountBasis?: 'identity' | 'partial' }> tools: Array<{ name: string; calls: number }> subagents: Array<{ name: string; calls: number; cost: number }> skills: Array<{ name: string; turns: number; cost: number }> diff --git a/dash/src/lib/utils.ts b/dash/src/lib/utils.ts index 1a6de0db..3fc45609 100644 --- a/dash/src/lib/utils.ts +++ b/dash/src/lib/utils.ts @@ -27,6 +27,15 @@ export function fmtNum(n: number | undefined | null): string { return v.toLocaleString() } +export function formatSessionCount(sessions: number, basis?: 'identity' | 'partial'): string { + if (basis !== 'identity') { + if (sessions <= 0) return 'Session count unavailable' + return sessions === 1 ? 'At least 1 session' : `At least ${sessions.toLocaleString()} sessions` + } + if (sessions === 1) return '1 session' + return `${sessions.toLocaleString()} sessions` +} + export function compactUsd(n: number): string { if (!isFinite(n)) return '$0' const sign = n < 0 ? '-' : '' diff --git a/gnome/indicator.js b/gnome/indicator.js index 6805c4d8..a1464f8a 100644 --- a/gnome/indicator.js +++ b/gnome/indicator.js @@ -13,6 +13,14 @@ const TOP_ACTIVITIES = 10; const CHART_HEIGHT = 52; const BAR_TRACK_WIDTH = 240; +function formatSessionCount(sessions, basis) { + if (basis !== 'identity') { + if (!sessions) return 'Session count unavailable'; + return sessions === 1 ? 'At least 1 session' : `At least ${sessions} sessions`; + } + return sessions === 1 ? '1 session' : `${sessions} sessions`; +} + const PERIODS = [ { id: 'today', label: 'Today' }, { id: 'week', label: '7 Days' }, @@ -587,7 +595,7 @@ class CodeBurnIndicator extends PanelMenu.Button { const calls = Number(current.calls ?? 0); const sessions = Number(current.sessions ?? 0); - const metaParts = [`${calls.toLocaleString()} calls`, `${sessions} sessions`]; + const metaParts = [`${calls.toLocaleString()} calls`, formatSessionCount(sessions, current.sessionCountBasis)]; if (savings > 0) metaParts.push(`saved ${this._fmt(savings)}`); this._heroMeta.set_text(metaParts.join(' ')); diff --git a/mac/Sources/CodeBurnMenubar/Data/MenubarPayload.swift b/mac/Sources/CodeBurnMenubar/Data/MenubarPayload.swift index 4165ddc7..9ca21a15 100644 --- a/mac/Sources/CodeBurnMenubar/Data/MenubarPayload.swift +++ b/mac/Sources/CodeBurnMenubar/Data/MenubarPayload.swift @@ -281,6 +281,9 @@ struct CurrentBlock: Codable, Sendable { let cost: Double let calls: Int let sessions: Int + /// How `sessions` was derived. Nil on older payloads. `identity` is exact; + /// `partial` is a lower bound. + var sessionCountBasis: String? = nil let oneShotRate: Double? let inputTokens: Int let outputTokens: Int @@ -328,7 +331,7 @@ struct PullRequestRow: Codable, Sendable { extension CurrentBlock { enum CodingKeys: String, CodingKey { - case label, cost, calls, sessions, oneShotRate, inputTokens, outputTokens, + case label, cost, calls, sessions, sessionCountBasis, oneShotRate, inputTokens, outputTokens, cacheHitPercent, codexCredits, topActivities, topModels, localModelSavings, providers, providerDetails, topProjects, modelEfficiency, topSessions, retryTax, routingWaste, tools, skills, subagents, mcpServers, @@ -340,6 +343,7 @@ extension CurrentBlock { cost = try c.decode(Double.self, forKey: .cost) calls = try c.decode(Int.self, forKey: .calls) sessions = try c.decode(Int.self, forKey: .sessions) + sessionCountBasis = try c.decodeIfPresent(String.self, forKey: .sessionCountBasis) oneShotRate = try c.decodeIfPresent(Double.self, forKey: .oneShotRate) inputTokens = try c.decode(Int.self, forKey: .inputTokens) outputTokens = try c.decode(Int.self, forKey: .outputTokens) @@ -378,6 +382,7 @@ struct ProviderDetail: Codable, Sendable { let inputTokens: Int? let outputTokens: Int? let sessions: Int? + var sessionCountBasis: String? = nil init( id: String, @@ -387,7 +392,8 @@ struct ProviderDetail: Codable, Sendable { hasUsage: Bool, inputTokens: Int? = nil, outputTokens: Int? = nil, - sessions: Int? = nil + sessions: Int? = nil, + sessionCountBasis: String? = nil ) { self.id = id self.label = label @@ -397,10 +403,11 @@ struct ProviderDetail: Codable, Sendable { self.inputTokens = inputTokens self.outputTokens = outputTokens self.sessions = sessions + self.sessionCountBasis = sessionCountBasis } private enum CodingKeys: String, CodingKey { - case id, label, cost, calls, hasUsage, inputTokens, outputTokens, sessions + case id, label, cost, calls, hasUsage, inputTokens, outputTokens, sessions, sessionCountBasis } init(from decoder: Decoder) throws { @@ -419,6 +426,7 @@ struct ProviderDetail: Codable, Sendable { inputTokens = try c.decodeIfPresent(Int.self, forKey: .inputTokens) outputTokens = try c.decodeIfPresent(Int.self, forKey: .outputTokens) sessions = try c.decodeIfPresent(Int.self, forKey: .sessions) + sessionCountBasis = try c.decodeIfPresent(String.self, forKey: .sessionCountBasis) } } @@ -550,7 +558,8 @@ struct ProjectEntry: Codable, Sendable { let cost: Double let savingsUSD: Double let sessions: Int - let avgCostPerSession: Double + let avgCostPerSession: Double? + let sessionCountBasis: String? let sessionDetails: [SessionDetailEntry] init(from decoder: Decoder) throws { @@ -559,12 +568,13 @@ struct ProjectEntry: Codable, Sendable { cost = try c.decode(Double.self, forKey: .cost) savingsUSD = try c.decodeIfPresent(Double.self, forKey: .savingsUSD) ?? 0 sessions = try c.decode(Int.self, forKey: .sessions) - avgCostPerSession = try c.decode(Double.self, forKey: .avgCostPerSession) + avgCostPerSession = try c.decodeIfPresent(Double.self, forKey: .avgCostPerSession) + sessionCountBasis = try c.decodeIfPresent(String.self, forKey: .sessionCountBasis) sessionDetails = try c.decodeIfPresent([SessionDetailEntry].self, forKey: .sessionDetails) ?? [] } private enum CodingKeys: String, CodingKey { - case name, cost, savingsUSD, sessions, avgCostPerSession, sessionDetails + case name, cost, savingsUSD, sessions, avgCostPerSession, sessionCountBasis, sessionDetails } } diff --git a/mac/Sources/CodeBurnMenubar/SessionCountLabel.swift b/mac/Sources/CodeBurnMenubar/SessionCountLabel.swift new file mode 100644 index 00000000..9a42864a --- /dev/null +++ b/mac/Sources/CodeBurnMenubar/SessionCountLabel.swift @@ -0,0 +1,38 @@ +/// Shared session-count phrasing. Keep in lockstep with `src/session-count-label.ts`. +enum SessionCountLabel { + static let help = "Older session logs may be unavailable." + /// Combined-scope counts are a per-device numeric sum with no shared identity. + /// Do not show that sum as unique or as a lower bound. + static let combinedHelp = "Session identities are unavailable across devices." + static let combinedText = "Session count unavailable" + + static func isExact(_ basis: String?) -> Bool { + basis == "identity" + } + + static func text(sessions: Int, basis: String?) -> String { + if !isExact(basis) { + if sessions <= 0 { return "Session count unavailable" } + return sessions == 1 ? "At least 1 session" : "At least \(sessions) sessions" + } + return sessions == 1 ? "1 session" : "\(sessions) sessions" + } + + static func compact(sessions: Int, basis: String?) -> String { + if !isExact(basis) { + if sessions <= 0 { return "Unavailable" } + return "At least \(sessions)" + } + return "\(sessions)" + } + + static func averageText(_ value: Double?, basis: String?, format: (Double) -> String) -> String { + guard isExact(basis), let value, value.isFinite else { return "—" } + return format(value) + } + + static func helpText(combined: Bool, basis: String?) -> String { + if combined { return combinedHelp } + return isExact(basis) ? "" : help + } +} diff --git a/mac/Sources/CodeBurnMenubar/Views/HeatmapSection.swift b/mac/Sources/CodeBurnMenubar/Views/HeatmapSection.swift index b43f6bc9..2e7c7801 100644 --- a/mac/Sources/CodeBurnMenubar/Views/HeatmapSection.swift +++ b/mac/Sources/CodeBurnMenubar/Views/HeatmapSection.swift @@ -1041,9 +1041,13 @@ private struct PulseInsight: View { PulseTile(label: "1-shot", value: oneShotText, color: oneShotColor) PulseTile( label: "Cost / session", - value: payload.current.sessions > 0 - ? (payload.current.cost / Double(payload.current.sessions)).asCompactCurrency() - : "—", + value: SessionCountLabel.averageText( + SessionCountLabel.isExact(payload.current.sessionCountBasis) && payload.current.sessions > 0 + ? payload.current.cost / Double(payload.current.sessions) + : nil, + basis: payload.current.sessionCountBasis, + format: { $0.asCompactCurrency() } + ), color: .secondary ) } @@ -1212,7 +1216,7 @@ private struct StatsInsight: View { .frame(maxWidth: .infinity, alignment: .leading) VStack(alignment: .leading, spacing: 8) { - StatRow(label: "Sessions today", value: "\(payload.current.sessions)") + StatRow(label: "Sessions today", value: SessionCountLabel.text(sessions: payload.current.sessions, basis: payload.current.sessionCountBasis)) StatRow(label: "Calls today", value: payload.current.calls.asThousandsSeparated()) StatRow(label: "Current streak", value: stats.currentStreak) StatRow(label: "Longest streak", value: stats.longestStreak) @@ -1376,39 +1380,17 @@ private struct TopProjectsList: View { ForEach(Array(top.enumerated()), id: \.offset) { idx, project in let expandKey = "\(idx):\(project.name)" let isOpen = expanded == expandKey + let canExpand = !project.sessionDetails.isEmpty VStack(alignment: .leading, spacing: 0) { - HStack(spacing: 6) { - Image(systemName: "chevron.right") - .font(.system(size: 7, weight: .bold)) - .foregroundStyle(.quaternary) - .rotationEffect(.degrees(isOpen ? 90 : 0)) - Text(projectDisplayName(project.name)) - .font(.system(size: 10.5, weight: .medium)) - .foregroundStyle(.primary) - .lineLimit(1) - Spacer() - Text("\(project.sessions) sess") - .font(.system(size: 9.5)) - .foregroundStyle(.quaternary) - Text(project.cost.asCompactCurrency()) - .font(.codeMono(size: 10.5, weight: .semibold)) - .foregroundStyle(.secondary) - .monospacedDigit() - RoundedRectangle(cornerRadius: 2) - .fill(Theme.brandAccent.opacity(0.5)) - .frame( - width: max(2, 40 * CGFloat(project.cost / max(maxCost, 0.01))), - height: 6 - ) - } - .contentShape(Rectangle()) - .onTapGesture { - withAnimation(.spring(response: 0.3, dampingFraction: 0.85)) { - expanded = isOpen ? nil : expandKey - } - } + projectRowHeader( + project: project, + isOpen: isOpen, + canExpand: canExpand, + maxCost: maxCost, + expandKey: expandKey + ) - if isOpen, !project.sessionDetails.isEmpty { + if isOpen, canExpand { SessionDetailsList(sessions: project.sessionDetails) .padding(.top, 6) .padding(.leading, 14) @@ -1417,6 +1399,74 @@ private struct TopProjectsList: View { } } } + + @ViewBuilder + private func projectRowHeader( + project: ProjectEntry, + isOpen: Bool, + canExpand: Bool, + maxCost: Double, + expandKey: String + ) -> some View { + let header = HStack(spacing: 6) { + Image(systemName: "chevron.right") + .font(.system(size: 7, weight: .bold)) + .foregroundStyle(.quaternary) + .rotationEffect(.degrees(isOpen ? 90 : 0)) + .opacity(canExpand ? 1 : 0) + Text(projectDisplayName(project.name)) + .font(.system(size: 10.5, weight: .medium)) + .foregroundStyle(.primary) + .lineLimit(1) + Spacer() + Text(SessionCountLabel.isExact(project.sessionCountBasis) + ? "\(project.sessions) sess" + : SessionCountLabel.text(sessions: project.sessions, basis: project.sessionCountBasis)) + .font(.system(size: 9.5)) + .foregroundStyle(.quaternary) + Text(project.cost.asCompactCurrency()) + .font(.codeMono(size: 10.5, weight: .semibold)) + .foregroundStyle(.secondary) + .monospacedDigit() + RoundedRectangle(cornerRadius: 2) + .fill(Theme.brandAccent.opacity(0.5)) + .frame( + width: max(2, 40 * CGFloat(project.cost / max(maxCost, 0.01))), + height: 6 + ) + } + .contentShape(Rectangle()) + .frame(maxWidth: .infinity, alignment: .leading) + + if canExpand { + Button { + withAnimation(.spring(response: 0.3, dampingFraction: 0.85)) { + expanded = isOpen ? nil : expandKey + } + } label: { + header + } + .buttonStyle(.plain) + .accessibilityLabel(projectRowAccessibilityLabel(project, isOpen: isOpen, canExpand: true)) + .accessibilityHint(isOpen ? "Hides session details" : "Shows session details") + } else { + header + .accessibilityElement(children: .combine) + .accessibilityLabel(projectRowAccessibilityLabel(project, isOpen: false, canExpand: false)) + } + } + + private func projectRowAccessibilityLabel(_ project: ProjectEntry, isOpen: Bool, canExpand: Bool) -> String { + var parts = [ + project.name, + SessionCountLabel.text(sessions: project.sessions, basis: project.sessionCountBasis), + project.cost.asCompactCurrency() + ] + if canExpand { + parts.append(isOpen ? "Expanded" : "Collapsed") + } + return parts.joined(separator: ", ") + } } private struct SessionDetailsList: View { @@ -1432,7 +1482,7 @@ private struct SessionDetailsList: View { .foregroundStyle(.primary) .monospacedDigit() .frame(width: 52, alignment: .trailing) - Text(" \(sess.calls) calls") + Text(" \(sess.calls) \(sess.calls == 1 ? "call" : "calls")") .font(.system(size: 9)) .foregroundStyle(.quaternary) Spacer() @@ -1691,8 +1741,8 @@ private struct AllStats { activeDaysFraction: activeDaysFraction, mostActiveDay: mostActiveDay, peakDaySpend: peakDaySpend, - currentStreak: currentStreak == 0 ? "—" : "\(currentStreak) days", - longestStreak: longestStreak == 0 ? "—" : "\(longestStreak) days", + currentStreak: currentStreak == 0 ? "—" : (currentStreak == 1 ? "1 day" : "\(currentStreak) days"), + longestStreak: longestStreak == 0 ? "—" : (longestStreak == 1 ? "1 day" : "\(longestStreak) days"), lifetimeTotal: lifetimeTotal, historyDayCount: history.count ) diff --git a/mac/Sources/CodeBurnMenubar/Views/HeroSection.swift b/mac/Sources/CodeBurnMenubar/Views/HeroSection.swift index e05adfec..4d78b7de 100644 --- a/mac/Sources/CodeBurnMenubar/Views/HeroSection.swift +++ b/mac/Sources/CodeBurnMenubar/Views/HeroSection.swift @@ -41,14 +41,17 @@ struct HeroSection: View { .monospacedDigit() .foregroundStyle(.tertiary) } else { - Text("\(totals.calls.asThousandsSeparated()) calls") + Text("\(totals.calls.asThousandsSeparated()) \(totals.calls == 1 ? "call" : "calls")") .font(.system(size: 11)) .monospacedDigit() .foregroundStyle(.secondary) - Text("\(totals.sessions) sessions") + Text(combinedUsage != nil + ? SessionCountLabel.combinedText + : SessionCountLabel.text(sessions: totals.sessions, basis: totals.sessionCountBasis)) .font(.system(size: 10.5)) .monospacedDigit() .foregroundStyle(.tertiary) + .help(SessionCountLabel.helpText(combined: combinedUsage != nil, basis: totals.sessionCountBasis)) } } } @@ -154,14 +157,16 @@ struct HeroTotals: Equatable { let cost: Double let calls: Int let sessions: Int + let sessionCountBasis: String? let inputTokens: Int let outputTokens: Int let totalTokens: Int - init(cost: Double, calls: Int, sessions: Int, inputTokens: Int, outputTokens: Int, totalTokens: Int) { + init(cost: Double, calls: Int, sessions: Int, inputTokens: Int, outputTokens: Int, totalTokens: Int, sessionCountBasis: String? = nil) { self.cost = cost self.calls = calls self.sessions = sessions + self.sessionCountBasis = sessionCountBasis self.inputTokens = inputTokens self.outputTokens = outputTokens self.totalTokens = totalTokens @@ -169,6 +174,8 @@ struct HeroTotals: Equatable { init(payload: MenubarPayload, activeScope: MenubarScope) { if activeScope == .combined, let combined = payload.combined?.combined { + // Keep the numeric wire sum for compatibility. Combined-scope UI + // must not present it as a unique or lower-bound count. self.init( cost: combined.cost, calls: combined.calls, @@ -187,7 +194,8 @@ struct HeroTotals: Equatable { sessions: current.sessions, inputTokens: current.inputTokens, outputTokens: current.outputTokens, - totalTokens: current.inputTokens + current.outputTokens + totalTokens: current.inputTokens + current.outputTokens, + sessionCountBasis: current.sessionCountBasis ) } } diff --git a/mac/Tests/CodeBurnMenubarTests/MenubarPayloadCombinedTests.swift b/mac/Tests/CodeBurnMenubarTests/MenubarPayloadCombinedTests.swift index 3b616cc0..5542ac19 100644 --- a/mac/Tests/CodeBurnMenubarTests/MenubarPayloadCombinedTests.swift +++ b/mac/Tests/CodeBurnMenubarTests/MenubarPayloadCombinedTests.swift @@ -29,6 +29,8 @@ struct MenubarPayloadCombinedTests { #expect(totals.inputTokens == 1000) #expect(totals.outputTokens == 500) #expect(totals.totalTokens == 1500) + #expect(totals.sessions == 3) + #expect(SessionCountLabel.combinedText == "Session count unavailable") } @Test("combined block is nil when absent") diff --git a/mac/Tests/CodeBurnMenubarTests/SessionCountLabelTests.swift b/mac/Tests/CodeBurnMenubarTests/SessionCountLabelTests.swift new file mode 100644 index 00000000..228b7621 --- /dev/null +++ b/mac/Tests/CodeBurnMenubarTests/SessionCountLabelTests.swift @@ -0,0 +1,65 @@ +import Foundation +import Testing +@testable import CodeBurnMenubar + +@Suite("Session count labels and payload decode") +struct SessionCountLabelTests { + @Test("lower-bound phrasing never names occupancy or cache") + func phrasing() { + #expect(SessionCountLabel.text(sessions: 3, basis: "partial") == "At least 3 sessions") + #expect(SessionCountLabel.text(sessions: 1, basis: "partial") == "At least 1 session") + #expect(SessionCountLabel.text(sessions: 0, basis: "partial") == "Session count unavailable") + #expect(SessionCountLabel.text(sessions: 1, basis: "identity") == "1 session") + #expect(SessionCountLabel.text(sessions: 2, basis: nil) == "At least 2 sessions") + #expect(!SessionCountLabel.text(sessions: 3, basis: "partial").localizedCaseInsensitiveContains("occupancy")) + #expect(!SessionCountLabel.text(sessions: 3, basis: "partial").localizedCaseInsensitiveContains("cache")) + #expect(SessionCountLabel.text(sessions: 0, basis: "identity") == "0 sessions") + } + + @Test("combined-scope copy never presents a device sum as a count") + func combinedScopeUnavailable() { + #expect(SessionCountLabel.combinedText == "Session count unavailable") + #expect(SessionCountLabel.combinedHelp == "Session identities are unavailable across devices.") + #expect(!SessionCountLabel.combinedText.hasPrefix("At least")) + #expect(SessionCountLabel.helpText(combined: true, basis: "identity") == SessionCountLabel.combinedHelp) + #expect(SessionCountLabel.helpText(combined: true, basis: nil) == SessionCountLabel.combinedHelp) + #expect(SessionCountLabel.helpText(combined: false, basis: "identity") == "") + #expect(SessionCountLabel.text(sessions: 0, basis: "identity") == "0 sessions") + #expect(SessionCountLabel.text(sessions: 3, basis: "partial") == "At least 3 sessions") + } + + @Test("older payloads with a required numeric average still decode") + func legacyAverageDecodes() throws { + let json = """ + {"name":"vault","cost":4,"savingsUSD":0,"sessions":2,"avgCostPerSession":2,"sessionDetails":[]} + """.data(using: .utf8)! + let row = try JSONDecoder().decode(ProjectEntry.self, from: json) + #expect(row.sessions == 2) + #expect(row.avgCostPerSession == 2) + #expect(row.sessionCountBasis == nil) + #expect(SessionCountLabel.averageText(row.avgCostPerSession, basis: row.sessionCountBasis, format: { _ in "$2" }) == "—") + } + + @Test("partial project omits average and keeps the numeric sessions field") + func partialOmitsAverage() throws { + let json = """ + {"name":"vault","cost":4,"savingsUSD":0,"sessions":3,"sessionCountBasis":"partial","sessionDetails":[]} + """.data(using: .utf8)! + let row = try JSONDecoder().decode(ProjectEntry.self, from: json) + #expect(row.sessions == 3) + #expect(row.avgCostPerSession == nil) + #expect(row.sessionCountBasis == "partial") + #expect(SessionCountLabel.text(sessions: row.sessions, basis: row.sessionCountBasis) == "At least 3 sessions") + } + + @Test("headline basis is optional on older current blocks") + func currentBlockLegacy() throws { + let json = """ + {"label":"Last 7 days","cost":4,"calls":4,"sessions":1,"oneShotRate":null,"inputTokens":0,"outputTokens":0,"cacheHitPercent":0,"topActivities":[],"topModels":[],"localModelSavings":{"totalUSD":0,"calls":0,"byModel":[],"byProvider":[]},"providers":{},"topProjects":[],"modelEfficiency":[],"topSessions":[],"retryTax":{"totalUSD":0,"retries":0,"editTurns":0,"byModel":[]},"routingWaste":{"totalSavingsUSD":0,"baselineModel":"","baselineCostPerEdit":0,"byModel":[]},"tools":[],"skills":[],"subagents":[],"mcpServers":[]} + """.data(using: .utf8)! + let current = try JSONDecoder().decode(CurrentBlock.self, from: json) + #expect(current.sessions == 1) + #expect(current.sessionCountBasis == nil) + #expect(SessionCountLabel.text(sessions: current.sessions, basis: current.sessionCountBasis) == "At least 1 session") + } +} diff --git a/src/dashboard.tsx b/src/dashboard.tsx index 8363f5cc..3ecb340e 100644 --- a/src/dashboard.tsx +++ b/src/dashboard.tsx @@ -5,6 +5,7 @@ import React, { Fragment, useState, useCallback, useEffect, useLayoutEffect, use import { render, Box, Text, measureElement, useInput, useApp, useWindowSize, type DOMElement, type Instance, type RenderOptions } from 'ink' import { CATEGORY_LABELS, type DateRange, type ProjectSummary, type TaskCategory } from './types.js' import { formatCost, formatTokens, markEstimated, carriedCostNote } from './format.js' +import { formatSessionCount } from './session-count-label.js' import { aggregateModelEfficiency } from './model-efficiency.js' import { parseAllSessions, filterProjectsByDateRange, filterProjectsByName, setInteractiveScanUI, withSinglePassParse, withColdFirstPaintFloor, filesParsedFromSourceCount, isCompleteSessionSnapshotAvailable } from './parser.js' import { findUnpricedModels, isExpectedFreeModel, loadPricing } from './models.js' @@ -361,7 +362,8 @@ export type DurableOverview = { savingsUSD: number calls: number sessions: number - inputTokens: number + sessionCountBasis?: 'identity' | 'partial' + inputTokens: number, outputTokens: number cacheReadTokens: number cacheWriteTokens: number @@ -394,6 +396,7 @@ async function computeDurableOverview( savingsUSD: data.savingsUSD, calls: data.calls, sessions: data.sessions, + sessionCountBasis: data.sessionCountBasis, inputTokens: data.inputTokens, outputTokens: data.outputTokens, cacheReadTokens: data.cacheReadTokens, @@ -617,8 +620,8 @@ function Overview({ projects, label, width, planUsages, durable }: { projects: P cost {totalCalls.toLocaleString()} calls - {String(totalSessions)} - sessions + {durable ? formatSessionCount(totalSessions, durable.sessionCountBasis) : `${totalSessions.toLocaleString()} sessions`} + {cacheHit.toFixed(1)}% cache hit diff --git a/src/main.ts b/src/main.ts index 6c6a11f3..8563b0f9 100644 --- a/src/main.ts +++ b/src/main.ts @@ -999,6 +999,7 @@ program savingsUSD: durable.data.savingsUSD, calls: durable.data.calls, sessions: durable.data.sessions, + sessionCountBasis: durable.data.sessionCountBasis, inputTokens: durable.data.inputTokens, outputTokens: durable.data.outputTokens, cacheReadTokens: durable.data.cacheReadTokens, diff --git a/src/mcp/redact.ts b/src/mcp/redact.ts index fc9b85cb..3527362b 100644 --- a/src/mcp/redact.ts +++ b/src/mcp/redact.ts @@ -42,6 +42,7 @@ export function redactProjectNames(payload: MenubarPayload, includeNames: boolea topProjects: payload.current.topProjects.map(p => ({ ...p, name: pseudonym(p.name), + ...(p.id ? { id: pseudonym(p.id) } : {}), sessionDetails: p.sessionDetails ? redactSessionDetails(p.sessionDetails) : [], })), topSessions: payload.current.topSessions.map(s => ({ ...s, project: pseudonym(s.project) })), diff --git a/src/mcp/tables.ts b/src/mcp/tables.ts index c97110b9..f2ed49c8 100644 --- a/src/mcp/tables.ts +++ b/src/mcp/tables.ts @@ -1,6 +1,7 @@ import { formatCost, formatTokens, markEstimated } from '../format.js' import type { MenubarPayload } from '../menubar-json.js' import { unpricedModelHint } from '../models.js' +import { formatSessionCount } from '../session-count-label.js' const ESTIMATED_LEGEND = '_~ estimated cost (priced from estimated tokens)_' const isEstimated = (m: { estimatedCostUSD?: number }) => (m.estimatedCostUSD ?? 0) > 0 @@ -21,7 +22,7 @@ export function renderSummaryTable(p: MenubarPayload): string { const c = p.current const unpriced = c.unpricedModels ?? [] return [ - `**${c.label}** — ${formatCost(c.cost)} · ${c.calls} calls · ${c.sessions} sessions`, + `**${c.label}** — ${formatCost(c.cost)} · ${c.calls} calls · ${formatSessionCount(c.sessions, c.sessionCountBasis)}`, `cache hit ${pct(c.cacheHitPercent)} · one-shot ${oneShot(c.oneShotRate)} · in ${formatTokens(c.inputTokens)} / out ${formatTokens(c.outputTokens)}`, ...(unpriced.length > 0 ? [`⚠ ${unpriced.length} model${unpriced.length === 1 ? '' : 's'} unpriced, counted at $0: ${unpriced.map(u => `${u.model} (${u.calls} calls)`).join(', ')}. ${unpricedModelHint()}`] @@ -32,7 +33,7 @@ export function renderSummaryTable(p: MenubarPayload): string { ...(c.topModels.slice(0, 5).some(isEstimated) ? [ESTIMATED_LEGEND] : []), '', '_Top projects_', - mdTable(['Project', 'Cost', 'Sessions'], c.topProjects.slice(0, 5).map(x => [x.name, formatCost(x.cost), String(x.sessions)])), + mdTable(['Project', 'Cost', 'Sessions'], c.topProjects.slice(0, 5).map(x => [x.name, formatCost(x.cost), formatSessionCount(x.sessions, x.sessionCountBasis)])), ].join('\n') } @@ -43,7 +44,7 @@ export function renderBreakdownTable(p: MenubarPayload, by: BreakdownBy, limit: const table = mdTable(['Model', 'Cost', 'Calls'], rows.map(m => [m.name, markEstimated(formatCost(m.cost), isEstimated(m)), String(m.calls)])) return rows.some(isEstimated) ? `${table}\n\n${ESTIMATED_LEGEND}` : table } - if (by === 'project') return mdTable(['Project', 'Cost', 'Sessions'], c.topProjects.slice(0, limit).map(x => [x.name, formatCost(x.cost), String(x.sessions)])) + if (by === 'project') return mdTable(['Project', 'Cost', 'Sessions'], c.topProjects.slice(0, limit).map(x => [x.name, formatCost(x.cost), formatSessionCount(x.sessions, x.sessionCountBasis)])) if (by === 'task') return mdTable(['Task', 'Cost', 'Turns', 'One-shot'], c.topActivities.slice(0, limit).map(a => [a.name, formatCost(a.cost), String(a.turns), oneShot(a.oneShotRate)])) return mdTable(['Provider', 'Cost'], Object.entries(c.providers).sort(([, a], [, b]) => b - a).slice(0, limit).map(([name, cost]) => [name, formatCost(cost)])) } diff --git a/src/menubar-json.ts b/src/menubar-json.ts index 273e9d9a..2ac387e4 100644 --- a/src/menubar-json.ts +++ b/src/menubar-json.ts @@ -16,6 +16,10 @@ export type PeriodData = { estimatedCostUSD?: number calls: number sessions: number + /// How `sessions` was derived. `identity` is exact unique source ids with no + /// unknown-cache contribution; `partial` is a lower bound. Omitted on older + /// PeriodData producers. + sessionCountBasis?: SessionCountBasis inputTokens: number outputTokens: number cacheReadTokens: number @@ -29,7 +33,7 @@ export type PeriodData = { /// current tables (#638): their calls contribute $0 to `cost`. Optional so /// PeriodData producers that predate the field keep compiling. unpricedModels?: Array<{ model: string; calls: number; tokens: number }> - projects?: Array<{ name: string; cost: number; savingsUSD: number; sessions: number; sessionDetails?: Array<{ cost: number; savingsUSD: number; calls: number; inputTokens: number; outputTokens: number; date: string; models: Array<{ name: string; cost: number; savingsUSD: number }> }> }> + projects?: Array<{ id?: string; name: string; cost: number; savingsUSD: number; sessions: number; sessionCountBasis?: SessionCountBasis; sessionDetails?: Array<{ cost: number; savingsUSD: number; calls: number; inputTokens: number; outputTokens: number; date: string; models: Array<{ name: string; cost: number; savingsUSD: number }> }> }> modelEfficiency?: Array<{ name: string; costPerEdit: number | null; oneShotRate: number | null }> topSessions?: Array<{ project: string; cost: number; savingsUSD: number; calls: number; date: string }> /// Workflow-intelligence rollups (issue: workflow intelligence). Optional so @@ -91,6 +95,7 @@ export type ProviderCost = { outputTokens?: number /** Provider-scoped session count for the period, absent under the same rule. */ sessions?: number + sessionCountBasis?: SessionCountBasis } import type { OptimizeResult } from './optimize.js' import { getCurrency } from './currency.js' @@ -100,6 +105,7 @@ import type { ReworkedFile } from './workflow-insights.js' import type { PrRow, BranchRow } from './sessions-report.js' import type { LiveSessionsBlock } from './live-sessions.js' import { buildTelemetrySnapshot, type TelemetrySnapshot, type TelemetrySnapshotInput } from './telemetry-snapshot.js' +import { sessionCountIsExact, type SessionCountBasis } from './session-count-label.js' const TOP_ACTIVITIES_LIMIT = 20 const TOP_MODELS_LIMIT = 20 @@ -235,6 +241,8 @@ export type MenubarPayload = { cost: number calls: number sessions: number + /// How `sessions` was derived. Omitted on older producers. + sessionCountBasis?: SessionCountBasis oneShotRate: number | null inputTokens: number outputTokens: number @@ -296,13 +304,22 @@ export type MenubarPayload = { inputTokens?: number outputTokens?: number sessions?: number + sessionCountBasis?: SessionCountBasis }> topProjects: Array<{ + /// Stable identity (abs cwd when known). Optional so older PeriodData + /// producers keep compiling; renderer expand keys on `id ?? name`. + id?: string name: string cost: number savingsUSD: number sessions: number - avgCostPerSession: number + /// Present only when `sessionCountBasis` is `identity` and sessions > 0. + /// Omitted for lower-bound counts so clients cannot treat cost/count as exact. + avgCostPerSession?: number + /// How `sessions` was derived. Omitted on older producers. `identity` is + /// an exact unique count from surviving source files; `partial` is a lower bound. + sessionCountBasis?: SessionCountBasis sessionDetails: Array<{ cost: number savingsUSD: number @@ -513,6 +530,7 @@ function buildProviderDetails(providers: ProviderCost[]): MenubarPayload['curren ...(p.inputTokens === undefined ? {} : { inputTokens: p.inputTokens }), ...(p.outputTokens === undefined ? {} : { outputTokens: p.outputTokens }), ...(p.sessions === undefined ? {} : { sessions: p.sessions }), + ...(p.sessionCountBasis ? { sessionCountBasis: p.sessionCountBasis } : {}), })) } @@ -529,11 +547,15 @@ function buildTopProjects(projects: PeriodData['projects']): MenubarPayload['cur .sort((a, b) => (b.cost + b.savingsUSD) - (a.cost + a.savingsUSD)) .slice(0, TOP_PROJECTS_LIMIT) .map(p => ({ + ...(p.id ? { id: p.id } : {}), name: p.name, cost: p.cost, savingsUSD: p.savingsUSD, sessions: p.sessions, - avgCostPerSession: p.sessions > 0 ? p.cost / p.sessions : 0, + ...(sessionCountIsExact(p.sessionCountBasis) && p.sessions > 0 + ? { avgCostPerSession: p.cost / p.sessions } + : {}), + ...(p.sessionCountBasis ? { sessionCountBasis: p.sessionCountBasis } : {}), sessionDetails: (p.sessionDetails ?? []).map(s => ({ cost: s.cost, savingsUSD: s.savingsUSD, @@ -614,6 +636,7 @@ export function buildMenubarPayload( cost: current.cost, calls: current.calls, sessions: current.sessions, + ...(current.sessionCountBasis ? { sessionCountBasis: current.sessionCountBasis } : {}), oneShotRate: aggregateOneShotRate(current.categories), inputTokens: current.inputTokens, outputTokens: current.outputTokens, diff --git a/src/overview.ts b/src/overview.ts index 879c3b4d..bd53701d 100644 --- a/src/overview.ts +++ b/src/overview.ts @@ -7,6 +7,7 @@ import { formatCost as baseCost, getCurrency } from './currency.js' import { findUnpricedModels, getShortModelName, unpricedModelHint } from './models.js' import { callBillableOutputTokens, sessionBillableOutputTokens, sessionModelBillableOutputTokens } from './session-output.js' import { markEstimated } from './format.js' +import { formatSessionCount, SESSION_COUNT_HELP, type SessionCountBasis } from './session-count-label.js' import { dateKey } from './day-aggregator.js' import type { DailyEntry } from './daily-cache.js' import type { BudgetStatus, BudgetTier } from './budget.js' @@ -45,6 +46,28 @@ function projectName(p: ProjectSummary): string { return p.project.split('-').filter(Boolean).pop() || p.project } + +/** #1260: aggregate by abs path identity so /a/vault != /b/vault. */ +function projectAggKey(p: ProjectSummary): string { + const path = (p.projectPath ?? '').trim().replace(/\\/g, '/') + if (path && isAbsoluteProjectPath(path)) return path.replace(/\/+$/, '').toLowerCase() + // Codex-style stripped abs ("root/vault") still has a slash and no leading dash. + if (path.includes('/') && !path.startsWith('-')) return path.replace(/\/+$/, '').toLowerCase() + return `label:${projectName(p).toLowerCase()}` +} + +function disambiguatedProjectLabel(key: string, sample: ProjectSummary, basenameCounts: Map): string { + const base = projectName(sample) + if ((basenameCounts.get(base) ?? 0) <= 1) return base + const path = (sample.projectPath ?? '').trim().replace(/\\/g, '/').replace(/\/+$/, '') + if (path && isAbsoluteProjectPath(path)) { + const parts = path.split('/').filter(Boolean) + if (parts.length >= 2) return parts.slice(-2).join('/') + return path + } + return sample.project || base || key +} + type Col = { header: string; right?: boolean } type OverviewBudget = { tier: BudgetTier @@ -92,6 +115,7 @@ export type OverviewDurable = { savingsUSD: number calls: number sessions: number + sessionCountBasis?: SessionCountBasis inputTokens: number outputTokens: number cacheReadTokens: number @@ -127,18 +151,18 @@ export function renderOverview( const byCat = new Map() const byTool = new Map() const byDay = new Map }>() - const byProject = new Map() + const byProject = new Map() for (const p of projects) { cost += p.totalCostUSD savings += p.totalSavingsUSD calls += p.totalApiCalls sessions += p.sessions.length - const pname = projectName(p) - const pe = byProject.get(pname) ?? { cost: 0, sessions: 0 } + const pkey = projectAggKey(p) + const pe = byProject.get(pkey) ?? { cost: 0, sessions: 0, sample: p } pe.cost += p.totalCostUSD pe.sessions += p.sessions.length - byProject.set(pname, pe) + byProject.set(pkey, pe) for (const s of p.sessions) { inTok += s.totalInputTokens outTok += sessionBillableOutputTokens(s) @@ -222,7 +246,10 @@ export function renderOverview( const kv = (k: string, v: string): string => ' ' + c.dim(k.padEnd(11)) + v out.push(kv('Cost', c.bold(formatCost(cost)))) out.push(kv('Tokens', formatTokens(totalTokens) + c.dim(' (breakdown below)'))) - out.push(kv('Calls', formatCount(calls) + c.dim(' sessions ') + formatCount(sessions))) + out.push(kv('Calls', formatCount(calls) + c.dim(' ') + formatSessionCount(sessions, durable ? durable.sessionCountBasis : 'identity'))) + if (durable && durable.sessionCountBasis !== 'identity' && sessions > 0) { + out.push(kv('', c.dim(SESSION_COUNT_HELP))) + } out.push(kv('Cache hit', `${cacheHit.toFixed(1)}%`)) if (savings > 0) out.push(kv('Savings', formatCost(savings) + c.dim(' (local models)'))) const unpriced = findUnpricedModels( @@ -307,13 +334,18 @@ export function renderOverview( out.push('') } - // Top projects + // Top projects (#1260: labels disambiguate when basename collides across abs paths) const projRows = [...byProject.entries()].sort((a, b) => b[1].cost - a[1].cost).slice(0, 10) if (projRows.length) { + const basenameCounts = new Map() + for (const [, v] of projRows) { + const b = projectName(v.sample) + basenameCounts.set(b, (basenameCounts.get(b) ?? 0) + 1) + } out.push(heading('Top projects')) out.push(renderTable(c, [{ header: 'Project' }, { header: 'Cost', right: true }, { header: 'Sessions', right: true }], - projRows.map(([name, v]) => [name, formatCost(v.cost), formatCount(v.sessions)]), + projRows.map(([key, v]) => [disambiguatedProjectLabel(key, v.sample, basenameCounts), formatCost(v.cost), formatCount(v.sessions)]), )) out.push('') } diff --git a/src/parser.ts b/src/parser.ts index 8db0160c..ba618d03 100644 --- a/src/parser.ts +++ b/src/parser.ts @@ -77,9 +77,22 @@ function claudeSlugFallbackPath(dirName: string): string { return dirName } -function normalizeProjectPathKey(projectPath: string): string { +/// Drive-letter and UNC (`//server/share` after slash-normalize) are Windows +/// identity: directory case folds. A single leading slash is POSIX and does not. +function isWindowsAbsPath(slashNormalized: string): boolean { + return /^[a-zA-Z]:(\/|$)/.test(slashNormalized) || slashNormalized.startsWith('//') +} + +function foldIdentifiedWindowsPath(slashNormalized: string): string { + return isWindowsAbsPath(slashNormalized) ? slashNormalized.toLowerCase() : slashNormalized +} + +/// Cache/live grouping key for a stored cwd. Separators always normalize. +/// Identified Windows paths casefold; POSIX case is identity. +export function normalizeProjectPathKey(projectPath: string): string { const normalized = projectPath.trim().replace(/\\/g, '/') - return (normalized.replace(/\/+$/, '') || normalized).toLowerCase() + const trimmed = normalized.replace(/\/+$/, '') || normalized + return foldIdentifiedWindowsPath(trimmed) } function projectNameFromPath(projectPath: string, fallback: string): string { @@ -4221,7 +4234,12 @@ export async function parseProviderSources( } } - const projectMap = new Map() + // #1260 REVISE3: group by absolute projectPath / workingDirectory when + // available — never by display basename alone. Two Pi roots with cwd=/a/vault + // and /b/vault both display as "vault"; keying on the leaf collapsed them + // (first projectPath wins) before mergeProjectsByCrossProviderKey could see + // distinct abs identities. + const projectMap = new Map() for (const [key, { project, projectPath, workingDirectory, turns, prLinks, title, lineage, agentName, agentStartedAt }] of sessionMap) { const sessionId = key.split(':')[1] ?? key const assembledTurns = providerName === 'copilot' @@ -4242,19 +4260,28 @@ export async function parseProviderSources( // Supplementary-only sessions (e.g. a rollup with no per-turn calls) have // apiCalls 0 by design but their tokens/cost are real and must serve. if (session.apiCalls > 0 || session.totalCostUSD > 0 || session.totalInputTokens + session.totalOutputTokens + session.totalCacheReadTokens + session.totalCacheWriteTokens + session.totalReasoningTokens > 0) { - const existing = projectMap.get(project) + const absFromPath = projectPath ? normalizeAbsProjectPathKey(projectPath) : null + const absFromWd = workingDirectory ? normalizeAbsProjectPathKey(workingDirectory) : null + const absKey = absFromPath ?? absFromWd + const groupKey = absKey ? `path:${absKey}` : `label:${project}` + const resolvedPath = absFromPath ? projectPath : (absFromWd ? workingDirectory : projectPath) + const existing = projectMap.get(groupKey) if (existing) { existing.sessions.push(session) - if (!existing.projectPath && projectPath) existing.projectPath = projectPath + if (absFromPath && !normalizeAbsProjectPathKey(existing.projectPath ?? '')) { + existing.projectPath = projectPath + } else if (!existing.projectPath && resolvedPath) { + existing.projectPath = resolvedPath + } } else { - projectMap.set(project, { projectPath, sessions: [session] }) + projectMap.set(groupKey, { project, projectPath: resolvedPath, sessions: [session] }) } } } const projects: ProjectSummary[] = [] - for (const [dirName, { projectPath, sessions }] of projectMap) { - projects.push(summarizeProject(dirName, projectPath ?? unsanitizePath(dirName), sessions)) + for (const { project, projectPath, sessions } of projectMap.values()) { + projects.push(summarizeProject(project, projectPath ?? unsanitizePath(project), sessions)) } return projects @@ -4573,31 +4600,152 @@ export function filterProjectsByDays(projects: ProjectSummary[], days: Set { - const crossProviderKey = (p: ProjectSummary): string => { - const path = p.projectPath.replace(/\\/g, '/').replace(/^\/+/, '').toLowerCase() - return path.includes('/') ? path : p.project.toLowerCase() +// verification). totalSavingsUSD is summed with cost/calls. totalProxiedCostUSD +// is re-derived after the merge rather than summed here. +// +// #1260: providers sanitize the same absolute cwd differently (-root-vault / +// root-vault / vault). Prefer absolute projectPath (or session.workingDirectory) +// as the merge key; attach slug/basename-only rows only when they uniquely match +// one absolute path. Ambiguous basenames across distinct parents stay separate. +// POSIX path case is identity: /a/Vault and /a/vault are two keys. Identified +// Windows drive/UNC paths still casefold (C:\\Work\\Vault ≡ c:/work/vault). +// Lowercased labels are matching hints only — two path keys sharing a hint +// stay unattached. +export function normalizeAbsProjectPathKey(projectPath: string): string | null { + const raw = projectPath.trim().replace(/\\/g, '/') + if (!raw) return null + // Absolute POSIX, Windows drive, or Codex-style stripped abs ("root/vault"). + const looksAbs = raw.startsWith('/') || /^[a-zA-Z]:\//.test(raw) || (raw.includes('/') && !raw.startsWith('-')) + if (!looksAbs) return null + const folded = foldIdentifiedWindowsPath(raw) + const stripped = folded.replace(/^\/+/, '').replace(/\/+$/, '') + return stripped || null +} + +function sanitizePathAsLabel(absKey: string): string { + return absKey.replace(/\//g, '-') +} + +function labelAliases(project: string): string[] { + const raw = project.trim().replace(/\\/g, '/').toLowerCase() + if (!raw) return [] + const noLeadDash = raw.replace(/^-+/, '') + return [...new Set([raw, noLeadDash].filter(Boolean))] +} + +function foldInto(existing: ProjectSummary, p: ProjectSummary): void { + existing.sessions.push(...p.sessions) + if (p.subagentAnchors?.length) existing.subagentAnchors = [...(existing.subagentAnchors ?? []), ...p.subagentAnchors] + existing.totalCostUSD += p.totalCostUSD + existing.totalSavingsUSD = (existing.totalSavingsUSD ?? 0) + (p.totalSavingsUSD ?? 0) + existing.totalEstimatedCostUSD = (existing.totalEstimatedCostUSD ?? 0) + (p.totalEstimatedCostUSD ?? 0) + existing.totalApiCalls += p.totalApiCalls +} + +export function crossProviderProjectKey(p: ProjectSummary): string { + const fromPath = normalizeAbsProjectPathKey(p.projectPath) + if (fromPath) return `path:${fromPath}` + const wd = p.sessions.map(s => s.workingDirectory).find(w => typeof w === 'string' && w.trim()) + if (wd) { + const fromWd = normalizeAbsProjectPathKey(wd) + if (fromWd) return `path:${fromWd}` } - const mergedMap = new Map() + const aliases = labelAliases(p.project) + return `label:${aliases[0] ?? p.project.toLowerCase()}` +} + +const SANITIZED_COLLISION = '__collision__' + +function registerSanitizedLabel( + pathBySanitized: Map, + sanitizedMembers: Map>, + label: string, + key: string, +): void { + const members = sanitizedMembers.get(label) ?? new Set() + members.add(key) + sanitizedMembers.set(label, members) + const prev = pathBySanitized.get(label) + if (prev === undefined) { + pathBySanitized.set(label, key) + return + } + if (prev !== key) pathBySanitized.set(label, SANITIZED_COLLISION) +} + +export function mergeProjectsByCrossProviderKey(projects: ProjectSummary[]): Map { + const pathProjects = new Map() + const pathBySanitized = new Map() + const sanitizedMembers = new Map>() + const pathByBasename = new Map() + const deferred: ProjectSummary[] = [] + for (const p of projects) { - const key = crossProviderKey(p) - const existing = mergedMap.get(key) + const key = crossProviderProjectKey(p) + if (!key.startsWith('path:')) { + deferred.push(p) + continue + } + const abs = key.slice('path:'.length) + const existing = pathProjects.get(key) if (existing) { - existing.sessions.push(...p.sessions) - if (p.subagentAnchors?.length) existing.subagentAnchors = [...(existing.subagentAnchors ?? []), ...p.subagentAnchors] - existing.totalCostUSD += p.totalCostUSD - existing.totalEstimatedCostUSD = (existing.totalEstimatedCostUSD ?? 0) + (p.totalEstimatedCostUSD ?? 0) - existing.totalApiCalls += p.totalApiCalls + foldInto(existing, p) + if (normalizeAbsProjectPathKey(p.projectPath) && !normalizeAbsProjectPathKey(existing.projectPath)) { + existing.projectPath = p.projectPath + existing.project = p.project + } } else { - mergedMap.set(key, { ...p }) + pathProjects.set(key, { ...p }) + const sanitized = sanitizePathAsLabel(abs).toLowerCase() + registerSanitizedLabel(pathBySanitized, sanitizedMembers, sanitized, key) + registerSanitizedLabel(pathBySanitized, sanitizedMembers, `-${sanitized}`, key) + const base = abs.split('/').filter(Boolean).pop() + if (base) { + const hint = base.toLowerCase() + const bucket = pathByBasename.get(hint) ?? [] + bucket.push(key) + pathByBasename.set(hint, bucket) + } } } + + const labelOnly = new Map() + for (const p of deferred) { + // Collect ALL candidates from sanitized + basename maps across aliases. + // On sanitized COLLISION, retain the full member set (do not ignore collision + // so a weaker basename unique-hit can still attach). Attach only when exactly + // one path key remains; otherwise stay label-only. + const candidates = new Set() + for (const alias of labelAliases(p.project)) { + const viaSanitized = pathBySanitized.get(alias) + if (viaSanitized === SANITIZED_COLLISION) { + const members = sanitizedMembers.get(alias) + if (members) for (const m of members) candidates.add(m) + } else if (viaSanitized) { + candidates.add(viaSanitized) + } + const bases = pathByBasename.get(alias) + if (bases) for (const b of bases) candidates.add(b) + } + if (candidates.size === 1) { + const attach = [...candidates][0]! + foldInto(pathProjects.get(attach)!, p) + continue + } + // size === 0: no match; size > 1: ambiguous (sanitized collision, multi-parent, …) + const labelKey = `label:${labelAliases(p.project)[0] ?? p.project.toLowerCase()}` + const existing = labelOnly.get(labelKey) + if (existing) foldInto(existing, p) + else labelOnly.set(labelKey, { ...p }) + } + + const mergedMap = new Map() + for (const [k, v] of pathProjects) mergedMap.set(k, v) + for (const [k, v] of labelOnly) mergedMap.set(k, v) return mergedMap } + function summaryProvider(session: SessionSummary): string { return session.turns.flatMap(t => t.assistantCalls)[0]?.provider ?? 'unknown' } diff --git a/src/providers/pi.ts b/src/providers/pi.ts index a81ed7d3..e03914a8 100644 --- a/src/providers/pi.ts +++ b/src/providers/pi.ts @@ -107,6 +107,12 @@ function getOmpSessionsDir(override?: string): string { // pathological run of blank/junk lines). const MAX_HEADER_LINES_SCANNED = 20 +function looksAbsolutePath(value: string): boolean { + const trimmed = value.trim() + if (!trimmed) return false + return trimmed.startsWith('/') || /^[a-zA-Z]:[\\/]/.test(trimmed) +} + async function readSessionEntry(filePath: string): Promise { let linesScanned = 0 for await (const line of readSessionLines(filePath)) { @@ -149,11 +155,17 @@ async function discoverSessionsInDir(sessionsDir: string, providerName: string): const addSession = async (filePath: string, agentName?: string): Promise => { const entry = await readSessionEntry(filePath) if (!entry) return - const cwd = entry.cwd ?? dirName + // Prefer the session header cwd when present. Keep basename(project) for + // display, but retain the absolute cwd on sourcePath so parse/grouping + // never have to infer identity from the sole observed leaf name (#1260). + const rawCwd = typeof entry.cwd === 'string' ? entry.cwd.trim() : '' + const cwd = rawCwd || dirName + const absCwd = looksAbsolutePath(cwd) ? cwd : undefined sources.push({ path: filePath, - project: basename(cwd), + project: basename(cwd) || cwd, provider: providerName, + ...(absCwd ? { sourcePath: absCwd } : {}), ...(agentName ? { agentName, ...(typeof entry.timestamp === 'string' ? { agentStartedAt: entry.timestamp } : {}), @@ -204,6 +216,12 @@ function createParser(source: SessionSource, seenKeys: Set): SessionPars let pendingUserMessage = '' let sessionTimestamp = '' let pendingUserTimestamp = '' + // Absolute session cwd from the header (or discovery sourcePath). Must + // survive into projectPath/workingDirectory so cross-provider merge can + // key by real path instead of basename-only (#1260 Codex REVISE2). + let sessionCwd = typeof source.sourcePath === 'string' && looksAbsolutePath(source.sourcePath) + ? source.sourcePath.trim() + : '' for (const [lineIdx, line] of lines.entries()) { let entry: PiEntry @@ -216,6 +234,10 @@ function createParser(source: SessionSource, seenKeys: Set): SessionPars if (entry.type === 'session') { sessionId = entry.id ?? sessionId if (typeof entry.timestamp === 'string' && entry.timestamp) sessionTimestamp = entry.timestamp + if (typeof entry.cwd === 'string' && entry.cwd.trim()) { + const headerCwd = entry.cwd.trim() + if (looksAbsolutePath(headerCwd)) sessionCwd = headerCwd + } continue } if (entry.type === 'model_change') { @@ -318,6 +340,11 @@ function createParser(source: SessionSource, seenKeys: Set): SessionPars deduplicationKey: dedupKey, userMessage: pendingUserMessage, sessionId, + project: source.project, + ...(sessionCwd ? { + projectPath: sessionCwd, + workingDirectory: sessionCwd, + } : {}), } pendingUserMessage = '' diff --git a/src/session-cache.ts b/src/session-cache.ts index 54a78ae9..ffbfda4d 100644 --- a/src/session-cache.ts +++ b/src/session-cache.ts @@ -389,7 +389,13 @@ export const PROVIDER_PARSE_VERSIONS: Record = { // nested-agent-v1: OMP writes crewmate transcripts one directory below each // parent session. reported-cost-v2 persists those measured costs through the // cache, including the explicit zero on xai-oauth turns. - omp: 'nested-agent-v1-reported-cost-v2', + // cwd-project-path-v1 (#1260): retain absolute session header cwd on + // projectPath/workingDirectory instead of basename-only identity. + // project-group-by-abs-v1 (#1260 REVISE3): parseProviderSources groups by + // abs projectPath/workingDirectory so same-basename distinct roots stay apart. + pi: 'cwd-project-path-v1-project-group-by-abs-v1', + // project-group-by-abs-v1: shared Pi/OMP serve grouping uses abs identity. + omp: 'nested-agent-v1-reported-cost-v2-cwd-project-path-v1-project-group-by-abs-v1', opencode: 'session-model-v1', quickdesk: 'emf-sqlite-v2-est-cost', // session-lineage-capture-v1: SessionLineage (CB-1, slice 1) is now carried diff --git a/src/session-count-label.ts b/src/session-count-label.ts new file mode 100644 index 00000000..39266893 --- /dev/null +++ b/src/session-count-label.ts @@ -0,0 +1,38 @@ +/// Shared session-count phrasing for CLI, MCP, and tests. +/// Exact unique counts come only from surviving source identities with no +/// unknown cache contribution. Everything else is a lower bound. +export type SessionCountBasis = 'identity' | 'partial' + +export const SESSION_COUNT_HELP = 'Older session logs may be unavailable.' +/// Combined-scope counts are a sum of per-device numbers with no shared identity +/// contract. Do not show that sum as unique or as a lower bound. +export const COMBINED_SESSION_COUNT_HELP = 'Session identities are unavailable across devices.' +export const COMBINED_SESSION_COUNT_LABEL = 'Session count unavailable' + +export function sessionCountIsExact(basis: SessionCountBasis | undefined): boolean { + return basis === 'identity' +} + +export function formatSessionCount( + sessions: number, + basis: SessionCountBasis | undefined, +): string { + if (!sessionCountIsExact(basis)) { + if (sessions <= 0) return 'Session count unavailable' + return sessions === 1 ? 'At least 1 session' : `At least ${sessions.toLocaleString('en-US')} sessions` + } + if (sessions === 1) return '1 session' + return `${sessions.toLocaleString('en-US')} sessions` +} + +/// Compact average for surfaces that show one. Never invent $0 or cost/count +/// when the count is a bound. +export function formatSessionAveragePlaceholder(): string { + return '—' +} + +/// Combined-scope display only. Ignores the numeric wire sum; do not pass 0 to +/// `formatSessionCount` to obtain this string. +export function formatCombinedSessionCount(): string { + return COMBINED_SESSION_COUNT_LABEL +} diff --git a/src/sharing/host.ts b/src/sharing/host.ts index f5aaf3e3..d5cce747 100644 --- a/src/sharing/host.ts +++ b/src/sharing/host.ts @@ -96,6 +96,9 @@ export function summarizeDeviceUsage(results: DeviceUsage[], window?: SummaryWin return { cost: a.cost + d.cost, calls: a.calls + d.calls, + // Numeric wire sum only. Combined-scope UI must not present this as a + // unique or lower-bound session count until a cross-device identity + // contract exists. sessions: a.sessions + d.sessions, inputTokens: a.inputTokens + d.inputTokens, outputTokens: a.outputTokens + d.outputTokens, diff --git a/src/spend-flow.ts b/src/spend-flow.ts index 3693dc4b..e9947664 100644 --- a/src/spend-flow.ts +++ b/src/spend-flow.ts @@ -22,6 +22,18 @@ function addToMap(map: Map, key: K, cost: number): void { map.set(key, (map.get(key) ?? 0) + cost) } +/** #1260: identity for spend nodes — abs projectPath when present, else display label. */ +export function spendProjectIdentity(project: { project: string; projectPath?: string }): { id: string; label: string } { + const raw = (project.projectPath ?? '').trim().replace(/\\/g, '/') + const looksAbs = raw.startsWith('/') || /^[a-zA-Z]:\//.test(raw) || (raw.includes('/') && !raw.startsWith('-')) + if (looksAbs && raw) { + const id = raw.replace(/\/+$/, '') + const base = id.split('/').filter(Boolean).pop() || project.project + return { id, label: base } + } + return { id: project.project, label: project.project } +} + function sortedEntries(totals: Map): Array<[string, number]> { return [...totals.entries()].sort(([aName, aCost], [bName, bCost]) => { const byCost = bCost - aCost @@ -40,24 +52,62 @@ function buildNodes(totals: Map): { nodes: SpendFlowNode[]; keep return { nodes, keep } } +function looksAbsId(id: string): boolean { + return id.startsWith('/') || /^[a-zA-Z]:\//.test(id) +} + +function pathParts(id: string): string[] { + return id.replace(/\\/g, '/').replace(/\/+$/, '').split('/').filter(Boolean) +} + +/// Visible chart labels keep the literal basename (hyphens stay hyphens). +/// Same-basename abs cwds pick up enough parent segments to distinguish. +/// Legacy slug ids and Other are left as-is. +function assignDistinguishingProjectLabels(nodes: SpendFlowNode[], labels: Map): void { + const visible = nodes.filter(node => node.id !== OTHER_ID) + for (const node of visible) { + if (!looksAbsId(node.id)) { + node.label = labels.get(node.id) ?? node.id + continue + } + const parts = pathParts(node.id) + const base = parts.at(-1) || labels.get(node.id) || node.id + const collisions = visible.filter(other => other.id !== node.id && looksAbsId(other.id) && pathParts(other.id).at(-1) === base) + if (collisions.length === 0) { + node.label = base + continue + } + let label = base + for (let n = 2; n <= parts.length; n++) { + label = parts.slice(-n).join('/') + const clash = collisions.some(other => pathParts(other.id).slice(-n).join('/') === label) + if (!clash) break + } + node.label = label + } +} + export async function computeSpendFlow(range: DateRange, provider: string): Promise { const projects = await parseAllSessions(range, provider) const matrix = new Map>() const projectTotals = new Map() const modelTotals = new Map() + const projectLabels = new Map() for (const project of projects) { + const { id: projectId, label: projectLabel } = spendProjectIdentity(project) + if (!projectLabels.has(projectId)) projectLabels.set(projectId, projectLabel) for (const session of project.sessions) { for (const [model, breakdown] of Object.entries(session.modelBreakdown)) { const cost = breakdown.costUSD if (cost <= 0) continue - let modelCosts = matrix.get(project.project) + let modelCosts = matrix.get(projectId) if (!modelCosts) { modelCosts = new Map() - matrix.set(project.project, modelCosts) + matrix.set(projectId, modelCosts) } addToMap(modelCosts, model, cost) - addToMap(projectTotals, project.project, cost) + addToMap(projectTotals, projectId, cost) addToMap(modelTotals, model, cost) } } @@ -65,6 +115,7 @@ export async function computeSpendFlow(range: DateRange, provider: string): Prom const { nodes: models, keep: keptModels } = buildNodes(modelTotals) const { nodes: projectsNodes, keep: keptProjects } = buildNodes(projectTotals) + assignDistinguishingProjectLabels(projectsNodes, projectLabels) const rolledLinks = new Map() for (const [project, modelCosts] of matrix.entries()) { diff --git a/src/usage-aggregator.ts b/src/usage-aggregator.ts index ff273f23..70649931 100644 --- a/src/usage-aggregator.ts +++ b/src/usage-aggregator.ts @@ -1,7 +1,8 @@ import { homedir } from 'node:os' -import { CATEGORY_LABELS, type ProjectSummary, type TaskCategory, type DateRange } from './types.js' +import { CATEGORY_LABELS, type ProjectSummary, type SessionSummary, type TaskCategory, type DateRange } from './types.js' import { isBehavioralCall } from './behavioral-weight.js' import { type PeriodData, type ProviderCost, type BreakdownArrays, type MenubarPayload, type ClaudeConfigSelector, type HydrationState, buildMenubarPayload } from './menubar-json.js' +import { type SessionCountBasis } from './session-count-label.js' import { parseAllSessions, filterProjectsByName, filterProjectsByDays, filterProjectsByClaudeConfigSource, filterProjectsByDateRange, isSessionHydrationComplete, sessionHydrationSnapshot } from './parser.js' import { findUnpricedModels, getFlatRateModelsConfigHash, getLocalModelSavingsConfigHash, getPriceOverridesConfigHash, getShortModelName, isExpectedFreeModel } from './models.js' import { getAllProviders, safeDiscoverSessions } from './providers/index.js' @@ -16,9 +17,10 @@ import { aggregateModelTaskTurns, sessionDurationMinutes } from './telemetry-sna import { scanUserCorrections, medianTimeToFirstEditMs, aggregateFileChurn, computePricingCoverage } from './workflow-insights.js' import { buildPrAttribution, aggregateByBranch } from './sessions-report.js' import { scanAndDetect } from './optimize.js' -import { callBillableOutputTokens, sessionBillableOutputTokens } from './session-output.js' +import { callBillableOutputTokens, sessionBillableOutputTokens, inferSessionProvider } from './session-output.js' import { getDaysInRange, ensureCacheHydrated, loadDailyCache, emptyCache, mergeDayEntries, BACKFILL_DAYS, toDateString, type DailyCache, type DailyEntry, type ProjectDayStats, type ProviderDaySlice } from './daily-cache.js' import { buildGranularHistory } from './granular-history.js' +import { spendProjectIdentity } from './spend-flow.js' // Row caps for the by-PR / by-branch payload aggregations, ranked by cost. const TOP_BRANCHES = 15 @@ -31,6 +33,7 @@ export type ProviderSliceTotal = { inputTokens?: number outputTokens?: number sessions?: number + sessionCountBasis?: SessionCountBasis } /// Folds one day's provider slice into the period total. Tokens and sessions are @@ -44,7 +47,9 @@ export function addProviderSlice(totals: Record, nam total.hasUsage ||= providerSliceHasUsage(slice) if (slice.inputTokens !== undefined) total.inputTokens = (total.inputTokens ?? 0) + slice.inputTokens if (slice.outputTokens !== undefined) total.outputTokens = (total.outputTokens ?? 0) + slice.outputTokens - if (slice.sessions !== undefined) total.sessions = (total.sessions ?? 0) + slice.sessions + // Per-day session ticks are not distinct identities. Keep the max day as a + // lower bound; never sum occupancy across dates. + if (slice.sessions !== undefined) total.sessions = Math.max(total.sessions ?? 0, slice.sessions) totals[name] = total } @@ -102,7 +107,8 @@ export function buildPeriodData(label: string, projects: ProjectSummary[]): Peri savingsUSD: projects.reduce((s, p) => s + p.totalSavingsUSD, 0), estimatedCostUSD: projects.reduce((s, p) => s + (p.totalEstimatedCostUSD ?? 0), 0), calls: projects.reduce((s, p) => s + p.totalApiCalls, 0), - sessions: projects.reduce((s, p) => s + p.sessions.length, 0), + sessions: uniqueCanonicalSessionCountFromProjects(projects), + sessionCountBasis: 'identity', inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens, categories: Object.entries(catTotals) .sort(([, a], [, b]) => b.cost - a.cost) @@ -504,6 +510,7 @@ export type IndexedDurableOverview = { savingsUSD: number calls: number sessions: number + sessionCountBasis?: SessionCountBasis inputTokens: number outputTokens: number cacheReadTokens: number @@ -574,7 +581,9 @@ export function buildDurableOverviewFromNormalizedIndex( // Fields whose durable day rows cannot project under a project filter come // from the same normalized period slice that feeds the visible detail panels. const scan = buildPeriodData(periodInfo.label, scanProjects) - data.sessions = Math.max(data.sessions, scan.sessions) + const sessionCount = uniquePeriodSessionCount(scanProjects, days) + data.sessions = sessionCount.sessions + data.sessionCountBasis = sessionCount.basis if (hasProjectFilter) { data.inputTokens = scan.inputTokens data.outputTokens = scan.outputTokens @@ -587,6 +596,7 @@ export function buildDurableOverviewFromNormalizedIndex( savingsUSD: data.savingsUSD, calls: data.calls, sessions: data.sessions, + sessionCountBasis: data.sessionCountBasis, inputTokens: data.inputTokens, outputTokens: data.outputTokens, cacheReadTokens: data.cacheReadTokens, @@ -737,9 +747,12 @@ export async function buildDurablePeriod(periodInfo: PeriodInfo, opts: Aggregate data.workflow = scanData.workflow data.topReworkedFiles = scanData.topReworkedFiles data.pricingCoverage = scanData.pricingCoverage - // Cache buckets a session on its START day, the scan on any ACTIVE day; both - // are lower bounds of distinct sessions, so max is the tightest safe bound. - data.sessions = Math.max(data.sessions, scanData.sessions) + // Daily occupancy ticks are not unique across a period (one session file + // active on two days is two ticks). Prefer canonical provider+sessionId + // from the live parse; occupancy remains only for source-dead days. + const sessionCount = uniquePeriodSessionCount(liveProjects, days) + data.sessions = sessionCount.sessions + data.sessionCountBasis = sessionCount.basis // Tokens/models/categories have no per-project split in the day cache, so // sliceDayToProject drops them (see there). Under a project filter they come // from the live parse instead: exact for the filtered projects, bounded by @@ -768,6 +781,472 @@ export async function buildDurablePeriod(periodInfo: PeriodInfo, opts: Aggregate return { data, days, carriedCostUSD, unattributedCostUSD, liveProjects, cache, todayAllDays, scanRange } } +type PayloadProject = NonNullable[number] +type PayloadSessionDetail = NonNullable[number] + +/// Period unique-count key: provider + cwd/project + canonical sessionId. +/// Filename-colliding `sess.jsonl` in two folders stay distinct. Same file +/// spanning days stays one. Not fingerprint/cost/calls. +export function canonicalSessionCountKey(session: SessionSummary, projectPath?: string): string { + const loc = projectPath || session.workingDirectory || session.project + return `${inferSessionProvider(session)}\0${loc}\0${session.sessionId}` +} + +export function uniqueCanonicalSessionCount( + sessions: Iterable, + projectPath?: string, +): number { + const ids = new Set() + let anonymous = 0 + for (const session of sessions) { + if (session.sessionId) ids.add(canonicalSessionCountKey(session, projectPath)) + else anonymous += 1 + } + return ids.size + anonymous +} + +export function uniqueCanonicalSessionCountFromProjects(projects: Iterable): number { + const ids = new Set() + let anonymous = 0 + for (const project of projects) { + for (const session of project.sessions) { + if (session.sessionId) ids.add(canonicalSessionCountKey(session, project.projectPath)) + else anonymous += 1 + } + } + return ids.size + anonymous +} + +export function uniqueCanonicalSessionCountForProvider( + projects: Iterable, + provider: string, +): number { + const ids = new Set() + let anonymous = 0 + for (const project of projects) { + for (const session of project.sessions) { + if (inferSessionProvider(session) !== provider) continue + if (session.sessionId) ids.add(canonicalSessionCountKey(session, project.projectPath)) + else anonymous += 1 + } + } + return ids.size + anonymous +} + +/// Live unique IDs are a lower bound. Per-day cache ticks are another. +/// Never sum those bounds; never sum ticks across dates; never treat matching +/// counts as identity. Exact only when accounting did not use cache rows that +/// lack identities (including empty source-only data → 0). +export function boundSessionCount( + liveUnique: number, + cacheDayBound: number, + unknownCache: boolean, +): { sessions: number, basis: SessionCountBasis } { + if (!unknownCache) return { sessions: liveUnique, basis: 'identity' } + return { sessions: Math.max(liveUnique, cacheDayBound), basis: 'partial' } +} + +export function maxDaySessionBound(days: Array<{ sessions?: number }>): number { + let max = 0 + for (const day of days) { + const n = day.sessions ?? 0 + if (n > max) max = n + } + return max +} + +function hasUnknownCacheAccounting(entry: { + cost?: number + calls?: number + savingsUSD?: number + sessions?: number + inputTokens?: number + outputTokens?: number + cacheReadTokens?: number + cacheWriteTokens?: number +}): boolean { + return (entry.cost ?? 0) > 0 + || (entry.calls ?? 0) > 0 + || (entry.savingsUSD ?? 0) > 0 + || (entry.sessions ?? 0) > 0 + || (entry.inputTokens ?? 0) > 0 + || (entry.outputTokens ?? 0) > 0 + || (entry.cacheReadTokens ?? 0) > 0 + || (entry.cacheWriteTokens ?? 0) > 0 +} + +/// Cache rows have no session identities. Any retained accounting on a row +/// (cost, calls, tokens, savings, or a positive session tick) is unknown +/// provenance — including sessions 0 / absent. A truly empty row is not. +function dayLacksSessionIdentities(day: DailyEntry): boolean { + if (day.carried) return true + if (hasUnknownCacheAccounting(day)) return true + for (const project of Object.values(day.projects ?? {})) { + if (hasUnknownCacheAccounting(project)) return true + } + for (const slice of Object.values(day.providers ?? {})) { + if (hasUnknownCacheAccounting(slice)) return true + } + return false +} + +export function uniquePeriodSessionCount( + liveProjects: ProjectSummary[], + days: DailyEntry[], +): { sessions: number, basis: SessionCountBasis } { + const liveUnique = uniqueCanonicalSessionCountFromProjects(liveProjects) + const unknownCache = days.some(dayLacksSessionIdentities) + return boundSessionCount(liveUnique, maxDaySessionBound(days), unknownCache) +} + +function applyProviderSessionCounts( + providers: ProviderCost[], + liveProjects: ProjectSummary[], + unknownCache: boolean, +): void { + for (const provider of providers) { + const liveUnique = uniqueCanonicalSessionCountForProvider(liveProjects, provider.name) + if (!unknownCache) { + if (liveUnique > 0 || provider.sessions !== undefined) { + provider.sessions = liveUnique + provider.sessionCountBasis = 'identity' + } + continue + } + const cacheBound = provider.sessions ?? 0 + const counted = boundSessionCount(liveUnique, cacheBound, true) + if (counted.sessions === 0 && provider.sessions === undefined && liveUnique === 0) { + if ((provider.cost ?? 0) > 0) { + provider.sessions = 0 + provider.sessionCountBasis = 'partial' + } + continue + } + provider.sessions = counted.sessions + provider.sessionCountBasis = counted.basis + } +} + +function sessionDetailsOf(sessions: SessionSummary[]): PayloadSessionDetail[] { + return [...sessions] + .sort((a, b) => b.totalCostUSD - a.totalCostUSD) + .slice(0, 10) + .map(s => ({ + cost: s.totalCostUSD, + savingsUSD: s.totalSavingsUSD, + calls: s.apiCalls, + inputTokens: s.totalInputTokens, + outputTokens: sessionBillableOutputTokens(s), + date: s.firstTimestamp?.split('T')[0] ?? '', + models: Object.entries(s.modelBreakdown) + .map(([name, m]) => ({ name, cost: m.costUSD, savingsUSD: m.savingsUSD })) + .sort((a, b) => b.cost - a.cost) + .slice(0, 3), + })) +} + +function displayBasename(path: string | undefined, fallback: string, home: string): string { + if (!path) return fallback + if (path === home || path === home + '/') return 'Home' + return path.replace(/\\/g, '/').split('/').filter(Boolean).pop() || fallback +} + +function disambiguatedProjectName( + path: string | undefined, + basename: string, + fallback: string, + basenameCounts: Map, +): string { + if (basename === 'Home') return 'Home' + if ((basenameCounts.get(basename) ?? 0) <= 1) return basename + const normalized = (path ?? '').trim().replace(/\\/g, '/').replace(/\/+$/, '') + const parts = normalized.split('/').filter(Boolean) + if (parts.length >= 2) return parts.slice(-2).join('/') + return normalized || fallback || basename +} + +/// Join cache project slugs with live parse rows by abs-cwd identity (#1260). +/// Canonical identity is case-preserving: POSIX `/tmp/Case/Vault` and +/// `/tmp/case/vault` are distinct. Same cwd across providers coalesces once; +/// distinct cwd with the same basename stays distinct. +/// +/// Explicit known cache paths are identities of their own — a later day of the +/// same slug at a different path does not fold into the first path. Pathless +/// cache days attach only when cache+live agree on exactly one known identity. +/// Otherwise the pathless total stays at the legacy slug (unallocated) and is +/// cache-authoritative for matching live rows of that slug: do not add those +/// live costs again. A truly different live-only slug at a cwd still counts. +/// +/// Cost/savings stay per-contributor (cache ?? live) except for the +/// unallocated matching-slug case above. Session *counts* are live unique IDs +/// when accounting is source-only; any cache row without identities is a +/// lower bound (max of live unique and the max per-day tick, never a sum). +/// Session details follow the same allocation: only matching sessions, never +/// the whole grouped project, and an unresolved legacy row does not inherit a +/// live folder path or name. +export function buildPayloadProjects( + scanProjects: ProjectSummary[], + cacheDays: DailyEntry[] | null, + home: string, +): PayloadProject[] { + type Contrib = { + cacheCost: number + cacheSavings: number + cacheSessions: number + cacheSessionDays: number + cacheMaxDaySessions: number + cacheCalls: number + hasCache: boolean + liveCost: number + liveSavings: number + liveSessions: number + } + type Acc = { + id: string + path?: string + fallbackName: string + contribs: Map + sessions: SessionSummary[] + } + const byKey = new Map() + const take = (project: string, projectPath: string | undefined, fallbackName: string): Acc => { + const ident = spendProjectIdentity({ project, projectPath }) + const key = ident.id + let acc = byKey.get(key) + if (!acc) { + acc = { + id: ident.id, + path: projectPath, + fallbackName, + contribs: new Map(), + sessions: [], + } + byKey.set(key, acc) + } else if (projectPath && !acc.path) { + acc.path = projectPath + acc.id = ident.id + } + return acc + } + const contribOf = (acc: Acc, slug: string): Contrib => { + let c = acc.contribs.get(slug) + if (!c) { + c = { + cacheCost: 0, + cacheSavings: 0, + cacheSessions: 0, + cacheSessionDays: 0, + cacheMaxDaySessions: 0, + cacheCalls: 0, + hasCache: false, + liveCost: 0, + liveSavings: 0, + liveSessions: 0, + } + acc.contribs.set(slug, c) + } + return c + } + const addSessionOnce = (acc: Acc, s: SessionSummary): void => { + if (!acc.sessions.includes(s)) acc.sessions.push(s) + } + const placeCache = ( + slug: string, + path: string | undefined, + cost: number, + savingsUSD: number, + occupancy: { sessions: number, sessionDays: number, maxDaySessions: number, calls: number }, + ): Acc => { + const acc = take(slug, path, slug) + const c = contribOf(acc, slug) + c.hasCache = true + c.cacheCost += cost + c.cacheSavings += savingsUSD + c.cacheCalls += occupancy.calls + c.cacheSessions += occupancy.sessions + c.cacheSessionDays += occupancy.sessionDays + if (occupancy.maxDaySessions > c.cacheMaxDaySessions) c.cacheMaxDaySessions = occupancy.maxDaySessions + return acc + } + + const livePathsBySlug = new Map>() + const rememberLiveSlug = (slug: string, projectPath: string | undefined): void => { + if (!projectPath) return + const id = spendProjectIdentity({ project: slug, projectPath }).id + let paths = livePathsBySlug.get(slug) + if (!paths) { + paths = new Set() + livePathsBySlug.set(slug, paths) + } + paths.add(id) + } + for (const p of scanProjects) { + rememberLiveSlug(p.project, p.projectPath) + for (const s of p.sessions) rememberLiveSlug(s.project, p.projectPath) + } + + type Totals = { cost: number; savingsUSD: number; sessions: number; sessionDays: number; maxDaySessions: number; calls: number } + const knownBySlug = new Map>() + const pathlessBySlug = new Map() + const emptyTotals = (): Totals => ({ cost: 0, savingsUSD: 0, sessions: 0, sessionDays: 0, maxDaySessions: 0, calls: 0 }) + const addTotals = (into: Totals, cost: number, savingsUSD: number, sessions: number, calls: number): void => { + into.cost += cost + into.savingsUSD += savingsUSD + into.calls += calls + into.sessions += sessions + if (sessions > 0) { + into.sessionDays += 1 + if (sessions > into.maxDaySessions) into.maxDaySessions = sessions + } + } + if (cacheDays) { + for (const d of cacheDays) { + for (const [name, p] of Object.entries(d.projects ?? {})) { + if (p.path) { + const id = spendProjectIdentity({ project: name, projectPath: p.path }).id + let byId = knownBySlug.get(name) + if (!byId) { + byId = new Map() + knownBySlug.set(name, byId) + } + const acc = byId.get(id) ?? emptyTotals() + addTotals(acc, p.cost, p.savingsUSD, p.sessions, p.calls) + byId.set(id, acc) + } else { + const acc = pathlessBySlug.get(name) ?? emptyTotals() + addTotals(acc, p.cost, p.savingsUSD, p.sessions, p.calls) + pathlessBySlug.set(name, acc) + } + } + } + } + + const cacheIdentities = new Map>() + const unallocatedSlugs = new Set() + const rememberCacheIdentity = (slug: string, id: string): void => { + let ids = cacheIdentities.get(slug) + if (!ids) { + ids = new Set() + cacheIdentities.set(slug, ids) + } + ids.add(id) + } + + for (const [slug, byId] of knownBySlug) { + for (const [id, totals] of byId) { + placeCache(slug, id, totals.cost, totals.savingsUSD, totals) + rememberCacheIdentity(slug, id) + } + } + for (const [slug, totals] of pathlessBySlug) { + const known = new Set(cacheIdentities.get(slug) ?? []) + for (const id of livePathsBySlug.get(slug) ?? []) known.add(id) + if (known.size === 1) { + const id = [...known][0]! + placeCache(slug, id, totals.cost, totals.savingsUSD, totals) + rememberCacheIdentity(slug, id) + } else { + const acc = placeCache(slug, undefined, totals.cost, totals.savingsUSD, totals) + unallocatedSlugs.add(slug) + rememberCacheIdentity(slug, acc.id) + } + } + + const policyFor = (slug: string, liveId: string): 'use-cache' | 'use-live' | 'suppress' => { + if (cacheIdentities.get(slug)?.has(liveId)) return 'use-cache' + if (unallocatedSlugs.has(slug)) return 'suppress' + return 'use-live' + } + + for (const p of scanProjects) { + const liveId = spendProjectIdentity({ project: p.project, projectPath: p.projectPath }).id + if (p.sessions.length === 0) { + const policy = policyFor(p.project, liveId) + if (policy === 'suppress') continue + const acc = take(p.project, p.projectPath, p.project) + if (policy === 'use-live') { + const c = contribOf(acc, p.project) + c.liveCost += p.totalCostUSD + c.liveSavings += p.totalSavingsUSD + } + continue + } + for (const s of p.sessions) { + const policy = policyFor(s.project, liveId) + if (policy === 'suppress') { + const cacheAcc = byKey.get(s.project) + if (cacheAcc) addSessionOnce(cacheAcc, s) + continue + } + const acc = take(p.project, p.projectPath, p.project) + addSessionOnce(acc, s) + const c = contribOf(acc, s.project) + if (policy === 'use-live') { + c.liveCost += s.totalCostUSD + c.liveSavings += s.totalSavingsUSD + c.liveSessions += 1 + } else { + c.liveSessions += 1 + } + } + } + + const rows = [...byKey.values()].map(acc => { + const path = acc.path + let cost = 0 + let savingsUSD = 0 + for (const c of acc.contribs.values()) { + cost += c.hasCache ? c.cacheCost : c.liveCost + savingsUSD += c.hasCache ? c.cacheSavings : c.liveSavings + } + const liveUnique = uniqueCanonicalSessionCount(acc.sessions, acc.path) + let cacheDayBound = 0 + let unknownCache = false + for (const c of acc.contribs.values()) { + if (!c.hasCache) continue + if ( + c.cacheCost > 0 + || c.cacheSavings > 0 + || c.cacheCalls > 0 + || c.cacheSessions > 0 + || c.cacheMaxDaySessions > 0 + ) { + unknownCache = true + } + if (c.cacheMaxDaySessions > cacheDayBound) cacheDayBound = c.cacheMaxDaySessions + } + const counted = boundSessionCount(liveUnique, cacheDayBound, unknownCache) + const sessions = counted.sessions + const sessionCountBasis = counted.basis + return { + acc, + path, + basename: displayBasename(path, acc.fallbackName, home), + cost, + savingsUSD, + sessions, + sessionCountBasis, + } + }) + const basenameCounts = new Map() + for (const row of rows) basenameCounts.set(row.basename, (basenameCounts.get(row.basename) ?? 0) + 1) + + return rows + .map(({ acc, path, basename, cost, savingsUSD, sessions, sessionCountBasis }) => { + const details = sessionDetailsOf(acc.sessions) + return { + id: acc.id, + name: disambiguatedProjectName(path, basename, acc.fallbackName, basenameCounts), + cost, + savingsUSD, + sessions, + sessionCountBasis, + ...(details.length ? { sessionDetails: details } : {}), + } + }) + .sort((a, b) => b.cost - a.cost) +} + /** * Resolved-range aggregation shared by `status --format menubar-json` and the MCP server. * Pricing must already be loaded (callers run loadPricing first). When opts.optimize is @@ -931,6 +1410,7 @@ export async function buildMenubarPayloadForRange(periodInfo: PeriodInfo, opts: inputTokens: currentData.inputTokens, outputTokens: currentData.outputTokens, sessions: currentData.sessions, + sessionCountBasis: currentData.sessionCountBasis, hasUsage: currentData.cost > 0 || currentData.savingsUSD > 0 || currentData.calls > 0 @@ -942,6 +1422,15 @@ export async function buildMenubarPayloadForRange(periodInfo: PeriodInfo, opts: }) } + if (isAllProviders || (isClaudeConfigScoped && effectivelyScoped)) { + applyProviderSessionCounts( + providers, + scanProjects, + !(isClaudeConfigScoped && effectivelyScoped) + && (cacheDaysForPeriod ?? []).some(dayLacksSessionIdentities), + ) + } + // DAILY HISTORY (last 365 days) // Cache stores per-provider cost+calls per day in DailyEntry.providers, so we can derive // a provider-filtered history without re-parsing. Tokens aren't broken down per provider @@ -977,65 +1466,18 @@ export async function buildMenubarPayloadForRange(periodInfo: PeriodInfo, opts: return path.split('/').filter(Boolean).pop() || fallback } const friendlyProject = (p: ProjectSummary) => friendlyFromPath(p.projectPath || p.project, p.project) - const sessionDetailsOf = (p: ProjectSummary) => [...p.sessions] - .sort((a, b) => b.totalCostUSD - a.totalCostUSD) - .slice(0, 10) - .map(s => ({ - cost: s.totalCostUSD, - savingsUSD: s.totalSavingsUSD, - calls: s.apiCalls, - inputTokens: s.totalInputTokens, - outputTokens: sessionBillableOutputTokens(s), - date: s.firstTimestamp?.split('T')[0] ?? '', - models: Object.entries(s.modelBreakdown) - .map(([name, m]) => ({ name, cost: m.costUSD, savingsUSD: m.savingsUSD })) - .sort((a, b) => b.cost - a.cost) - .slice(0, 3), - })) - if (cacheDaysForPeriod !== null) { - // Project totals come from the SAME day set as the headline, so carried - // days count here too. The surviving-session parse contributes only what - // day entries cannot: the per-session drill-down and a fresher project - // path. Days recorded before the projects rollup existed have totals but - // no project split, so this list can sum to less than the headline — an - // honest gap, not a bug. - type CachedProjectTotal = { cost: number; savingsUSD: number; sessions: number; path?: string } - const cachedTotals = new Map() - for (const d of cacheDaysForPeriod) { - for (const [name, p] of Object.entries(d.projects ?? {})) { - const acc = cachedTotals.get(name) ?? { cost: 0, savingsUSD: 0, sessions: 0 } - acc.cost += p.cost - acc.savingsUSD += p.savingsUSD - acc.sessions += p.sessions - if (!acc.path && p.path) acc.path = p.path - cachedTotals.set(name, acc) - } - } - const liveByName = new Map(scanProjects.map(p => [p.project, p])) - const names = new Set([...cachedTotals.keys(), ...liveByName.keys()]) - currentData.projects = [...names].map(name => { - const cached = cachedTotals.get(name) - const live = liveByName.get(name) - return { - name: live ? friendlyProject(live) : friendlyFromPath(cached?.path, name), - cost: cached?.cost ?? live!.totalCostUSD, - savingsUSD: cached?.savingsUSD ?? live!.totalSavingsUSD, - // max for the same reason as the headline: start-day bucketing vs - // active-day counting, both lower bounds of distinct sessions. - sessions: Math.max(cached?.sessions ?? 0, live?.sessions.length ?? 0), - ...(live ? { sessionDetails: sessionDetailsOf(live) } : {}), - } - }).sort((a, b) => b.cost - a.cost) - } else { - currentData.projects = scanProjects.map(p => ({ - name: friendlyProject(p), - cost: p.totalCostUSD, - savingsUSD: p.totalSavingsUSD, - sessions: p.sessions.length, - sessionDetails: sessionDetailsOf(p), - })) - } + // Project totals come from the SAME day set as the headline when a cache + // day set exists, so carried days count here too. Join is by case-preserving + // abs-cwd identity, not provider slug: same cwd coalesces once; distinct cwd + // with the same basename stays distinct. Explicit known cache paths never + // fold into each other; pathless cache attaches only when cache+live agree + // on one identity. Ambiguous pathless cache stays at the legacy slug and is + // authoritative for matching live rows of that slug. Cost is per-contributor + // (cache ?? live) otherwise. Days recorded before the projects rollup existed + // have totals but no project split, so this list can sum to less than the + // headline — an honest gap. + currentData.projects = buildPayloadProjects(scanProjects, cacheDaysForPeriod, home) const effMap = aggregateModelEfficiency(scanProjects) currentData.modelEfficiency = [...effMap.entries()].map(([name, eff]) => ({ diff --git a/tests/codex-review-1260-residuals.test.ts b/tests/codex-review-1260-residuals.test.ts new file mode 100644 index 00000000..09a9a040 --- /dev/null +++ b/tests/codex-review-1260-residuals.test.ts @@ -0,0 +1,421 @@ +/** + * #1260 REVISE3-residuals — Codex remaining gates after two-root PARTIAL ACCEPT: + * 1) five-provider (claude, codex, hermes, kimicode, pi) discovery→parse→cache + * cold/warm abs-cwd pipeline + * 2) missing / ambiguous cwd exact contracts (no vacuous >=1) + * 3) cross-provider merge of five abs identities at /a/vault vs /b/vault + */ +import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest' +import { mkdtemp, mkdir, writeFile, rm, utimes } from 'node:fs/promises' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { createHash } from 'node:crypto' + +import { + clearSessionCache, + mergeProjectsByCrossProviderKey, + parseAllSessions, + parseProviderSources, +} from '../src/parser.js' +import { createPiProvider } from '../src/providers/pi.js' +import { createCodexProvider } from '../src/providers/codex.js' +import { createKimicodeProvider } from '../src/providers/kimicode.js' +import { createHermesProvider } from '../src/providers/hermes.js' +import { CACHE_VERSION } from '../src/session-cache.js' +import { isSqliteAvailable } from '../src/sqlite.js' +import type { ProjectSummary } from '../src/types.js' + +function summary( + project: string, + projectPath: string, + opts: { cost?: number; wd?: string } = {}, +): ProjectSummary { + return { + project, + projectPath, + sessions: opts.wd ? ([{ workingDirectory: opts.wd }] as ProjectSummary['sessions']) : [], + totalCostUSD: opts.cost ?? 1, + totalApiCalls: 1, + totalProxiedCostUSD: 0, + } as ProjectSummary +} + +function norm(p: string | undefined): string { + return (p ?? '').replace(/\\/g, '/').replace(/\/+$/, '') +} + +function sortedPaths(projects: ProjectSummary[]): string[] { + return projects.map(p => norm(p.projectPath)).filter(Boolean).sort() +} + +async function writePiSession(root: string, parent: 'a' | 'b'): Promise { + const dir = join(root, 'sessions', parent) + await mkdir(dir, { recursive: true }) + await writeFile(join(dir, `pi-${parent}.jsonl`), [ + { type: 'session', version: 3, id: `pi-${parent}`, cwd: `/${parent}/vault`, timestamp: '2026-04-14T10:00:00Z' }, + { type: 'message', id: `m-${parent}`, timestamp: '2026-04-14T10:01:00Z', message: { + role: 'assistant', model: 'gpt-5.4', content: [], responseId: `r-${parent}`, + usage: { input: 10, output: 5, cacheRead: 0, cacheWrite: 0, cost: { total: 0.0055 } }, + } }, + ].map(JSON.stringify).join('\n') + '\n') +} + +async function writeCodexSession(root: string, parent: 'a' | 'b'): Promise { + const sessions = join(root, 'sessions', '2026', '04', '14') + await mkdir(sessions, { recursive: true }) + const file = join(sessions, `rollout-codex-${parent}.jsonl`) + await writeFile(file, [ + JSON.stringify({ type: 'session_meta', timestamp: '2026-04-14T10:00:00Z', payload: { + session_id: `codex-${parent}`, model: 'gpt-5.4', cwd: `/${parent}/vault`, originator: 'codex_cli_rs', + } }), + JSON.stringify({ type: 'response_item', timestamp: '2026-04-14T10:00:30Z', payload: { + type: 'message', role: 'user', content: [{ type: 'input_text', text: 'hi' }], + } }), + JSON.stringify({ type: 'event_msg', timestamp: '2026-04-14T10:01:00Z', payload: { + type: 'token_count', info: { + last_token_usage: { input_tokens: 100, output_tokens: 20, total_tokens: 120 }, + total_token_usage: { total_tokens: 120 }, + }, + } }), + '', + ].join('\n')) + return file +} + +async function writeKimicodeSession(home: string, parent: 'a' | 'b'): Promise { + const workDir = `/${parent}/vault` + const hash = createHash('md5').update(workDir).digest('hex').slice(0, 12) + const sessionDir = join(home, 'sessions', `wd_vault_${hash}`, `session_${parent}`) + const agentDir = join(sessionDir, 'agents', 'main') + await mkdir(agentDir, { recursive: true }) + await writeFile(join(sessionDir, 'state.json'), JSON.stringify({ + createdAt: '2026-07-01T10:00:00.000Z', + updatedAt: '2026-07-01T10:05:00.000Z', + workDir, + agents: { main: { homedir: '/workspace', type: 'main', parentAgentId: null } }, + })) + await writeFile(join(agentDir, 'wire.jsonl'), [ + JSON.stringify({ type: 'metadata', protocol_version: '1.4', created_at: 1782900000000 }), + JSON.stringify({ + type: 'turn.prompt', + input: [{ type: 'text', text: 'hi' }], + origin: { kind: 'user' }, + time: 1782900000000, + }), + JSON.stringify({ + type: 'llm.request', kind: 'loop', provider: 'fixture-provider', + model: 'kimi-k2', modelAlias: 'kimi-k2', maxTokens: 4096, messageCount: 2, + turnStep: '0.1', time: 1782900001000, + }), + JSON.stringify({ + type: 'usage.record', model: 'kimi-k2', + usage: { inputOther: 10, output: 5, inputCacheRead: 0, inputCacheCreation: 0 }, + usageScope: 'turn', time: 1782900002000, + }), + '', + ].join('\n')) +} + +describe('missing/ambiguous cwd exact contracts (#1260 residuals)', () => { + it('pins unique-basename empty-path attach (size 1, cost 11)', () => { + const merged = mergeProjectsByCrossProviderKey([ + summary('vault', '/root/vault', { cost: 10 }), + summary('vault', '', { cost: 1 }), + ]) + expect(merged.size).toBe(1) + expect([...merged.values()][0]!.totalCostUSD).toBe(11) + }) + + it('keeps non-matching empty-path label unresolved (size 2)', () => { + const merged = mergeProjectsByCrossProviderKey([ + summary('vault', '/root/vault', { cost: 10 }), + summary('orphan', '', { cost: 1 }), + ]) + expect(merged.size).toBe(2) + }) + + it('ambiguous basename across two abs parents stays size 3', () => { + const merged = mergeProjectsByCrossProviderKey([ + summary('a-vault', '/a/vault', { cost: 1 }), + summary('b-vault', '/b/vault', { cost: 2 }), + summary('vault', 'vault', { cost: 99 }), + ]) + expect(merged.size).toBe(3) + const costs = [...merged.values()].map(p => p.totalCostUSD).sort((a, b) => a - b) + expect(costs).toEqual([1, 2, 99]) + }) + + it('five-provider same-parent helper summaries fold to one abs key', () => { + const merged = mergeProjectsByCrossProviderKey([ + summary('-root-vault', '/root/vault', { cost: 10 }), // claude + summary('root-vault', 'root/vault', { cost: 5 }), // codex + summary('root-vault', '/root/vault', { cost: 4 }), // hermes + summary('vault', '/root/vault', { cost: 3 }), // kimicode + summary('vault', '/root/vault', { cost: 2 }), // pi + ]) + expect(merged.size).toBe(1) + expect([...merged.values()][0]!.totalCostUSD).toBe(24) + }) + + it('five-provider two-root helpers stay size 2 (a vs b)', () => { + const merged = mergeProjectsByCrossProviderKey([ + summary('vault', '/a/vault', { cost: 1 }), // claude + summary('vault', '/a/vault', { cost: 2 }), // codex + summary('vault', '/a/vault', { cost: 3 }), // hermes + summary('vault', '/b/vault', { cost: 4 }), // kimicode + summary('vault', '/b/vault', { cost: 5 }), // pi + ]) + expect(merged.size).toBe(2) + const byPath = new Map([...merged.values()].map(p => [norm(p.projectPath), p.totalCostUSD])) + expect(byPath.get('/a/vault')).toBe(6) + expect(byPath.get('/b/vault')).toBe(9) + }) +}) + +describe('pi residuals: two-root cold/warm', () => { + it('cold then warm keeps /a/vault and /b/vault', async () => { + const root = await mkdtemp(join(tmpdir(), 'r3res-pi-')) + try { + await writePiSession(root, 'a') + await writePiSession(root, 'b') + const sources = await createPiProvider(join(root, 'sessions')).discoverSessions() + const cache = { version: CACHE_VERSION, providers: {} } + const cold = await parseProviderSources('pi', sources, new Set(), cache) + expect(sortedPaths(cold)).toEqual(['/a/vault', '/b/vault']) + const warm = await parseProviderSources('pi', sources, new Set(), cache) + expect(sortedPaths(warm)).toEqual(['/a/vault', '/b/vault']) + expect(sortedPaths([...mergeProjectsByCrossProviderKey(warm).values()])).toEqual(['/a/vault', '/b/vault']) + } finally { + await rm(root, { recursive: true, force: true }) + } + }) +}) + +describe('codex residuals: two-root cold/warm', () => { + it('cold then warm keeps both abs cwds', async () => { + const root = await mkdtemp(join(tmpdir(), 'r3res-codex-')) + try { + await writeCodexSession(root, 'a') + await writeCodexSession(root, 'b') + const provider = createCodexProvider(root) + const sources = await provider.discoverSessions() + const cache = { version: CACHE_VERSION, providers: {} } + const cold = await parseProviderSources('codex', sources, new Set(), cache) + expect(sortedPaths(cold)).toEqual(['/a/vault', '/b/vault']) + const warm = await parseProviderSources('codex', sources, new Set(), cache) + expect(sortedPaths(warm)).toEqual(['/a/vault', '/b/vault']) + } finally { + await rm(root, { recursive: true, force: true }) + } + }) +}) + +describe('claude residuals: two-root abs cwd via parseAllSessions', () => { + let tmpDir: string + beforeEach(async () => { + tmpDir = await mkdtemp(join(tmpdir(), 'r3res-claude-')) + process.env['CLAUDE_CONFIG_DIR'] = tmpDir + process.env['CODEBURN_DESKTOP_SESSIONS_DIR'] = join(tmpDir, 'desktop-sessions') + process.env['CODEBURN_CACHE_DIR'] = join(tmpDir, 'cache') + clearSessionCache() + }) + afterEach(async () => { + clearSessionCache() + await rm(tmpDir, { recursive: true, force: true }) + }) + + it('keeps /a/vault and /b/vault as distinct projectPaths', async () => { + for (const parent of ['a', 'b'] as const) { + const projectDir = join(tmpDir, 'projects', `-${parent}-vault`) + await mkdir(projectDir, { recursive: true }) + const filePath = join(projectDir, `claude-${parent}.jsonl`) + await writeFile(filePath, JSON.stringify({ + type: 'assistant', + sessionId: `claude-${parent}`, + timestamp: '2099-05-01T12:00:00.000Z', + cwd: `/${parent}/vault`, + message: { + id: `msg-${parent}`, type: 'message', role: 'assistant', model: 'claude-sonnet-4-5', + content: [], usage: { input_tokens: 100, output_tokens: 50 }, + }, + }) + '\n') + await utimes(filePath, new Date('2099-05-01T12:00:00.000Z'), new Date('2099-05-01T12:00:00.000Z')) + } + const cold = await parseAllSessions({ + start: new Date('2099-05-01T00:00:00.000Z'), + end: new Date('2099-05-01T23:59:59.999Z'), + }, 'claude') + expect(sortedPaths(cold)).toEqual(['/a/vault', '/b/vault']) + const warm = await parseAllSessions({ + start: new Date('2099-05-01T00:00:00.000Z'), + end: new Date('2099-05-01T23:59:59.999Z'), + }, 'claude') + expect(sortedPaths(warm)).toEqual(['/a/vault', '/b/vault']) + }) +}) + +describe('kimicode residuals: two-root cold/warm', () => { + const fixtureHome = vi.hoisted(() => { + const base = process.env['TMPDIR'] || '/tmp' + return `${base.replace(/[\\/]+$/, '')}/kimicode-r3res-${process.pid}-${Date.now()}` + }) + + beforeEach(async () => { + await rm(fixtureHome, { recursive: true, force: true }) + await mkdir(fixtureHome, { recursive: true }) + process.env['KIMI_CODE_HOME'] = fixtureHome + clearSessionCache() + }) + afterEach(async () => { + clearSessionCache() + delete process.env['KIMI_CODE_HOME'] + await rm(fixtureHome, { recursive: true, force: true }) + }) + + it('preserves both workDirs through cold/warm parse', async () => { + await writeKimicodeSession(fixtureHome, 'a') + await writeKimicodeSession(fixtureHome, 'b') + const provider = createKimicodeProvider(fixtureHome) + const sources = await provider.discoverSessions() + const cache = { version: CACHE_VERSION, providers: {} } + const cold = await parseProviderSources('kimicode', sources, new Set(), cache) + expect(sortedPaths(cold)).toEqual(['/a/vault', '/b/vault']) + const warm = await parseProviderSources('kimicode', sources, new Set(), cache) + expect(sortedPaths(warm)).toEqual(['/a/vault', '/b/vault']) + }) +}) + +const requireForTest = createRequire(import.meta.url) +const hermesRoot = vi.hoisted(() => { + const base = process.env['TMPDIR'] || '/tmp' + const root = `${base.replace(/[\\/]+$/, '')}/hermes-r3res-${process.pid}-${Date.now()}` + process.env['HERMES_HOME'] = `${root}/hermes` + return root +}) + +const skipUnlessSqlite = isSqliteAvailable() ? describe : describe.skip + +skipUnlessSqlite('hermes residuals: two-root via parseAllSessions', () => { + const HERMES_HOME = join(hermesRoot, 'hermes') + const CACHE_DIR = join(hermesRoot, 'cache') + + beforeEach(async () => { + clearSessionCache() + await rm(hermesRoot, { recursive: true, force: true }) + await mkdir(HERMES_HOME, { recursive: true }) + process.env['HERMES_HOME'] = HERMES_HOME + process.env['CODEBURN_CACHE_DIR'] = CACHE_DIR + }) + afterEach(async () => { + clearSessionCache() + await rm(hermesRoot, { recursive: true, force: true }) + }) + + it('keeps /a/vault and /b/vault distinct', async () => { + const { DatabaseSync: Database } = requireForTest('node:sqlite') + const db = new Database(join(HERMES_HOME, 'state.db')) + db.exec(` + CREATE TABLE sessions ( + id TEXT PRIMARY KEY, source TEXT, model TEXT, cwd TEXT, git_repo_root TEXT, + input_tokens INTEGER DEFAULT 0, output_tokens INTEGER DEFAULT 0, + cache_read_tokens INTEGER DEFAULT 0, cache_write_tokens INTEGER DEFAULT 0, + reasoning_tokens INTEGER DEFAULT 0, estimated_cost_usd REAL, actual_cost_usd REAL, + api_call_count INTEGER DEFAULT 0, tool_call_count INTEGER DEFAULT 0, + started_at REAL, title TEXT + ) + `) + db.exec(` + CREATE TABLE messages ( + id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, role TEXT NOT NULL, + content TEXT, tool_calls TEXT, timestamp REAL NOT NULL + ) + `) + const startedAt = Date.now() / 1000 - 3600 + for (const parent of ['a', 'b'] as const) { + db.prepare( + `INSERT INTO sessions (id, source, model, cwd, input_tokens, output_tokens, + estimated_cost_usd, api_call_count, started_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ).run(`cwd-${parent}`, 'cli', 'claude-opus-4-6', `/${parent}/vault`, 1000, 200, 0.5, 1, startedAt) + db.prepare('INSERT INTO messages (session_id, role, content, timestamp) VALUES (?, ?, ?, ?)') + .run(`cwd-${parent}`, 'user', 'hello', startedAt) + db.prepare('INSERT INTO messages (session_id, role, content, timestamp) VALUES (?, ?, ?, ?)') + .run(`cwd-${parent}`, 'assistant', 'world', startedAt + 1) + } + db.close() + + // Touch createHermesProvider so residuals import stays live even if discovery + // goes through parseAllSessions env wiring. + expect(createHermesProvider(HERMES_HOME).name).toBe('hermes') + + const cold = await parseAllSessions(undefined, 'hermes') + expect(sortedPaths(cold)).toEqual(['/a/vault', '/b/vault']) + const warm = await parseAllSessions(undefined, 'hermes') + expect(sortedPaths(warm)).toEqual(['/a/vault', '/b/vault']) + }) +}) + +describe('five-provider pipeline merge (#1260 residuals)', () => { + it('merged abs paths from five providers keep /a/vault ≠ /b/vault', async () => { + const root = await mkdtemp(join(tmpdir(), 'r3res-five-')) + const kimiHome = join(root, 'kimi') + try { + await writePiSession(root, 'a') + await writePiSession(root, 'b') + await writeCodexSession(join(root, 'codex'), 'a') + await writeCodexSession(join(root, 'codex'), 'b') + await mkdir(kimiHome, { recursive: true }) + await writeKimicodeSession(kimiHome, 'a') + await writeKimicodeSession(kimiHome, 'b') + + const pi = await parseProviderSources( + 'pi', + await createPiProvider(join(root, 'sessions')).discoverSessions(), + new Set(), + { version: CACHE_VERSION, providers: {} }, + ) + const codex = await parseProviderSources( + 'codex', + await createCodexProvider(join(root, 'codex')).discoverSessions(), + new Set(), + { version: CACHE_VERSION, providers: {} }, + ) + const kimicode = await parseProviderSources( + 'kimicode', + await createKimicodeProvider(kimiHome).discoverSessions(), + new Set(), + { version: CACHE_VERSION, providers: {} }, + ) + + // Claude/hermes abs identities supplied as pipeline-shaped summaries so this + // test stays hermetic without clobbering process.env CLAUDE_CONFIG_DIR / + // HERMES_HOME used by sibling suites. Their discovery→parse paths are + // covered in dedicated describes above. + const claudeish = [ + summary('vault', '/a/vault', { cost: 1 }), + summary('vault', '/b/vault', { cost: 1 }), + ] + const hermesish = [ + summary('vault', '/a/vault', { cost: 1 }), + summary('vault', '/b/vault', { cost: 1 }), + ] + + expect(sortedPaths(pi)).toEqual(['/a/vault', '/b/vault']) + expect(sortedPaths(codex)).toEqual(['/a/vault', '/b/vault']) + expect(sortedPaths(kimicode)).toEqual(['/a/vault', '/b/vault']) + + const merged = mergeProjectsByCrossProviderKey([ + ...claudeish, + ...codex, + ...hermesish, + ...kimicode, + ...pi, + ]) + expect(merged.size).toBe(2) + expect(sortedPaths([...merged.values()])).toEqual(['/a/vault', '/b/vault']) + } finally { + await rm(root, { recursive: true, force: true }) + } + }) +}) diff --git a/tests/codex-review-pi-cwd.test.ts b/tests/codex-review-pi-cwd.test.ts new file mode 100644 index 00000000..b2a8477e --- /dev/null +++ b/tests/codex-review-pi-cwd.test.ts @@ -0,0 +1,59 @@ +/** + * Codex REVISE2 independent fixture (#1260): real Pi JSONL header cwd=/b/vault + * must survive discovery → parseProviderSources → mergeProjectsByCrossProviderKey + * and must NOT fold into an unrelated /a/vault via basename-only identity. + */ +import { expect, it } from 'vitest' +import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { createPiProvider } from '../src/providers/pi.js' +import { parseProviderSources, mergeProjectsByCrossProviderKey } from '../src/parser.js' +import { CACHE_VERSION } from '../src/session-cache.js' +import type { ProjectSummary } from '../src/types.js' + +it('does not attribute a Pi session from /b/vault to the unrelated /a/vault', async () => { + const root = await mkdtemp(join(tmpdir(), 'codex-review-pi-')) + try { + const dir = join(root, 'sessions', '--b-vault--') + await mkdir(dir, { recursive: true }) + await writeFile(join(dir, 'pi-real-cwd.jsonl'), [ + { type: 'session', version: 3, id: 'pi-real-cwd', cwd: '/b/vault', timestamp: '2026-04-14T10:00:00Z' }, + { type: 'message', id: 'pi-message', timestamp: '2026-04-14T10:01:00Z', message: { + role: 'assistant', model: 'gpt-5.4', content: [], responseId: 'pi-response', + usage: { input: 1000, output: 200, cacheRead: 0, cacheWrite: 0, cost: { total: 1 } }, + } }, + ].map(JSON.stringify).join('\n') + '\n') + + const sources = await createPiProvider(join(root, 'sessions')).discoverSessions() + expect(sources).toHaveLength(1) + expect(sources[0]!.sourcePath).toBe('/b/vault') + expect(sources[0]!.project).toBe('vault') + + const pi = await parseProviderSources('pi', sources, new Set(), { version: CACHE_VERSION, providers: {} }) + expect(pi).toHaveLength(1) + expect(pi[0]!.sessions).toHaveLength(1) + // Production-path assertion: abs cwd preserved end-to-end (not basename "vault"). + expect(pi[0]!.projectPath.replace(/\\/g, '/')).toMatch(/\/b\/vault$|^\/b\/vault$/) + expect(pi[0]!.sessions[0]!.workingDirectory?.replace(/\\/g, '/')).toBe('/b/vault') + + const unrelated: ProjectSummary = { + project: 'vault', projectPath: '/a/vault', sessions: [], + totalCostUSD: 10, totalApiCalls: 1, totalProxiedCostUSD: 0, + } + const after = mergeProjectsByCrossProviderKey(structuredClone([unrelated, ...pi])) + expect(after.size).toBe(2) + // Pi is not on the reported-cost allowlist, so token reprice (~0.0055) is + // expected — same figure Codex observed. Guard attribution, not nominal $1. + const byKey = Object.fromEntries([...after.entries()].map(([k, v]) => [k, v.totalCostUSD])) + const aKey = Object.keys(byKey).find(k => k.includes('a/vault')) + const bKey = Object.keys(byKey).find(k => k.includes('b/vault')) + expect(aKey).toBeTruthy() + expect(bKey).toBeTruthy() + expect(byKey[aKey!]).toBe(10) + expect(byKey[bKey!]).toBeGreaterThan(0) + expect(byKey[bKey!]).toBeLessThan(10) + } finally { + await rm(root, { recursive: true, force: true }) + } +}) diff --git a/tests/codex-review-two-pi-roots.test.ts b/tests/codex-review-two-pi-roots.test.ts new file mode 100644 index 00000000..380d8cf8 --- /dev/null +++ b/tests/codex-review-two-pi-roots.test.ts @@ -0,0 +1,116 @@ +/** + * Codex REVISE3 (#1260): two Pi sessions with cwd=/a/vault and /b/vault both + * display as basename "vault". parseProviderSources must keep them distinct + * through cold/warm cache and either discovery order, then merge must report + * both abs projectPaths. + */ +import { describe, expect, it } from 'vitest' +import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { createPiProvider } from '../src/providers/pi.js' +import { parseProviderSources, mergeProjectsByCrossProviderKey } from '../src/parser.js' +import { CACHE_VERSION } from '../src/session-cache.js' +import type { ProjectSummary, SessionSource } from '../src/types.js' + +async function writeTwoVaultRoots(root: string): Promise { + const sessionsRoot = join(root, 'sessions') + for (const parent of ['a', 'b']) { + const dir = join(sessionsRoot, `--${parent}-vault--`) + await mkdir(dir, { recursive: true }) + await writeFile(join(dir, `pi-${parent}.jsonl`), [ + { type: 'session', version: 3, id: `pi-${parent}`, cwd: `/${parent}/vault`, timestamp: '2026-04-14T10:00:00Z' }, + { type: 'message', id: `message-${parent}`, timestamp: '2026-04-14T10:01:00Z', message: { + role: 'assistant', model: 'gpt-5.4', content: [], responseId: `response-${parent}`, + usage: { input: 1000, output: 200, cacheRead: 0, cacheWrite: 0, cost: { total: 1 } }, + } }, + ].map(x => JSON.stringify(x)).join('\n') + '\n') + } + return sessionsRoot +} + +function sortedPaths(projects: ProjectSummary[]): string[] { + return projects.map(p => p.projectPath.replace(/\\/g, '/')).sort() +} + +function reorder(sources: SessionSource[], firstParent: 'a' | 'b'): SessionSource[] { + const prefer = `/${firstParent}/vault` + return [...sources].sort((x, y) => { + const ax = x.sourcePath === prefer ? 0 : 1 + const bx = y.sourcePath === prefer ? 0 : 1 + return ax - bx + }) +} + +describe('two Pi roots same display basename (#1260 REVISE3)', () => { + it('preserves both explicit cwd roots when two Pi sessions share the basename vault', async () => { + const root = await mkdtemp(join(tmpdir(), 'codex-two-pi-')) + try { + const sessionsRoot = await writeTwoVaultRoots(root) + const sources = await createPiProvider(sessionsRoot).discoverSessions() + expect(sources).toHaveLength(2) + const pi = await parseProviderSources('pi', sources, new Set(), { version: CACHE_VERSION, providers: {} }) + const merged = mergeProjectsByCrossProviderKey(pi) + expect([...merged.values()].map(p => p.projectPath.replace(/\\/g, '/')).sort()).toEqual(['/a/vault', '/b/vault']) + } finally { + await rm(root, { recursive: true, force: true }) + } + }) + + it('keeps both roots under cold then warm cache serve', async () => { + const root = await mkdtemp(join(tmpdir(), 'codex-two-pi-cache-')) + try { + const sessionsRoot = await writeTwoVaultRoots(root) + const sources = await createPiProvider(sessionsRoot).discoverSessions() + const cache = { version: CACHE_VERSION, providers: {} } + const cold = await parseProviderSources('pi', sources, new Set(), cache) + expect(sortedPaths(cold)).toEqual(['/a/vault', '/b/vault']) + const warm = await parseProviderSources('pi', sources, new Set(), cache) + expect(sortedPaths(warm)).toEqual(['/a/vault', '/b/vault']) + expect(sortedPaths([...mergeProjectsByCrossProviderKey(warm).values()])).toEqual(['/a/vault', '/b/vault']) + } finally { + await rm(root, { recursive: true, force: true }) + } + }) + + it('is stable across both discovery orders', async () => { + const root = await mkdtemp(join(tmpdir(), 'codex-two-pi-order-')) + try { + const sessionsRoot = await writeTwoVaultRoots(root) + const sources = await createPiProvider(sessionsRoot).discoverSessions() + for (const first of ['a', 'b'] as const) { + const ordered = reorder(sources, first) + const projects = await parseProviderSources('pi', ordered, new Set(), { version: CACHE_VERSION, providers: {} }) + expect(sortedPaths(projects)).toEqual(['/a/vault', '/b/vault']) + expect(sortedPaths([...mergeProjectsByCrossProviderKey(projects).values()])).toEqual(['/a/vault', '/b/vault']) + } + } finally { + await rm(root, { recursive: true, force: true }) + } + }) + + it('same basename across different providers stays distinct by abs path', async () => { + const root = await mkdtemp(join(tmpdir(), 'codex-two-pi-xprov-')) + try { + const sessionsRoot = await writeTwoVaultRoots(root) + const sources = await createPiProvider(sessionsRoot).discoverSessions() + const pi = await parseProviderSources('pi', sources, new Set(), { version: CACHE_VERSION, providers: {} }) + const foreign: ProjectSummary = { + project: 'vault', + projectPath: '/a/vault', + sessions: [], + totalCostUSD: 10, + totalApiCalls: 1, + totalProxiedCostUSD: 0, + } + const merged = mergeProjectsByCrossProviderKey([foreign, ...pi]) + // /a/vault folds with matching Pi root; /b/vault stays separate. + expect(merged.size).toBe(2) + expect(sortedPaths([...merged.values()])).toEqual(['/a/vault', '/b/vault']) + const a = [...merged.values()].find(p => p.projectPath.replace(/\\/g, '/') === '/a/vault')! + expect(a.totalCostUSD).toBeGreaterThan(10) + } finally { + await rm(root, { recursive: true, force: true }) + } + }) +}) diff --git a/tests/cross-provider-project-merge.test.ts b/tests/cross-provider-project-merge.test.ts new file mode 100644 index 00000000..16b73feb --- /dev/null +++ b/tests/cross-provider-project-merge.test.ts @@ -0,0 +1,354 @@ +import { describe, expect, it } from 'vitest' +import type { ProjectSummary } from '../src/types.js' +import { + crossProviderProjectKey, + mergeProjectsByCrossProviderKey, + normalizeAbsProjectPathKey, + normalizeProjectPathKey, +} from '../src/parser.js' + +function summary( + project: string, + projectPath: string, + opts: { cost?: number; calls?: number; wd?: string; savings?: number } = {}, +): ProjectSummary { + return { + project, + projectPath, + sessions: opts.wd + ? ([{ workingDirectory: opts.wd }] as ProjectSummary['sessions']) + : [], + totalCostUSD: opts.cost ?? 1, + totalSavingsUSD: opts.savings ?? 0, + totalApiCalls: opts.calls ?? 1, + totalProxiedCostUSD: 0, + } as ProjectSummary +} + +function costsByKey(merged: Map): Record { + return Object.fromEntries([...merged.entries()].map(([k, v]) => [k, v.totalCostUSD])) +} + +describe('crossProviderProjectKey (#1260)', () => { + it('keys absolute POSIX paths as path:… without folding case', () => { + expect(crossProviderProjectKey(summary('vault', '/root/vault'))).toBe('path:root/vault') + expect(crossProviderProjectKey(summary('Vault', '/a/Vault'))).toBe('path:a/Vault') + expect(crossProviderProjectKey(summary('vault', '/a/vault'))).toBe('path:a/vault') + }) + + it('keys Codex-style stripped abs paths as path:…', () => { + expect(crossProviderProjectKey(summary('root-vault', 'root/vault'))).toBe('path:root/vault') + }) + + it('falls back to session.workingDirectory when projectPath is a slug', () => { + expect( + crossProviderProjectKey(summary('vault', 'vault', { wd: '/root/vault' })), + ).toBe('path:root/vault') + }) + + it('uses a label: key for basename-only rows with no abs hint', () => { + expect(crossProviderProjectKey(summary('vault', 'vault')).startsWith('label:')).toBe(true) + }) +}) + +describe('mergeProjectsByCrossProviderKey (#1260)', () => { + it('folds -root-vault / root-vault / vault into one when abs paths align', () => { + const merged = mergeProjectsByCrossProviderKey([ + summary('-root-vault', '/root/vault', { cost: 10, calls: 2 }), + summary('root-vault', 'root/vault', { cost: 5, calls: 1 }), + summary('vault', 'vault', { cost: 3, calls: 1 }), + ]) + expect(merged.size).toBe(1) + const p = [...merged.values()][0]! + expect(p.totalCostUSD).toBe(18) + expect(p.totalApiCalls).toBe(4) + expect(normalizePathish(p.projectPath)).toMatch(/root\/vault$/) + }) + + it('keeps distinct parents with the same basename separate', () => { + const merged = mergeProjectsByCrossProviderKey([ + summary('a-vault', '/a/vault', { cost: 1 }), + summary('b-vault', '/b/vault', { cost: 2 }), + summary('vault', 'vault', { cost: 99 }), // ambiguous — must NOT fold into either + ]) + expect(merged.size).toBe(3) + const costs = [...merged.values()].map(p => p.totalCostUSD).sort((a, b) => a - b) + expect(costs).toEqual([1, 2, 99]) + }) + + it('attaches a unique basename slug to the only matching abs parent', () => { + const merged = mergeProjectsByCrossProviderKey([ + summary('-root-vault', '/root/vault', { cost: 4 }), + summary('vault', 'vault', { cost: 6 }), + ]) + expect(merged.size).toBe(1) + expect([...merged.values()][0]!.totalCostUSD).toBe(10) + }) + + it('still merges identical abs paths across providers (regression #639)', () => { + const merged = mergeProjectsByCrossProviderKey([ + summary('shared', '/repos/shared', { cost: 10 }), + summary('shared', '/repos/shared', { cost: 5 }), + ]) + expect(merged.size).toBe(1) + expect([...merged.values()][0]!.totalCostUSD).toBe(15) + }) + + it('does not attach slug via sanitized when basename also matches another parent', () => { + // High #1: /root/vault → sanitized root-vault, basename vault + // /other/root-vault → sanitized other-root-vault, basename root-vault + // slug root-vault must NOT fold into /root/vault (sanitized hit) while + // a distinct parent's leaf is literally root-vault. + const merged = mergeProjectsByCrossProviderKey([ + summary('root-vault', '/root/vault', { cost: 1 }), + summary('other-root-vault', '/other/root-vault', { cost: 2 }), + summary('root-vault', 'root-vault', { cost: 99 }), + ]) + expect(merged.size).toBe(3) + const costs = [...merged.values()].map(p => p.totalCostUSD).sort((a, b) => a - b) + expect(costs).toEqual([1, 2, 99]) + const labelRows = [...merged.entries()].filter(([k]) => k.startsWith('label:')) + expect(labelRows).toHaveLength(1) + expect(labelRows[0]![1].totalCostUSD).toBe(99) + }) + + it('does not attach slug when dash/slash sanitized labels collide', () => { + // High #2: /foo/bar/baz and /foo/bar-baz both sanitize to foo-bar-baz. + // Slug foo-bar-baz must stay separate (not last-write-wins attach). + const merged = mergeProjectsByCrossProviderKey([ + summary('foo-bar-baz', '/foo/bar/baz', { cost: 1 }), + summary('foo-bar-baz', '/foo/bar-baz', { cost: 2 }), + summary('foo-bar-baz', 'foo-bar-baz', { cost: 99 }), + ]) + expect(merged.size).toBe(3) + const costs = [...merged.values()].map(p => p.totalCostUSD).sort((a, b) => a - b) + expect(costs).toEqual([1, 2, 99]) + const labelRows = [...merged.entries()].filter(([k]) => k.startsWith('label:')) + expect(labelRows).toHaveLength(1) + expect(labelRows[0]![1].totalCostUSD).toBe(99) + }) + + it('Codex repro: sanitized collision retains full member set (label-only $5)', () => { + // /root/vault + /root-vault both sanitize to root-vault. Label-only + // project:'root-vault' must NOT fold into path:root-vault via basename + // after ignoring the sanitized collision. + const merged = mergeProjectsByCrossProviderKey([ + summary('vault', '/root/vault', { cost: 10 }), + summary('root-vault', '/root-vault', { cost: 20 }), + summary('root-vault', '', { cost: 5 }), + ]) + expect(merged.size).toBe(3) + const byKey = costsByKey(merged) + expect(byKey['path:root/vault']).toBe(10) + expect(byKey['path:root-vault']).toBe(20) + const labelRows = [...merged.entries()].filter(([k]) => k.startsWith('label:')) + expect(labelRows).toHaveLength(1) + expect(labelRows[0]![1].totalCostUSD).toBe(5) + }) + + it.each([ + [0, 1, 2], + [0, 2, 1], + [1, 0, 2], + [1, 2, 0], + [2, 0, 1], + [2, 1, 0], + ] as const)('Codex repro order permutation %i,%i,%i keeps third label-only', (a, b, c) => { + const rows = [ + summary('vault', '/root/vault', { cost: 10 }), + summary('root-vault', '/root-vault', { cost: 20 }), + summary('root-vault', '', { cost: 5 }), + ] + const merged = mergeProjectsByCrossProviderKey([rows[a]!, rows[b]!, rows[c]!]) + expect(merged.size).toBe(3) + const byKey = costsByKey(merged) + expect(byKey['path:root/vault']).toBe(10) + expect(byKey['path:root-vault']).toBe(20) + const labelRows = [...merged.entries()].filter(([k]) => k.startsWith('label:')) + expect(labelRows).toHaveLength(1) + expect(labelRows[0]![1].totalCostUSD).toBe(5) + }) + + it('Codex repro leading-dash alias also stays label-only on collision', () => { + const merged = mergeProjectsByCrossProviderKey([ + summary('vault', '/root/vault', { cost: 10 }), + summary('root-vault', '/root-vault', { cost: 20 }), + summary('-root-vault', '', { cost: 5 }), + ]) + expect(merged.size).toBe(3) + const byKey = costsByKey(merged) + expect(byKey['path:root/vault']).toBe(10) + expect(byKey['path:root-vault']).toBe(20) + const labelRows = [...merged.entries()].filter(([k]) => k.startsWith('label:')) + expect(labelRows).toHaveLength(1) + expect(labelRows[0]![1].totalCostUSD).toBe(5) + }) + + it('shallow /a/b + /a-b sanitized collision keeps empty-path slug separate', () => { + const merged = mergeProjectsByCrossProviderKey([ + summary('b', '/a/b', { cost: 1 }), + summary('a-b', '/a-b', { cost: 2 }), + summary('a-b', '', { cost: 99 }), + ]) + expect(merged.size).toBe(3) + const byKey = costsByKey(merged) + expect(byKey['path:a/b']).toBe(1) + expect(byKey['path:a-b']).toBe(2) + const labelRows = [...merged.entries()].filter(([k]) => k.startsWith('label:')) + expect(labelRows).toHaveLength(1) + expect(labelRows[0]![1].totalCostUSD).toBe(99) + }) + + it('Windows drive paths fold same abs; sanitized collision retains members', () => { + // Same abs via forward/backslash and mixed directory case. + const mixed = mergeProjectsByCrossProviderKey([ + summary('Vault', 'C:\\Work\\Vault', { cost: 2 }), + summary('Vault', 'c:/work/vault', { cost: 2 }), + ]) + expect(mixed.size).toBe(1) + expect([...mixed.values()][0]!.totalCostUSD).toBe(4) + + const same = mergeProjectsByCrossProviderKey([ + summary('vault', 'C:/root/vault', { cost: 10 }), + summary('vault', 'C:\\root\\vault', { cost: 5 }), + ]) + expect(same.size).toBe(1) + expect([...same.values()][0]!.totalCostUSD).toBe(15) + expect(costsByKey(same)['path:c:/root/vault']).toBe(15) + + // Drive-letter sanitized collision (c:-root-vault) must expand members; + // slug matching that sanitized form stays label-only (not basename-wins). + const merged = mergeProjectsByCrossProviderKey([ + summary('vault', 'C:/root/vault', { cost: 10 }), + summary('root-vault', 'C:/root-vault', { cost: 20 }), + summary('c:-root-vault', '', { cost: 5 }), + ]) + expect(merged.size).toBe(3) + const byKey = costsByKey(merged) + expect(byKey['path:c:/root/vault']).toBe(10) + expect(byKey['path:c:/root-vault']).toBe(20) + const labelRows = [...merged.entries()].filter(([k]) => k.startsWith('label:')) + expect(labelRows).toHaveLength(1) + expect(labelRows[0]![1].totalCostUSD).toBe(5) + }) + + it('empty projectPath with no wd stays label-only', () => { + expect(crossProviderProjectKey(summary('vault', '')).startsWith('label:')).toBe(true) + const merged = mergeProjectsByCrossProviderKey([ + summary('vault', '', { cost: 7 }), + ]) + expect(merged.size).toBe(1) + expect([...merged.keys()][0]!.startsWith('label:')).toBe(true) + expect([...merged.values()][0]!.totalCostUSD).toBe(7) + }) + + it('documents multi-segment relative looksAbs over-merge residual', () => { + // looksAbs treats "packages/api"-style relatives as abs-ish (Codex stripped). + // Unrelated trees that share the same relative string therefore fold — known + // residual, pinned here; not expanded into a #1260 fix. + const over = mergeProjectsByCrossProviderKey([ + summary('api', 'packages/api', { cost: 10 }), + summary('api', 'packages/api', { cost: 5 }), + ]) + expect(over.size).toBe(1) + expect([...over.values()][0]!.totalCostUSD).toBe(15) + expect(costsByKey(over)['path:packages/api']).toBe(15) + + // Distinct relative trees stay separate. + const distinct = mergeProjectsByCrossProviderKey([ + summary('api', 'packages/api', { cost: 10 }), + summary('web', 'packages/web', { cost: 5 }), + ]) + expect(distinct.size).toBe(2) + }) + + it('leading-dash project label aliases attach to unique abs parent', () => { + const merged = mergeProjectsByCrossProviderKey([ + summary('vault', '/root/vault', { cost: 4 }), + summary('-root-vault', '', { cost: 6 }), + ]) + expect(merged.size).toBe(1) + expect([...merged.values()][0]!.totalCostUSD).toBe(10) + }) + + it('Windows drive and POSIX abs of different roots stay separate', () => { + const merged = mergeProjectsByCrossProviderKey([ + summary('vault', 'C:/root/vault', { cost: 10 }), + summary('vault', '/root/vault', { cost: 5 }), + ]) + expect(merged.size).toBe(2) + const byKey = costsByKey(merged) + expect(byKey['path:c:/root/vault']).toBe(10) + expect(byKey['path:root/vault']).toBe(5) + }) + + it('UNC-style paths key as path and fold slash-normalized forms', () => { + const unc = '\\\\server\\share\\vault' // JS: \\server\share\vault + const a = crossProviderProjectKey(summary('share', unc)) + const b = crossProviderProjectKey(summary('share', '//server/share/vault')) + expect(a.startsWith('path:')).toBe(true) + expect(a).toBe(b) + const merged = mergeProjectsByCrossProviderKey([ + summary('share', unc, { cost: 10 }), + summary('share', '//server/share/vault', { cost: 5 }), + ]) + expect(merged.size).toBe(1) + expect([...merged.values()][0]!.totalCostUSD).toBe(15) + + const mixedUnc = mergeProjectsByCrossProviderKey([ + summary('share', '\\\\Server\\Share\\Vault', { cost: 10 }), + summary('share', '//server/share/vault', { cost: 5 }), + ]) + expect(mixedUnc.size).toBe(1) + expect([...mixedUnc.values()][0]!.totalCostUSD).toBe(15) + + // Light \\?\ prefix form — still path-keyed after slash normalize. + const long = crossProviderProjectKey(summary('vault', '\\\\?\\C:\\root\\vault')) + expect(long.startsWith('path:')).toBe(true) + }) + + it('promotes display projectPath when existing lacks abs and incoming has abs', () => { + // First row keys via wd but projectPath is a slug; second promotes display path. + const merged = mergeProjectsByCrossProviderKey([ + summary('vault', 'vault', { cost: 3, wd: '/root/vault' }), + summary('vault', '/root/vault', { cost: 7 }), + ]) + expect(merged.size).toBe(1) + const p = [...merged.values()][0]! + expect(p.totalCostUSD).toBe(10) + expect(normalizePathish(p.projectPath)).toMatch(/root\/vault$/) + }) + + it('display projectPath promotion is order-dependent when both look abs', () => { + // Both Codex-stripped and POSIX look abs → first writer keeps projectPath. + const aFirst = mergeProjectsByCrossProviderKey([ + summary('vault', 'root/vault', { cost: 1 }), + summary('vault', '/root/vault', { cost: 2 }), + ]) + const bFirst = mergeProjectsByCrossProviderKey([ + summary('vault', '/root/vault', { cost: 2 }), + summary('vault', 'root/vault', { cost: 1 }), + ]) + expect([...aFirst.values()][0]!.projectPath).toBe('root/vault') + expect([...bFirst.values()][0]!.projectPath).toBe('/root/vault') + expect([...aFirst.values()][0]!.totalCostUSD).toBe(3) + expect([...bFirst.values()][0]!.totalCostUSD).toBe(3) + }) + + it('sums totalSavingsUSD when the same abs root is grouped', () => { + // Root log root-project-case-savings-51765867.log recorded 30 because + // foldInto dropped the second savings. Product expectation is 32. + const merged = mergeProjectsByCrossProviderKey([ + summary('shared', '/repos/shared', { cost: 10, savings: 30 }), + summary('shared', '/repos/shared', { cost: 5, savings: 2 }), + ]) + expect(merged.size).toBe(1) + const p = [...merged.values()][0]! + expect(p.totalCostUSD).toBe(15) + expect(p.totalSavingsUSD).toBe(32) + }) +}) + +function normalizePathish(path: string): string { + return path.replace(/\\/g, '/').replace(/^\/+/, '').toLowerCase() +} diff --git a/tests/dashboard-progressive-startup.test.ts b/tests/dashboard-progressive-startup.test.ts index df731484..fb225563 100644 --- a/tests/dashboard-progressive-startup.test.ts +++ b/tests/dashboard-progressive-startup.test.ts @@ -281,6 +281,7 @@ describe('interactive dashboard progressive startup', () => { savingsUSD: expected.data.savingsUSD, calls: expected.data.calls, sessions: expected.data.sessions, + sessionCountBasis: expected.data.sessionCountBasis, inputTokens: expected.data.inputTokens, outputTokens: expected.data.outputTokens, cacheReadTokens: expected.data.cacheReadTokens, diff --git a/tests/mcp-redact.test.ts b/tests/mcp-redact.test.ts index 6ad8ad12..2d31feb0 100644 --- a/tests/mcp-redact.test.ts +++ b/tests/mcp-redact.test.ts @@ -46,6 +46,13 @@ describe('redact', () => { expect(out.current.topSessions[0]!.project).toMatch(/^project-[0-9a-f]{6}$/) expect(out.current.topProjects[0]!.cost).toBe(5) }) + it('hashes topProjects id when present so cwd is not leaked', () => { + const withId = payload() + withId.current.topProjects[0]!.id = '/tmp/secret-client-repo' + const out = redactProjectNames(withId, false) + expect(out.current.topProjects[0]!.id).toMatch(/^project-[0-9a-f]{6}$/) + expect(JSON.stringify(out)).not.toContain('/tmp/secret-client-repo') + }) it('redacts session details when hashing', () => { const out = redactProjectNames(payload(), false) const details = out.current.topProjects[0]!.sessionDetails! diff --git a/tests/menubar-project-identity.test.ts b/tests/menubar-project-identity.test.ts new file mode 100644 index 00000000..e182cd14 --- /dev/null +++ b/tests/menubar-project-identity.test.ts @@ -0,0 +1,502 @@ +import { existsSync, mkdirSync, unlinkSync, writeFileSync } from 'node:fs' +import { mkdtemp } from 'node:fs/promises' +import { homedir, tmpdir } from 'node:os' +import { join } from 'node:path' + +import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest' + +import { getDateRange } from '../src/cli-date.js' +import { currentTzKey, DAILY_CACHE_VERSION, toDateString, type DailyCache, type DailyEntry } from '../src/daily-cache.js' +import { calculateCost, loadPricing } from '../src/models.js' +import { computeSpendFlow } from '../src/spend-flow.js' +import type { ProjectSummary, SessionSummary } from '../src/types.js' +import { buildMenubarPayloadForRange, buildPayloadProjects, getDailyCacheConfigHash } from '../src/usage-aggregator.js' + +vi.setConfig({ testTimeout: 30_000 }) + +const emptyTokens = { + inputTokens: 0, + outputTokens: 0, + cacheCreationInputTokens: 0, + cacheReadInputTokens: 0, + cachedInputTokens: 0, + reasoningTokens: 0, + webSearchRequests: 0, +} + +function session(opts: { + id: string + project: string + cost: number + models: Record +}): SessionSummary { + return { + sessionId: opts.id, + project: opts.project, + firstTimestamp: '2026-09-07T12:00:00.000Z', + lastTimestamp: '2026-09-07T12:01:00.000Z', + totalCostUSD: opts.cost, + totalSavingsUSD: 0, + totalInputTokens: 0, + totalOutputTokens: 0, + totalReasoningTokens: 0, + totalCacheReadTokens: 0, + totalCacheWriteTokens: 0, + apiCalls: Object.keys(opts.models).length, + turns: [], + modelBreakdown: Object.fromEntries( + Object.entries(opts.models).map(([name, costUSD]) => [ + name, + { calls: 1, costUSD, savingsUSD: 0, tokens: emptyTokens }, + ]), + ), + toolBreakdown: {}, + mcpBreakdown: {}, + bashBreakdown: {}, + categoryBreakdown: {}, + skillBreakdown: {}, + subagentBreakdown: {}, + } as SessionSummary +} + +function live(project: string, projectPath: string, sessions: SessionSummary[]): ProjectSummary { + return { + project, + projectPath, + sessions, + totalCostUSD: sessions.reduce((s, sess) => s + sess.totalCostUSD, 0), + totalSavingsUSD: 0, + totalApiCalls: sessions.reduce((s, sess) => s + sess.apiCalls, 0), + totalProxiedCostUSD: 0, + } +} + +function cacheDay(projects: NonNullable): DailyEntry { + return { + date: '2026-09-07', + cost: 0, + savingsUSD: 0, + calls: 0, + sessions: 0, + inputTokens: 0, + outputTokens: 0, + cacheReadTokens: 0, + cacheWriteTokens: 0, + editTurns: 0, + oneShotTurns: 0, + models: {}, + categories: {}, + providers: {}, + projects, + } +} + +describe('buildPayloadProjects identity', () => { + const home = '/Users/me' + + it('coalesces provider-split cache slugs for the same cwd with cost/session conservation', () => { + const shared = '/tmp/shared-vault' + const other = '/tmp/other-vault' + const rows = buildPayloadProjects( + [ + live('shared-vault', shared, [ + session({ id: 'claude', project: 'shared-vault', cost: 0.468, models: { 'Opus 4.6': 0.45, 'Sonnet 4.5': 0.018 } }), + session({ id: 'codex', project: '-tmp-shared-vault', cost: 0.00091, models: { 'GPT-5.3 Codex': 0.00091 } }), + ]), + live('other-vault', other, [ + session({ id: 'haiku', project: 'other-vault', cost: 0.015, models: { 'Haiku 4.5': 0.015 } }), + ]), + ], + [cacheDay({ + 'shared-vault': { cost: 0.468, calls: 3, savingsUSD: 0, sessions: 1, path: shared }, + '-tmp-shared-vault': { cost: 0.00091, calls: 2, savingsUSD: 0, sessions: 1, path: shared }, + 'other-vault': { cost: 0.015, calls: 1, savingsUSD: 0, sessions: 1, path: other }, + })], + home, + ) + + expect(rows.map(r => r.id)).toEqual([shared, other]) + expect(rows.map(r => r.name)).toEqual(['shared-vault', 'other-vault']) + expect(rows[0]!.cost).toBeCloseTo(0.46891, 10) + expect(rows[0]!.sessions).toBe(2) + expect(rows[0]!.sessionDetails?.map(s => s.models[0]?.name)).toEqual(['Opus 4.6', 'GPT-5.3 Codex']) + expect(rows[1]!.cost).toBeCloseTo(0.015, 10) + expect(rows.reduce((s, r) => s + r.cost, 0)).toBeCloseTo(0.48391, 10) + expect(rows.reduce((s, r) => s + r.sessions, 0)).toBe(3) + }) + + it('keeps distinct cwd with the same basename separate and disambiguates labels', () => { + const rows = buildPayloadProjects( + [ + live('vault', '/a/vault', [session({ id: 'a', project: 'vault', cost: 10, models: { opus: 10 } })]), + live('vault', '/b/vault', [session({ id: 'b', project: 'vault', cost: 1, models: { sonnet: 1 } })]), + ], + null, + home, + ) + expect(rows).toHaveLength(2) + expect(rows.map(r => r.id).sort()).toEqual(['/a/vault', '/b/vault']) + expect(rows.map(r => r.name).sort()).toEqual(['a/vault', 'b/vault']) + expect(rows.map(r => r.cost).sort((a, b) => b - a)).toEqual([10, 1]) + }) + + it('keeps old cache rows with no path as a slug fallback', () => { + const rows = buildPayloadProjects( + [], + [cacheDay({ + 'legacy-slug': { cost: 2, calls: 4, savingsUSD: 0, sessions: 1 }, + })], + home, + ) + expect(rows).toHaveLength(1) + expect(rows[0]!.id).toBe('legacy-slug') + expect(rows[0]!.name).toBe('legacy-slug') + expect(rows[0]!.cost).toBe(2) + expect(rows[0]!.sessionDetails).toBeUndefined() + }) + + // Root fixture root-project-adjacent-repro.ts — adapt only the import. + it('distinct POSIX cwd must not be lowercased into one project', () => { + const days: any = [{ projects: { first: { path: '/tmp/Case/Vault', cost: 1, savingsUSD: 0, sessions: 1 }, second: { path: '/tmp/case/vault', cost: 2, savingsUSD: 0, sessions: 1 } } }] + const rows = buildPayloadProjects([], days, '/Users/synthetic') + expect(rows.length).toBe(2) + expect(rows.map(r => r.id).sort()).toEqual(['/tmp/Case/Vault', '/tmp/case/vault']) + expect(rows.map(r => r.cost).sort((a, b) => a - b)).toEqual([1, 2]) + }) + + it('joins a pathless cache slug with a unique live path without double-counting', () => { + const rows = buildPayloadProjects( + [live('legacy-slug', '/tmp/legacy-slug', [session({ id: 's', project: 'legacy-slug', cost: 2, models: { opus: 2 } })])], + [cacheDay({ + 'legacy-slug': { cost: 2, calls: 4, savingsUSD: 0, sessions: 1 }, + })], + home, + ) + expect(rows).toHaveLength(1) + expect(rows[0]!.id).toBe('/tmp/legacy-slug') + expect(rows[0]!.cost).toBe(2) + expect(rows[0]!.sessions).toBe(1) + expect(rows[0]!.sessionDetails).toHaveLength(1) + }) + + it('joins pathless and later-pathed cache days for the same slug', () => { + const rows = buildPayloadProjects( + [], + [ + cacheDay({ 'legacy-slug': { cost: 1, calls: 1, savingsUSD: 0, sessions: 1 } }), + { ...cacheDay({ 'legacy-slug': { cost: 1, calls: 1, savingsUSD: 0, sessions: 1, path: '/tmp/legacy-slug' } }), date: '2026-09-06' }, + ], + home, + ) + expect(rows).toHaveLength(1) + expect(rows[0]!.id).toBe('/tmp/legacy-slug') + expect(rows[0]!.cost).toBe(2) + }) + + it('keeps ambiguous pathless cache authoritative and does not add matching live cost', () => { + // Cache-authoritative: the pathless slug total already accounts for those + // live folders. Guessing /a vs /b would double-count. Matching live stays + // as detail on the legacy key (cost 0 assigned is not emitted as a path row). + const rows = buildPayloadProjects( + [ + live('vault', '/a/vault', [session({ id: 'a', project: 'vault', cost: 6, models: { opus: 6 } })]), + live('vault', '/b/vault', [session({ id: 'b', project: 'vault', cost: 4, models: { sonnet: 4 } })]), + ], + [cacheDay({ + vault: { cost: 10, calls: 2, savingsUSD: 0, sessions: 2 }, + })], + home, + ) + expect(rows.reduce((s, r) => s + r.cost, 0)).toBe(10) + expect(rows.find(r => r.id === 'vault')!.cost).toBe(10) + expect(rows.filter(r => r.id === '/a/vault' || r.id === '/b/vault').every(r => r.cost === 0)).toBe(true) + }) + + it('conserves live-only provider cost when coalescing a cached provider at the same cwd', () => { + const shared = '/tmp/shared-vault' + const rows = buildPayloadProjects( + [ + live('shared-vault', shared, [ + session({ id: 'claude', project: 'shared-vault', cost: 0.45, models: { 'Opus 4.6': 0.45 } }), + ]), + live('-tmp-shared-vault', shared, [ + session({ id: 'codex', project: '-tmp-shared-vault', cost: 0.00091, models: { 'GPT-5.3 Codex': 0.00091 } }), + ]), + ], + [cacheDay({ + 'shared-vault': { cost: 0.45, calls: 1, savingsUSD: 0, sessions: 1, path: shared }, + })], + home, + ) + expect(rows).toHaveLength(1) + expect(rows[0]!.id).toBe(shared) + expect(rows[0]!.cost).toBeCloseTo(0.45091, 10) + expect(rows[0]!.sessions).toBe(2) + expect(rows[0]!.sessionDetails?.map(s => s.models[0]?.name)).toEqual(['Opus 4.6', 'GPT-5.3 Codex']) + }) + + // Root fixture root-project-cache-path-repro.ts — adapt only the import. + it('Known different cwd must survive cache-day folding', () => { + const rows = buildPayloadProjects([], [ + { date: '2026-09-06', projects: { vault: { path: '/a/vault', cost: 2, savingsUSD: 0, sessions: 1 } } }, + { date: '2026-09-07', projects: { vault: { path: '/b/vault', cost: 3, savingsUSD: 0, sessions: 1 } } }, + ] as any, '/Users/synthetic') + expect(rows.length).toBe(2) + expect(rows.map(r => [r.id, r.cost]).sort()).toEqual([['/a/vault', 2], ['/b/vault', 3]]) + }) + + // Root fixture root-project-ambiguous-repro.ts — adapt only the import. + it('A legacy cached total must not be added to its matching live breakdown again', () => { + const sess = (id: string, cost: number): any => ({ sessionId: id, project: id, firstTimestamp: '2026-09-07T12:00:00Z', totalCostUSD: cost, totalSavingsUSD: 0, apiCalls: 1, totalInputTokens: 100, totalOutputTokens: 20, totalReasoningTokens: 0, modelBreakdown: {}, turns: [] }) + const liveRow = (projectPath: string, cost: number): any => ({ project: 'vault', projectPath, sessions: [sess('vault', cost)], totalCostUSD: cost, totalSavingsUSD: 0, totalApiCalls: 1 }) + const rows = buildPayloadProjects([liveRow('/a/vault', 2), liveRow('/b/vault', 3)], [{ projects: { vault: { cost: 5, savingsUSD: 0, sessions: 2 } } }] as any, '/Users/synthetic') + expect(rows.reduce((n, r) => n + r.cost, 0)).toBe(5) + }) + + // Root fixture root-project-mixed-valid-repro.ts — adapt only the import. + it('Other provider cache must not suppress live-only provider cost', () => { + const sess = (id: string, cost: number): any => ({ sessionId: id, project: id, firstTimestamp: '2026-09-07T12:00:00Z', totalCostUSD: cost, totalSavingsUSD: 0, apiCalls: 1, totalInputTokens: 100, totalOutputTokens: 20, totalReasoningTokens: 0, modelBreakdown: {}, turns: [] }) + const liveRow = (project: string, cost: number): any => ({ project, projectPath: '/tmp/shared-vault', sessions: [sess(project, cost)], totalCostUSD: cost, totalSavingsUSD: 0, totalApiCalls: 1 }) + const rows = buildPayloadProjects([liveRow('claude-slug', 2), liveRow('codex-slug', 3)], [{ projects: { 'claude-slug': { path: '/tmp/shared-vault', cost: 2, savingsUSD: 0, sessions: 1 } } }] as any, '/Users/synthetic') + expect(rows.length).toBe(1) + expect(rows[0]!.cost).toBe(5) + }) + + // Root fixture root-project-detail-ownership-repro.ts — adapt only the import. + it('Unallocated legacy details must exclude live-only sibling', () => { + const sess = (id: string, cost: number): any => ({ sessionId: id, project: id, firstTimestamp: '2026-09-07T12:00:00Z', totalCostUSD: cost, totalSavingsUSD: 0, apiCalls: 1, totalInputTokens: 100, totalOutputTokens: 20, totalReasoningTokens: 0, modelBreakdown: {}, turns: [] }) + const liveRow = (path: string, sessions: any[]): any => ({ project: 'vault', projectPath: path, sessions, totalCostUSD: sessions.reduce((n: number, s: any) => n + s.totalCostUSD, 0), totalSavingsUSD: 0, totalApiCalls: sessions.length }) + const rows = buildPayloadProjects([liveRow('/a/vault', [sess('vault', 2), sess('codex-other', 7)]), liveRow('/b/vault', [sess('vault', 3)])], [{ projects: { vault: { cost: 5, savingsUSD: 0, sessions: 2 } } }] as any, '/Users/synthetic') + expect(rows.reduce((n, r) => n + r.cost, 0)).toBe(12) + const legacy = rows.find(r => r.id === 'vault')! + const other = rows.find(r => r.id === '/a/vault')! + expect(legacy.sessionDetails!.reduce((n, r) => n + r.cost, 0)).toBe(5) + expect(other.sessionDetails!.reduce((n, r) => n + r.cost, 0)).toBe(7) + expect(legacy.name).not.toBe(other.name) + }) + + it('conserves mixed bases when live parse already grouped both providers on one cwd row', () => { + const shared = '/tmp/shared-vault' + const rows = buildPayloadProjects( + [ + live('shared-vault', shared, [ + session({ id: 'claude', project: 'shared-vault', cost: 0.45, models: { 'Opus 4.6': 0.45 } }), + session({ id: 'codex', project: '-tmp-shared-vault', cost: 0.00091, models: { 'GPT-5.3 Codex': 0.00091 } }), + ]), + ], + [cacheDay({ + 'shared-vault': { cost: 0.45, calls: 1, savingsUSD: 0, sessions: 1, path: shared }, + })], + home, + ) + expect(rows).toHaveLength(1) + expect(rows[0]!.id).toBe(shared) + expect(rows[0]!.cost).toBeCloseTo(0.45091, 10) + expect(rows[0]!.sessions).toBe(2) + }) +}) + +describe('menubar project identity pipeline', () => { + const saved: Record = {} + const named = ['CLAUDE_CONFIG_DIR', 'CODEBURN_CACHE_DIR', 'CODEBURN_DESKTOP_SESSIONS_DIR'] as const + + beforeAll(async () => { + await loadPricing() + }) + + afterEach(() => { + for (const key of named) { + if (saved[key] === undefined) delete process.env[key] + else process.env[key] = saved[key] + } + }) + + it('same cwd Claude+Codex coalesce once; distinct cwd same basename stay split', async () => { + for (const key of named) saved[key] = process.env[key] + + const stamp = `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}` + const claudeRoot = await mkdtemp(join(tmpdir(), 'cb-ident-claude-')) + const cacheDir = await mkdtemp(join(tmpdir(), 'cb-ident-cache-')) + const desktopDir = await mkdtemp(join(tmpdir(), 'cb-ident-desktop-')) + process.env['CLAUDE_CONFIG_DIR'] = claudeRoot + process.env['CODEBURN_CACHE_DIR'] = cacheDir + process.env['CODEBURN_DESKTOP_SESSIONS_DIR'] = desktopDir + + const shared = `/tmp/cb-ident-${stamp}/shared-vault` + const other = `/tmp/cb-ident-${stamp}/other-vault` + const altShared = `/tmp/cb-ident-${stamp}-alt/shared-vault` + const projShared = join(claudeRoot, 'projects', 'shared-vault') + const projOther = join(claudeRoot, 'projects', 'other-vault') + const projAlt = join(claudeRoot, 'projects', 'alt-shared-vault') + mkdirSync(projShared, { recursive: true }) + mkdirSync(projOther, { recursive: true }) + mkdirSync(projAlt, { recursive: true }) + mkdirSync(desktopDir, { recursive: true }) + + const now = new Date() + const todayTs = new Date(now.getTime() - 60_000).toISOString() + const todayStr = toDateString(now) + const opus = 'claude-opus-4-6' + const sonnet = 'claude-sonnet-4-5' + const haiku = 'claude-haiku-4-5' + + const user = (id: string, cwd: string) => JSON.stringify({ + type: 'user', sessionId: id, timestamp: todayTs, cwd, + message: { role: 'user', content: 'work' }, + }) + const assistant = (model: string, id: string, cwd: string, usage: { input: number; output: number; cacheR?: number }) => + JSON.stringify({ + type: 'assistant', + sessionId: id, + timestamp: todayTs, + cwd, + message: { + id, + type: 'message', + role: 'assistant', + model, + content: [{ type: 'text', text: 'ok' }], + usage: { + input_tokens: usage.input, + output_tokens: usage.output, + cache_creation_input_tokens: 0, + cache_read_input_tokens: usage.cacheR ?? 0, + }, + }, + }) + + writeFileSync(join(projShared, 'sess.jsonl'), [ + user('shared-sonnet', shared), + assistant(sonnet, 'shared-sonnet', shared, { input: 4000, output: 400 }), + user('shared-opus', shared), + assistant(opus, 'shared-opus', shared, { input: 0, output: 0, cacheR: 900_000 }), + ].join('\n') + '\n') + writeFileSync(join(projOther, 'sess.jsonl'), [ + user('other-haiku', other), + assistant(haiku, 'other-haiku', other, { input: 10_000, output: 1_000 }), + ].join('\n') + '\n') + writeFileSync(join(projAlt, 'sess.jsonl'), [ + user('alt-sonnet', altShared), + assistant(sonnet, 'alt-sonnet', altShared, { input: 4000, output: 400 }), + ].join('\n') + '\n') + + const y = todayStr.slice(0, 4), m = todayStr.slice(5, 7), d = todayStr.slice(8, 10) + const codexDay = join(homedir(), '.codex', 'sessions', y, m, d) + mkdirSync(codexDay, { recursive: true }) + const tokenEvent = (n: number, cum: number) => JSON.stringify({ + type: 'event_msg', + timestamp: todayTs, + payload: { + type: 'token_count', + info: { + last_token_usage: { input_tokens: 100, output_tokens: 20, cached_input_tokens: 0, reasoning_output_tokens: 0 }, + total_token_usage: { total_tokens: cum, input_tokens: 100 * n, output_tokens: 20 * n }, + }, + }, + }) + const rolloutPath = join(codexDay, `rollout-ident-${stamp}.jsonl`) + writeFileSync(rolloutPath, [ + JSON.stringify({ + type: 'session_meta', + timestamp: todayTs, + payload: { session_id: `codex-shared-${stamp}`, cwd: shared, originator: 'codex-cli', model: 'gpt-5.3-codex' }, + }), + tokenEvent(1, 120), + tokenEvent(2, 240), + ].join('\n') + '\n') + + const sonnetCost = calculateCost(sonnet, 4000, 400, 0, 0, 0) + const opusCost = calculateCost(opus, 0, 0, 0, 900_000, 0) + const haikuCost = calculateCost(haiku, 10_000, 1_000, 0, 0, 0) + const codexCost = calculateCost('gpt-5.3-codex', 100, 20, 0, 0, 0) * 2 + const sharedCost = sonnetCost + opusCost + codexCost + const expectedTotal = sharedCost + haikuCost + sonnetCost + + try { + const period = getDateRange('today') + const payload = await buildMenubarPayloadForRange(period, { provider: 'all', optimize: false, timeline: false }) + const flow = await computeSpendFlow(period.range, 'all') + + expect(payload.current.cost).toBeCloseTo(expectedTotal, 8) + const projects = payload.current.topProjects + expect(projects.map(p => p.id).sort()).toEqual([altShared, other, shared].sort()) + const sharedRow = projects.find(p => p.id === shared)! + const altRow = projects.find(p => p.id === altShared)! + const otherRow = projects.find(p => p.id === other)! + expect(sharedRow.cost).toBeCloseTo(sharedCost, 8) + expect(sharedRow.sessions).toBe(2) + expect(sharedRow.sessionDetails.length).toBeGreaterThanOrEqual(2) + const sharedModels = sharedRow.sessionDetails.flatMap(s => s.models.map(m => m.name)).join(' ') + expect(sharedModels.toLowerCase()).toMatch(/opus/) + expect(sharedModels.toLowerCase()).toMatch(/codex/) + expect(altRow.cost).toBeCloseTo(sonnetCost, 8) + expect(altRow.sessions).toBe(1) + expect(otherRow.cost).toBeCloseTo(haikuCost, 8) + expect(new Set(projects.map(p => p.id)).size).toBe(3) + expect(sharedRow.name).not.toBe(altRow.name) + expect(projects.reduce((s, p) => s + p.cost, 0)).toBeCloseTo(payload.current.cost, 8) + expect(projects.reduce((s, p) => s + p.sessions, 0)).toBe(payload.current.sessions) + + expect(flow.projects.map(p => p.id).sort()).toEqual([altShared, other, shared].sort()) + expect(flow.projects.find(p => p.id === shared)!.cost).toBeCloseTo(sharedCost, 8) + } finally { + if (existsSync(rolloutPath)) unlinkSync(rolloutPath) + } + }) + + it('buildMenubarPayloadForRange keeps distinct known cache paths of the same slug', async () => { + for (const key of named) saved[key] = process.env[key] + + const claudeRoot = await mkdtemp(join(tmpdir(), 'cb-ident-cachepath-claude-')) + const cacheDir = await mkdtemp(join(tmpdir(), 'cb-ident-cachepath-cache-')) + const desktopDir = await mkdtemp(join(tmpdir(), 'cb-ident-cachepath-desktop-')) + process.env['CLAUDE_CONFIG_DIR'] = claudeRoot + process.env['CODEBURN_CACHE_DIR'] = cacheDir + process.env['CODEBURN_DESKTOP_SESSIONS_DIR'] = desktopDir + mkdirSync(join(claudeRoot, 'projects'), { recursive: true }) + mkdirSync(desktopDir, { recursive: true }) + + const day = (n: number): string => { + const d = new Date() + d.setDate(d.getDate() - n) + return toDateString(d) + } + const carried = (date: string, path: string, cost: number): DailyEntry => { + const projects = { vault: { cost, calls: 1, savingsUSD: 0, sessions: 1, path } } + return { + date, + cost, + savingsUSD: 0, + calls: 1, + sessions: 1, + inputTokens: 0, + outputTokens: 0, + cacheReadTokens: 0, + cacheWriteTokens: 0, + editTurns: 0, + oneShotTurns: 0, + models: {}, + categories: {}, + providers: { claude: { calls: 1, cost, savingsUSD: 0, sessions: 1, projects } }, + projects, + carried: true, + } + } + const cache: DailyCache = { + version: DAILY_CACHE_VERSION, + savingsConfigHash: getDailyCacheConfigHash(), + tzKey: currentTzKey(), + lastComputedDate: day(1), + days: [carried(day(3), '/a/vault', 2), carried(day(2), '/b/vault', 3)], + complete: true, + watermarkTrusted: true, + } + writeFileSync(join(cacheDir, `daily-cache.v${DAILY_CACHE_VERSION}.json`), JSON.stringify(cache)) + + const period = getDateRange('week') + const payload = await buildMenubarPayloadForRange(period, { provider: 'all', optimize: false, timeline: false }) + const ids = payload.current.topProjects.map(p => [p.id, p.cost] as const).sort() + expect(ids).toEqual([['/a/vault', 2], ['/b/vault', 3]]) + expect(payload.current.topProjects.reduce((s, p) => s + p.cost, 0)).toBe(5) + }) +}) diff --git a/tests/overview.test.ts b/tests/overview.test.ts index bdc38587..6679ac97 100644 --- a/tests/overview.test.ts +++ b/tests/overview.test.ts @@ -273,3 +273,35 @@ describe('renderOverview unpriced models', () => { expect(out).not.toContain('Unpriced') }) }) + +describe('renderOverview #1260 residuals', () => { + it('keeps same basename distinct abs paths as separate Top projects rows', () => { + const out = renderOverview([ + makeProject({ + project: 'vault', + projectPath: '/a/vault', + cost: 10, + calls: 1, + model: 'claude-sonnet-4-5', + provider: 'claude', + tokens: { input: 10, output: 5, cacheR: 0, cacheW: 0 }, + }), + makeProject({ + project: 'vault', + projectPath: '/b/vault', + cost: 1, + calls: 1, + model: 'gpt-5.4', + provider: 'pi', + tokens: { input: 10, output: 5, cacheR: 0, cacheW: 0 }, + }), + ], { label: 'residuals', color: false }) + expect(out).toContain('a/vault') + expect(out).toContain('b/vault') + expect(out).toContain('$10.00') + expect(out).toContain('$1.00') + // Must not collapse into a single basename-only vault row for both costs. + const top = out.split('Top projects')[1]?.split('Daily')[0] ?? '' + expect(top).not.toMatch(/│\s+vault\s+│\s+\$11\.00/) + }) +}) diff --git a/tests/project-key-cwd-preserve-1260.test.ts b/tests/project-key-cwd-preserve-1260.test.ts new file mode 100644 index 00000000..c2e3b518 --- /dev/null +++ b/tests/project-key-cwd-preserve-1260.test.ts @@ -0,0 +1,386 @@ +/** + * #1260 REVISE2 — preserve real cwd through the five issue providers + * (claude, codex, hermes, kimicode, pi) and refuse basename-only false merges + * when absolute parents differ. Also covers missing/ambiguous cwd, same-parent + * fold, cold/warm cache, and supported path shapes. + */ +import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest' +import { mkdtemp, mkdir, writeFile, rm, utimes } from 'node:fs/promises' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { createHash } from 'node:crypto' + +import { + clearSessionCache, + mergeProjectsByCrossProviderKey, + parseAllSessions, + parseProviderSources, +} from '../src/parser.js' +import { createPiProvider } from '../src/providers/pi.js' +import { createCodexProvider } from '../src/providers/codex.js' +import { createKimicodeProvider } from '../src/providers/kimicode.js' +import { CACHE_VERSION } from '../src/session-cache.js' +import { isSqliteAvailable } from '../src/sqlite.js' +import type { ProjectSummary } from '../src/types.js' + +function summary( + project: string, + projectPath: string, + opts: { cost?: number; wd?: string } = {}, +): ProjectSummary { + return { + project, + projectPath, + sessions: opts.wd ? ([{ workingDirectory: opts.wd }] as ProjectSummary['sessions']) : [], + totalCostUSD: opts.cost ?? 1, + totalApiCalls: 1, + totalProxiedCostUSD: 0, + } as ProjectSummary +} + +function norm(p: string | undefined): string { + return (p ?? '').replace(/\\/g, '/').replace(/\/+$/, '') +} + +describe('merge: same parent vs different parents (#1260 REVISE2)', () => { + it('folds five-provider same-parent labels into one abs key', () => { + const merged = mergeProjectsByCrossProviderKey([ + summary('-root-vault', '/root/vault', { cost: 10 }), // claude + summary('root-vault', 'root/vault', { cost: 5 }), // codex + summary('root-vault', '/root/vault', { cost: 4 }), // hermes + summary('vault', '/root/vault', { cost: 3 }), // kimicode (abs) + summary('vault', '/root/vault', { cost: 2 }), // pi (abs after fix) + ]) + expect(merged.size).toBe(1) + expect([...merged.values()][0]!.totalCostUSD).toBe(24) + }) + + it('keeps /a/vault and /b/vault separate even when both display as vault', () => { + const merged = mergeProjectsByCrossProviderKey([ + summary('vault', '/a/vault', { cost: 10 }), + summary('vault', '/b/vault', { cost: 1 }), + ]) + expect(merged.size).toBe(2) + const costs = [...merged.values()].map(p => p.totalCostUSD).sort((a, b) => a - b) + expect(costs).toEqual([1, 10]) + }) + + it('does not attach basename-only vault to unique /a/vault when wd proves /b/vault', () => { + // Session workingDirectory is an abs authority even if projectPath is slug. + const merged = mergeProjectsByCrossProviderKey([ + summary('vault', '/a/vault', { cost: 10 }), + summary('vault', 'vault', { cost: 1, wd: '/b/vault' }), + ]) + expect(merged.size).toBe(2) + }) + + it('unique-basename empty path attaches to the sole abs parent (exact contract)', () => { + const merged = mergeProjectsByCrossProviderKey([ + summary('vault', '/root/vault', { cost: 10 }), + summary('vault', '', { cost: 1 }), + ]) + // Intentional same-dir fallback: empty projectPath with display basename + // "vault" uniquely matches the sole abs parent /root/vault. + expect(merged.size).toBe(1) + expect([...merged.values()][0]!.totalCostUSD).toBe(11) + }) + + it('empty path with non-matching label stays unresolved (no invented parent)', () => { + const merged = mergeProjectsByCrossProviderKey([ + summary('vault', '/root/vault', { cost: 10 }), + summary('orphan', '', { cost: 1 }), + ]) + expect(merged.size).toBe(2) + const costs = [...merged.values()].map(p => p.totalCostUSD).sort((a, b) => a - b) + expect(costs).toEqual([1, 10]) + }) + + it('ambiguous basename across two abs parents stays label-only', () => { + const merged = mergeProjectsByCrossProviderKey([ + summary('a-vault', '/a/vault', { cost: 1 }), + summary('b-vault', '/b/vault', { cost: 2 }), + summary('vault', 'vault', { cost: 99 }), + ]) + expect(merged.size).toBe(3) + }) + + it('supports Windows drive and POSIX abs shapes as path keys', () => { + const merged = mergeProjectsByCrossProviderKey([ + summary('vault', 'C:/Users/x/vault', { cost: 1 }), + summary('vault', 'C:\\Users\\x\\vault', { cost: 2 }), + summary('vault', '/Users/x/vault', { cost: 3 }), + ]) + // Drive-letter variants normalize together; POSIX stays separate. + expect(merged.size).toBe(2) + const costs = [...merged.values()].map(p => p.totalCostUSD).sort((a, b) => a - b) + expect(costs).toEqual([3, 3]) + }) +}) + +describe('pi: discovery → parse → cache preserves abs cwd', () => { + it('cold parse keeps /b/vault as projectPath and workingDirectory', async () => { + const root = await mkdtemp(join(tmpdir(), 'pi-cwd-cold-')) + try { + const dir = join(root, 'sessions', 'slug') + await mkdir(dir, { recursive: true }) + await writeFile(join(dir, 's.jsonl'), [ + { type: 'session', version: 3, id: 's', cwd: '/b/vault', timestamp: '2026-04-14T10:00:00Z' }, + { type: 'message', id: 'm', timestamp: '2026-04-14T10:01:00Z', message: { + role: 'assistant', model: 'gpt-5.4', content: [], responseId: 'r', + usage: { input: 10, output: 5, cacheRead: 0, cacheWrite: 0, cost: { total: 0.01 } }, + } }, + ].map(JSON.stringify).join('\n') + '\n') + + const sources = await createPiProvider(join(root, 'sessions')).discoverSessions() + expect(sources[0]!.sourcePath).toBe('/b/vault') + + const cache = { version: CACHE_VERSION, providers: {} } + const cold = await parseProviderSources('pi', sources, new Set(), cache) + expect(norm(cold[0]!.projectPath)).toBe('/b/vault') + expect(norm(cold[0]!.sessions[0]!.workingDirectory)).toBe('/b/vault') + + // Warm: unchanged fingerprint serves from cache with cwd still present. + const warm = await parseProviderSources('pi', sources, new Set(), cache) + expect(norm(warm[0]!.projectPath)).toBe('/b/vault') + expect(norm(warm[0]!.sessions[0]!.workingDirectory)).toBe('/b/vault') + } finally { + await rm(root, { recursive: true, force: true }) + } + }) + + it('missing header cwd does not invent an abs parent from the leaf name', async () => { + const root = await mkdtemp(join(tmpdir(), 'pi-cwd-missing-')) + try { + const dir = join(root, 'sessions', 'vault') + await mkdir(dir, { recursive: true }) + await writeFile(join(dir, 's.jsonl'), [ + { type: 'session', version: 3, id: 's', timestamp: '2026-04-14T10:00:00Z' }, + { type: 'message', id: 'm', timestamp: '2026-04-14T10:01:00Z', message: { + role: 'assistant', model: 'gpt-5.4', content: [], responseId: 'r', + usage: { input: 10, output: 5, cacheRead: 0, cacheWrite: 0, cost: { total: 0.01 } }, + } }, + ].map(JSON.stringify).join('\n') + '\n') + + const sources = await createPiProvider(join(root, 'sessions')).discoverSessions() + expect(sources[0]!.sourcePath).toBeUndefined() + const projects = await parseProviderSources('pi', sources, new Set(), { version: CACHE_VERSION, providers: {} }) + // Without abs cwd, projectPath must not become a fabricated /…/vault. + expect(norm(projects[0]!.projectPath)).not.toMatch(/^\/.+\/vault$/) + expect(projects[0]!.sessions[0]!.workingDirectory).toBeUndefined() + } finally { + await rm(root, { recursive: true, force: true }) + } + }) +}) + +describe('codex: session_meta cwd becomes projectPath', () => { + it('preserves absolute cwd on ParsedProviderCall and through merge', async () => { + const root = await mkdtemp(join(tmpdir(), 'codex-cwd-')) + try { + const sessions = join(root, 'sessions', '2026', '04', '14') + await mkdir(sessions, { recursive: true }) + const file = join(sessions, 'rollout-codex-cwd.jsonl') + await writeFile(file, [ + JSON.stringify({ type: 'session_meta', timestamp: '2026-04-14T10:00:00Z', payload: { + session_id: 'codex-cwd', model: 'gpt-5.4', cwd: '/b/vault', originator: 'codex_cli_rs', + } }), + JSON.stringify({ type: 'response_item', timestamp: '2026-04-14T10:00:30Z', payload: { + type: 'message', role: 'user', content: [{ type: 'input_text', text: 'hi' }], + } }), + JSON.stringify({ type: 'event_msg', timestamp: '2026-04-14T10:01:00Z', payload: { + type: 'token_count', info: { + last_token_usage: { input_tokens: 100, output_tokens: 20, total_tokens: 120 }, + total_token_usage: { total_tokens: 120 }, + }, + } }), + '', + ].join('\n')) + + const provider = createCodexProvider(root) + const sources = await provider.discoverSessions() + expect(sources.some(s => s.path === file)).toBe(true) + const source = sources.find(s => s.path === file)! + const calls = [] + for await (const call of provider.createSessionParser(source, new Set()).parse()) calls.push(call) + expect(calls.length).toBeGreaterThanOrEqual(1) + expect(norm(calls[0]!.projectPath)).toBe('/b/vault') + expect(norm(calls[0]!.workingDirectory)).toBe('/b/vault') + + const projects = await parseProviderSources('codex', [source], new Set(), { version: CACHE_VERSION, providers: {} }) + expect(projects.some(p => norm(p.projectPath) === '/b/vault' || norm(p.projectPath) === 'b/vault')).toBe(true) + + const merged = mergeProjectsByCrossProviderKey([ + summary('vault', '/a/vault', { cost: 10 }), + ...projects.map(p => ({ ...p, totalCostUSD: p.totalCostUSD || 1 })), + ]) + expect(merged.size).toBe(2) + } finally { + await rm(root, { recursive: true, force: true }) + } + }) +}) + +describe('claude: JSONL cwd is canonical projectPath', () => { + let tmpDir: string + beforeEach(async () => { + tmpDir = await mkdtemp(join(tmpdir(), 'claude-cwd-1260-')) + process.env['CLAUDE_CONFIG_DIR'] = tmpDir + process.env['CODEBURN_DESKTOP_SESSIONS_DIR'] = join(tmpDir, 'desktop-sessions') + process.env['CODEBURN_CACHE_DIR'] = join(tmpDir, 'cache') + clearSessionCache() + }) + afterEach(async () => { + clearSessionCache() + await rm(tmpDir, { recursive: true, force: true }) + }) + + it('keeps /b/vault (not the -b-vault slug) as projectPath', async () => { + const projectDir = join(tmpDir, 'projects', '-b-vault') + await mkdir(projectDir, { recursive: true }) + const filePath = join(projectDir, 'claude-cwd.jsonl') + await writeFile(filePath, JSON.stringify({ + type: 'assistant', + sessionId: 'claude-cwd', + timestamp: '2099-05-01T12:00:00.000Z', + cwd: '/b/vault', + message: { + id: 'msg-1', type: 'message', role: 'assistant', model: 'claude-sonnet-4-5', + content: [], usage: { input_tokens: 100, output_tokens: 50 }, + }, + }) + '\n') + await utimes(filePath, new Date('2099-05-01T12:00:00.000Z'), new Date('2099-05-01T12:00:00.000Z')) + + const projects = await parseAllSessions({ + start: new Date('2099-05-01T00:00:00.000Z'), + end: new Date('2099-05-01T23:59:59.999Z'), + }, 'claude') + expect(projects).toHaveLength(1) + expect(norm(projects[0]!.projectPath)).toBe('/b/vault') + }) +}) + +describe('kimicode: state.json workDir becomes projectPath', () => { + const fixtureHome = vi.hoisted(() => { + const base = process.env['TMPDIR'] || '/tmp' + return `${base.replace(/[\\/]+$/, '')}/kimicode-cwd-1260-${process.pid}-${Date.now()}` + }) + + beforeEach(async () => { + await rm(fixtureHome, { recursive: true, force: true }) + await mkdir(fixtureHome, { recursive: true }) + process.env['KIMI_CODE_HOME'] = fixtureHome + clearSessionCache() + }) + afterEach(async () => { + clearSessionCache() + delete process.env['KIMI_CODE_HOME'] + await rm(fixtureHome, { recursive: true, force: true }) + }) + + it('preserves abs workDir through discovery and parse', async () => { + const workDir = '/b/vault' + const hash = createHash('md5').update(workDir).digest('hex').slice(0, 12) + const sessionDir = join(fixtureHome, 'sessions', `wd_vault_${hash}`, 'session_cwd1260') + const agentDir = join(sessionDir, 'agents', 'main') + await mkdir(agentDir, { recursive: true }) + await writeFile(join(sessionDir, 'state.json'), JSON.stringify({ + createdAt: '2026-07-01T10:00:00.000Z', + updatedAt: '2026-07-01T10:05:00.000Z', + workDir, + agents: { main: { homedir: '/workspace', type: 'main', parentAgentId: null } }, + })) + await writeFile(join(agentDir, 'wire.jsonl'), [ + JSON.stringify({ type: 'metadata', protocol_version: '1.4', created_at: 1782900000000 }), + JSON.stringify({ + type: 'turn.prompt', + input: [{ type: 'text', text: 'hi' }], + origin: { kind: 'user' }, + time: 1782900000000, + }), + JSON.stringify({ + type: 'llm.request', kind: 'loop', provider: 'fixture-provider', + model: 'kimi-k2', modelAlias: 'kimi-k2', maxTokens: 4096, messageCount: 2, + turnStep: '0.1', time: 1782900001000, + }), + JSON.stringify({ + type: 'usage.record', model: 'kimi-k2', + usage: { inputOther: 10, output: 5, inputCacheRead: 0, inputCacheCreation: 0 }, + usageScope: 'turn', time: 1782900002000, + }), + '', + ].join('\n')) + + const provider = createKimicodeProvider(fixtureHome) + const sources = await provider.discoverSessions() + expect(sources.length).toBeGreaterThanOrEqual(1) + expect(sources.every(s => s.sourcePath === workDir || s.project === 'vault')).toBe(true) + + const projects = await parseProviderSources('kimicode', sources, new Set(), { version: CACHE_VERSION, providers: {} }) + expect(projects.length).toBeGreaterThanOrEqual(1) + expect(projects.some(p => norm(p.projectPath) === workDir)).toBe(true) + }) +}) + +const requireForTest = createRequire(import.meta.url) +const hermesRoot = vi.hoisted(() => { + const base = process.env['TMPDIR'] || '/tmp' + const root = `${base.replace(/[\\/]+$/, '')}/hermes-cwd-1260-${process.pid}-${Date.now()}` + process.env['HERMES_HOME'] = `${root}/hermes` + return root +}) + +const skipUnlessSqlite = isSqliteAvailable() ? describe : describe.skip + +skipUnlessSqlite('hermes: cwd/git_repo_root becomes projectPath', () => { + const HERMES_HOME = join(hermesRoot, 'hermes') + const CACHE_DIR = join(hermesRoot, 'cache') + + beforeEach(async () => { + clearSessionCache() + await rm(hermesRoot, { recursive: true, force: true }) + await mkdir(HERMES_HOME, { recursive: true }) + process.env['HERMES_HOME'] = HERMES_HOME + process.env['CODEBURN_CACHE_DIR'] = CACHE_DIR + }) + afterEach(async () => { + clearSessionCache() + await rm(hermesRoot, { recursive: true, force: true }) + }) + + it('preserves abs workspace through parseAllSessions', async () => { + const { DatabaseSync: Database } = requireForTest('node:sqlite') + const db = new Database(join(HERMES_HOME, 'state.db')) + db.exec(` + CREATE TABLE sessions ( + id TEXT PRIMARY KEY, source TEXT, model TEXT, cwd TEXT, git_repo_root TEXT, + input_tokens INTEGER DEFAULT 0, output_tokens INTEGER DEFAULT 0, + cache_read_tokens INTEGER DEFAULT 0, cache_write_tokens INTEGER DEFAULT 0, + reasoning_tokens INTEGER DEFAULT 0, estimated_cost_usd REAL, actual_cost_usd REAL, + api_call_count INTEGER DEFAULT 0, tool_call_count INTEGER DEFAULT 0, + started_at REAL, title TEXT + ) + `) + db.exec(` + CREATE TABLE messages ( + id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, role TEXT NOT NULL, + content TEXT, tool_calls TEXT, timestamp REAL NOT NULL + ) + `) + const startedAt = Date.now() / 1000 - 3600 + db.prepare( + `INSERT INTO sessions (id, source, model, cwd, input_tokens, output_tokens, + estimated_cost_usd, api_call_count, started_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ).run('cwd1260', 'cli', 'claude-opus-4-6', '/b/vault', 1000, 200, 0.5, 1, startedAt) + db.prepare('INSERT INTO messages (session_id, role, content, timestamp) VALUES (?, ?, ?, ?)') + .run('cwd1260', 'user', 'hello', startedAt) + db.prepare('INSERT INTO messages (session_id, role, content, timestamp) VALUES (?, ?, ?, ?)') + .run('cwd1260', 'assistant', 'world', startedAt + 1) + db.close() + + const projects = await parseAllSessions(undefined, 'hermes') + expect(projects.length).toBeGreaterThanOrEqual(1) + expect(projects.some(p => norm(p.projectPath) === '/b/vault')).toBe(true) + }) +}) diff --git a/tests/project-path-posix-case.test.ts b/tests/project-path-posix-case.test.ts new file mode 100644 index 00000000..230e7b4c --- /dev/null +++ b/tests/project-path-posix-case.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, it } from 'vitest' +import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +import { createPiProvider } from '../src/providers/pi.js' +import { + mergeProjectsByCrossProviderKey, + normalizeAbsProjectPathKey, + normalizeProjectPathKey, + parseProviderSources, +} from '../src/parser.js' +import { CACHE_VERSION } from '../src/session-cache.js' +import { buildPayloadProjects } from '../src/usage-aggregator.js' +import type { ProjectSummary } from '../src/types.js' + +describe('exported path-identity helpers', () => { + it('preserves POSIX case and casefolds identified Windows drive/UNC paths', () => { + expect(normalizeAbsProjectPathKey('/a/Vault')).toBe('a/Vault') + expect(normalizeAbsProjectPathKey('/a/vault')).toBe('a/vault') + expect(normalizeAbsProjectPathKey('/a/Vault')).not.toBe(normalizeAbsProjectPathKey('/a/vault')) + expect(normalizeAbsProjectPathKey('C:/root/vault')).toBe('c:/root/vault') + expect(normalizeAbsProjectPathKey('C:\\root\\vault')).toBe('c:/root/vault') + expect(normalizeAbsProjectPathKey('C:\\Work\\Vault')).toBe('c:/work/vault') + expect(normalizeAbsProjectPathKey('c:/work/vault')).toBe('c:/work/vault') + expect(normalizeAbsProjectPathKey('\\\\Server\\Share\\Vault')).toBe( + normalizeAbsProjectPathKey('//server/share/vault'), + ) + expect(normalizeAbsProjectPathKey('\\\\Server\\Share\\Vault')).toBe('server/share/vault') + expect(normalizeAbsProjectPathKey('a-vault')).toBeNull() + + expect(normalizeProjectPathKey('/a/Vault')).toBe('/a/Vault') + expect(normalizeProjectPathKey('/a/vault')).toBe('/a/vault') + expect(normalizeProjectPathKey('C:\\Work\\Vault')).toBe('c:/work/vault') + }) +}) + +describe('cold+warm Pi cwd case identity', () => { + it('keeps /a/Vault and /a/vault distinct through cache and payload', async () => { + const root = await mkdtemp(join(tmpdir(), 'posix-case-pi-')) + try { + const sessionsRoot = join(root, 'sessions') + // Dir/file names must not differ only by case: the host volume may be + // case-insensitive. Identity under test is the cwd string in the JSONL. + const rows = [ + { cwd: '/a/Vault', slot: 'upper', cost: 2 }, + { cwd: '/a/vault', slot: 'lower', cost: 3 }, + ] as const + for (const row of rows) { + const dir = join(sessionsRoot, row.slot) + await mkdir(dir, { recursive: true }) + await writeFile(join(dir, 'session.jsonl'), [ + { type: 'session', version: 3, id: `pi-${row.slot}`, cwd: row.cwd, timestamp: '2026-04-14T10:00:00Z' }, + { type: 'message', id: `message-${row.slot}`, timestamp: '2026-04-14T10:01:00Z', message: { + role: 'assistant', model: 'gpt-5.4', content: [], responseId: `response-${row.slot}`, + usage: { input: 1000, output: 200, cacheRead: 0, cacheWrite: 0, cost: { total: row.cost } }, + } }, + ].map(x => JSON.stringify(x)).join('\n') + '\n') + } + + const sources = await createPiProvider(sessionsRoot).discoverSessions() + const cache = { version: CACHE_VERSION, providers: {} } + const cold = await parseProviderSources('pi', sources, new Set(), cache) + const warm = await parseProviderSources('pi', sources, new Set(), cache) + const paths = (projects: ProjectSummary[]) => projects.map(p => p.projectPath.replace(/\\/g, '/')).sort() + expect(paths(cold)).toEqual(['/a/Vault', '/a/vault']) + expect(paths(warm)).toEqual(['/a/Vault', '/a/vault']) + + const merged = mergeProjectsByCrossProviderKey(warm) + expect([...merged.values()].map(p => p.projectPath.replace(/\\/g, '/')).sort()).toEqual(['/a/Vault', '/a/vault']) + + const payload = buildPayloadProjects([...merged.values()], null, '/Users/synthetic') + expect(payload.map(p => p.id).sort()).toEqual(['/a/Vault', '/a/vault']) + expect(payload).toHaveLength(2) + expect(payload.every(p => p.cost > 0)).toBe(true) + } finally { + await rm(root, { recursive: true, force: true }) + } + }) +}) diff --git a/tests/root-pi-case-cold-warm.verify.test.ts b/tests/root-pi-case-cold-warm.verify.test.ts new file mode 100644 index 00000000..e6338926 --- /dev/null +++ b/tests/root-pi-case-cold-warm.verify.test.ts @@ -0,0 +1,32 @@ +import {describe,it,expect} from 'vitest' +import {mkdtemp,mkdir,writeFile,readFile,rm} from 'node:fs/promises' +import {tmpdir} from 'node:os' +import {join} from 'node:path' +import {createPiProvider} from '../src/providers/pi.js' +import {parseProviderSources,mergeProjectsByCrossProviderKey} from '../src/parser.js' +import {CACHE_VERSION} from '../src/session-cache.js' + +describe('root real Pi case identity decode and cache roundtrip',()=>{ + it('preserves exact cwd through cold parse, warm read and serialized cache reload',async()=>{ + const dir=await mkdtemp(join(tmpdir(),'codex-root-pi-case-')) + try { + for (const [index,cwd] of ['/a/Vault','/a/vault'].entries()) { + const folder=join(dir,'sessions','source-'+index);await mkdir(folder,{recursive:true}) + const rows=[{type:'session',version:3,id:'case-'+index,cwd,timestamp:'2026-09-07T01:00:00Z'}, + {type:'message',id:'message-'+index,timestamp:'2026-09-07T01:01:00Z',message:{role:'assistant',model:'gpt-5.4',content:[],responseId:'response-'+index,usage:{input:1000,output:200,cacheRead:0,cacheWrite:0,cost:{total:1}}}}] + await writeFile(join(folder,'session.jsonl'),rows.map(x=>JSON.stringify(x)).join('\n')+'\n') + } + const sources=await createPiProvider(join(dir,'sessions')).discoverSessions();expect(sources).toHaveLength(2) + let cache={version:CACHE_VERSION,providers:{}} + for (const stage of ['cold','warm','reloaded']) { + if(stage==='reloaded'){const file=join(dir,'cache.json');await writeFile(file,JSON.stringify(cache));cache=JSON.parse(await readFile(file,'utf8'))} + const parsed=await parseProviderSources('pi',sources,new Set(),cache) + const paths=parsed.map(p=>p.projectPath).sort() + const merged=[...mergeProjectsByCrossProviderKey(parsed).values()] + console.log('ROOT_PI_CASE',stage,JSON.stringify(paths),JSON.stringify(merged.map(p=>p.projectPath))) + expect(paths,stage+' parser roots').toEqual(['/a/Vault','/a/vault']) + expect(merged.map(p=>p.projectPath).sort(),stage+' merged roots').toEqual(['/a/Vault','/a/vault']) + } + } finally {await rm(dir,{recursive:true,force:true})} + }) +}) diff --git a/tests/root-project-case-savings.verify.test.ts b/tests/root-project-case-savings.verify.test.ts new file mode 100644 index 00000000..b4e92c60 --- /dev/null +++ b/tests/root-project-case-savings.verify.test.ts @@ -0,0 +1,24 @@ +import {describe,it,expect} from 'vitest' +import {mergeProjectsByCrossProviderKey} from '../src/parser.js' +import type {ProjectSummary} from '../src/types.js' +function summary(projectPath:string,cost:number,savings=0):ProjectSummary { + return {project:projectPath.split('/').pop()!,projectPath,sessions:[],totalCostUSD:cost,totalSavingsUSD:savings,totalApiCalls:1,totalProxiedCostUSD:0} +} +describe('root identity and adjacent additive values',()=>{ + it('preserves distinct case-sensitive absolute roots before payload allocation',()=>{ + const rows=[...mergeProjectsByCrossProviderKey([summary('/a/Vault',2),summary('/a/vault',3)]).values()] + expect(rows.map(r=>r.projectPath).sort()).toEqual(['/a/Vault','/a/vault']) + expect(rows.map(r=>r.totalCostUSD).sort()).toEqual([2,3]) + }) + it('keeps a lossy lowercase alias unallocated when it matches two absolute roots',()=>{ + const rows=[...mergeProjectsByCrossProviderKey([summary('/a/Vault',2),summary('/a/vault',3),summary('a-vault',7)]).values()] + expect(rows.length).toBe(3) + expect(rows.map(r=>r.totalCostUSD).sort((a,b)=>a-b)).toEqual([2,3,7]) + }) + it('preserves additive savings when the same actual root is grouped',()=>{ + const rows=[...mergeProjectsByCrossProviderKey([summary('/repos/shared',10,30),summary('/repos/shared',5,2)]).values()] + expect(rows.length).toBe(1) + expect(rows[0].totalCostUSD).toBe(15) + expect(rows[0].totalSavingsUSD).toBe(32) + }) +}) diff --git a/tests/root-session-count-boundaries.verify.test.ts b/tests/root-session-count-boundaries.verify.test.ts new file mode 100644 index 00000000..859a381c --- /dev/null +++ b/tests/root-session-count-boundaries.verify.test.ts @@ -0,0 +1,30 @@ +import { it, expect } from 'vitest' +import { buildPayloadProjects, uniquePeriodSessionCount } from '../src/usage-aggregator.js' +import type { ProjectSummary, SessionSummary } from '../src/types.js' +import type { DailyEntry } from '../src/daily-cache.js' + +const path = '/tmp/count-boundary' +const session = { + sessionId: 'surviving-id', project: 'vault', workingDirectory: path, + firstTimestamp: '2026-09-02T12:00:00Z', lastTimestamp: '2026-09-07T12:00:00Z', + totalCostUSD: 1, totalSavingsUSD: 0, apiCalls: 1, + totalInputTokens: 100, totalOutputTokens: 20, totalCacheReadTokens: 0, totalCacheWriteTokens: 0, + modelBreakdown: {}, categoryBreakdown: {}, turns: [{timestamp:'2026-09-07T12:00:00Z',userMessage:'task',assistantCalls:[{provider:'claude',model:'claude-sonnet-4-5',costUSD:1,inputTokens:100,outputTokens:20,cacheReadTokens:0,cacheWriteTokens:0}]}], +} as SessionSummary +const live = [{ project: 'vault', projectPath: path, sessions: [session], totalCostUSD: 1, totalSavingsUSD: 0, totalApiCalls: 1, totalProxiedCostUSD: 0 }] as ProjectSummary[] +function day(date: string, count: number, cost: number, carried = false): DailyEntry { + const projects = { vault: {path, cost, calls:count, savingsUSD:0, sessions:count} } + return { date, cost, calls:count, sessions:count, savingsUSD:0, inputTokens:100, outputTokens:20, cacheReadTokens:0,cacheWriteTokens:0,editTurns:0,oneShotTurns:0,models:{},categories:{},projects,providers:{claude:{cost,calls:count,sessions:count,savingsUSD:0,projects}}, ...(carried?{carried:true as const}:{}) } +} +it('one surviving identity cannot certify completeness for a cache row containing three sessions', () => { + const days = [day('2026-09-02', 3, 3), day('2026-09-07', 1, 1)] + const row = buildPayloadProjects(live, days, '/Users/synthetic')[0]! + console.log('ROOT_PARTIAL_COUNT',JSON.stringify({row,headline:uniquePeriodSessionCount(live,days)})) + expect(row.cost).toBe(4) + expect(row.sessions >= 3 || row.sessionCountBasis !== 'identity').toBe(true) +}) +it('a carried-day tick does not prove a different session from a surviving identity', () => { + const count = uniquePeriodSessionCount(live, [day('2026-09-02',1,1,true),day('2026-09-07',1,1)]) + console.log('ROOT_CARRIED_IDENTITY',JSON.stringify(count)) + expect(count.sessions === 1 || count.basis !== 'identity').toBe(true) +}) diff --git a/tests/root-session-days.verify.test.ts b/tests/root-session-days.verify.test.ts new file mode 100644 index 00000000..dce67459 --- /dev/null +++ b/tests/root-session-days.verify.test.ts @@ -0,0 +1,22 @@ +import {it,expect} from 'vitest' +import {mkdtempSync,mkdirSync,writeFileSync} from 'node:fs' +import {homedir} from 'node:os' +import {join} from 'node:path' +import {spawnSync} from 'node:child_process' +it('one real session spanning two days is one period project session',()=>{ + const dir=mkdtempSync(join(homedir(),'root-session-days-'));const claude=join(dir,'claude');const projects=join(claude,'projects','project-a');mkdirSync(projects,{recursive:true}) + const now=new Date(Date.now()-60000);const older=new Date(now.getTime()-5*86400000);const sessionId='same-actual-session';const cwd='/tmp/same-session-project' + const rows=[older,now].flatMap((date,i)=>[ + {type:'user',sessionId,timestamp:date.toISOString(),cwd,message:{role:'user',content:'task'+i}}, + {type:'assistant',sessionId,timestamp:date.toISOString(),cwd,message:{id:'response'+i,role:'assistant',model:'claude-sonnet-4-5',content:[{type:'text',text:'done'}],usage:{input_tokens:1000,output_tokens:200,cache_creation_input_tokens:0,cache_read_input_tokens:0}}} + ]) + writeFileSync(join(projects,sessionId+'.jsonl'),rows.map(x=>JSON.stringify(x)).join('\n')+'\n') + const env={...process.env,CLAUDE_CONFIG_DIR:claude,CODEBURN_CACHE_DIR:join(dir,'cache'),CODEBURN_DESKTOP_SESSIONS_DIR:join(dir,'desktop')} + const cli=(args:string[])=>{const r=spawnSync(process.execPath,['dist/cli.js',...args],{cwd:process.cwd(),env,encoding:'utf8',timeout:60000});expect(r.status,r.stderr).toBe(0);return JSON.parse(r.stdout)} + cli(['models','--format','json','--period','week']) + const json=cli(['status','--format','menubar-json','--period','week','--provider','claude','--no-timeline']) + const row=json.current.topProjects.find((r:any)=>r.id===cwd) + console.log('ROOT_REAL_SESSION_DAYS',JSON.stringify({headline:json.current.sessions,row})) + expect(row.sessionDetails).toHaveLength(1) + expect(row.sessions).toBe(1) +},120000) diff --git a/tests/root-session-metadata-gap.verify.test.ts b/tests/root-session-metadata-gap.verify.test.ts new file mode 100644 index 00000000..24ad23b3 --- /dev/null +++ b/tests/root-session-metadata-gap.verify.test.ts @@ -0,0 +1,28 @@ +import { it, expect } from 'vitest' +import { buildPayloadProjects, uniquePeriodSessionCount } from '../src/usage-aggregator.js' +import type { ProjectSummary, SessionSummary } from '../src/types.js' +import type { DailyEntry } from '../src/daily-cache.js' + +const path = '/tmp/count-boundary' +const session = { + sessionId: 'surviving-id', project: 'vault', workingDirectory: path, + firstTimestamp: '2026-09-02T12:00:00Z', lastTimestamp: '2026-09-07T12:00:00Z', + totalCostUSD: 1, totalSavingsUSD: 0, apiCalls: 1, + totalInputTokens: 100, totalOutputTokens: 20, totalCacheReadTokens: 0, totalCacheWriteTokens: 0, + modelBreakdown: {}, categoryBreakdown: {}, turns: [{timestamp:'2026-09-07T12:00:00Z',userMessage:'task',assistantCalls:[{provider:'claude',model:'claude-sonnet-4-5',costUSD:1,inputTokens:100,outputTokens:20,cacheReadTokens:0,cacheWriteTokens:0}]}], +} as SessionSummary +const live = [{ project: 'vault', projectPath: path, sessions: [session], totalCostUSD: 1, totalSavingsUSD: 0, totalApiCalls: 1, totalProxiedCostUSD: 0 }] as ProjectSummary[] +function day(date: string, count: number, cost: number, carried = false): DailyEntry { + const projects = { vault: {path, cost, calls:count, savingsUSD:0, sessions:count} } + return { date, cost, calls:count, sessions:count, savingsUSD:0, inputTokens:100, outputTokens:20, cacheReadTokens:0,cacheWriteTokens:0,editTurns:0,oneShotTurns:0,models:{},categories:{},projects,providers:{claude:{cost,calls:count,sessions:count,savingsUSD:0,projects}}, ...(carried?{carried:true as const}:{}) } +} +it('positive historical accounting with no count metadata cannot certify exact live count', () => { + const missing = day('2026-09-02', 0, 3) + missing.calls = 2 + missing.providers.claude!.calls = 2 + const counted = uniquePeriodSessionCount(live, [missing]) + const row = buildPayloadProjects(live, [missing], '/Users/synthetic')[0]! + console.log('ROOT_COUNT_METADATA_GAP', JSON.stringify({counted,row})) + expect(row.cost).toBe(3) + expect(counted.basis).toBe('partial') +}) diff --git a/tests/root-windows-project-normalization.verify.test.ts b/tests/root-windows-project-normalization.verify.test.ts new file mode 100644 index 00000000..377fb66a --- /dev/null +++ b/tests/root-windows-project-normalization.verify.test.ts @@ -0,0 +1,9 @@ +import {it,expect} from 'vitest' +import {mergeProjectsByCrossProviderKey} from '../src/parser.js' +import type {ProjectSummary} from '../src/types.js' +it('retains existing mixed-case Windows-drive cross-provider equivalence',()=>{ + const row=(projectPath:string):ProjectSummary=>({project:'Vault',projectPath,sessions:[],totalCostUSD:2,totalApiCalls:1,totalProxiedCostUSD:0}) + const rows=[...mergeProjectsByCrossProviderKey([row('C:\\Work\\Vault'),row('c:/work/vault')]).values()] + console.log('ROOT_WINDOWS_ROWS',JSON.stringify(rows)) + expect(rows.length).toBe(1);expect(rows[0].totalCostUSD).toBe(4) +}) diff --git a/tests/session-count-label.test.ts b/tests/session-count-label.test.ts new file mode 100644 index 00000000..d106d4d4 --- /dev/null +++ b/tests/session-count-label.test.ts @@ -0,0 +1,128 @@ +import { describe, expect, it } from 'vitest' +import { buildMenubarPayload } from '../src/menubar-json.js' +import { formatCombinedSessionCount, formatSessionCount, sessionCountIsExact, COMBINED_SESSION_COUNT_HELP, COMBINED_SESSION_COUNT_LABEL, SESSION_COUNT_HELP } from '../src/session-count-label.js' +import type { PeriodData } from '../src/menubar-json.js' + +describe('session count labels', () => { + it('uses plain lower-bound phrasing and never names occupancy or cache', () => { + expect(formatSessionCount(3, 'partial')).toBe('At least 3 sessions') + expect(formatSessionCount(1, 'partial')).toBe('At least 1 session') + expect(formatSessionCount(0, 'partial')).toBe('Session count unavailable') + expect(formatSessionCount(1, 'identity')).toBe('1 session') + expect(formatSessionCount(2, 'identity')).toBe('2 sessions') + expect(formatSessionCount(0, 'identity')).toBe('0 sessions') + expect(formatSessionCount(3, undefined)).toBe('At least 3 sessions') + expect(SESSION_COUNT_HELP).toContain('Older session logs') + expect(formatSessionCount(3, 'partial')).not.toMatch(/occupancy|canonical|cache/i) + }) + + it('combined-scope copy never presents a device sum as a count', () => { + expect(formatCombinedSessionCount()).toBe('Session count unavailable') + expect(formatCombinedSessionCount()).toBe(COMBINED_SESSION_COUNT_LABEL) + expect(COMBINED_SESSION_COUNT_HELP).toBe('Session identities are unavailable across devices.') + expect(formatCombinedSessionCount()).not.toMatch(/At least|^\d/) + expect(formatSessionCount(0, 'identity')).toBe('0 sessions') + expect(formatSessionCount(3, 'partial')).toBe('At least 3 sessions') + }) +}) + +describe('payload serialization', () => { + const emptyPeriod = (): PeriodData => ({ + label: 'Last 7 days', + cost: 4, + savingsUSD: 0, + calls: 4, + sessions: 3, + sessionCountBasis: 'partial', + inputTokens: 0, + outputTokens: 0, + cacheReadTokens: 0, + cacheWriteTokens: 0, + categories: [], + models: [], + projects: [{ + id: '/tmp/count-boundary', + name: 'vault', + cost: 4, + savingsUSD: 0, + sessions: 3, + sessionCountBasis: 'partial', + }], + }) + + it('omits average when the count is a bound and keeps numeric sessions', () => { + const payload = buildMenubarPayload(emptyPeriod(), [], null) + const json = JSON.parse(JSON.stringify(payload)) as { + current: { sessions: number, sessionCountBasis?: string, topProjects: Array<{ sessions: number, avgCostPerSession?: number, sessionCountBasis?: string }> } + } + expect(json.current.sessions).toBe(3) + expect(json.current.sessionCountBasis).toBe('partial') + expect(json.current.topProjects[0]!.sessions).toBe(3) + expect(json.current.topProjects[0]!.sessionCountBasis).toBe('partial') + expect(json.current.topProjects[0]!.avgCostPerSession).toBeUndefined() + expect(sessionCountIsExact('partial')).toBe(false) + }) + + it('emits average only for source-only exact identity', () => { + const period = emptyPeriod() + period.sessionCountBasis = 'identity' + period.sessions = 1 + period.cost = 0.012 + period.projects = [{ + id: '/tmp/same-session-project', + name: 'vault', + cost: 0.012, + savingsUSD: 0, + sessions: 1, + sessionCountBasis: 'identity', + }] + const payload = buildMenubarPayload(period, [], null) + expect(payload.current.topProjects[0]!.avgCostPerSession).toBeCloseTo(0.012) + expect(payload.current.topProjects[0]!.sessionCountBasis).toBe('identity') + }) + + it('still decodes an older payload that required a numeric average', () => { + const legacy = { + generated: '2026-09-07T00:00:00Z', + current: { + label: 'Last 7 days', + cost: 4, + calls: 4, + sessions: 2, + oneShotRate: null, + inputTokens: 0, + outputTokens: 0, + cacheReadTokens: 0, + cacheWriteTokens: 0, + cacheHitPercent: 0, + codexCredits: 0, + topActivities: [], + topModels: [], + localModelSavings: { totalUSD: 0, calls: 0, byModel: [], byProvider: [] }, + providers: {}, + providerDetails: [], + topProjects: [{ + name: 'vault', + cost: 4, + savingsUSD: 0, + sessions: 2, + avgCostPerSession: 2, + sessionDetails: [], + }], + modelEfficiency: [], + topSessions: [], + retryTax: { totalUSD: 0, retries: 0, editTurns: 0, byModel: [] }, + routingWaste: { totalSavingsUSD: 0, baselineModel: '', baselineCostPerEdit: 0, byModel: [] }, + tools: [], + skills: [], + subagents: [], + mcpServers: [], + }, + optimize: { findingCount: 0, savingsUSD: 0, topFindings: [] }, + history: { daily: [] }, + } + expect(legacy.current.topProjects[0]!.avgCostPerSession).toBe(2) + expect(legacy.current.topProjects[0]!.sessions).toBe(2) + expect(formatSessionCount(legacy.current.topProjects[0]!.sessions, undefined)).toBe('At least 2 sessions') + }) +}) diff --git a/tests/session-period-count.test.ts b/tests/session-period-count.test.ts new file mode 100644 index 00000000..f517056c --- /dev/null +++ b/tests/session-period-count.test.ts @@ -0,0 +1,295 @@ +import { describe, expect, it } from 'vitest' +import type { DailyEntry } from '../src/daily-cache.js' +import type { ProjectSummary, SessionSummary } from '../src/types.js' +import { + buildPayloadProjects, + uniqueCanonicalSessionCount, + uniqueCanonicalSessionCountFromProjects, + uniquePeriodSessionCount, +} from '../src/usage-aggregator.js' + +function session(opts: { + id: string + project: string + cost: number + provider?: string + firstTimestamp?: string +}): SessionSummary { + return { + sessionId: opts.id, + project: opts.project, + firstTimestamp: opts.firstTimestamp ?? '2026-09-02T12:00:00.000Z', + lastTimestamp: '2026-09-07T12:00:00.000Z', + totalCostUSD: opts.cost, + totalSavingsUSD: 0, + apiCalls: 1, + totalInputTokens: 100, + totalOutputTokens: 20, + totalCacheReadTokens: 0, + totalCacheWriteTokens: 0, + totalReasoningTokens: 0, + modelBreakdown: {}, + categoryBreakdown: {}, + turns: [{ + userMessage: 'task', + timestamp: opts.firstTimestamp ?? '2026-09-02T12:00:00.000Z', + assistantCalls: [{ + timestamp: opts.firstTimestamp ?? '2026-09-02T12:00:00.000Z', + model: 'claude-sonnet-4-5', + provider: opts.provider ?? 'claude', + inputTokens: 100, + outputTokens: 20, + cacheReadTokens: 0, + cacheWriteTokens: 0, + reasoningTokens: 0, + costUSD: opts.cost, + cacheCostUSD: 0, + }], + }], + } as SessionSummary +} + +function liveRow(path: string, sessions: SessionSummary[]): ProjectSummary { + return { + project: 'vault', + projectPath: path, + sessions, + totalCostUSD: sessions.reduce((n, s) => n + s.totalCostUSD, 0), + totalSavingsUSD: 0, + totalApiCalls: sessions.length, + totalProxiedCostUSD: 0, + } +} + +function cacheDay(date: string, sessions: number, cost: number, path: string, carried = false): DailyEntry { + const projects = { vault: { cost, calls: 1, savingsUSD: 0, sessions, path } } + return { + date, + cost, + savingsUSD: 0, + calls: 1, + sessions, + inputTokens: 0, + outputTokens: 0, + cacheReadTokens: 0, + cacheWriteTokens: 0, + editTurns: 0, + oneShotTurns: 0, + models: {}, + categories: {}, + providers: { claude: { calls: 1, cost, savingsUSD: 0, sessions, projects } }, + projects, + ...(carried ? { carried: true as const } : {}), + } +} + +describe('canonical session unique-count', () => { + it('counts one provider+sessionId once', () => { + const a = session({ id: 'same-actual-session', project: 'vault', cost: 0.006 }) + const b = session({ id: 'same-actual-session', project: 'vault', cost: 0.006, firstTimestamp: '2026-09-07T12:00:00.000Z' }) + expect(uniqueCanonicalSessionCount([a, b])).toBe(1) + }) + + it('keeps same-provider distinct ids and cross-provider same id string', () => { + const claude = session({ id: 'sess', project: 'vault', cost: 1, provider: 'claude' }) + const otherClaude = session({ id: 'other', project: 'vault', cost: 1, provider: 'claude' }) + const codex = session({ id: 'sess', project: 'vault', cost: 1, provider: 'codex' }) + expect(uniqueCanonicalSessionCount([claude, otherClaude], '/tmp/p')).toBe(2) + expect(uniqueCanonicalSessionCount([claude, codex], '/tmp/p')).toBe(2) + }) + + it('same filename sessionId in two folders stays two', () => { + const a = session({ id: 'sess', project: 'vault', cost: 1 }) + const b = session({ id: 'sess', project: 'vault', cost: 1 }) + expect(uniqueCanonicalSessionCount([a], '/tmp/a/vault')).toBe(1) + expect(uniqueCanonicalSessionCountFromProjects([ + liveRow('/tmp/a/vault', [a]), + liveRow('/tmp/b/vault', [b]), + ])).toBe(2) + }) +}) + +describe('buildPayloadProjects session counts', () => { + const path = '/tmp/same-session-project' + + it('one live session spanning two occupancy days is one project session', () => { + const live = [liveRow(path, [session({ id: 'same-actual-session', project: 'vault', cost: 0.012 })])] + const days = [ + cacheDay('2026-09-02', 1, 0.006, path), + cacheDay('2026-09-07', 1, 0.006, path), + ] + const rows = buildPayloadProjects(live, days, '/Users/synthetic') + expect(rows).toHaveLength(1) + expect(rows[0]!.cost).toBeCloseTo(0.012) + expect(rows[0]!.sessions).toBe(1) + expect(rows[0]!.sessionCountBasis).toBe('partial') + expect(rows[0]!.sessionDetails).toHaveLength(1) + }) + + it('same-provider distinct session ids stay two', () => { + const live = [liveRow(path, [ + session({ id: 'a', project: 'vault', cost: 0.01 }), + session({ id: 'b', project: 'vault', cost: 0.02 }), + ])] + const days = [ + cacheDay('2026-09-02', 1, 0.01, path), + cacheDay('2026-09-07', 1, 0.02, path), + ] + const rows = buildPayloadProjects(live, days, '/Users/synthetic') + expect(rows[0]!.sessions).toBe(2) + expect(rows[0]!.sessionCountBasis).toBe('partial') + expect(rows[0]!.cost).toBeCloseTo(0.03) + }) + + it('cross-provider identities stay distinct at one cwd', () => { + const live = [liveRow(path, [ + session({ id: 'claude-1', project: 'vault', cost: 0.01, provider: 'claude' }), + session({ id: 'codex-1', project: 'vault', cost: 0.02, provider: 'codex' }), + ])] + const days = [cacheDay('2026-09-07', 2, 0.03, path)] + const rows = buildPayloadProjects(live, days, '/Users/synthetic') + expect(rows[0]!.sessions).toBe(2) + expect(rows[0]!.sessionCountBasis).toBe('partial') + }) + + it('source-dead multi-day occupancy without identities is not a false unique 2', () => { + const days = [ + cacheDay('2026-08-01', 1, 1, path, true), + cacheDay('2026-08-02', 1, 1, path, true), + ] + const rows = buildPayloadProjects([], days, '/Users/synthetic') + expect(rows).toHaveLength(1) + expect(rows[0]!.cost).toBe(2) + expect(rows[0]!.sessions).toBe(1) + expect(rows[0]!.sessionCountBasis).toBe('partial') + }) + + it('source-only live identities with no cache rows are exact', () => { + const live = [liveRow(path, [session({ id: 'same-actual-session', project: 'vault', cost: 0.012 })])] + const rows = buildPayloadProjects(live, null, '/Users/synthetic') + expect(rows[0]!.sessions).toBe(1) + expect(rows[0]!.sessionCountBasis).toBe('identity') + }) + + it('one surviving identity plus a cache day of three sessions is a lower bound of 3', () => { + const live = [liveRow(path, [session({ id: 'surviving-id', project: 'vault', cost: 1 })])] + const days = [cacheDay('2026-09-02', 3, 3, path), cacheDay('2026-09-07', 1, 1, path)] + const rows = buildPayloadProjects(live, days, '/Users/synthetic') + expect(rows[0]!.cost).toBe(4) + expect(rows[0]!.sessions).toBe(3) + expect(rows[0]!.sessionCountBasis).toBe('partial') + }) + + it('empty source-only data is exact 0', () => { + expect(uniquePeriodSessionCount([], [])).toEqual({ sessions: 0, basis: 'identity' }) + }) +}) + +function blankDay(date: string, path: string): DailyEntry { + const projects = { vault: { path, cost: 0, calls: 0, savingsUSD: 0, sessions: 0 } } + return { + date, + cost: 0, + savingsUSD: 0, + calls: 0, + sessions: 0, + inputTokens: 0, + outputTokens: 0, + cacheReadTokens: 0, + cacheWriteTokens: 0, + editTurns: 0, + oneShotTurns: 0, + models: {}, + categories: {}, + providers: { claude: { calls: 0, cost: 0, savingsUSD: 0, sessions: 0, projects } }, + projects, + } +} + +describe('unknown cache accounting without session identities', () => { + const path = '/tmp/same-session-project' + const live = [liveRow(path, [session({ id: 'surviving-id', project: 'vault', cost: 1 })])] + + it('a truly empty cache row does not poison source-only exactness', () => { + expect(uniquePeriodSessionCount(live, [blankDay('2026-09-02', path)])).toEqual({ sessions: 1, basis: 'identity' }) + expect(uniquePeriodSessionCount([], [blankDay('2026-09-02', path)])).toEqual({ sessions: 0, basis: 'identity' }) + const rows = buildPayloadProjects(live, [blankDay('2026-09-02', path)], '/Users/synthetic') + expect(rows[0]!.sessionCountBasis).toBe('identity') + expect(rows[0]!.sessions).toBe(1) + }) + + it('cost-bearing history with sessions 0 is a bound, not identity', () => { + const day = blankDay('2026-09-02', path) + day.cost = 3 + day.calls = 2 + day.projects!.vault!.cost = 3 + day.projects!.vault!.calls = 2 + day.providers.claude!.cost = 3 + day.providers.claude!.calls = 2 + const counted = uniquePeriodSessionCount(live, [day]) + expect(counted).toEqual({ sessions: 1, basis: 'partial' }) + const row = buildPayloadProjects(live, [day], '/Users/synthetic')[0]! + expect(row.cost).toBe(3) + expect(row.sessionCountBasis).toBe('partial') + }) + + it('call-only history with no session ids is unknown', () => { + const day = blankDay('2026-09-02', path) + day.calls = 4 + day.projects!.vault!.calls = 4 + day.providers.claude!.calls = 4 + expect(uniquePeriodSessionCount(live, [day]).basis).toBe('partial') + }) + + it('savings-only history with no session ids is unknown', () => { + const day = blankDay('2026-09-02', path) + day.savingsUSD = 1.5 + day.projects!.vault!.savingsUSD = 1.5 + day.providers.claude!.savingsUSD = 1.5 + expect(uniquePeriodSessionCount(live, [day]).basis).toBe('partial') + }) + + it('token-only history with no session ids is unknown', () => { + const day = blankDay('2026-09-02', path) + day.inputTokens = 900 + day.outputTokens = 40 + day.providers.claude!.inputTokens = 900 + day.providers.claude!.outputTokens = 40 + expect(uniquePeriodSessionCount(live, [day]).basis).toBe('partial') + expect(uniquePeriodSessionCount(live, [day]).sessions).toBe(1) + }) + + it('absent session field on a cost-bearing row is unknown', () => { + const day = blankDay('2026-09-02', path) + day.cost = 2 + day.projects!.vault!.cost = 2 + delete (day as { sessions?: number }).sessions + delete (day.projects!.vault! as { sessions?: number }).sessions + delete (day.providers.claude! as { sessions?: number }).sessions + expect(uniquePeriodSessionCount(live, [day as DailyEntry]).basis).toBe('partial') + }) +}) + +describe('uniquePeriodSessionCount headline', () => { + it('uses live identity over occupancy ticks', () => { + const live = [liveRow('/tmp/p', [session({ id: 'same-actual-session', project: 'vault', cost: 0.012 })])] + const days = [ + cacheDay('2026-09-02', 1, 0.006, '/tmp/p'), + cacheDay('2026-09-07', 1, 0.006, '/tmp/p'), + ] + expect(uniquePeriodSessionCount(live, days)).toEqual({ sessions: 1, basis: 'partial' }) + }) + + it('keeps single-day carried occupancy when no live sessions survive', () => { + const days = [cacheDay('2026-08-01', 3, 100, '/gone', true)] + expect(uniquePeriodSessionCount([], days)).toEqual({ sessions: 3, basis: 'partial' }) + }) + + it('does not add a carried-day tick to a surviving identity', () => { + const live = [liveRow('/tmp/p', [session({ id: 'surviving-id', project: 'vault', cost: 1 })])] + const days = [cacheDay('2026-09-02', 1, 1, '/tmp/p', true), cacheDay('2026-09-07', 1, 1, '/tmp/p')] + const count = uniquePeriodSessionCount(live, days) + expect(count.sessions).toBe(1) + expect(count.basis).not.toBe('identity') + }) +}) diff --git a/tests/spend-flow.test.ts b/tests/spend-flow.test.ts index 176d8756..5c2636dc 100644 --- a/tests/spend-flow.test.ts +++ b/tests/spend-flow.test.ts @@ -64,10 +64,10 @@ function session(id: string, project: string, costs: Record): Se } as SessionSummary } -function project(name: string, sessions: SessionSummary[]): ProjectSummary { +function project(name: string, sessions: SessionSummary[], projectPath = `/tmp/${name}`): ProjectSummary { return { project: name, - projectPath: `/tmp/${name}`, + projectPath, sessions, totalCostUSD: sessions.reduce((sum, s) => sum + s.totalCostUSD, 0), totalSavingsUSD: 0, @@ -155,14 +155,36 @@ describe('computeSpendFlow', () => { { id: 'sonnet', label: 'sonnet', cost: 5 }, ]) expect(flow.projects).toEqual([ - { id: 'beta', label: 'beta', cost: 15 }, - { id: 'alpha', label: 'alpha', cost: 6 }, + { id: '/tmp/beta', label: 'beta', cost: 15 }, + { id: '/tmp/alpha', label: 'alpha', cost: 6 }, ]) expectTotalsReconcile(flow.models, sumLinksBy(flow.links, 'model')) expectTotalsReconcile(flow.projects, sumLinksBy(flow.links, 'project')) expect(flow.links.reduce((sum, link) => sum + link.cost, 0)).toBeCloseTo(21, 10) }) + it('distinguishes same-basename hyphenated cwd labels without rewriting the hyphen', async () => { + const { computeSpendFlow } = await import('../src/spend-flow.js') + const range: DateRange = { + start: new Date('2026-09-01T00:00:00.000Z'), + end: new Date('2026-09-07T23:59:59.999Z'), + } + parserMock.parseAllSessions.mockResolvedValueOnce([ + project('shared-vault', [session('s-shared', 'shared-vault', { opus: 0.46891 })], '/tmp/shared-vault'), + project('shared-vault', [session('s-alt', 'shared-vault', { sonnet: 0.018 })], '/tmp/alt/shared-vault'), + project('foo-bar', [session('s-hyphen', 'foo-bar', { haiku: 0.015 })], '/tmp/foo-bar'), + ]) + + const flow = await computeSpendFlow(range, 'all') + const byId = Object.fromEntries(flow.projects.map(p => [p.id, p])) + expect(byId['/tmp/shared-vault']?.label).toBe('tmp/shared-vault') + expect(byId['/tmp/alt/shared-vault']?.label).toBe('alt/shared-vault') + expect(byId['/tmp/foo-bar']?.label).toBe('foo-bar') + expect(flow.projects.map(p => p.label)).not.toContain('shared/vault') + expect(byId['/tmp/shared-vault']?.cost).toBeCloseTo(0.46891, 10) + expect(byId['/tmp/alt/shared-vault']?.cost).toBeCloseTo(0.018, 10) + }) + it('rolls models and projects beyond the top 8 into other without losing cost', async () => { const { computeSpendFlow } = await import('../src/spend-flow.js') const range: DateRange = { @@ -212,9 +234,9 @@ describe('computeSpendFlow', () => { expect(flow.models).toContainEqual({ id: 'other', label: 'other', cost: 1000 }) expect(flow.models).toContainEqual({ id: '__other__', label: 'Other', cost: 30 }) - expect(flow.projects).toContainEqual({ id: 'other', label: 'other', cost: 1000 }) + expect(flow.projects).toContainEqual({ id: '/tmp/other', label: 'other', cost: 1000 }) expect(flow.projects).toContainEqual({ id: '__other__', label: 'Other', cost: 30 }) - expect(flow.links).toContainEqual({ model: 'other', project: 'other', cost: 1000 }) + expect(flow.links).toContainEqual({ model: 'other', project: '/tmp/other', cost: 1000 }) expect(flow.links).toContainEqual({ model: '__other__', project: '__other__', cost: 30 }) expectTotalsReconcile(flow.models, sumLinksBy(flow.links, 'model')) expectTotalsReconcile(flow.projects, sumLinksBy(flow.links, 'project')) diff --git a/tests/usage-aggregator.test.ts b/tests/usage-aggregator.test.ts index a8818555..18a3efc1 100644 --- a/tests/usage-aggregator.test.ts +++ b/tests/usage-aggregator.test.ts @@ -46,13 +46,13 @@ describe('buildMenubarPayloadForRange', () => { // all-providers). The dock's glance reads these per-provider figures, so a sum // that leaked across providers would print another provider's spend. describe('addProviderSlice', () => { - it('sums cost, calls, tokens and sessions per provider across days', () => { + it('sums cost, calls and tokens; session ticks stay a per-day max bound', () => { const totals: Record = {} addProviderSlice(totals, 'claude', { cost: 10, calls: 4, savingsUSD: 0, inputTokens: 100, outputTokens: 20, sessions: 2 }) addProviderSlice(totals, 'claude', { cost: 2.5, calls: 1, savingsUSD: 0, inputTokens: 50, outputTokens: 5, sessions: 1 }) addProviderSlice(totals, 'codex', { cost: 1, calls: 3, savingsUSD: 0, inputTokens: 7, outputTokens: 3, sessions: 1 }) - expect(totals.claude).toEqual({ cost: 12.5, calls: 5, hasUsage: true, inputTokens: 150, outputTokens: 25, sessions: 3 }) + expect(totals.claude).toEqual({ cost: 12.5, calls: 5, hasUsage: true, inputTokens: 150, outputTokens: 25, sessions: 2 }) expect(totals.codex).toEqual({ cost: 1, calls: 3, hasUsage: true, inputTokens: 7, outputTokens: 3, sessions: 1 }) }) diff --git a/windows/src/components/HeroSection.tsx b/windows/src/components/HeroSection.tsx index 11ca8aba..a498abd1 100644 --- a/windows/src/components/HeroSection.tsx +++ b/windows/src/components/HeroSection.tsx @@ -1,10 +1,11 @@ import type { CombinedUsage, MenubarPayload } from '../lib/payload' import type { CurrencyState } from '../lib/currency' -import { formatCurrency, formatTokens, plural } from '../lib/currency' +import { formatCurrency, formatTokens } from '../lib/currency' import { prettyDate, todayKey } from '../lib/dates' import { SectionCaption } from './CollapsibleSection' import { ArrowDownRight, ArrowUpRight, LeafIcon, MonitorIcon, WarningIcon } from './Icons' import type { DisplayMetric } from '../lib/appSettings' +import { formatCombinedSessionCount, formatSessionCount, sessionCountIsExact, COMBINED_SESSION_COUNT_HELP, SESSION_COUNT_HELP } from '../lib/session-count-label' type Props = { payload: MenubarPayload | null @@ -29,6 +30,12 @@ export function HeroSection({ payload, currency, periodLabel, isToday, dailyBudg const cost = totals?.cost ?? payload?.current.cost ?? 0 const calls = totals?.calls ?? payload?.current.calls ?? 0 const sessions = totals?.sessions ?? payload?.current.sessions ?? 0 + const sessionLabel = combined + ? formatCombinedSessionCount() + : formatSessionCount(sessions, payload?.current.sessionCountBasis) + const sessionHelp = combined + ? COMBINED_SESSION_COUNT_HELP + : (sessionCountIsExact(payload?.current.sessionCountBasis) ? undefined : SESSION_COUNT_HELP) const inputTokens = totals?.inputTokens ?? payload?.current.inputTokens ?? 0 const outputTokens = totals?.outputTokens ?? payload?.current.outputTokens ?? 0 @@ -72,7 +79,7 @@ export function HeroSection({ payload, currency, periodLabel, isToday, dailyBudg ) : ( <> {calls.toLocaleString()} {calls === 1 ? 'call' : 'calls'} - {plural(sessions, 'session')} + {sessionLabel} )}
diff --git a/windows/src/components/PulseInsight.tsx b/windows/src/components/PulseInsight.tsx index 4b0f5b87..d363d47d 100644 --- a/windows/src/components/PulseInsight.tsx +++ b/windows/src/components/PulseInsight.tsx @@ -1,6 +1,7 @@ import type { MenubarPayload } from '../lib/payload' import type { CurrencyState } from '../lib/currency' import { formatCompactCurrency } from '../lib/currency' +import { formatSessionAveragePlaceholder, sessionCountIsExact } from '../lib/session-count-label' import { PencilLineIcon } from './Icons' type Props = { @@ -9,10 +10,12 @@ type Props = { } export function PulseInsight({ payload, currency }: Props) { - const { cacheHitPercent, oneShotRate, cost, sessions } = payload.current + const { cacheHitPercent, oneShotRate, cost, sessions, sessionCountBasis } = payload.current const cacheText = cacheHitPercent <= 0 ? '-' : `${Math.round(cacheHitPercent)}%` const oneShotText = oneShotRate == null ? '-' : `${Math.round(oneShotRate * 100)}%` - const costPerSession = sessions > 0 ? formatCompactCurrency(cost / sessions, currency) : '-' + const costPerSession = sessionCountIsExact(sessionCountBasis) && sessions > 0 + ? formatCompactCurrency(cost / sessions, currency) + : formatSessionAveragePlaceholder() return (
diff --git a/windows/src/components/StatsInsight.tsx b/windows/src/components/StatsInsight.tsx index 24c06766..50d97d9d 100644 --- a/windows/src/components/StatsInsight.tsx +++ b/windows/src/components/StatsInsight.tsx @@ -6,6 +6,7 @@ import { daysInMonth, monthDay } from '../lib/dates' import { computeHistoryStats } from '../lib/history' import type { Period } from './PeriodTabs' import { ArrowDownRight, ArrowUpRight, ChevronRight, FlameIcon } from './Icons' +import { formatSessionCount, SESSION_COUNT_HELP } from '../lib/session-count-label' type Props = { payload: MenubarPayload @@ -44,7 +45,7 @@ export function StatsInsight({ payload, currency, period }: Props) {
- + 0 ? plural(s.currentStreak, 'day') : '-'} /> 0 ? plural(s.longestStreak, 'day') : '-'} /> @@ -96,7 +97,7 @@ function TopProjects({ projects, currency }: { projects: ProjectEntry[]; currenc {projectDisplayName(project.name)} - {project.sessions} sess + {formatSessionCount(project.sessions, project.sessionCountBasis)} {formatCompactCurrency(project.cost, currency)} diff --git a/windows/src/lib/payload.ts b/windows/src/lib/payload.ts index c3029ad4..12ac4f0a 100644 --- a/windows/src/lib/payload.ts +++ b/windows/src/lib/payload.ts @@ -8,6 +8,7 @@ export type MenubarPayload = { cost: number calls: number sessions: number + sessionCountBasis?: 'identity' | 'partial' oneShotRate: number | null inputTokens: number outputTokens: number @@ -42,6 +43,8 @@ export type MenubarPayload = { cost: number calls?: number hasUsage?: boolean + sessions?: number + sessionCountBasis?: 'identity' | 'partial' }> } optimize: { @@ -117,7 +120,8 @@ export type ProjectEntry = { name: string cost: number sessions: number - avgCostPerSession: number + avgCostPerSession?: number + sessionCountBasis?: 'identity' | 'partial' sessionDetails?: SessionDetailEntry[] } diff --git a/windows/src/lib/session-count-label.ts b/windows/src/lib/session-count-label.ts new file mode 100644 index 00000000..2957e1dd --- /dev/null +++ b/windows/src/lib/session-count-label.ts @@ -0,0 +1,31 @@ +/// Display copy for period session counts. Keep in lockstep with +/// `src/session-count-label.ts`. +export type SessionCountBasis = 'identity' | 'partial' + +export const SESSION_COUNT_HELP = 'Older session logs may be unavailable.' +export const COMBINED_SESSION_COUNT_HELP = 'Session identities are unavailable across devices.' +export const COMBINED_SESSION_COUNT_LABEL = 'Session count unavailable' + +export function sessionCountIsExact(basis: SessionCountBasis | undefined): boolean { + return basis === 'identity' +} + +export function formatSessionCount( + sessions: number, + basis: SessionCountBasis | undefined, +): string { + if (!sessionCountIsExact(basis)) { + if (sessions <= 0) return 'Session count unavailable' + return sessions === 1 ? 'At least 1 session' : `At least ${sessions.toLocaleString('en-US')} sessions` + } + if (sessions === 1) return '1 session' + return `${sessions.toLocaleString('en-US')} sessions` +} + +export function formatSessionAveragePlaceholder(): string { + return '—' +} + +export function formatCombinedSessionCount(): string { + return COMBINED_SESSION_COUNT_LABEL +}