codeburn/app/renderer/sections/Spend.tsx
Resham Joshi 8fb478904e
feat: group a deleted sibling clone with its repository by folder name (#1692)
* feat(app): transient project selector in the desktop top bar

Scopes every report to one project path for the current session through
the same narrowing the VS Code workspace scope uses. The saved project
filter is never written; a restart is back on all projects.

* fix(app): let the name pickers ellipsize before the top bar overflows

* fix: key the daily project split per real path, not per label

A project label can span several paths: every Claude session started from the
home folder shares -Users-<name>, while its cwd puts it in a different project.
The day rollup keyed by label kept the first path it saw, so a rooted
--project headline took the whole label bucket on some days and missed it on
others. Key per (label, path), read old label-keyed days unchanged, bump the
daily cache to v68.

* fix(app): list only selectable, non-zero projects in the top bar picker

Rows with no session cwd (the Cursor and Grok Bot imports, provider label
fallbacks) report their label as the path, so the picker offered names the
bridge refuses and dash-to-slash guesses like eywa/lab. Keep only absolute
paths, and drop rows whose lifetime cost rounds to $0.00. The old test that
rooted a slashless Codex path is replaced: Codex now records the absolute cwd,
and a slashless path is always the label fallback.

* fix(app): show a toast when a project pick is refused

The pick was dropped silently. Also pin that an encoded -Users-... label
never reaches the picker list.

* feat: group projects by git repository

Clones and worktrees that share an origin remote are one project in every
project list (report JSON, By Project, the top bar picker, the terminal
dashboard), with the checkouts listed under the row. A --project path inside
a checkout scopes to the whole repository; --exact-project keeps the old
single-folder match. The origin is learned while the folder exists, kept in
git-origins.json and on each day's project entry (daily cache v69), so a
deleted scratch clone stays in its repository. The report JSON project list
now comes from the durable day set, so a row costs what selecting it reports.

* fix: a picked project row selects that row exactly

The top bar pick sends =<path>: a checkout in a repository still selects the
whole repository, and a plain folder selects itself without the folders under
it, which are rows of their own. So the picker row and the headline it opens
are the same set. Typed --project paths keep their prefix match. Days adopted
from an older cache learn the origin of every checkout that still exists, and
lookups outside a parse are saved on exit.

* fix: key the status snapshot on --exact-project

* feat: one Temporary folders row for scratch folders outside a repository

Every project path under a temp root (os.tmpdir(), /tmp, /var/folders and
their /private spellings) that is not a checkout of a known repository folds
into one row, in the report JSON, By Project, the terminal dashboard, the top
bar picker and the Settings Projects pane. Its pattern @temp selects or hides
all of them. The Projects pane leaves out rows that round to $0.00 unless a
saved pattern names them, and a saved pattern naming any checkout of a
repository row now names the whole row in the renderer too.

* feat: group a deleted sibling folder with its repository by folder name

A deleted folder with no recorded origin, named <checkout>-<suffix> or
<checkout>_<suffix> next to exactly one repository's checkout, joins that
repository row. The checkout entry carries matchedByFolderName and the Spend
drill-down labels it. Existing folders and names two repositories could claim
are left alone.

* feat: the longest checkout name wins a folder-name match

A deleted folder that fits several sibling checkouts joins the one with the
longest name; it is skipped only when the longest fits belong to two
repositories. The report project type declares matchedByFolderName.

* fix(claude): attribute each call to the project of its own cwd

* test: fold the temp roots the tests set, compare checkout ids as identities (Windows)

* test: compare folder-name checkout ids as identities (Windows)

* fix(claude): keep subfolder cwds in their project, count and show a split session once

* fix: an exclude path hides that checkout only, repository rows count a session once

* feat: mark folder-name matches in the CLI report and the project picker

* fix(claude): a deleted subfolder stays its own project
2026-10-08 06:54:41 +02:00

302 lines
12 KiB
TypeScript

import { Fragment, useState } from 'react'
import { BranchBreakdown } from '../components/BranchBreakdown'
import { CliErrorPanel, CliErrorText } from '../components/CliErrorPanel'
import { EmptyNote } from '../components/EmptyState'
import { ListRow } from '../components/ListRow'
import { Panel } from '../components/Panel'
import { Punchcard } from '../components/Punchcard'
import { Sankey } from '../components/Sankey'
import { SectionSkeleton } from '../components/Skeleton'
import { StackedBars } from '../components/StackedBars'
import { StaleBanner } from '../components/StaleBanner'
import { type Polled, usePolled } from '../hooks/usePolled'
import { formatCount, formatUsd, shortenProjectPath } from '../lib/format'
import { codeburn } from '../lib/ipc'
import { contiguousDailyWindow, dataStartKey, localDateKey } from '../lib/period'
import { reportMemoKey } from '../lib/reportMemoKey'
import { projectFilters } from '../lib/investigation'
import { formatSessionCount, sessionCountHelp } from '../lib/session-count-label'
import type { CliError, DateRange, MenubarPayload, Period, SpendFlow } from '../lib/types'
import { localeTag, t } from '../i18n'
import type { InvestigateRequest } from './Overview'
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`)
return Number.isNaN(d.getTime()) ? '—' : d.toLocaleDateString(localeTag(), { month: 'short', day: 'numeric' })
}
const SPEND_CHART_DAYS = 15
function providerLabel(provider: string): string {
if (provider === 'all') return t('spend.provider.allModels')
return provider
.split(/[-\s]+/)
.filter(Boolean)
.map(part => part.charAt(0).toUpperCase() + part.slice(1))
.join(' ')
}
function SpendPunchcard({ period, provider, range }: { period: Period; provider: string; range: DateRange | null }) {
const payload = usePolled<MenubarPayload>(
() => range ? codeburn.getTimeline(period, provider, range) : codeburn.getTimeline(period, provider),
[period, provider, range?.from, range?.to],
)
const timeline = payload.data?.history.timeline
if (!timeline) return null
return (
<Panel title={t('spend.punchcard.title')} right={t('spend.punchcard.right')}>
<Punchcard timeline={timeline} />
</Panel>
)
}
export function Spend({ period, provider, range = null }: { period: Period; provider: string; range?: DateRange | null }) {
const overview = usePolled<MenubarPayload>(
() => range ? codeburn.getOverview(period, provider, range) : codeburn.getOverview(period, provider),
[period, provider, range?.from, range?.to],
)
return <SpendContent period={period} provider={provider} range={range} overview={overview} />
}
export function SpendContent({
period,
provider,
range = null,
overview,
refreshToken = 0,
ready = true,
onInvestigate,
}: {
period: Period
provider: string
range?: DateRange | null
overview: Polled<MenubarPayload>
refreshToken?: number
ready?: boolean
onInvestigate?: (request: InvestigateRequest) => void
}) {
// Gate on app-level readiness so boot hydrates the cache once (default true
// keeps standalone renders/tests polling normally).
const flow = usePolled<SpendFlow>(
() => range ? codeburn.getSpendFlow(period, provider, range) : codeburn.getSpendFlow(period, provider),
[period, provider, range?.from, range?.to, refreshToken],
{ enabled: ready, memoKey: reportMemoKey('spendflow', period, provider, range) },
)
if (!overview.data) {
if (overview.error) return <CliErrorPanel error={overview.error} subject={t('common.subject.spend')} />
return <SectionSkeleton label={t('spend.loading.scanning')} rows={3} chart />
}
const animateKey = `${period}|${provider}|${range?.from ?? ''}|${range?.to ?? ''}`
return <SpendPage data={overview.data} flow={flow} period={period} provider={provider} range={range} staleError={overview.error} animateKey={animateKey} onInvestigate={onInvestigate} />
}
function SpendPage({
data,
flow,
period,
provider,
range,
staleError,
animateKey,
onInvestigate,
}: {
data: MenubarPayload
flow: ReturnType<typeof usePolled<SpendFlow>>
period: Period
provider: string
range: DateRange | null
staleError: CliError | null
animateKey: string
onInvestigate?: (request: InvestigateRequest) => void
}) {
// `history.daily` is SPARSE (active days only), so zero-fill a contiguous
// calendar window client-side; date keys are localDateKey / the CLI dateKey,
// which match exactly, so real days always land in place.
const now = new Date()
const chartDaily = range
? contiguousDailyWindow(data.history.daily, range.from, range.to)
: contiguousDailyWindow(
data.history.daily,
localDateKey(new Date(now.getFullYear(), now.getMonth(), now.getDate() - (SPEND_CHART_DAYS - 1))),
localDateKey(now),
)
const chartHasSpend = chartDaily.some(day => day.cost > 0)
const dataStart = dataStartKey(data.history.daily)
const projects = data.current.topProjects
const breakdowns = [
{
title: t('spend.breakdown.activity'),
rows: [
...data.current.topActivities.map(row => ({
key: `activity-${row.name}`,
title: row.name,
sub: formatCount(row.turns, 'turn'),
value: formatUsd(row.cost),
})),
...data.current.skills.map(row => ({
key: `skill-${row.name}`,
title: row.name,
sub: t('spend.breakdown.skillSuffix', { turns: formatCount(row.turns, 'turn') }),
value: formatUsd(row.cost),
})),
],
},
{
title: t('spend.breakdown.tools'),
rows: data.current.tools.map(row => ({
key: row.name,
title: row.name,
sub: formatCount(row.calls, 'call'),
value: undefined,
})),
},
{
title: t('spend.breakdown.mcp'),
rows: data.current.mcpServers.map(row => ({
key: row.name,
title: row.name,
sub: formatCount(row.calls, 'call'),
value: undefined,
})),
},
{
title: t('spend.breakdown.subagents'),
rows: data.current.subagents.map(row => ({
key: row.name,
title: row.name,
sub: formatCount(row.calls, 'call'),
value: formatUsd(row.cost),
})),
},
].filter(section => section.rows.length)
return (
<>
{staleError && <StaleBanner error={staleError} />}
<div className="spend-top-row">
<Panel title={t('spend.chart.title')} className="spend-chart-panel">
{chartHasSpend ? <StackedBars daily={chartDaily} fallbackLabel={providerLabel(provider)} animateKey={animateKey} dataStart={dataStart} /> : <EmptyNote>{t('spend.chart.empty')}</EmptyNote>}
</Panel>
<ProjectBreakdown projects={projects} onInvestigate={onInvestigate} />
</div>
<BranchBreakdown period={period} provider={provider} range={range} />
<Panel title={t('spend.flow.title')} right={t('spend.flow.right')} className="scroll-x">
{flow.data && flow.data.links.length ? (
<Sankey flow={flow.data} />
) : flow.error ? (
<CliErrorText error={flow.error} />
) : (
<EmptyNote>{flow.loading ? t('spend.flow.loading') : t('spend.flow.empty')}</EmptyNote>
)}
</Panel>
<SpendPunchcard period={period} provider={provider} range={range} />
<div className="spend-breakdowns">
{breakdowns.length ? (
breakdowns.map(section => <RowsPanel key={section.title} title={section.title} rows={section.rows} />)
) : (
<EmptyNote>{t('spend.breakdown.emptyAll')}</EmptyNote>
)}
</div>
</>
)
}
function ProjectBreakdown({ projects, onInvestigate }: { projects: Project[]; onInvestigate?: (request: InvestigateRequest) => void }) {
const [expanded, setExpanded] = useState<string | null>(null)
return (
<Panel title={t('spend.project.title')} right={projects.length ? t('spend.project.top', { count: projects.length }) : undefined} className="spend-scroll">
{projects.length ? (
projects.map((project, i) => {
const rowKey = projectRowKey(project, i)
const open = expanded === rowKey
const name = project.temporary ? t('shell.project.temporary') : project.name
// Sessions filter by exact checkout ids, so only a complete list drills.
const drillable = (project.checkoutCount ?? 0) <= (project.checkouts?.length ?? 0)
return (
<Fragment key={rowKey}>
<ListRow
no={String(i + 1).padStart(2, '0')}
title={name}
sub={<span title={project.sessionCountBasis === 'identity' ? undefined : sessionCountHelp()}>{formatSessionCount(project.sessions, project.sessionCountBasis)}</span>}
value={formatUsd(project.cost)}
expanded={open}
onClick={() => setExpanded(current => current === rowKey ? null : rowKey)}
/>
{open && (
<div className="spend-proj-detail" role="region" aria-label={t('spend.project.sessionsAria', { name })}>
{/* Drill-through entry: canonical project id (the same one the
session rows carry), so the destination matches exactly. */}
{onInvestigate && drillable && (
<button
className="ov-link spend-proj-drill"
type="button"
onClick={() => onInvestigate({ filters: projectFilters(...(project.checkouts?.map(c => c.id) ?? [project.id || project.name])) })}
>
{t('spend.project.viewSessions')}
</button>
)}
{project.checkouts?.map(checkout => (
<div className="spend-proj-session" key={checkout.id}>
<span className="sps-date" />
<span className="sps-model" title={checkout.id}>{shortenProjectPath(checkout.id, 2)}</span>
<span className="sps-calls" title={checkout.matchedByFolderName ? t('spend.project.matchedByFolderNameTip') : undefined}>
{checkout.matchedByFolderName ? t('spend.project.matchedByFolderName') : null}
</span>
<span className="sps-cost">{formatUsd(checkout.cost)}</span>
</div>
))}
{project.sessionDetails.length ? (
project.sessionDetails.map((session, j) => (
<div className="spend-proj-session" key={`${session.date}-${j}`}>
<span className="sps-date">{formatProjectDay(session.date)}</span>
<span className="sps-model">{session.models[0]?.name ?? '—'}</span>
<span className="sps-calls">{formatCount(session.calls, 'call')}</span>
<span className="sps-cost">{formatUsd(session.cost)}</span>
</div>
))
) : (
<div className="spend-proj-empty">{t('spend.project.noDetail')}</div>
)}
</div>
)}
</Fragment>
)
})
) : (
<EmptyNote>{t('spend.project.empty')}</EmptyNote>
)}
</Panel>
)
}
function RowsPanel({
title,
rows,
}: {
title: string
rows: Array<{ key: string; title: string; sub: string; value?: string }>
}) {
return (
<Panel title={title} className="spend-scroll">
{rows.map((row, i) => (
<ListRow key={row.key} no={String(i + 1).padStart(2, '0')} title={row.title} sub={row.sub} value={row.value} />
))}
</Panel>
)
}