From c2d514d1e563c2a00525072b4bfd36f1973fbfbc Mon Sep 17 00:00:00 2001 From: Resham Joshi <65915470+iamtoruk@users.noreply.github.com> Date: Tue, 15 Sep 2026 22:53:43 +0200 Subject: [PATCH] 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 --- app/renderer/components/SessionDrawer.tsx | 113 +++++++++++++++++----- app/renderer/lib/format.test.ts | 1 + app/renderer/lib/format.ts | 3 +- app/renderer/sections/Sessions.test.tsx | 99 ++++++++++++++++++- app/renderer/sections/Sessions.tsx | 11 +++ app/renderer/styles/plain.css | 19 ++++ 6 files changed, 218 insertions(+), 28 deletions(-) diff --git a/app/renderer/components/SessionDrawer.tsx b/app/renderer/components/SessionDrawer.tsx index 12714f3d..2422302a 100644 --- a/app/renderer/components/SessionDrawer.tsx +++ b/app/renderer/components/SessionDrawer.tsx @@ -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(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)} · {row.sessionId.slice(0, 18)}
- {formatDayLong(row.startedAt)} → {formatDayLong(row.endedAt)} · {formatDuration(row.durationMs)} + {formatDayLong(row.startedAt)} → {formatDayLong(row.endedAt)} + {row.durationMs > 0 && <> · {formatDuration(row.durationMs)}}
-
- - {contribution !== null && ( - - )} - - - - - - - +

+ {selectedCost === null ? 'This session cost ' : 'Your selection of this session cost '} + {formatUsd(leadCost)} + {ratio === null ? '.' : ratio < 0.1 ? ', a fraction of your usual.' : <>, about {formatRatio(ratio)}x your usual.} +

+ +
+ well below median + : = 1 ? 'up' : 'down'}>{formatRatio(ratio)}x your median} + /> + + {row.durationMs > 0 + ? + : }
{row.isSidechain && row.parentSessionId && ( @@ -102,17 +123,59 @@ export function SessionDrawer({ row, filters, onClose }: { - - {breakdown.days.length > 1 && } - - {breakdown.unattributedPrCost > 0 && ( -

Not tied to a specific PR: {formatUsd(breakdown.unattributedPrCost)}

+ +
+ + Tokens: {formatCompact(row.inputTokens)} in, {formatCompact(row.outputTokens)} out,{' '} + {formatCompact(row.cacheWriteTokens)} written to cache, {cacheHit}% cache hits + +
+
+ + + + +
+
+
+ + {foldLabel !== null && ( +
+ Branches and pull requests: {foldLabel} +
+ + {breakdown.days.length > 1 && } + + {breakdown.unattributedPrCost > 0 && ( +

Not tied to a specific PR: {formatUsd(breakdown.unattributedPrCost)}

+ )} +
+
)} + +

+ {row.savingsUSD > 0 ? `Saved vs baseline: ${formatUsd(row.savingsUSD)}.` : 'Saved vs baseline: none this session.'} +

) } +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): { diff --git a/app/renderer/lib/format.test.ts b/app/renderer/lib/format.test.ts index f2fff1f1..85b76f10 100644 --- a/app/renderer/lib/format.test.ts +++ b/app/renderer/lib/format.test.ts @@ -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('—') }) }) diff --git a/app/renderer/lib/format.ts b/app/renderer/lib/format.ts index a92371a3..664f8dc4 100644 --- a/app/renderer/lib/format.ts +++ b/app/renderer/lib/format.ts @@ -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` } diff --git a/app/renderer/sections/Sessions.test.tsx b/app/renderer/sections/Sessions.test.tsx index c0abf7ca..9a695b23 100644 --- a/app/renderer/sections/Sessions.test.tsx +++ b/app/renderer/sections/Sessions.test.tsx @@ -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() + 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() + 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() + 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() + 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( + , + ) + 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() diff --git a/app/renderer/sections/Sessions.tsx b/app/renderer/sections/Sessions.tsx index 818b001e..9b33fe7d 100644 --- a/app/renderer/sections/Sessions.tsx +++ b/app/renderer/sections/Sessions.tsx @@ -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({ )} diff --git a/app/renderer/styles/plain.css b/app/renderer/styles/plain.css index ae2f5a77..4c89073f 100644 --- a/app/renderer/styles/plain.css +++ b/app/renderer/styles/plain.css @@ -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; }