codeburn/app/renderer/components/SessionDrawer.tsx
Resham Joshi d3fecffa9a
feat(sessions): fold subagent sessions into their parent row (#1690)
* feat(sessions): fold subagent sessions into their parent row

The default sessions list (table, JSON, TUI, contributions, desktop) now shows
one row per parent session with its provider-recorded subagents summed in and
listed under subagents. Grouping reuses the work-unit resolver, so only rows
move; totals are unchanged. --by-work-unit keeps the flat rows.

* test: reconcile the session diagnosis with the folded sessions row

* fix(sessions): find and open a parent row by its subagents, count subagents apart from top-level rows
2026-10-08 06:27:58 +02:00

320 lines
15 KiB
TypeScript

import { useEffect, useMemo, useRef } from 'react'
import { Stat } from './Stat'
import { useEscape } from '../hooks/useEscape'
import { formatCompact, formatCount, formatDayLong, formatDuration, formatUsd, shortenProjectPath } from '../lib/format'
import { DUR, useExitAnimation } from '../lib/motion'
import { codeburn } from '../lib/ipc'
import type { InvestigationFilters } from '../lib/investigation'
import { contributeRow } from '../lib/investigation'
import type { SessionDrillRow, SessionRow } from '../lib/types'
import { Icon } from './icons'
import { t } from '../i18n'
/**
* The drill-through side drawer: a plain-language read of one session, then the
* cost/token figures and every link the report carries (PR URLs). All content
* derives from the already-loaded contributions report, and the heavy
* breakdowns below only render while the drawer is open (lazy by mount, not by
* fetch), so the list behind it stays responsive. Transcript text crosses IPC
* only for the session view (SessionView.tsx): read on demand when that view
* opens, never cached, never synced or sent in telemetry.
*
* A11y contract: role="dialog", Escape closes, focus moves into the panel on
* open and the PARENT returns focus to the control that opened it (the opener
* element is still alive behind the drawer). Tab is trapped inside.
*/
export function SessionDrawer({ row, openKey, filters, medianCost, onClose }: {
row: SessionDrillRow
/** Row identity, so a drawer still exiting on the old row disarms its close
* when the user picks a new one. */
openKey: string
filters: InvestigationFilters
/** Median cost of the sessions the list is currently showing (the searched
* and filtered set). Absent when the population is too small for the
* comparison to mean anything. */
medianCost?: number
onClose: () => void
}) {
const panelRef = useRef<HTMLDivElement>(null)
const { closing, beginExit } = useExitAnimation(onClose, DUR.slow, openKey)
useEscape(true, beginExit)
useEffect(() => {
const panel = panelRef.current
panel?.focus()
const onKeyDown = (event: KeyboardEvent) => {
if (event.key !== 'Tab' || !panel) return
// Keep Tab cycling inside the drawer while it is open.
const focusable = panel.querySelectorAll<HTMLElement>('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')
if (focusable.length === 0) return
const first = focusable[0]!
const last = focusable[focusable.length - 1]!
if (event.shiftKey && document.activeElement === first) {
event.preventDefault()
last.focus()
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault()
first.focus()
}
}
window.addEventListener('keydown', onKeyDown, true)
return () => window.removeEventListener('keydown', onKeyDown, true)
}, [])
return (
<>
<div className={closing ? 'drawer-scrim closing' : 'drawer-scrim'} aria-hidden="true" onClick={beginExit} />
<aside
ref={panelRef}
className={closing ? 'session-drawer closing' : 'session-drawer'}
role="dialog"
aria-modal="true"
aria-label={t('sessions.drawer.ariaLabel', { title: row.title || shortenProjectPath(row.project) })}
tabIndex={-1}
>
<div className="drawer-head">
<div>
<h3 className="drawer-title">{row.title || shortenProjectPath(row.project)}</h3>
<div className="drawer-sub">
{row.provider} · {shortenProjectPath(row.project)} · <span className="mono">{row.sessionId.slice(0, 18)}</span>
</div>
<div className="drawer-sub">
{formatDayLong(row.startedAt)} → {formatDayLong(row.endedAt)}
{row.durationMs > 0 && <> · {formatDuration(row.durationMs)}</>}
</div>
</div>
<button type="button" className="drawer-close" aria-label={t('sessions.drawer.closeAriaLabel')} onClick={beginExit}><Icon name="x" /></button>
</div>
<SessionDetails row={row} filters={filters} medianCost={medianCost} />
</aside>
</>
)
}
/** The session's cost, tokens, models, categories, branches and PRs, from the
* contributions report. The drawer's body, and the session view's details. */
export function SessionDetails({ row, filters, medianCost }: { row: SessionDrillRow; filters: InvestigationFilters; medianCost?: number }) {
const contribution = useMemo(() => contributeRow(row, filters), [row, filters])
const breakdown = useMemo(() => buildBreakdowns(row), [row])
const cacheTotal = row.inputTokens + row.cacheReadTokens
const cacheHit = cacheTotal > 0 ? Math.round(row.cacheReadTokens / cacheTotal * 100) : 0
const median = medianCost !== undefined && medianCost > 0 ? medianCost : null
const selectedCost = contribution !== null && contribution.cost < row.cost - 1e-9 ? contribution.cost : null
const leadCost = selectedCost ?? row.cost
// Past 100x the multiple says nothing the dollar figure has not already said.
const ratio = median === null || leadCost / median > 100 ? null : leadCost / median
const foldLabel = branchPrLabel(breakdown)
return (
<>
<p className="drawer-lead">
{selectedCost === null ? t('sessions.drawer.leadCost') : t('sessions.drawer.leadCostSelection')}
<b>{formatUsd(leadCost)}</b>
{ratio === null
? '.'
: ratio < 0.1
? t('sessions.drawer.leadFraction')
: <>{t('sessions.drawer.leadRatioPrefix')}<b>{formatRatio(ratio)}{t('sessions.drawer.ratioUnit')}</b>{t('sessions.drawer.leadRatioSuffix')}</>}
</p>
<div className="stats drawer-tiles">
<Stat
label={t('sessions.drawer.statCostLabel')}
value={formatUsd(leadCost)}
delta={selectedCost !== null
? t('sessions.drawer.deltaOfTotal', { total: formatUsd(row.cost) })
: ratio === null
? t('sessions.drawer.deltaFullSession')
: ratio < 0.1
? <span className="down">{t('sessions.drawer.deltaBelowMedian')}</span>
: <span className={ratio >= 1 ? 'up' : 'down'}>{t('sessions.drawer.deltaRatioMedian', { ratio: `${formatRatio(ratio)}${t('sessions.drawer.ratioUnit')}` })}</span>}
/>
<Stat label={t('sessions.drawer.statTurnsLabel')} value={row.turns.toLocaleString()} delta={formatCount(row.calls, 'call')} />
{row.durationMs > 0
? <Stat label={t('sessions.drawer.statDurationLabel')} value={formatDuration(row.durationMs)} delta={t('sessions.drawer.deltaWallClock')} />
: <Stat label={t('sessions.drawer.statCallsLabel')} value={row.calls.toLocaleString()} delta={t('sessions.drawer.deltaApiCalls')} />}
</div>
{row.isSidechain && row.parentSessionId && (
<p className="drawer-note">{t('sessions.drawer.subagentPrefix')}<span className="mono">{row.parentSessionId.slice(0, 18)}</span>.</p>
)}
<DrawerBreakdown label={t('sessions.drawer.modelsLabel')} rows={breakdown.models} />
<DrawerBreakdown label={t('sessions.drawer.categoriesLabel')} rows={breakdown.categories} />
{row.subagents && row.subagents.length > 0 && <SubagentBreakdown subagents={row.subagents} />}
<details className="drawer-fold">
<summary>
{t('sessions.drawer.tokensSummary', {
inTok: formatCompact(row.inputTokens),
outTok: formatCompact(row.outputTokens),
cacheTok: formatCompact(row.cacheWriteTokens),
hitPct: cacheHit,
})}
</summary>
<div className="drawer-fold-body">
<div className="stats">
<Stat label={t('sessions.drawer.statInputLabel')} value={formatCompact(row.inputTokens)} delta={t('sessions.drawer.deltaTokensSent')} />
<Stat label={t('sessions.drawer.statOutputLabel')} value={formatCompact(row.outputTokens)} delta={t('sessions.drawer.deltaTokensGenerated')} />
<Stat label={t('sessions.drawer.statCacheReadLabel')} value={formatCompact(row.cacheReadTokens)} delta={t('sessions.drawer.deltaCacheHit', { percent: cacheHit })} />
<Stat label={t('sessions.drawer.statCacheWriteLabel')} value={formatCompact(row.cacheWriteTokens)} delta={t('sessions.drawer.deltaTokensCached')} />
</div>
</div>
</details>
{foldLabel !== null && (
<details className="drawer-fold">
<summary>{t('sessions.drawer.branchesPrsSummary', { label: foldLabel })}</summary>
<div className="drawer-fold-body">
<DrawerBreakdown label={t('sessions.drawer.branchesLabel')} rows={breakdown.branches} caption={t('sessions.drawer.branchesCaption')} />
{breakdown.days.length > 1 && <DrawerBreakdown label={t('sessions.drawer.daysLabel')} rows={breakdown.days} />}
<DrawerBreakdown label={t('sessions.drawer.prsLabel')} rows={breakdown.prs} caption={t('sessions.drawer.prsCaption')} link />
{breakdown.unattributedPrCost > 0 && (
<p className="drawer-note">{t('sessions.drawer.notTiedToPr', { amount: formatUsd(breakdown.unattributedPrCost) })}</p>
)}
</div>
</details>
)}
<p className="drawer-note">
{row.savingsUSD > 0 ? t('sessions.drawer.savedBaseline', { amount: formatUsd(row.savingsUSD) }) : t('sessions.drawer.savedBaselineNone')}
</p>
</>
)
}
const SUBAGENTS_SHOWN = 20
/** The subagent sessions folded into this row, most expensive first. */
function SubagentBreakdown({ subagents }: { subagents: SessionRow[] }) {
const sorted = [...subagents].sort((a, b) => b.cost - a.cost)
const total = sorted.reduce((sum, entry) => sum + entry.cost, 0)
const rest = sorted.slice(SUBAGENTS_SHOWN)
return (
<details className="drawer-fold">
<summary>{t(`sessions.drawer.subagentsSummary.${sorted.length === 1 ? 'one' : 'other'}`, { count: sorted.length, amount: formatUsd(total) })}</summary>
<div className="drawer-fold-body">
<DrawerBreakdown
label={t('sessions.drawer.subagentsLabel')}
rows={sorted.slice(0, SUBAGENTS_SHOWN).map(entry => ({ key: entry.sessionId, label: entry.title || entry.sessionId, cost: entry.cost }))}
caption={rest.length > 0 ? t('sessions.drawer.subagentsMore', { count: rest.length, amount: formatUsd(rest.reduce((sum, entry) => sum + entry.cost, 0)) }) : undefined}
/>
</div>
</details>
)
}
function formatRatio(ratio: number): string {
return (ratio >= 10 ? Math.round(ratio) : Math.round(ratio * 10) / 10).toLocaleString('en-US')
}
function branchPrLabel({ branches, prs }: { branches: BreakdownRow[]; prs: BreakdownRow[] }): string | null {
const parts: string[] = []
// A lone `main` with no PRs is every session's default: nothing to unfold.
if (branches.length > 0 && !(branches.length === 1 && branches[0]!.label === 'main' && prs.length === 0)) {
const named = branches.slice(0, 2).map(entry => entry.label).join(', ')
parts.push(branches.length > 2 ? t('sessions.drawer.branchesMoreList', { named, count: branches.length - 2 }) : named)
}
if (prs.length > 0) parts.push(t(prs.length === 1 ? 'sessions.drawer.prCount.one' : 'sessions.drawer.prCount.other', { count: prs.length }))
return parts.length > 0 ? parts.join(', ') : null
}
type BreakdownRow = { key: string; label: string; cost: number; approx?: boolean; url?: string }
function buildBreakdowns(row: SessionDrillRow): {
models: BreakdownRow[]
categories: BreakdownRow[]
branches: BreakdownRow[]
days: BreakdownRow[]
prs: BreakdownRow[]
unattributedPrCost: number
} {
const models = new Map<string, number>()
const categories = new Map<string, number>()
const branches = new Map<string, number>()
const days = new Map<string, number>()
const prs = new Map<string, { cost: number; approx: boolean }>()
let unattributedPrCost = 0
const segments = row.contributions?.segments ?? []
for (const segment of segments) {
for (const [model, cost] of Object.entries(segment.models)) {
if (cost === 0) continue
models.set(model, (models.get(model) ?? 0) + cost)
}
if (segment.category && segment.cost > 0) categories.set(segment.category, (categories.get(segment.category) ?? 0) + segment.cost)
if (segment.branch && segment.cost > 0) branches.set(segment.branch, (branches.get(segment.branch) ?? 0) + segment.cost)
if (segment.day && segment.cost > 0) days.set(segment.day, (days.get(segment.day) ?? 0) + segment.cost)
if (segment.prs.length === 0) {
unattributedPrCost += segment.cost
} else {
const share = 1 / segment.prs.length
for (const url of segment.prs) {
const entry = prs.get(url) ?? { cost: 0, approx: false }
entry.cost += segment.cost * share
entry.approx = entry.approx || segment.approx === true
prs.set(url, entry)
}
}
}
const toRows = (map: Map<string, number>): BreakdownRow[] =>
[...map.entries()]
.map(([key, cost]) => ({ key, label: key, cost }))
.sort((a, b) => b.cost - a.cost)
return {
models: toRows(models).map(entry => ({ ...entry, label: entry.key === '' ? t('sessions.drawer.unknownModel') : entry.key })),
categories: toRows(categories),
branches: toRows(branches).map(entry => ({ ...entry, label: entry.key })),
days: toRows(days),
prs: [...prs.entries()]
.map(([url, entry]) => ({ key: url, label: prLabel(url), cost: entry.cost, approx: entry.approx || undefined, url }))
.sort((a, b) => b.cost - a.cost),
unattributedPrCost,
}
}
/** Short `owner/repo#123` form for GitHub URLs, else the URL itself — the same
* rule the by-PR report uses for labels. */
function prLabel(url: string): string {
const match = /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)/.exec(url)
return match ? `${match[1]}/${match[2]}#${match[3]}` : url
}
function DrawerBreakdown({ label, rows, caption, link = false }: {
label: string
rows: BreakdownRow[]
caption?: string
link?: boolean
}) {
if (rows.length === 0) return null
const max = rows[0]!.cost
return (
<div className="drawer-breakdown" role="group" aria-label={t('sessions.drawer.breakdownAriaLabel', { label })}>
<div className="drawer-breakdown-head">{label}</div>
{rows.map(entry => (
<div className="drawer-breakdown-row" key={entry.key}>
<span className="drawer-breakdown-label" title={entry.url ?? entry.label}>{entry.label}</span>
<div className="drawer-breakdown-bar" aria-hidden="true"><span style={{ width: `${max > 0 ? entry.cost / max * 100 : 0}%` }} /></div>
{link && entry.url
? (
<a
className="drawer-breakdown-cost drawer-link"
href={entry.url}
onClick={event => {
event.preventDefault()
void codeburn.openExternal(entry.url!)
}}
>
{entry.approx ? '~' : ''}{formatUsd(entry.cost)}
</a>
)
: <span className="drawer-breakdown-cost">{formatUsd(entry.cost)}</span>}
</div>
))}
{caption && <p className="drawer-caption">{caption}</p>}
</div>
)
}