Session drawer: plain-language lead, three tiles, folded detail (#1444)

* Fix session drawer tile grid wrapping and edge clipping

* Stop the session drawer tile value from clipping

* Rewrite the session drawer around a plain-language lead, three tiles, and folds

* Reword the pull-requests caption to drop the em dash

* Drop the drawer's shape clause instead of labelling most sessions the same

* Base the drawer's multiple on the rows the list shows, and keep it readable

* Put the selected figure in the drawer's lead and Cost tile

* Swap the drawer's empty Duration tile for Calls and say long spans in days

* Name the drawer's breakdowns, singularize one call, and hide an empty fold

* Cover the drawer's ratio bounds, selected cost, Calls tile, and fold rule

* Separate the drawer fold count, punctuate the cost caption, and soften the smallest ratio

* Shorten the drawer cost caption and name the smallest ratio without an inequality
This commit is contained in:
Resham Joshi 2026-09-15 22:53:43 +02:00 • committed by GitHub
parent 38a3d3b1cf
commit c2d514d1e5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 218 additions and 28 deletions

View file

@ -8,20 +8,24 @@ import { contributeRow } from '../lib/investigation'
import type { SessionDrillRow } from '../lib/types'
/**
* The drill-through side drawer: a session's metadata, the cost/token figures
* that matter in the CURRENT selection next to its full totals, and every link
* the report carries (PR URLs). All content derives from the already-loaded
* contributions report — no transcript text ever crosses the IPC boundary 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.
* 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: no transcript text
* ever crosses the IPC boundary 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.
*
* 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, filters, onClose }: {
export function SessionDrawer({ row, filters, medianCost, onClose }: {
row: SessionDrillRow
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)
@ -57,6 +61,12 @@ export function SessionDrawer({ row, filters, onClose }: {
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 (
<>
@ -76,24 +86,35 @@ export function SessionDrawer({ row, filters, onClose }: {
{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)} · {formatDuration(row.durationMs)}
{formatDayLong(row.startedAt)} → {formatDayLong(row.endedAt)}
{row.durationMs > 0 && <> · {formatDuration(row.durationMs)}</>}
</div>
</div>
<button type="button" className="drawer-close" aria-label="Close session details" onClick={onClose}>×</button>
</div>
<div className="stats">
<Stat label="Cost" value={formatUsd(row.cost)} delta="full session" />
{contribution !== null && (
<Stat label="In selection" value={formatUsd(contribution.cost)} delta={contribution.cost < row.cost - 1e-9 ? 'part of this session' : 'whole session'} />
)}
<Stat label="Calls" value={row.calls.toLocaleString()} delta="API calls" />
<Stat label="Turns" value={row.turns.toLocaleString()} delta="assistant turns" />
<Stat label="Saved" value={formatUsd(row.savingsUSD)} delta="vs baseline" />
<Stat label="Input" value={formatCompact(row.inputTokens)} delta="tokens sent" />
<Stat label="Output" value={formatCompact(row.outputTokens)} delta="tokens generated" />
<Stat label="Cache read" value={formatCompact(row.cacheReadTokens)} delta={`${cacheHit}% hit`} />
<Stat label="Cache write" value={formatCompact(row.cacheWriteTokens)} delta="tokens cached" />
<p className="drawer-lead">
{selectedCost === null ? 'This session cost ' : 'Your selection of this session cost '}
<b>{formatUsd(leadCost)}</b>
{ratio === null ? '.' : ratio < 0.1 ? ', a fraction of your usual.' : <>, about <b>{formatRatio(ratio)}x</b> your usual.</>}
</p>
<div className="stats drawer-tiles">
<Stat
label="Cost"
value={formatUsd(leadCost)}
delta={selectedCost !== null
? `of ${formatUsd(row.cost)} total`
: ratio === null
? 'full session'
: ratio < 0.1
? <span className="down">well below median</span>
: <span className={ratio >= 1 ? 'up' : 'down'}>{formatRatio(ratio)}x your median</span>}
/>
<Stat label="Turns" value={row.turns.toLocaleString()} delta={`${row.calls.toLocaleString()} ${row.calls === 1 ? 'call' : 'calls'}`} />
{row.durationMs > 0
? <Stat label="Duration" value={formatDuration(row.durationMs)} delta="wall clock" />
: <Stat label="Calls" value={row.calls.toLocaleString()} delta="API calls" />}
</div>
{row.isSidechain && row.parentSessionId && (
@ -102,17 +123,59 @@ export function SessionDrawer({ row, filters, onClose }: {
<DrawerBreakdown label="Models" rows={breakdown.models} />
<DrawerBreakdown label="Task categories" rows={breakdown.categories} />
<DrawerBreakdown label="Branches" rows={breakdown.branches} caption="Git branch carried across turns (Claude sessions only)." />
{breakdown.days.length > 1 && <DrawerBreakdown label="Days" rows={breakdown.days} />}
<DrawerBreakdown label="Pull requests" rows={breakdown.prs} caption="A turn split across several PRs contributes its share to each — rows are not an exclusive partition." link />
{breakdown.unattributedPrCost > 0 && (
<p className="drawer-note">Not tied to a specific PR: {formatUsd(breakdown.unattributedPrCost)}</p>
<details className="drawer-fold">
<summary>
Tokens: {formatCompact(row.inputTokens)} in, {formatCompact(row.outputTokens)} out,{' '}
{formatCompact(row.cacheWriteTokens)} written to cache, {cacheHit}% cache hits
</summary>
<div className="drawer-fold-body">
<div className="stats">
<Stat label="Input" value={formatCompact(row.inputTokens)} delta="tokens sent" />
<Stat label="Output" value={formatCompact(row.outputTokens)} delta="tokens generated" />
<Stat label="Cache read" value={formatCompact(row.cacheReadTokens)} delta={`${cacheHit}% hit`} />
<Stat label="Cache write" value={formatCompact(row.cacheWriteTokens)} delta="tokens cached" />
</div>
</div>
</details>
{foldLabel !== null && (
<details className="drawer-fold">
<summary>Branches and pull requests: {foldLabel}</summary>
<div className="drawer-fold-body">
<DrawerBreakdown label="Branches" rows={breakdown.branches} caption="Git branch carried across turns (Claude sessions only)." />
{breakdown.days.length > 1 && <DrawerBreakdown label="Days" rows={breakdown.days} />}
<DrawerBreakdown label="Pull requests" rows={breakdown.prs} caption="A turn that touched several PRs counts toward each of them, so the rows can add up to more than the total." link />
{breakdown.unattributedPrCost > 0 && (
<p className="drawer-note">Not tied to a specific PR: {formatUsd(breakdown.unattributedPrCost)}</p>
)}
</div>
</details>
)}
<p className="drawer-note">
{row.savingsUSD > 0 ? `Saved vs baseline: ${formatUsd(row.savingsUSD)}.` : 'Saved vs baseline: none this session.'}
</p>
</aside>
</>
)
}
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 ? `${named}, +${branches.length - 2} more` : named)
}
if (prs.length > 0) parts.push(`${prs.length} PR${prs.length === 1 ? '' : 's'}`)
return parts.length > 0 ? parts.join(', ') : null
}
type BreakdownRow = { key: string; label: string; cost: number; approx?: boolean; url?: string }
function buildBreakdowns(row: SessionDrillRow): {

View file

@ -53,6 +53,7 @@ describe('date and duration formatters', () => {
expect(formatDuration(29_000)).toBe('29s')
expect(formatDuration(47 * 60_000)).toBe('47m')
expect(formatDuration(134 * 60_000)).toBe('2h 14m')
expect(formatDuration(286 * 3_600_000 + 39 * 60_000)).toBe('12 days')
expect(formatDuration(0)).toBe('—')
})
})

View file

@ -79,11 +79,12 @@ export function formatDayLong(iso: string): string {
return Number.isNaN(d.getTime()) ? '—' : d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
}
/** "2h 14m" / "47m" / "38s" from a duration in ms. */
/** "12 days" / "2h 14m" / "47m" / "38s" from a duration in ms. */
export function formatDuration(ms: number): string {
if (!Number.isFinite(ms) || ms <= 0) return '—'
const totalMin = Math.round(ms / 60_000)
if (totalMin < 1) return `${Math.round(ms / 1000)}s`
if (totalMin < 60) return `${totalMin}m`
if (totalMin >= 2_880) return `${Math.round(totalMin / 1_440)} days`
return `${Math.floor(totalMin / 60)}h ${totalMin % 60}m`
}

View file

@ -4,7 +4,7 @@ import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { EMPTY_FILTERS } from '../lib/investigation'
import type { SessionRow } from '../lib/types'
import type { SessionDrillRow, SessionRow } from '../lib/types'
import { INITIAL_VISIBLE, sessionRowKey, Sessions } from './Sessions'
const { getSessions, getSessionsContributions } = vi.hoisted(() => ({
@ -227,9 +227,14 @@ describe('Sessions', () => {
expect(within(drawer).getByText(/claude · projects\/codeburn/)).toBeInTheDocument()
expect(within(drawer).getByText(/Jul 11, 2026 → Jul 11, 2026 · 1h 35m/)).toBeInTheDocument()
expect(container.querySelectorAll('.session-row')).toHaveLength(6)
for (const label of ['Cost', 'Calls', 'Turns', 'Saved', 'Input', 'Output', 'Cache read', 'Cache write']) {
expect(container.querySelector('.drawer-lead')).toHaveTextContent('This session cost $8.41, about 2.8x your usual.')
for (const label of ['Cost', 'Turns', 'Duration']) {
expect(within(drawer).getByText(label)).toBeInTheDocument()
}
expect(within(drawer).getByText('2.8x your median')).toBeInTheDocument()
expect(within(drawer).getByText('44 calls')).toBeInTheDocument()
expect(within(drawer).queryByText('Selected')).not.toBeInTheDocument()
expect(within(drawer).getByText('Saved vs baseline: $1.25.')).toBeInTheDocument()
expect(within(drawer).getByText('44% hit')).toBeInTheDocument()
// Escape closes the drawer (the drawer's own key handler), focus returns
@ -241,6 +246,96 @@ describe('Sessions', () => {
expect(container.querySelectorAll('.session-row')).toHaveLength(6)
})
it('folds the token tiles behind a summary line and opens them on click', async () => {
const user = userEvent.setup()
getSessions.mockResolvedValue(rows)
const { container } = render(<Sessions period="30days" provider="all" openSessionId={sessionRowKey(rows[0]!)} />)
await screen.findByRole('dialog', { name: /session details/i })
// Plain rows carry no contributions, so branches and PRs have nothing to
// fold: the token fold is the only one.
const folds = container.querySelectorAll('.session-drawer details')
expect(folds).toHaveLength(1)
const fold = folds[0]!
expect(fold).toHaveTextContent('Tokens: 1.4M in, 64K out, 12K written to cache, 44% cache hits')
expect(fold).not.toHaveAttribute('open')
await user.click(container.querySelector('.session-drawer summary')!)
expect(fold).toHaveAttribute('open')
for (const label of ['Input', 'Output', 'Cache read', 'Cache write']) {
expect(within(fold as HTMLElement).getByText(label)).toBeInTheDocument()
}
})
it('drops the median comparison under five loaded sessions and dims an empty saving', async () => {
const small = [{ ...rows[0]!, savingsUSD: 0 }, rows[1]!, rows[2]!]
getSessions.mockResolvedValue(small)
const { container } = render(<Sessions period="30days" provider="all" openSessionId={sessionRowKey(small[0]!)} />)
const drawer = await screen.findByRole('dialog', { name: /session details/i })
expect(container.querySelector('.drawer-lead')).toHaveTextContent('This session cost $8.41.')
expect(within(drawer).getByText('full session')).toBeInTheDocument()
expect(within(drawer).queryByText(/your median/)).not.toBeInTheDocument()
expect(within(drawer).getByText('Saved vs baseline: none this session.')).toBeInTheDocument()
})
it('drops a multiple past 100x, floors a tiny one, shows Calls without a duration, and folds nothing for a lone main', async () => {
const usual = [0, 1, 2, 3, 4].map(index => session({
sessionId: `usual-${index}`, project: 'usual-project', provider: 'claude', cost: 1,
}))
const subject: SessionDrillRow = {
...session({ sessionId: 'outlier-session', project: 'outlier-project', provider: 'claude', cost: 500, calls: 1, turns: 1, durationMs: 0 }),
contributions: { segments: [
{ day: '2026-09-10', category: 'coding', branch: 'main', models: { 'Opus 4.8': 500 }, prs: [], cost: 500, calls: 1, savingsUSD: 0, inputTokens: 1_000, outputTokens: 100 },
] },
}
getSessions.mockResolvedValue([subject, ...usual])
const { container, rerender } = render(<Sessions period="30days" provider="all" openSessionId={sessionRowKey(subject)} />)
const drawer = await screen.findByRole('dialog', { name: /session details/i })
// 500x the median is no more informative than the dollar figure itself.
expect(container.querySelector('.drawer-lead')).toHaveTextContent('This session cost $500.00.')
expect(within(drawer).queryByText(/your median/)).not.toBeInTheDocument()
expect(within(drawer).getByText('full session')).toBeInTheDocument()
expect(within(drawer).getByText('Calls')).toBeInTheDocument()
expect(within(drawer).queryByText('Duration')).not.toBeInTheDocument()
expect(within(drawer).getByText('1 call')).toBeInTheDocument()
expect(container.querySelector('.session-drawer details')).not.toHaveTextContent('Branches and pull requests')
const tiny = { ...subject, cost: 0.02 }
getSessions.mockResolvedValue([tiny, ...usual])
rerender(<Sessions period="30days" provider="all" refreshToken={1} openSessionId={sessionRowKey(tiny)} />)
await waitFor(() => expect(container.querySelector('.drawer-lead')).toHaveTextContent('a fraction of your usual'))
})
it('puts the selected figure in the Cost tile and the lead, with the session total as its caption', async () => {
const drillRows: SessionDrillRow[] = [
{
...session({ sessionId: 'mixed-1', project: 'mixed-project', provider: 'claude', cost: 1.0, calls: 10, turns: 8 }),
contributions: { segments: [
{ day: '2026-09-10', category: 'coding', branch: null, models: { 'Sonnet 4.5': 0.2 }, prs: [], cost: 0.2, calls: 2, savingsUSD: 0, inputTokens: 140_000, outputTokens: 20_000 },
{ day: '2026-09-10', category: 'debugging', branch: null, models: { 'Sonnet 4.5': 0.8 }, prs: [], cost: 0.8, calls: 8, savingsUSD: 0, inputTokens: 560_000, outputTokens: 80_000 },
] },
},
]
getSessionsContributions.mockResolvedValue(drillRows)
const { container } = render(
<Sessions
period="30days"
provider="all"
filters={{ ...EMPTY_FILTERS, categories: ['coding'] }}
openSessionId={sessionRowKey(drillRows[0]!)}
/>,
)
const drawer = await screen.findByRole('dialog', { name: /session details/i })
expect(container.querySelector('.drawer-lead')).toHaveTextContent('Your selection of this session cost $0.20.')
const cost = container.querySelector('.drawer-tiles .stat')!
expect(cost.querySelector('.v')).toHaveTextContent('$0.20')
expect(cost.querySelector('.d')).toHaveTextContent('of $1.00 total')
expect(within(drawer).queryByText(/^Selected/)).not.toBeInTheDocument()
})
it('closes (invalidates) the drawer when the open session leaves the population', async () => {
getSessions.mockResolvedValue(rows)
const onSessionClose = vi.fn()

View file

@ -229,6 +229,16 @@ export function Sessions({
].some(value => value.toLowerCase().includes(q)))
}, [selection, q])
// "Your usual" for the drawer's lead sentence: the median over the rows the
// list is actually showing. Under five rows a median is noise, so the drawer
// drops the comparison instead.
const medianCost = useMemo(() => {
if (searched.length < 5) return undefined
const sorted = searched.map(({ row }) => row.cost).sort((left, right) => left - right)
const mid = sorted.length >> 1
return sorted.length % 2 === 1 ? sorted[mid]! : (sorted[mid - 1]! + sorted[mid]!) / 2
}, [searched])
const summary = useMemo(() => {
if (investigating) {
return {
@ -475,6 +485,7 @@ export function Sessions({
<SessionDrawer
row={openRow}
filters={filters}
medianCost={medianCost}
onClose={closeDrawer}
/>
)}

View file

@ -1263,6 +1263,25 @@ html.page-hidden *::after {
.drawer-breakdown-cost { font-variant-numeric: tabular-nums; }
.drawer-link { color: var(--accent); text-decoration: none; }
.drawer-link:hover { text-decoration: underline; }
/* The drawer is much narrower than the 4-column .stats grid was sized for,
which wrapped titles and pushed the last tile off the drawer's edge. */
.session-drawer .stats { grid-template-columns: repeat(auto-fill, minmax(112px, 1fr)); }
.session-drawer .stats .phead b { display: block; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.session-drawer .stats .stat .d { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.session-drawer .stats .stat .v { font-size: var(--fs-kpi); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.session-drawer .drawer-tiles { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.drawer-lead { margin: 0; font-size: 14.5px; line-height: 1.45; color: var(--ink); }
.drawer-lead b { font-weight: var(--fw-strong); }
.session-drawer .stat .d .up { color: var(--bad); }
.session-drawer .stat .d .down { color: var(--ok); }
.drawer-fold { border: 1px solid var(--line); border-radius: 8px; background: var(--panel); }
.drawer-fold > summary { padding: 9px 11px; color: var(--mut); font-size: 12px; list-style: none; cursor: pointer; }
.drawer-fold > summary::-webkit-details-marker { display: none; }
.drawer-fold > summary::before { content: '\203A'; display: inline-block; width: 10px; color: var(--mut2); }
.drawer-fold[open] > summary::before { transform: rotate(90deg); }
.drawer-fold > summary:hover { color: var(--ink); }
.drawer-fold-body { display: flex; flex-direction: column; gap: 12px; padding: 2px 11px 11px; }
.drawer-fold-body .stats { grid-template-columns: repeat(2, minmax(0, 1fr)); }
/* Drill affordances inside expanded report rows. */
.spend-proj-drill, .pr-drill { margin-bottom: 8px; }