diff --git a/src/ui/sidebar-lines.ts b/src/ui/sidebar-lines.ts index 9d06741..f6c434e 100644 --- a/src/ui/sidebar-lines.ts +++ b/src/ui/sidebar-lines.ts @@ -1,6 +1,11 @@ import { PERCENT, THOUSAND } from '../constants/units.ts'; import type { KeepaliveSnapshot } from '../models/keepalive.ts'; -import { formatCompactTokens, formatRemaining } from '../utils/format.ts'; +import { + formatCompactTokens, + formatMultiple, + formatRemaining, + formatUsd, +} from '../utils/format.ts'; type Tone = 'base' | 'muted' | 'success' | 'warning' | 'error'; interface SidebarLine { @@ -43,7 +48,7 @@ function cachedLine(cache: NonNullable): Sidebar } /** The keepalive rows of a warm cache: why pings stopped, or the next ping and the pings used so far. */ -function keepaliveLines( +function keepaliveRows( snapshot: KeepaliveSnapshot, now: number, formatClock: (ms: number) => string @@ -71,6 +76,43 @@ function keepaliveLines( return pingLines(snapshot, now, formatClock); } +/** The keepalive rows of a warm cache followed by the savings rows. */ +function keepaliveLines( + snapshot: KeepaliveSnapshot, + now: number, + formatClock: (ms: number) => string +): SidebarLine[] { + return [...keepaliveRows(snapshot, now, formatClock), ...savingsLines(snapshot)]; +} + +/** The session's `saved` and `return` rows; empty when hidden, not loaded, or before the first ping. */ +function savingsLines(snapshot: KeepaliveSnapshot): SidebarLine[] { + const { savings } = snapshot; + if (!snapshot.showSavings || savings === null || savings.pings === 0) return []; + if (savings.rescues === 0) return [{ right: 'nothing yet', text: 'saved', tone: 'base' }]; + const rewrites = `${savings.rescues} ${savings.rescues === 1 ? 'rewrite' : 'rewrites'}`; + const saved = + savings.priced && savings.netUsd !== null + ? `${formatUsd(savings.netUsd)} · ${rewrites}` + : `${rewrites} · ${formatCompactTokens(savings.avoidedTokens)}`; + const lines: SidebarLine[] = [{ right: saved, text: 'saved', tone: 'base' }]; + if (savings.returnRatio !== null) { + lines.push({ + right: `${formatMultiple(savings.returnRatio)} ping cost`, + text: 'return', + tone: 'base', + }); + } + return lines; +} + +/** The ` ($0.05)` cost of the current stretch's pings; empty when hidden or unpriced. */ +function stretchCost(snapshot: KeepaliveSnapshot): string { + const { savings } = snapshot; + if (!snapshot.showSavings || savings === null || !savings.priced) return ''; + return savings.stretchUsd === null ? '' : ` (${formatUsd(savings.stretchUsd)})`; +} + function pingLines( snapshot: KeepaliveSnapshot, now: number, @@ -88,7 +130,7 @@ function pingLines( } const outcome = snapshot.lastPing === null ? '' : PING_OUTCOMES[snapshot.lastPing]; const pings: SidebarLine = { - right: `${snapshot.pingsUsed}/${snapshot.maxPings}${outcome}`, + right: `${snapshot.pingsUsed}/${snapshot.maxPings}${outcome}${stretchCost(snapshot)}`, text: 'pings', tone: 'base', }; @@ -137,6 +179,7 @@ function sidebarLines( ...cached, { right: `${formatRemaining(now - snapshot.expiresAt)} ago`, text: 'expired', tone: 'base' }, ttl, + ...savingsLines(snapshot), ]; } return [ diff --git a/src/utils/format.ts b/src/utils/format.ts index 5ec12bf..b626720 100644 --- a/src/utils/format.ts +++ b/src/utils/format.ts @@ -9,6 +9,15 @@ import { /** Below this many tokens `formatCompactTokens` keeps one decimal of thousands. */ const COMPACT_DECIMAL_LIMIT = 100_000; +/** Smallest amount `formatUsd` shows as a number. */ +const MIN_USD = 0.01; + +/** Below this ratio `formatMultiple` keeps one decimal. */ +const MULTIPLE_DECIMAL_LIMIT = 10; + +/** Smallest ratio `formatMultiple` shows as a number. */ +const MIN_MULTIPLE = 0.05; + /** "52m", "3m", "45s"; "1h 05m" at 60 minutes and above. */ function formatRemaining(ms: number): string { const totalSeconds = Math.max(0, Math.floor(ms / MS_PER_SECOND)); @@ -37,9 +46,30 @@ function formatCompactTokens(tokens: number): string { return `${trim(tokens / MILLION)}M`; } +/** "$0.42", "<$0.01" for a non-zero amount below a cent, "-$0.02" when negative. */ +function formatUsd(amount: number): string { + const sign = amount < 0 ? '-' : ''; + const magnitude = Math.abs(amount); + if (magnitude > 0 && magnitude < MIN_USD) return `${sign}<$${MIN_USD.toFixed(2)}`; + return `${sign}$${magnitude.toFixed(2)}`; +} + +/** "9×", "9.4×" below 10, "13×" from 10, "<0.1×" for a positive ratio that would round to 0. */ +function formatMultiple(ratio: number): string { + if (ratio > 0 && ratio < MIN_MULTIPLE) return '<0.1×'; + return `${ratio < MULTIPLE_DECIMAL_LIMIT ? trim(ratio) : Math.round(ratio)}×`; +} + function errorMessage(error: unknown): string { if (error instanceof Error) return error.message; return String(error); } -export { formatRemaining, formatTokens, formatCompactTokens, errorMessage }; +export { + formatRemaining, + formatTokens, + formatCompactTokens, + formatUsd, + formatMultiple, + errorMessage, +}; diff --git a/tests/ui/sidebar-lines.test.ts b/tests/ui/sidebar-lines.test.ts index 03250da..c15bc48 100644 --- a/tests/ui/sidebar-lines.test.ts +++ b/tests/ui/sidebar-lines.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test } from 'bun:test'; import type { KeepaliveSnapshot } from '../../src/models/keepalive.ts'; +import type { SavingsReadout } from '../../src/models/savings.ts'; import { sidebarLines, type SidebarLine } from '../../src/ui/sidebar-lines.ts'; const NOW = 1_000_000_000; @@ -277,3 +278,106 @@ describe('sidebarLines: implicit sessions', () => { expect(lines(snap({ ...implicit, skipReason: 'child' }))).toEqual([]); }); }); + +describe('sidebarLines: savings rows', () => { + const readout = (overrides: Partial = {}): SavingsReadout => ({ + priced: true, + pings: 2, + rescues: 2, + avoidedTokens: 282_000, + netUsd: 0.42, + returnRatio: 9, + stretchUsd: 0.05, + ...overrides, + }); + const warm = ( + savings: SavingsReadout | null, + overrides: Partial = {} + ): SidebarLine[] => + lines(snap({ pingsUsed: 2, lastPing: 'hit', nextPingAt: NOW + MIN, savings, ...overrides })); + const rows = (ls: SidebarLine[]): string[] => + ls + .filter((l) => ['pings', 'saved', 'return'].includes(l.text)) + .map((l) => `${l.text} ${l.right}`); + + test('priced: suffix on pings, then saved and return', () => { + expect(rows(warm(readout()))).toEqual([ + 'pings 2/5 ✓ hit ($0.05)', + 'saved $0.42 · 2 rewrites', + 'return 9× ping cost', + ]); + expect(warm(readout()).at(-3)?.rightTone).toBe('success'); + }); + + test('unpriced: no suffix, tokens instead of dollars', () => { + const r = readout({ priced: false, netUsd: null, stretchUsd: null }); + expect(rows(warm(r))).toEqual([ + 'pings 2/5 ✓ hit', + 'saved 2 rewrites · 282k', + 'return 9× ping cost', + ]); + }); + + test('priced without a stretch cost has no suffix', () => { + expect(rows(warm(readout({ stretchUsd: null })))[0]).toBe('pings 2/5 ✓ hit'); + }); + + test('singular rewrite', () => { + expect(rows(warm(readout({ rescues: 1 })))[1]).toBe('saved $0.42 · 1 rewrite'); + }); + + test('a negative net below a cent', () => { + expect(rows(warm(readout({ netUsd: -0.004, returnRatio: 0.5 })))[1]).toBe( + 'saved -<$0.01 · 2 rewrites' + ); + }); + + test('no return row without a ratio', () => { + expect(rows(warm(readout({ returnRatio: null })))).toHaveLength(2); + }); + + test('pings paid but nothing saved', () => { + expect(rows(warm(readout({ rescues: 0, returnRatio: null, netUsd: -0.05 })))).toEqual([ + 'pings 2/5 ✓ hit ($0.05)', + 'saved nothing yet', + ]); + }); + + test('no rows before the first ping', () => { + expect( + rows(warm(readout({ pings: 0, rescues: 0, returnRatio: null, stretchUsd: null }))) + ).toEqual(['pings 2/5 ✓ hit']); + }); + + test('hidden when savings are off', () => { + const off = warm(readout(), { showSavings: false }); + expect(rows(off)).toEqual(['pings 2/5 ✓ hit']); + expect(off).toEqual(warm(null)); + }); + + test('also on the pings-used-up layout', () => { + const ls = warm(readout(), { nextPingAt: null, skipReason: 'exhausted', pingsUsed: 5 }); + expect(rows(ls).slice(1)).toEqual(['saved $0.42 · 2 rewrites', 'return 9× ping cost']); + }); + + test('after the ttl row on the expired layout', () => { + const ls = lines(snap({ expiresAt: NOW - MIN, savings: readout() })); + expect(ls.map((l) => l.text).slice(-3)).toEqual(['ttl', 'saved', 'return']); + }); + + test('never on the implicit layout', () => { + expect(rows(lines(snap({ skipReason: 'implicit', savings: readout() })))).toEqual([]); + }); + + test.each([ + ['missed', 'stopped · last ping missed'], + ['busy', 'waiting · session busy'], + ['disabled', 'off · disabled'], + ['small-context', 'off · 30k < 50k'], + ] as const)('%s keepalive row is followed by the savings rows', (skipReason, right) => { + const ls = warm(readout(), { skipReason, contextTokens: 30_000 }); + expect(ls.find((l) => l.text === 'keepalive')?.right).toBe(right); + expect(rows(ls)).toEqual(['saved $0.42 · 2 rewrites', 'return 9× ping cost']); + expect(ls.at(-3)?.text).toBe('keepalive'); + }); +}); diff --git a/tests/utils/format.test.ts b/tests/utils/format.test.ts index 6edaf36..19d5e12 100644 --- a/tests/utils/format.test.ts +++ b/tests/utils/format.test.ts @@ -1,6 +1,11 @@ import { describe, expect, test } from 'bun:test'; -import { formatCompactTokens, formatRemaining } from '../../src/utils/format.ts'; +import { + formatCompactTokens, + formatMultiple, + formatRemaining, + formatUsd, +} from '../../src/utils/format.ts'; const MIN = 60_000; @@ -45,3 +50,33 @@ describe('formatCompactTokens', () => { expect(formatCompactTokens(2_000_000)).toBe('2M'); }); }); + +describe('formatUsd', () => { + test('two decimals, with a floor for sub-cent amounts', () => { + expect(formatUsd(0.42)).toBe('$0.42'); + expect(formatUsd(12.5)).toBe('$12.50'); + expect(formatUsd(0)).toBe('$0.00'); + expect(formatUsd(0.004)).toBe('<$0.01'); + }); + + test('negative amounts keep the sign', () => { + expect(formatUsd(-0.02)).toBe('-$0.02'); + expect(formatUsd(-0.004)).toBe('-<$0.01'); + }); +}); + +describe('formatMultiple', () => { + test('one decimal below 10, none from 10', () => { + expect(formatMultiple(9.04)).toBe('9×'); + expect(formatMultiple(9.44)).toBe('9.4×'); + expect(formatMultiple(12.6)).toBe('13×'); + expect(formatMultiple(0.8)).toBe('0.8×'); + }); + + test('a tiny positive ratio is <0.1×, never 0×', () => { + expect(formatMultiple(0.04)).toBe('<0.1×'); + expect(formatMultiple(0.0001)).toBe('<0.1×'); + expect(formatMultiple(0.05)).toBe('0.1×'); + expect(formatMultiple(0)).toBe('0×'); + }); +});