diff --git a/app/renderer/components/SessionDrawer.tsx b/app/renderer/components/SessionDrawer.tsx index a88756ed..36140e57 100644 --- a/app/renderer/components/SessionDrawer.tsx +++ b/app/renderer/components/SessionDrawer.tsx @@ -2,7 +2,7 @@ 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 { formatCompact, formatCount, formatDayLong, formatDuration, formatUsd, sessionCacheHitPercent, shortenProjectPath } from '../lib/format' import { DUR, useExitAnimation } from '../lib/motion' import { codeburn } from '../lib/ipc' import type { InvestigationFilters } from '../lib/investigation' @@ -99,8 +99,8 @@ export function SessionDrawer({ row, openKey, filters, medianCost, onClose }: { 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 cacheHitPercent = sessionCacheHitPercent(row.inputTokens, row.cacheReadTokens, row.cacheWriteTokens) + const cacheHit = cacheHitPercent === null ? null : Math.round(cacheHitPercent) 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 @@ -149,18 +149,18 @@ export function SessionDetails({ row, filters, medianCost }: { row: SessionDrill
- {t('sessions.drawer.tokensSummary', { + {t(cacheHit === null ? 'sessions.drawer.tokensSummaryNoHit' : 'sessions.drawer.tokensSummary', { inTok: formatCompact(row.inputTokens), outTok: formatCompact(row.outputTokens), cacheTok: formatCompact(row.cacheWriteTokens), - hitPct: cacheHit, + ...(cacheHit === null ? {} : { hitPct: cacheHit }), })}
- +
diff --git a/app/renderer/i18n/catalogs/sessions.ts b/app/renderer/i18n/catalogs/sessions.ts index 7147520c..e2e32f48 100644 --- a/app/renderer/i18n/catalogs/sessions.ts +++ b/app/renderer/i18n/catalogs/sessions.ts @@ -6,6 +6,7 @@ export const sessions: SectionCatalog = { 'sessions.sort.recent': 'Recent', 'sessions.sort.turns': 'Turns', 'sessions.sort.tokens': 'Tokens', + 'sessions.sort.cache': 'Cache hit rate', 'sessions.providerFilter.ariaLabel': 'Filter sessions by provider', 'sessions.providerFilter.all': 'All', 'sessions.skeleton.label': 'Scanning sessions…', @@ -76,6 +77,7 @@ export const sessions: SectionCatalog = { 'sessions.drawer.savedBaselineNone': 'Saved vs baseline: none this session.', 'sessions.drawer.unknownModel': 'Unknown model', 'sessions.drawer.tokensSummary': 'Tokens: {inTok} in, {outTok} out, {cacheTok} written to cache, {hitPct}% cache hits', + 'sessions.drawer.tokensSummaryNoHit': 'Tokens: {inTok} in, {outTok} out, {cacheTok} written to cache', 'sessions.drawer.branchesPrsSummary': 'Branches and pull requests: {label}', 'sessions.drawer.branchesMoreList': '{named}, +{count} more', 'sessions.drawer.prCount.one': '{count} PR', @@ -87,6 +89,7 @@ export const sessions: SectionCatalog = { 'sessions.sort.recent': 'Récent', 'sessions.sort.turns': 'Tours', 'sessions.sort.tokens': 'Tokens', + 'sessions.sort.cache': 'Taux de cache', 'sessions.providerFilter.ariaLabel': 'Filtrer les sessions par fournisseur', 'sessions.providerFilter.all': 'Tous', 'sessions.skeleton.label': 'Analyse des sessions…', @@ -157,6 +160,7 @@ export const sessions: SectionCatalog = { 'sessions.drawer.savedBaselineNone': 'Économisé par rapport à la référence : aucune économie sur cette session.', 'sessions.drawer.unknownModel': 'Modèle inconnu', 'sessions.drawer.tokensSummary': 'Tokens : {inTok} entrants, {outTok} sortants, {cacheTok} écrits en cache, {hitPct} % de succès de cache', + 'sessions.drawer.tokensSummaryNoHit': 'Tokens : {inTok} entrants, {outTok} sortants, {cacheTok} écrits en cache', 'sessions.drawer.branchesPrsSummary': 'Branches et pull requests : {label}', 'sessions.drawer.branchesMoreList': '{named}, +{count} de plus', 'sessions.drawer.prCount.one': '{count} PR', @@ -168,6 +172,7 @@ export const sessions: SectionCatalog = { 'sessions.sort.recent': '最近', 'sessions.sort.turns': 'ターン', 'sessions.sort.tokens': 'トークン', + 'sessions.sort.cache': 'キャッシュヒット率', 'sessions.providerFilter.ariaLabel': 'プロバイダーでセッションを絞り込む', 'sessions.providerFilter.all': 'すべて', 'sessions.skeleton.label': 'セッションを読み込み中…', @@ -238,6 +243,7 @@ export const sessions: SectionCatalog = { 'sessions.drawer.savedBaselineNone': 'ベースライン比の節約額: このセッションではありません。', 'sessions.drawer.unknownModel': '不明なモデル', 'sessions.drawer.tokensSummary': 'トークン: 入力 {inTok}、出力 {outTok}、キャッシュ書き込み {cacheTok}、キャッシュヒット率 {hitPct}%', + 'sessions.drawer.tokensSummaryNoHit': 'トークン: 入力 {inTok}、出力 {outTok}、キャッシュ書き込み {cacheTok}', 'sessions.drawer.branchesPrsSummary': 'ブランチとプルリクエスト: {label}', 'sessions.drawer.branchesMoreList': '{named} 他{count}件', 'sessions.drawer.prCount.one': '{count} 件のPR', @@ -249,6 +255,7 @@ export const sessions: SectionCatalog = { 'sessions.sort.recent': '최근', 'sessions.sort.turns': '턴', 'sessions.sort.tokens': '토큰', + 'sessions.sort.cache': '캐시 적중률', 'sessions.providerFilter.ariaLabel': '제공자별로 세션 필터링', 'sessions.providerFilter.all': '전체', 'sessions.skeleton.label': '세션 스캔 중…', @@ -319,6 +326,7 @@ export const sessions: SectionCatalog = { 'sessions.drawer.savedBaselineNone': '기준선 대비 절감액: 이 세션에서는 없습니다.', 'sessions.drawer.unknownModel': '알 수 없는 모델', 'sessions.drawer.tokensSummary': '토큰: 입력 {inTok}, 출력 {outTok}, 캐시 기록 {cacheTok}, 캐시 적중률 {hitPct}%', + 'sessions.drawer.tokensSummaryNoHit': '토큰: 입력 {inTok}, 출력 {outTok}, 캐시 기록 {cacheTok}', 'sessions.drawer.branchesPrsSummary': '브랜치 및 풀 리퀘스트: {label}', 'sessions.drawer.branchesMoreList': '{named} 외 {count}개', 'sessions.drawer.prCount.one': 'PR {count}개', @@ -330,6 +338,7 @@ export const sessions: SectionCatalog = { 'sessions.sort.recent': '最近', 'sessions.sort.turns': '轮次', 'sessions.sort.tokens': 'Token', + 'sessions.sort.cache': '缓存命中率', 'sessions.providerFilter.ariaLabel': '按提供商筛选会话', 'sessions.providerFilter.all': '全部', 'sessions.skeleton.label': '正在扫描会话…', @@ -400,6 +409,7 @@ export const sessions: SectionCatalog = { 'sessions.drawer.savedBaselineNone': '相比基准节省:本次会话无节省。', 'sessions.drawer.unknownModel': '未知模型', 'sessions.drawer.tokensSummary': 'Token:输入 {inTok},输出 {outTok},写入缓存 {cacheTok},缓存命中率 {hitPct}%', + 'sessions.drawer.tokensSummaryNoHit': 'Token:输入 {inTok},输出 {outTok},写入缓存 {cacheTok}', 'sessions.drawer.branchesPrsSummary': '分支与拉取请求:{label}', 'sessions.drawer.branchesMoreList': '{named},另外 {count} 个', 'sessions.drawer.prCount.one': '{count} 个 PR', @@ -411,6 +421,7 @@ export const sessions: SectionCatalog = { 'sessions.sort.recent': '最近', 'sessions.sort.turns': '輪次', 'sessions.sort.tokens': 'Token', + 'sessions.sort.cache': '快取命中率', 'sessions.providerFilter.ariaLabel': '依供應商篩選工作階段', 'sessions.providerFilter.all': '全部', 'sessions.skeleton.label': '正在掃描工作階段…', @@ -481,6 +492,7 @@ export const sessions: SectionCatalog = { 'sessions.drawer.savedBaselineNone': '相較基準節省:本次工作階段無節省。', 'sessions.drawer.unknownModel': '未知模型', 'sessions.drawer.tokensSummary': 'Token:輸入 {inTok},輸出 {outTok},寫入快取 {cacheTok},快取命中率 {hitPct}%', + 'sessions.drawer.tokensSummaryNoHit': 'Token:輸入 {inTok},輸出 {outTok},寫入快取 {cacheTok}', 'sessions.drawer.branchesPrsSummary': '分支與拉取請求:{label}', 'sessions.drawer.branchesMoreList': '{named},另外 {count} 個', 'sessions.drawer.prCount.one': '{count} 個 PR', diff --git a/app/renderer/lib/format.ts b/app/renderer/lib/format.ts index 322fe9bb..b0b7e117 100644 --- a/app/renderer/lib/format.ts +++ b/app/renderer/lib/format.ts @@ -35,6 +35,10 @@ export function estimatedPortion(current: MenubarPayload['current']): number { return (current.topModels ?? []).reduce((sum, row) => sum + (row.estimatedCostUSD ?? 0), 0) } +export function sessionCacheHitPercent(input: number, reads: number, writes: number): number | null { + return reads + writes === 0 ? null : reads / (input + reads + writes) * 100 +} + /** Raw-USD input formatted against an explicit payload currency. This keeps a * persisted exact snapshot correct on its very first paint, before App's * global active-currency effect has had a chance to run. */ diff --git a/app/renderer/lib/types.ts b/app/renderer/lib/types.ts index 86c01ffc..d2ee775d 100644 --- a/app/renderer/lib/types.ts +++ b/app/renderer/lib/types.ts @@ -716,6 +716,7 @@ export type SessionRow = { outputTokens: number cacheReadTokens: number cacheWriteTokens: number + cacheHitPercent?: number | null startedAt: string endedAt: string durationMs: number diff --git a/app/renderer/sections/Compare.test.tsx b/app/renderer/sections/Compare.test.tsx index edfa6641..4d6b0c69 100644 --- a/app/renderer/sections/Compare.test.tsx +++ b/app/renderer/sections/Compare.test.tsx @@ -142,16 +142,16 @@ describe('Compare', () => { expect(mocks.getCompare).toHaveBeenCalledWith('30days', 'all', 'Sonnet 5', 'Opus 4.8') }) - it('computes cache hit rate over input + cache reads (excludes cache writes)', async () => { + it('computes cache hit rate over input + cache reads + cache writes', async () => { mocks.getCompareModels.mockResolvedValue([modelA, modelB]) mocks.getCompare.mockResolvedValue(report) render() const context = (await screen.findByText('Context')).closest('.cmp-card')! const row = within(context).getByText('Cache hit rate').closest('.cmp-metric')! - // 119.4M / (152.6M + 119.4M) = 44%, not 119.4 / (152.6 + 119.4 + 16) = 41%. - expect(row).toHaveTextContent('44%') - expect(row).not.toHaveTextContent('41%') + // 119.4M / (152.6M + 119.4M + 16M) = 41%, not 119.4 / (152.6 + 119.4) = 44%. + expect(row).toHaveTextContent('41%') + expect(row).not.toHaveTextContent('44%') }) it('notes that custom ranges are unsupported and still compares by period', async () => { diff --git a/app/renderer/sections/Compare.tsx b/app/renderer/sections/Compare.tsx index 28d41475..ce3ff72d 100644 --- a/app/renderer/sections/Compare.tsx +++ b/app/renderer/sections/Compare.tsx @@ -13,7 +13,7 @@ import { type VolumeBand, type VolumeMeasure, } from '../lib/cohortStats' -import { formatCompact, formatCount, formatUsd, shortenProjectPath } from '../lib/format' +import { formatCompact, formatCount, formatUsd, sessionCacheHitPercent, shortenProjectPath } from '../lib/format' import { Usd, tokensOf } from '../components/Usd' import { t } from '../i18n' import { codeburn } from '../lib/ipc' @@ -341,9 +341,8 @@ function CategoryCard({ report }: { report: CompareJsonReport }) { } function cacheHitRate(model: ModelStats): string { - // reads over reads + fresh input (matches menubar-json + compare-stats). - const total = model.inputTokens + model.cacheReadTokens - return total > 0 ? `${Math.round(model.cacheReadTokens / total * 100)}%` : '—' + const percent = sessionCacheHitPercent(model.inputTokens, model.cacheReadTokens, model.cacheWriteTokens) + return percent === null ? '—' : `${Math.round(percent)}%` } function daysOfData(model: ModelStats): string { diff --git a/app/renderer/sections/Sessions.test.tsx b/app/renderer/sections/Sessions.test.tsx index e0c6e4d6..266fa14e 100644 --- a/app/renderer/sections/Sessions.test.tsx +++ b/app/renderer/sections/Sessions.test.tsx @@ -175,6 +175,27 @@ describe('Sessions', () => { expect(container.querySelector('.session-row .session-title')).toHaveTextContent('alpha/worker') }) + it('shows each session cache hit rate, sorts unmeasured sessions last, and hides the drawer hit line for them', async () => { + const user = userEvent.setup() + getSessions.mockResolvedValue([ + session({ sessionId: 'low', project: 'low-cache', provider: 'claude', cost: 3, cacheReadTokens: 40_000, cacheWriteTokens: 4_000, cacheHitPercent: 24.4 }), + session({ sessionId: 'none', project: 'no-cache', provider: 'claude', cost: 2, cacheHitPercent: null }), + session({ sessionId: 'high', project: 'high-cache', provider: 'claude', cost: 1, cacheHitPercent: 91.6 }), + ]) + const { container } = render() + await waitFor(() => expect(container.querySelectorAll('.session-row')).toHaveLength(3)) + const hitCells = () => [...container.querySelectorAll('.session-row')].map(row => row.lastElementChild?.textContent) + + expect(hitCells()).toEqual(['24%', '—', '92%']) + await user.click(screen.getByRole('tab', { name: 'Cache hit rate' })) + expect(hitCells()).toEqual(['92%', '24%', '—']) + + await user.click(screen.getByRole('button', { name: /no\/cache/ })) + const drawer = screen.getByRole('dialog', { name: /session details/i }) + expect(within(drawer).queryByText(/% hit/)).not.toBeInTheDocument() + expect(within(drawer).getByText(/written to cache$/)).toBeInTheDocument() + }) + it('turns provider grouping off and back on', async () => { const user = userEvent.setup() getSessions.mockResolvedValue(rows) diff --git a/app/renderer/sections/Sessions.tsx b/app/renderer/sections/Sessions.tsx index 241647a0..7c8bbc3a 100644 --- a/app/renderer/sections/Sessions.tsx +++ b/app/renderer/sections/Sessions.tsx @@ -30,7 +30,7 @@ import { t } from '../i18n' export const INITIAL_VISIBLE = 120 const STEP = 120 -export type SessionSort = 'cost' | 'recent' | 'turns' | 'tokens' +export type SessionSort = 'cost' | 'recent' | 'turns' | 'tokens' | 'cache' /** Composite identity of a session row: provider + project + sessionId. An id * alone is not globally unique (another provider, or an imported transcript, @@ -67,6 +67,10 @@ function rowTokens(row: SessionRow): number { return row.inputTokens + row.outputTokens } +function rowCacheHit(row: SessionRow): number { + return row.cacheHitPercent ?? -1 +} + /** Under a selection the Cost column (and the sort) mean the row's * CONTRIBUTION to the selection; otherwise the plain row cost. */ function entryCost(entry: IncludedRow, filtered: boolean): number { @@ -77,6 +81,7 @@ function compareEntries(sort: SessionSort, filtered: boolean, a: IncludedRow, b: if (sort === 'cost') return entryCost(b, filtered) - entryCost(a, filtered) if (sort === 'turns') return b.row.turns - a.row.turns if (sort === 'tokens') return rowTokens(b.row) - rowTokens(a.row) + if (sort === 'cache') return rowCacheHit(b.row) - rowCacheHit(a.row) return endedAtTime(b.row) - endedAtTime(a.row) } @@ -84,6 +89,7 @@ function groupSortValue(sort: SessionSort, filtered: boolean, entries: IncludedR if (sort === 'cost') return entries.reduce((sum, entry) => sum + entryCost(entry, filtered), 0) if (sort === 'turns') return entries.reduce((sum, entry) => sum + entry.row.turns, 0) if (sort === 'tokens') return entries.reduce((sum, entry) => sum + rowTokens(entry.row), 0) + if (sort === 'cache') return entries.reduce((best, entry) => Math.max(best, rowCacheHit(entry.row)), -1) return entries.reduce((latest, entry) => Math.max(latest, endedAtTime(entry.row)), 0) } @@ -396,6 +402,7 @@ export function Sessions({ { value: 'recent', label: t('sessions.sort.recent') }, { value: 'turns', label: t('sessions.sort.turns') }, { value: 'tokens', label: t('sessions.sort.tokens') }, + { value: 'cache', label: t('sessions.sort.cache') }, ]} value={sort} onChange={value => setSort(value as SessionSort)} @@ -489,6 +496,7 @@ export function Sessions({ )} {formatCompact(rowTokens(entry.entry.row))} + {entry.entry.row.cacheHitPercent == null ? '—' : `${Math.round(entry.entry.row.cacheHitPercent)}%`} ))} diff --git a/app/renderer/styles/plain.css b/app/renderer/styles/plain.css index 5e1d0d56..c15e8339 100644 --- a/app/renderer/styles/plain.css +++ b/app/renderer/styles/plain.css @@ -1064,9 +1064,9 @@ td:first-child { font-size: var(--fs-body); font-weight: var(--fw-medium); } .sessions-empty { display: flex; align-items: center; gap: var(--sp-3); padding: var(--sp-4); border: 1px solid var(--line); border-radius: 14px; background: var(--panel); } .sessions-clear { padding: 0; border: 0; background: transparent; color: var(--mut); font: inherit; font-size: var(--fs-meta); cursor: pointer; } .sessions-clear:hover, .sessions-clear:focus-visible { color: var(--accent-text); text-decoration: underline; } -.session-list { --session-columns: minmax(160px, 1.6fr) 64px minmax(144px, 1fr) 48px 68px 72px; padding: 0 2px 2px; border: 1px solid var(--line); border-radius: 14px; background: var(--panel); box-shadow: var(--card-shadow); } +.session-list { --session-columns: minmax(160px, 1.6fr) 64px minmax(144px, 1fr) 48px 68px 72px 48px; padding: 0 2px 2px; border: 1px solid var(--line); border-radius: 14px; background: var(--panel); box-shadow: var(--card-shadow); } .session-list-inner { overflow-x: auto; margin-top: 2px; border: 1px solid var(--line); border-radius: 12px; background: var(--card-inner); box-shadow: var(--card-inner-shadow); } -.provider-h, .session-row { display: grid; min-width: 650px; grid-template-columns: var(--session-columns); align-items: center; column-gap: 8px; } +.provider-h, .session-row { display: grid; min-width: 706px; grid-template-columns: var(--session-columns); align-items: center; column-gap: 8px; } .provider-h { position: sticky; top: 0; z-index: 2; padding: var(--sp-2) var(--sp-3) var(--sp-1); background: var(--card-inner); color: var(--mut2); font-size: var(--fs-eyebrow); font-weight: var(--fw-subhead); font-variant-numeric: tabular-nums; letter-spacing: .05em; text-transform: uppercase; } .provider-h > span:not(:first-child) { font-family: var(--mono); letter-spacing: 0; text-align: right; } .provider-h-name { display: inline-flex; min-width: 0; align-items: center; gap: 6px; } diff --git a/src/compare-stats.ts b/src/compare-stats.ts index ff789836..31c3c564 100644 --- a/src/compare-stats.ts +++ b/src/compare-stats.ts @@ -5,6 +5,7 @@ import type { ClassifiedTurn, ProjectSummary } from './types.js' import { behavioralCallWeight, isBehavioralCall } from './behavioral-weight.js' import { modelRowKey } from './models.js' import { callBillableOutputTokens } from './session-output.js' +import { sessionCacheHitPercent } from './sessions-report.js' const PLANNING_TOOLS = new Set(['TaskCreate', 'TaskUpdate', 'TodoWrite', 'EnterPlanMode', 'ExitPlanMode']) @@ -188,12 +189,7 @@ const METRICS: MetricDef[] = [ label: 'Cache hit rate', formatFn: 'percent', higherIsBetter: true, - compute: s => { - // Cache-hit = reads over reads + fresh input (excludes cache writes), to - // match src/menubar-json.ts:cacheHitPercent and the rest of the app. - const total = s.inputTokens + s.cacheReadTokens - return total > 0 ? (s.cacheReadTokens / total) * 100 : null - }, + compute: s => sessionCacheHitPercent(s.inputTokens, s.cacheReadTokens, s.cacheWriteTokens), }, ] diff --git a/src/dashboard.tsx b/src/dashboard.tsx index 932fa3d3..91181b38 100644 --- a/src/dashboard.tsx +++ b/src/dashboard.tsx @@ -29,6 +29,7 @@ import { BSU, patchStdoutForWindows } from './ink-win.js' import { startUserTimingGuard } from './user-timing-guard.js' import { folderNameOriginKey, isTemporaryProjectPath, linkedOriginKey, originRepoName, projectOriginKey, TEMPORARY_PROJECTS } from './git-origin.js' import { countSessions } from './session-output.js' +import { sessionCacheHitPercent } from './sessions-report.js' type View = 'dashboard' | 'optimize' | 'compare' @@ -612,9 +613,7 @@ function Overview({ projects, label, width, planUsages, durable }: { projects: P const totalOutput = durable ? durable.outputTokens : allSessions.reduce((s, sess) => s + sess.totalOutputTokens, 0) const totalCacheRead = durable ? durable.cacheReadTokens : allSessions.reduce((s, sess) => s + sess.totalCacheReadTokens, 0) const totalCacheWrite = durable ? durable.cacheWriteTokens : allSessions.reduce((s, sess) => s + sess.totalCacheWriteTokens, 0) - const allInputTokens = totalInput + totalCacheRead + totalCacheWrite - const cacheHit = allInputTokens > 0 - ? (totalCacheRead / allInputTokens) * 100 : 0 + const cacheHit = sessionCacheHitPercent(totalInput, totalCacheRead, totalCacheWrite) ?? 0 const activePlanUsages = planUsages ?? [] return ( diff --git a/src/main.ts b/src/main.ts index 21f38993..f2c66702 100644 --- a/src/main.ts +++ b/src/main.ts @@ -17,7 +17,7 @@ import { ESTIMATED_COST_LEGEND, excludedGatewayNote, formatTokens, isEstimatedCo import { toDateString } from './daily-cache.js' import { statusSnapshotSemanticKey } from './status-snapshot-semantic.js' import { dateKey } from './day-aggregator.js' -import { foldedSessionRows } from './sessions-report.js' +import { foldedSessionRows, sessionCacheHitPercent } from './sessions-report.js' import { behavioralCallWeight } from './behavioral-weight.js' import { CATEGORY_LABELS, type DateRange, type ProjectSummary, type TaskCategory } from './types.js' import type { AppliedFix } from './act/types.js' @@ -618,10 +618,7 @@ function buildJsonReport(projects: ProjectSummary[], period: string, periodKey: const totalOutput = durable.data.outputTokens const totalCacheRead = durable.data.cacheReadTokens const totalCacheWrite = durable.data.cacheWriteTokens - // Match src/menubar-json.ts:cacheHitPercent: reads over reads+fresh-input. cache_write - // counts tokens being stored, not served, so it doesn't belong in the denominator. - const cacheHitDenom = totalInput + totalCacheRead - const cacheHitPercent = cacheHitDenom > 0 ? Math.round((totalCacheRead / cacheHitDenom) * 1000) / 10 : 0 + const cacheHitPercent = Math.round((sessionCacheHitPercent(totalInput, totalCacheRead, totalCacheWrite) ?? 0) * 10) / 10 // Daily rows come from the same durable day set as the headline so they sum // to it, carried days included. Both JSON call sites always pass durable diff --git a/src/menubar-json.ts b/src/menubar-json.ts index 7b84d5d0..1e375b74 100644 --- a/src/menubar-json.ts +++ b/src/menubar-json.ts @@ -143,7 +143,7 @@ import { getCurrency } from './currency.js' import type { GranularHistory } from './granular-history.js' import { getShortModelName, modelRowKey } from './models.js' import type { ReworkedFile } from './workflow-insights.js' -import type { PrRow, BranchRow } from './sessions-report.js' +import { sessionCacheHitPercent, type PrRow, type BranchRow } from './sessions-report.js' import type { LiveSessionsBlock } from './live-sessions.js' import type { CursorSyncStatus } from './cursor-sync.js' import { buildTelemetrySnapshot, type TelemetrySnapshot, type TelemetrySnapshotInput } from './telemetry-snapshot.js' @@ -566,12 +566,6 @@ function aggregateOneShotRate(categories: PeriodData['categories']): number | nu return oneShots / edits } -function cacheHitPercent(inputTokens: number, cacheReadTokens: number): number { - const denom = inputTokens + cacheReadTokens - if (denom === 0) return 0 - return (cacheReadTokens / denom) * 100 -} - function buildTopActivities(categories: PeriodData['categories']): MenubarPayload['current']['topActivities'] { return categories.slice(0, TOP_ACTIVITIES_LIMIT).map(cat => ({ name: cat.name, @@ -831,7 +825,7 @@ export function buildMenubarPayload( outputTokens: current.outputTokens, cacheReadTokens: current.cacheReadTokens, cacheWriteTokens: current.cacheWriteTokens, - cacheHitPercent: cacheHitPercent(current.inputTokens, current.cacheReadTokens), + cacheHitPercent: sessionCacheHitPercent(current.inputTokens, current.cacheReadTokens, current.cacheWriteTokens) ?? 0, codexCredits: current.codexCredits ?? 0, estimatedCostUSD: current.estimatedCostUSD ?? 0, topActivities: buildTopActivities(current.categories), diff --git a/src/optimize.ts b/src/optimize.ts index dd6daf75..f1ad82a7 100644 --- a/src/optimize.ts +++ b/src/optimize.ts @@ -19,6 +19,7 @@ import { recommendModelDefault, type ModelDefaultRecommendation } from './act/mo import { appliedFixGlyph, formatAppliedFix, type AppliedFix } from './act/types.js' import { isUserStartedSession, userStartedProjects } from './session-population.js' import { countSessions, inferSessionProvider, sessionBillableOutputTokens } from './session-output.js' +import { sessionCacheHitPercent } from './sessions-report.js' import { aggregateFileChurn, buildCoachingNotes, scanUserCorrections, medianTimeToFirstEditMs, worstOneShotCategory, type ReworkedFile } from './workflow-insights.js' // ============================================================================ @@ -3980,14 +3981,11 @@ export function detectLowCacheHitSessions(projects: ProjectSummary[]): WasteFind if (!isOptimizeSession(session)) continue const reads = session.totalCacheReadTokens const writes = session.totalCacheWriteTokens - // Parsers record unreported cache usage as 0, so a session with no cache - // tokens at all is unmeasured, not a 0% hit rate. - if (reads + writes === 0) continue + const hitPercent = sessionCacheHitPercent(session.totalInputTokens, reads, writes) + if (hitPercent === null) continue if (session.apiCalls < LOW_CACHE_HIT_MIN_CALLS) continue const totalInput = session.totalInputTokens + reads + writes if (totalInput < LOW_CACHE_HIT_MIN_INPUT_TOKENS) continue - // Same formula as the dashboard overview: reads over all input incl. writes. - const hitPercent = (reads / totalInput) * 100 if (hitPercent >= LOW_CACHE_HIT_TARGET_PERCENT) continue candidates.push({ project: project.project, diff --git a/src/sessions-report.ts b/src/sessions-report.ts index c03c6b87..1ddaece6 100644 --- a/src/sessions-report.ts +++ b/src/sessions-report.ts @@ -30,6 +30,7 @@ export type SessionRow = { outputTokens: number cacheReadTokens: number cacheWriteTokens: number + cacheHitPercent: number | null startedAt: string endedAt: string durationMs: number @@ -42,6 +43,14 @@ function sessionCostLabel(cost: number): string { return `$${cost.toFixed(2)}` } +export function sessionCacheHitPercent(input: number, reads: number, writes: number): number | null { + return reads + writes === 0 ? null : reads / (input + reads + writes) * 100 +} + +export function cacheHitLabel(percent: number | null): string { + return percent === null ? '\u2014' : `${Math.round(percent)}%` +} + function durationMs(startedAt: string, endedAt: string): number { const duration = new Date(endedAt).getTime() - new Date(startedAt).getTime() return Number.isFinite(duration) ? duration : 0 @@ -62,6 +71,7 @@ export function aggregateSessions(projects: ProjectSummary[]): SessionRow[] { outputTokens: sessionBillableOutputTokens(session), cacheReadTokens: session.totalCacheReadTokens, cacheWriteTokens: session.totalCacheWriteTokens, + cacheHitPercent: sessionCacheHitPercent(session.totalInputTokens, session.totalCacheReadTokens, session.totalCacheWriteTokens), startedAt: session.firstTimestamp, endedAt: session.lastTimestamp, durationMs: durationMs(session.firstTimestamp, session.lastTimestamp), @@ -74,7 +84,7 @@ export function renderJson(rows: SessionRow[]): string { return JSON.stringify(rows, null, 2) } -type SessionColumnKey = 'started' | 'session' | 'children' | 'project' | 'provider' | 'models' | 'cost' | 'saved' | 'calls' | 'turns' +type SessionColumnKey = 'started' | 'session' | 'children' | 'project' | 'provider' | 'models' | 'cost' | 'cache' | 'saved' | 'calls' | 'turns' type SessionColumn = { key: SessionColumnKey header: string @@ -106,7 +116,7 @@ function fitColumns(columns: SessionColumn[], available: number, dropOrder?: Ses const fitted = columns.map(col => ({ ...col })) // Remove low-value columns before squeezing names into unreadable slivers. - for (const key of dropOrder ?? ['turns', 'saved', 'provider', 'calls'] as SessionColumnKey[]) { + for (const key of dropOrder ?? ['turns', 'saved', 'provider', 'calls', 'cache'] as SessionColumnKey[]) { if (frameWidth(fitted) <= available) break const index = fitted.findIndex(col => col.key === key && col.optional) if (index >= 0) fitted.splice(index, 1) @@ -194,6 +204,7 @@ function cellValue(row: SessionRow, key: SessionColumnKey): string { case 'provider': return row.provider case 'models': return sessionModelLabel(row.models) case 'cost': return markEstimated(sessionCostLabel(row.cost), row.isEstimated) + case 'cache': return cacheHitLabel(row.cacheHitPercent) case 'saved': return `$${row.savingsUSD.toFixed(2)}` case 'calls': return row.calls.toLocaleString('en-US') case 'turns': return row.turns.toLocaleString('en-US') @@ -242,6 +253,7 @@ function sessionColumns(hasSavings: boolean, childrenColumn: boolean): SessionCo { key: 'provider', header: 'Provider', width: 9, minWidth: 8, optional: true }, { key: 'models', header: 'Models', width: 22, minWidth: 10, flex: 2 }, { key: 'cost', header: 'Cost', width: 9, minWidth: 7, right: true }, + { key: 'cache', header: 'Cache', width: 6, minWidth: 6, right: true, optional: true }, ...(hasSavings ? [{ key: 'saved' as const, header: 'Saved', width: 9, minWidth: 7, right: true, optional: true }] : []), { key: 'calls', header: 'Calls', width: 7, minWidth: 5, right: true, optional: true }, { key: 'turns', header: 'Turns', width: 7, minWidth: 5, right: true, optional: true }, @@ -321,6 +333,9 @@ function groupWorkUnitRows(rows: T[], resolution: WorkUnit } const cost = sum(member => member.cost) const estimatedCost = sum(member => member.estimatedCost) + const inputTokens = sum(member => member.inputTokens) + const cacheReadTokens = sum(member => member.cacheReadTokens) + const cacheWriteTokens = sum(member => member.cacheWriteTokens) entries.push({ row: { ...root, @@ -331,10 +346,11 @@ function groupWorkUnitRows(rows: T[], resolution: WorkUnit savingsUSD: sum(member => member.savingsUSD), calls: sum(member => member.calls), turns: sum(member => member.turns), - inputTokens: sum(member => member.inputTokens), + inputTokens, outputTokens: sum(member => member.outputTokens), - cacheReadTokens: sum(member => member.cacheReadTokens), - cacheWriteTokens: sum(member => member.cacheWriteTokens), + cacheReadTokens, + cacheWriteTokens, + cacheHitPercent: sessionCacheHitPercent(inputTokens, cacheReadTokens, cacheWriteTokens), startedAt, endedAt, durationMs: durationMs(startedAt, endedAt), @@ -392,7 +408,7 @@ export function renderWorkUnitTable(rows: SessionRow[], resolution: WorkUnitReso const totalCost = entries.reduce((total, entry) => total + entry.display.row.cost, 0) const unitCount = entries.filter(entry => entry.display.childCount > 0).length const footer = `${rows.length.toLocaleString('en-US')} sessions \u2022 ${unitCount.toLocaleString('en-US')} work unit${unitCount === 1 ? '' : 's'} \u2022 $${totalCost.toFixed(2)} total \u2022 newest first${estimatedLegend(displays.map(d => d.row))}` - return renderSessionGrid(sessionColumns(hasSavings, true), displays, workUnitCell, footer, available, ['children', 'turns', 'saved', 'provider', 'calls']) + return renderSessionGrid(sessionColumns(hasSavings, true), displays, workUnitCell, footer, available, ['children', 'turns', 'saved', 'provider', 'calls', 'cache']) } /// `sessions --by-work-unit --format json`: an add-only envelope. `sessions` diff --git a/src/sessions-tui.tsx b/src/sessions-tui.tsx index 0e85e313..fd6802fd 100644 --- a/src/sessions-tui.tsx +++ b/src/sessions-tui.tsx @@ -5,6 +5,7 @@ import { formatTokens, markEstimated } from './format.js' import { patchStdoutForWindows } from './ink-win.js' import { startUserTimingGuard } from './user-timing-guard.js' import { + cacheHitLabel, cleanSessionProjectLabel, sessionDisplayName, sessionModelLabel, @@ -17,7 +18,7 @@ const MUTED = '#71717A' const BORDER = '#3F3F46' type Column = { - key: 'started' | 'session' | 'project' | 'provider' | 'models' | 'cost' | 'calls' | 'turns' + key: 'started' | 'session' | 'project' | 'provider' | 'models' | 'cost' | 'cache' | 'calls' | 'turns' label: string width: number right?: boolean @@ -56,6 +57,7 @@ function columnsFor(width: number): Column[] { { key: 'provider', label: 'PROVIDER', width: 9 }, { key: 'models', label: 'MODELS', width: 24 }, { key: 'cost', label: 'COST', width: 9, right: true }, + { key: 'cache', label: 'CACHE', width: 6, right: true }, { key: 'calls', label: 'CALLS', width: 7, right: true }, { key: 'turns', label: 'TURNS', width: 7, right: true }, ] @@ -106,6 +108,7 @@ function rowValue(row: SessionRow, key: Column['key']): string { case 'provider': return row.provider case 'models': return sessionModelLabel(row.models) case 'cost': return markEstimated(`$${row.cost.toFixed(2)}`, row.isEstimated) + case 'cache': return cacheHitLabel(row.cacheHitPercent) case 'calls': return row.calls.toLocaleString('en-US') case 'turns': return row.turns.toLocaleString('en-US') } diff --git a/tests/cli-emitters.test.ts b/tests/cli-emitters.test.ts index df6a2ad0..ed0a7da7 100644 --- a/tests/cli-emitters.test.ts +++ b/tests/cli-emitters.test.ts @@ -133,7 +133,7 @@ describe('CLI JSON emitters', () => { expect(rows).toHaveLength(2) expect(Object.keys(rows[0]!)).toEqual([ 'sessionId', 'title', 'project', 'provider', 'models', 'cost', 'savingsUSD', 'calls', 'turns', - 'inputTokens', 'outputTokens', 'cacheReadTokens', 'cacheWriteTokens', + 'inputTokens', 'outputTokens', 'cacheReadTokens', 'cacheWriteTokens', 'cacheHitPercent', 'startedAt', 'endedAt', 'durationMs', 'estimatedCost', 'isEstimated', ]) expect(rows.every(row => row.provider === 'claude')).toBe(true) diff --git a/tests/compare-stats.test.ts b/tests/compare-stats.test.ts index 17df188a..33ffb638 100644 --- a/tests/compare-stats.test.ts +++ b/tests/compare-stats.test.ts @@ -230,10 +230,8 @@ describe('computeComparison', () => { const rows = computeComparison(a, b) const cacheRow = rows.find(r => r.label === 'Cache hit rate')! - // Cache writes are excluded from the denominator (reads / reads + fresh - // input), matching src/menubar-json.ts and the desktop app. - const totalA = 5000 + 30000 - const totalB = 10000 + 10000 + const totalA = 5000 + 30000 + 5000 + const totalB = 10000 + 10000 + 5000 expect(cacheRow.valueA).toBeCloseTo(30000 / totalA * 100) expect(cacheRow.valueB).toBeCloseTo(10000 / totalB * 100) expect(cacheRow.winner).toBe('a') diff --git a/tests/sessions-report.test.ts b/tests/sessions-report.test.ts index 5b32e417..5cbd5aa7 100644 --- a/tests/sessions-report.test.ts +++ b/tests/sessions-report.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' -import { aggregateByBranch, aggregateSessions, attributeSessionPrSpend, renderJson, renderTable } from '../src/sessions-report.js' +import { aggregateByBranch, aggregateSessions, attributeSessionPrSpend, renderJson, renderTable, sessionCacheHitPercent } from '../src/sessions-report.js' import type { ClassifiedTurn, ParsedApiCall, ProjectSummary, SessionSummary } from '../src/types.js' function makeProject(): ProjectSummary { @@ -90,6 +90,7 @@ describe('sessions JSON emitter', () => { outputTokens: 20, cacheReadTokens: 400, cacheWriteTokens: 30, + cacheHitPercent: 400 / 530 * 100, startedAt: '2026-07-10T10:00:00.000Z', endedAt: '2026-07-10T10:05:00.000Z', durationMs: 300_000, @@ -128,6 +129,22 @@ describe('sessions JSON emitter', () => { expect(output).toContain('1 sessions') }) + it('shows each session cache hit rate, and a dash when cache use is unmeasured', () => { + const rows = aggregateSessions([makeProject()]) + const unmeasured = { ...rows[0]!, sessionId: 'no-cache', cacheReadTokens: 0, cacheWriteTokens: 0, cacheHitPercent: null } + const lines = renderTable([rows[0]!, unmeasured], { terminalWidth: 140 }).split('\n') + + expect(lines[1]).toMatch(/│ +Cache │/) + expect(lines.find(line => line.includes('session-1'))).toMatch(/│ +75% │/) + expect(lines.find(line => line.includes('no-cache'))).toMatch(/│ +— │/) + }) + + it('computes the cache hit rate as reads over the whole prompt', () => { + expect(sessionCacheHitPercent(100, 400, 30)).toBeCloseTo(75.47, 2) + expect(sessionCacheHitPercent(100, 300, 0)).toBe(75) + expect(sessionCacheHitPercent(500, 0, 0)).toBeNull() + }) + it('hides home-directory slugs and renders compact agent/worktree names', () => { const rows = aggregateSessions([makeProject()]) rows[0]!.sessionId = 'agent-a72cc958e305e4957' diff --git a/tests/telemetry-snapshot.test.ts b/tests/telemetry-snapshot.test.ts index 3d120bc2..82873479 100644 --- a/tests/telemetry-snapshot.test.ts +++ b/tests/telemetry-snapshot.test.ts @@ -307,7 +307,7 @@ describe('buildTelemetrySnapshot', () => { it('reports cache hit and retry tax as shares, not dollars', () => { const snapshot = buildTelemetrySnapshot(richPayload()) - expect(snapshot.efficiency.cacheHitRate).toBe(0.75) + expect(snapshot.efficiency.cacheHitRate).toBe(0.71) expect(snapshot.efficiency.retryTaxShare).toBe(0.1) })