import { Fragment, useEffect, useMemo, useState } from 'react' import { ChartTip } from '../components/ChartTip' import { cliErrorDisplay } from '../components/CliErrorPanel' import { Panel } from '../components/Panel' import { SessionDetails } from '../components/SessionDrawer' import { SectionSkeleton } from '../components/Skeleton' import { Usd } from '../components/Usd' import { Icon } from '../components/icons' import { t } from '../i18n' import { formatAxisMoney, niceTicks } from '../lib/chartAxis' import { formatCompact, formatDayLong, formatUsd, formatUsdDifference, shortenProjectPath } from '../lib/format' import type { InvestigationFilters } from '../lib/investigation' import { codeburn, normalizeCliError } from '../lib/ipc' import type { CliError, SessionDrillRow, SessionWhy, WhyFinding, WhyParts, WhyPrWork, WhyStep, WhyTokens, WhyTurn } from '../lib/types' /** Claude Code main sessions are `.jsonl`; `--why` resolves only those. */ const CLAUDE_SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i export function hasSessionView(row: SessionDrillRow): boolean { return row.provider === 'claude' && !row.isSidechain && CLAUDE_SESSION_ID.test(row.sessionId) } const FINDINGS_SHOWN = 5 const STEPS_SHOWN = 12 const pct = (p: number) => (p > 0 && p < 0.01 ? '<1%' : `${Math.round(p * 100)}%`) const tok = (n: number) => formatCompact(Math.round(n)) const usdFine = (n: number) => (n > 0 && n < 0.01 ? `<${formatUsd(0.01)}` : formatUsd(n)) const plural = (key: string, count: number, vars: Record = {}) => t(`${key}.${count === 1 ? 'one' : 'other'}`, { count, ...vars }) const one = (key: string, count: number) => `${key}.${count === 1 ? 'one' : 'other'}` export function formatStepDuration(ms: number): string { if (ms < 1000) return `${Math.max(0, Math.round(ms))}ms` const s = ms / 1000 if (s < 10) return `${s.toFixed(1)}s` if (s < 60) return `${Math.round(s)}s` const m = Math.floor(s / 60) if (m < 60) return `${m}m ${String(Math.round(s % 60)).padStart(2, '0')}s` return `${Math.floor(m / 60)}h ${m % 60}m` } const clock = (iso: string) => new Date(iso).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) function describeHelpers(descs: string[]): string { const m = descs.map(d => /^(.*?)(\d+)$/.exec(d)) if (descs.length > 1 && m.every(x => x && x[1] === m[0]![1])) { const nums = m.map(x => Number(x![2])).sort((a, b) => a - b) if (nums.every((n, i) => i === 0 || n === nums[i - 1]! + 1)) return `'${m[0]![1]}${nums[0]}–${nums.at(-1)}'` } const uniq = [...new Set(descs)] return uniq.slice(0, 2).map(d => `'${d}'`).join(', ') + (uniq.length > 2 ? ` +${uniq.length - 2}` : '') } const PART_KEYS = ['output', 'cacheRead', 'cacheWrite', 'input', 'webSearch'] as const function partsLine(p: WhyParts, tk: WhyTokens, calls: number): string { const tokensOf = { output: tk.output, cacheRead: tk.cacheRead, cacheWrite: tk.cacheWrite, input: tk.input, webSearch: 0 } const text = PART_KEYS .filter(k => p[k] >= 0.005) .sort((a, b) => p[b] - p[a]) .map(k => t(k === 'cacheRead' ? one('sessions.why.part.cacheRead', calls) : `sessions.why.part.${k}`, { amount: formatUsd(p[k]), tokens: tok(tokensOf[k]), calls })) .join(t('sessions.why.part.sep')) return text ? text.charAt(0).toUpperCase() + text.slice(1) + t('sessions.why.part.end') : '' } type Line = { text: string; save?: boolean } type FindingCopy = { title: string; lines: Line[]; chip: string } function altLine(f: { alt: { model: string; cost: number } | null; usd: number | null }, what: 'helpers' | 'prompt' | 'steps'): Line[] { if (!f.alt) return [] return [{ text: t(`sessions.why.alt.${what}`, { model: f.alt.model, amount: formatUsd(f.alt.cost), saved: formatUsdDifference(f.usd ?? 0, f.alt.cost) }), save: true }] } function findingCopy(f: WhyFinding, why: SessionWhy): FindingCopy { const chip = t(`sessions.why.kind.${f.kind}`) const amount = formatUsd(f.usd ?? 0) switch (f.kind) { case 'helpers': { const head = f.direct > 0 ? plural('sessions.why.f.helpers.title', f.direct, { turn: f.turn ?? 0, models: f.models.join('/'), desc: f.descriptions.length ? ` (${describeHelpers(f.descriptions)})` : '' }) : plural('sessions.why.f.helpers.looseOnly', f.loose, { turn: f.turn ?? 0 }) const more = (f.nested ? t('sessions.why.f.helpers.nested', { count: f.nested }) : '') + (f.direct > 0 && f.loose ? t('sessions.why.f.helpers.loose', { count: f.loose }) : '') const range = f.minCalls === f.maxCalls ? String(f.minCalls) : `${f.minCalls}–${f.maxCalls}` return { chip, title: head + more + t('sessions.why.f.helpers.total', { amount }), lines: [ { text: partsLine(f.parts, f.tokens, f.calls) }, { text: t(one('sessions.why.f.helpers.calls', range === '1' ? 1 : 2), { range, tokens: tok(f.tokens.cacheRead / Math.max(1, f.calls)) }) }, ...altLine(f, 'helpers'), ], } } case 'hotspot': { const mult = f.median > 0 ? (f.usd ?? 0) / f.median : 0 const vars = { turn: f.turn ?? 0, calls: f.calls, models: f.models.join('/'), amount } return { chip, title: mult >= 2 ? t(one('sessions.why.f.hotspot.title', f.calls), { ...vars, mult: Math.round(mult), median: formatUsd(f.median) }) : t(one('sessions.why.f.hotspot.titleShare', f.calls), { ...vars, share: pct(f.share ?? 0) }), lines: [ { text: partsLine(f.parts, f.tokens, f.calls) }, ...(f.toolCalls ? [{ text: t(one('sessions.why.f.hotspot.tools', f.calls), { tools: f.toolCalls, calls: f.calls }) }] : []), ...altLine(f, 'prompt'), ], } } case 'coordination': { const turn = why.turns[(f.turn ?? 1) - 1] return { chip, title: t('sessions.why.f.coordination.title', { turn: f.turn ?? 0, tools: f.toolCalls, calls: f.calls, model: f.model, amount }), lines: [...(turn ? [{ text: partsLine(f.parts, turn.tokens, turn.calls) }] : []), ...altLine(f, 'steps')], } } case 'reread': return { chip, title: t('sessions.why.f.reread.title', { amount, share: pct(f.share ?? 0) }), lines: [{ text: t('sessions.why.f.reread.line', { calls: f.calls, tokens: tok(f.avgTokens) }) }, { text: t('sessions.why.f.reread.lever') }], } case 'failed': { if (f.userStopped) return { chip, title: t('sessions.why.f.failed.stopped', { tool: f.tool }), lines: [] } const what = (f.description || f.label).slice(0, 80) const title = f.tool === 'Bash' ? f.error.exitCode !== null ? t('sessions.why.f.failed.commandExit', { what, code: f.error.exitCode }) : t('sessions.why.f.failed.command', { what }) : t('sessions.why.f.failed.tool', { tool: f.label ? `${f.tool} (${f.label})` : f.tool }) return { chip, title, lines: [ { text: f.error.cause ? t('sessions.why.f.failed.ended', { cause: f.error.cause + (f.error.location ? ` (${f.error.location})` : '') }) : t('sessions.why.f.failed.noCause') }, ...(f.error.secondary.length ? [{ text: t('sessions.why.f.failed.also', { lines: f.error.secondary.slice(-2).join('; ') }) }] : []), ...(f.afterCalls !== null ? [{ text: plural('sessions.why.f.failed.after', f.afterCalls, { amount }) }] : []), ], } } case 'carry': return { chip, title: f.source === 'paste' ? t(one('sessions.why.f.carry.paste', f.calls), { chars: f.chars.toLocaleString(), tokens: tok(f.tokens), calls: f.calls }) : t(one('sessions.why.f.carry.tool', f.calls), { tool: f.tool, chars: f.chars.toLocaleString(), tokens: tok(f.tokens), calls: f.calls }), lines: [ { text: (f.label ? `“${f.label}”. ` : '') + t(one('sessions.why.f.carry.line', f.calls - 1), { write: formatUsd(f.writeUsd), later: f.calls - 1, read: formatUsd(f.readUsd), amount }) }, { text: t('sessions.why.f.carry.lever') }, ], } case 'prefix': return { chip, title: t('sessions.why.f.prefix.title', { tokens: tok(f.tokens) }), lines: [ { text: t(one('sessions.why.f.prefix.line', f.laterCalls), { uncached: tok(f.uncached), write: formatUsd(f.writeUsd), readCalls: f.readCalls, laterCalls: f.laterCalls, tokens: tok(f.cached), read: formatUsd(f.readUsd) }) }, { text: t('sessions.why.f.prefix.lever') }, ], } case 'idle': return { chip, title: t(f.endedBy === 'helper' ? 'sessions.why.f.idle.titleHelpers' : 'sessions.why.f.idle.title', { turn: f.turn ?? 0, duration: formatStepDuration(f.timeMs) }), lines: [{ text: t(`sessions.why.f.idle.${f.endedBy}`) }] } case 'slowCall': return { chip, title: t('sessions.why.f.slowCall.title', { turn: f.turn ?? 0, model: f.model, duration: formatStepDuration(f.timeMs) }), lines: [{ text: t('sessions.why.f.slowCall.line', { tokens: tok(f.outputTokens) }) }] } } } function verdict(why: SessionWhy): string { const top = why.findings.find(f => (f.usd ?? 0) > 0) const failed = why.findings.filter(f => f.kind === 'failed' && !f.userStopped).length const tail = failed ? ' ' + plural('sessions.why.verdict.failed', failed) : '' if (!top) return t('sessions.why.verdict.none') + tail const vars = { turn: top.turn ?? 0, amount: formatUsd(top.usd ?? 0), share: pct(top.share ?? 0) } if (top.kind === 'helpers' || top.kind === 'hotspot' || top.kind === 'reread') return t(`sessions.why.verdict.${top.kind}`, vars) + tail return t('sessions.why.verdict.other', { title: findingCopy(top, why).title }) + tail } const severity = (f: WhyFinding) => (f.kind === 'failed' && !f.userStopped ? 'bad' : f.kind === 'idle' || f.kind === 'slowCall' || f.kind === 'failed' ? 'info' : 'warn') const isEstimate = (f: WhyFinding) => f.kind === 'carry' || f.kind === 'prefix' function FindingFigure({ f }: { f: WhyFinding }) { if (f.usd === null) { return (
{'timeMs' in f ? formatStepDuration(f.timeMs) : '—'} {t('sessions.why.share.timeOnly')}
) } return (
{isEstimate(f) ? '≈' : ''}{formatUsd(f.usd)} {f.share !== null && {t(f.kind === 'helpers' ? 'sessions.why.share.withHelpers' : 'sessions.why.share.session', { share: pct(f.share) })}}
) } function FindingRow({ f, why, lead, onJump }: { f: WhyFinding; why: SessionWhy; lead: boolean; onJump: (turn: number, step?: number) => void }) { const copy = findingCopy(f, why) return (