From ebdbd838dd8a44ba7d9a281f19a45f62d447b88e Mon Sep 17 00:00:00 2001 From: GaganSD Date: Thu, 12 Nov 2026 08:39:42 +0530 Subject: [PATCH 01/15] feat(slate): add speed card and cache section to the sidebar Rebuild the top of the session rail around status, a single context bar, a speed hero card (exact end-to-end tok/s per response, live estimate while streaming, zero-based braille graph) and a prompt-cache section (hit %, read/write/new split, estimated savings, warm/cold countdown when the provider publishes a cache lifetime). Facts come from one cached pass over the active branch; the rail adapts to terminal height. --- pi-slate/CHANGELOG.md | 11 + pi-slate/extensions/pi-slate/index.ts | 32 +- pi-slate/extensions/pi-slate/perf-graphics.ts | 281 ++++++++++++++++++ pi-slate/extensions/pi-slate/perf-stats.ts | 215 ++++++++++++++ pi-slate/extensions/pi-slate/sidebar-data.ts | 4 + .../extensions/pi-slate/sidebar-layout.ts | 14 +- pi-slate/extensions/pi-slate/sidebar.ts | 98 ++++-- pi-slate/tests/perf-fixture.ts | 14 + pi-slate/tests/perf-graphics.test.ts | 232 +++++++++++++++ pi-slate/tests/perf-stats.test.ts | 143 +++++++++ pi-slate/tests/quiet-workbench.test.ts | 25 +- pi-slate/tests/sidebar-preview.test.ts | 142 +++++---- pi-slate/tests/surfaces-install.test.ts | 6 +- 13 files changed, 1104 insertions(+), 113 deletions(-) create mode 100644 pi-slate/extensions/pi-slate/perf-graphics.ts create mode 100644 pi-slate/extensions/pi-slate/perf-stats.ts create mode 100644 pi-slate/tests/perf-fixture.ts create mode 100644 pi-slate/tests/perf-graphics.test.ts create mode 100644 pi-slate/tests/perf-stats.test.ts diff --git a/pi-slate/CHANGELOG.md b/pi-slate/CHANGELOG.md index 658bb93..e1f114e 100644 --- a/pi-slate/CHANGELOG.md +++ b/pi-slate/CHANGELOG.md @@ -2,6 +2,17 @@ ## Unreleased +### Added + +- Sidebar SPEED card: a large tok/s figure, a graph of recent responses, turn average, output and peak. A finished response's speed is exact (output tokens ÷ response time); the live value while streaming is marked `~`. +- Sidebar CACHE section: hit % of the latest request, read/write/new split, spend and estimated savings. A warm/cold countdown appears only when the model publishes its cache lifetime. +- The status row shows Working/Idle, the turn number, and the running turn's elapsed time. + +### Changed + +- The sidebar header is reorganised into status, CONTEXT, SPEED and CACHE, and adapts to terminal height (full, compact, mini). CONTEXT is a single bar; use pi-context-view for the category breakdown. +- Live speed updates to the sidebar are throttled to about 4 per second. + ## 0.2.1 Fallback improvements for newer updates, Remove redundant notification in new sessions, misc. UI improvements around 'model', 'thinking', & 'warning' variables. diff --git a/pi-slate/extensions/pi-slate/index.ts b/pi-slate/extensions/pi-slate/index.ts index 49b856b..bf2ab0e 100644 --- a/pi-slate/extensions/pi-slate/index.ts +++ b/pi-slate/extensions/pi-slate/index.ts @@ -37,6 +37,7 @@ import { mcpDetails } from "./sidebar-mcp.ts"; import { SlateDiagnostics } from "./diagnostics.ts"; import { TurnCompletion } from "./turn-completion.ts"; import { resolveContextTokens } from "./context-usage.ts"; +import { branchPerf } from "./perf-stats.ts"; import { estimateAssistantTokens, TokenRateTracker } from "./token-rate.ts"; import { createWordPicker } from "./working-words.ts"; import { advanceWave, isProgressStyle, isWaveActive, PROGRESS_STYLES, setProgressStyle, setWaveActive, type ProgressStyle } from "./working-wave.ts"; @@ -229,7 +230,10 @@ export default function piSlate(pi: ExtensionAPI): void { let lastTurnMs: number | null = null; let dashboardClock: ReturnType | undefined; const dashboardSubscriptions: Array<() => void> = []; - let branchFacts: { leaf?: string | null; counts: ReturnType; usage: ReturnType } | undefined; + let branchFacts: { leaf?: string | null; counts: ReturnType; usage: ReturnType; perf: ReturnType } | undefined; + let liveStreaming = false; + let lastLiveSync = 0; + let liveSyncTimer: ReturnType | undefined; let inspectingSidebar = false; let sidebarYielded = false; let sessionEpoch = 0; @@ -329,8 +333,10 @@ export default function piSlate(pi: ExtensionAPI): void { const leaf = ctx.sessionManager.getLeafId?.(); if (!branchFacts || leaf === undefined || leaf !== branchFacts.leaf) { const entries = ctx.sessionManager.getBranch(); - branchFacts = { leaf, counts: sidebarMessageCounts(entries), usage: sidebarUsage(entries) }; + branchFacts = { leaf, counts: sidebarMessageCounts(entries), usage: sidebarUsage(entries), + perf: branchPerf(entries, { promptCache: ctx.model?.promptCache, retentionLong: process.env.PI_CACHE_RETENTION === "long" }) }; } + const liveRate = tokenRate.rate(); const mcpCount = resources.mcp.filter(server => server.enabled === true).length; if (owns("sidebar") && !sidebarYielded) { sidebar.setSession({ @@ -338,8 +344,9 @@ export default function piSlate(pi: ExtensionAPI): void { name: ctx.sessionManager.getSessionName?.(), pid: process.pid, cwd: ctx.cwd, model: modelStatusLabel(ctx.model, config.modelDisplay), thinking: ctx.thinkingLevel ?? "—", tokens, percent, contextWindow, estimated, - rate: tokenRate.rate() > 0 ? tokenRate.rate() : null, startedAt: sessionStartedAt, lastTurnMs, + rate: tokenRate.rate() > 0 ? tokenRate.rate() : null, startedAt: sessionStartedAt, lastTurnMs, turnStartedAt: turnStartedAt ?? null, working: typeof ctx.isIdle === "function" && !ctx.isIdle(), ...branchFacts.counts, usage: branchFacts.usage, + perf: { ...branchFacts.perf, live: { streaming: liveStreaming, rate: liveStreaming && liveRate > 0 ? liveRate : null } }, }); } contextEdge = { @@ -429,14 +436,21 @@ export default function piSlate(pi: ExtensionAPI): void { }, () => {}); } if (owns("editor")) branch.start(ctx.cwd); - sessionStartedAt = Date.now(); turnStartedAt = undefined; lastTurnMs = null; branchFacts = undefined; + sessionStartedAt = Date.now(); turnStartedAt = undefined; lastTurnMs = null; branchFacts = undefined; liveStreaming = false; if (owns("editor") || owns("sidebar")) { skills.reset([]); skills.restore(ctx.sessionManager.getBranch(), ctx.cwd); refreshResources(ctx); tokenRate.setOnChange(() => { - const ctx = liveContext(); - if (ctx) syncSidebar(ctx); + // Per-token updates reach the sidebar at most ~4/s; a trailing sync keeps the last one. + const flush = (): void => { + liveSyncTimer = undefined; lastLiveSync = Date.now(); + const live = liveContext(); + if (live) syncSidebar(live); + }; + const wait = 250 - (Date.now() - lastLiveSync); + if (wait <= 0) { if (liveSyncTimer) clearTimeout(liveSyncTimer); flush(); } + else if (!liveSyncTimer) liveSyncTimer = setTimeout(flush, wait); if (thinkingFold.elapsedMs() !== null) syncThinkingStatus(); }); syncSidebar(ctx); @@ -699,6 +713,7 @@ export default function piSlate(pi: ExtensionAPI): void { }); pi.on("model_select", (_event, ctx) => { currentContext = ctx; + branchFacts = undefined; // cache lifetime depends on the selected model syncSidebar(ctx); }); pi.on("thinking_level_select", (_event, ctx) => { @@ -710,6 +725,7 @@ export default function piSlate(pi: ExtensionAPI): void { currentContext = ctx; if (event.message.role === "assistant") { thinkingFold.stop(); + liveStreaming = true; if (ctx.mode === "tui" && (owns("editor") || owns("sidebar"))) tokenRate.startMessage(); } }); @@ -727,6 +743,7 @@ export default function piSlate(pi: ExtensionAPI): void { currentContext = ctx; if (event.message.role === "assistant") { thinkingFold.stop(); + liveStreaming = false; if (ctx.mode === "tui" && (owns("editor") || owns("sidebar"))) tokenRate.endMessage(); } else if (owns("sidebar") && ctx.mode === "tui" && event.message.role === "toolResult") { skills.observeNested(event.message.nestedCalls?.calls ?? [], ctx.cwd); @@ -773,7 +790,7 @@ export default function piSlate(pi: ExtensionAPI): void { currentContext = ctx; thinkingFold.stop(); if (owns("sidebar") && ctx.mode === "tui") { - branchFacts = undefined; skills.restore(ctx.sessionManager.getBranch(), ctx.cwd); + branchFacts = undefined; liveStreaming = false; skills.restore(ctx.sessionManager.getBranch(), ctx.cwd); background.reset(ctx.sessionManager.getSessionId?.() ?? ""); sidebar.setTasks([]); pi.events.emit?.(BACKGROUND_TASKS_REQUEST, { version: 1, sessionId: ctx.sessionManager.getSessionId?.() ?? "" }); refreshResources(ctx); syncSidebar(ctx); @@ -782,6 +799,7 @@ export default function piSlate(pi: ExtensionAPI): void { }); pi.on("session_shutdown", (_event, ctx) => { sessionEpoch += 1; + liveStreaming = false; if (liveSyncTimer) { clearTimeout(liveSyncTimer); liveSyncTimer = undefined; } workingWord = undefined; stopWave(); thinkingFold.stop(); diff --git a/pi-slate/extensions/pi-slate/perf-graphics.ts b/pi-slate/extensions/pi-slate/perf-graphics.ts new file mode 100644 index 0000000..375d2b6 --- /dev/null +++ b/pi-slate/extensions/pi-slate/perf-graphics.ts @@ -0,0 +1,281 @@ +/** + * Pure drawing + row composition for the SPEED and CACHE sections of the session rail. + * No state, no timers: every function maps (data, width, now) to bounded strings, so cost is + * O(width) plus the already-bounded `rates` window. + */ +import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui"; +import { formatCompactTokenCount } from "./layout.ts"; +import { sidebarCost, type SidebarTier } from "./sidebar-layout.ts"; +import { cacheWarmth, type SidebarPerf } from "./perf-stats.ts"; + +export type Tone = "text" | "muted" | "dim" | "accent" | "success" | "warning" | "error" | "mdHeading"; +export type PerfPaint = { + paint(tone: Tone, text: string): string; + heading(text: string): string; +}; + +const finite = (n: number | null | undefined): n is number => typeof n === "number" && Number.isFinite(n); +const nonneg = (n: number | null | undefined): n is number => finite(n) && n >= 0; + +/** tok/s: <100 one decimal, <1000 integer, then compact (1.2k, 12.3k, 123k, 1.2M). */ +export function formatRate(n: number | null | undefined): string { + if (!nonneg(n)) return "—"; + const tenth = Math.round(n * 10) / 10; + if (tenth < 100) return tenth.toFixed(1); + const whole = Math.round(n); + if (whole < 1000) return `${whole}`; + if (whole < 999_500) { + const k = whole / 1000; + return `${k >= 100 ? Math.round(k) : (Math.round(k * 10) / 10).toFixed(1)}k`; + } + if (whole < 1e15) { + const unit = whole >= 1e12 ? 1e12 : whole >= 1e9 ? 1e9 : 1e6; + const suffix = unit === 1e12 ? "T" : unit === 1e9 ? "B" : "M"; + const v = whole / unit; + return `${v >= 100 ? Math.round(v) : (Math.round(v * 10) / 10).toFixed(1)}${suffix}`; + } + return whole.toExponential(1); +} + +/** m:ss, or h:mm:ss from one hour. Unknown/negative clamps to 0:00. */ +export function formatCountdown(ms: number): string { + const total = finite(ms) ? Math.max(0, Math.floor(ms / 1000)) : 0; + const s = total % 60; + if (total < 3600) return `${Math.floor(total / 60)}:${String(s).padStart(2, "0")}`; + return `${Math.floor(total / 3600)}:${String(Math.floor(total % 3600 / 60)).padStart(2, "0")}:${String(s).padStart(2, "0")}`; +} + +// 3-row block digits; every glyph row of a glyph has the same width. +const FONT: Record = { + "0": ["█▀█", "█ █", "▀▀▀"], "1": ["▀█ ", " █ ", "▀▀▀"], "2": ["▀▀█", "█▀▀", "▀▀▀"], "3": ["▀▀█", " ▀█", "▀▀▀"], + "4": ["█ █", "▀▀█", " ▀"], "5": ["█▀▀", "▀▀█", "▀▀▀"], "6": ["█▀▀", "█▀█", "▀▀▀"], "7": ["▀▀█", " █", " ▀"], + "8": ["█▀█", "█▀█", "▀▀▀"], "9": ["█▀█", "▀▀█", "▀▀▀"], ".": [" ", " ", "▀"], + "k": ["█ ▄", "██ ", "█ ▀"], "~": [" ", "▄▀▄", " "], " ": [" ", " ", " "], +}; + +/** Three rows of block-drawn text; unknown characters render as blank. Glyphs joined by one space. */ +export function bigDigits(text: string): string[] { + const glyphs = [...text].map(ch => FONT[ch] ?? FONT[" "]!); + return [0, 1, 2].map(r => glyphs.map(g => g[r]!).join(" ")); +} +export function bigDigitsWidth(text: string): number { + return visibleWidth(bigDigits(text)[0]!); +} + +const DOT = [[0x01, 0x08], [0x02, 0x10], [0x04, 0x20], [0x40, 0x80]] as const; + +/** + * Zero-based braille bar graph, `rows` cells tall and `width` cells wide (2 columns per cell). + * Right-aligned: the newest value is the right-most column. Columns without data show baseline dots. + * A positive value always draws at least the bottom dot. + */ +export function brailleBars(values: readonly number[], width: number, rows: number): string[] { + const w = Math.max(0, Math.floor(width)); + const r = Math.max(0, Math.floor(rows)); + if (r === 0) return []; + if (w === 0) return Array.from({ length: r }, () => ""); + const columns = w * 2; + const shown = values.slice(-columns); + const offset = columns - shown.length; + const clean = shown.map(v => nonneg(v) ? v : 0); + const max = clean.reduce((a, b) => Math.max(a, b), 0); + const total = r * 4; + const heights = Array.from({ length: columns }, (_, c) => { + const v = c < offset ? 0 : clean[c - offset]!; + return v > 0 && max > 0 ? Math.max(1, Math.min(total, Math.round(v / max * total))) : 0; + }); + const lines: string[] = []; + for (let row = 0; row < r; row++) { + let s = ""; + for (let cell = 0; cell < w; cell++) { + let code = 0; + for (let k = 0; k < 2; k++) for (let d = 0; d < 4; d++) { + const level = (r - row) * 4 - d; + const h = heights[cell * 2 + k]!; + if (level <= h || (level === 1 && h === 0)) code |= DOT[d]![k]!; + } + s += code === 0 ? " " : String.fromCharCode(0x2800 + code); + } + lines.push(s); + } + return lines; +} + +const BLOCKS = "▁▂▃▄▅▆▇█"; +/** One-row zero-based sparkline of the newest `width` values, right-aligned; gaps show the baseline. */ +export function sparkBlocks(values: readonly number[], width: number): string { + const w = Math.max(0, Math.floor(width)); + if (w === 0) return ""; + const shown = values.slice(-w).map(v => nonneg(v) ? v : 0); + const max = shown.reduce((a, b) => Math.max(a, b), 0); + const body = shown.map(v => v > 0 && max > 0 ? BLOCKS[Math.max(0, Math.min(7, Math.round(v / max * 7)))]! : BLOCKS[0]!).join(""); + return BLOCKS[0]!.repeat(w - shown.length) + body; +} + +/** + * Split `width` cells among `parts` by largest remainder: counts sum exactly to `width` (when any part is + * positive) and every positive part gets at least one cell when the width allows. + */ +export function stackedBar(parts: readonly number[], width: number): number[] { + const w = Math.max(0, Math.floor(width)); + const p = parts.map(v => nonneg(v) ? v : 0); + const sum = p.reduce((a, b) => a + b, 0); + const out = p.map(() => 0); + if (w === 0 || sum <= 0) return out; + const exact = p.map(v => v / sum * w); + exact.forEach((v, i) => { out[i] = Math.floor(v); }); + let left = w - out.reduce((a, b) => a + b, 0); + const order = exact.map((v, i) => ({ i, frac: v - Math.floor(v) })).sort((a, b) => b.frac - a.frac || a.i - b.i); + for (let k = 0; left > 0; k = (k + 1) % order.length) { out[order[k]!.i]! += 1; left -= 1; } + const positive = p.map((v, i) => v > 0 ? i : -1).filter(i => i >= 0); + if (w >= positive.length) for (const i of positive) { + if (out[i]! > 0) continue; + let donor = -1; + for (let j = 0; j < out.length; j++) if (out[j]! > 1 && (donor < 0 || out[j]! > out[donor]!)) donor = j; + if (donor >= 0) { out[donor]! -= 1; out[i] = 1; } + } + return out; +} + +export function formatIdle(ms: number): string { + const s = Math.max(0, Math.floor(ms / 1000)); + if (s < 60) return `${s}s`; + if (s < 3600) return `${Math.floor(s / 60)}m`; + return `${Math.floor(s / 3600)}h`; +} + +// ---- row composition ------------------------------------------------------------------------- + +export type PerfInput = { perf: SidebarPerf; cost: number | null; now: number; inner: number; tier: SidebarTier } & PerfPaint; + +/** Left text wins: headings never get squeezed out by a long right-hand status. */ +function pairLine(left: string, right: string, width: number): string { + if (width <= 0) return ""; + const l = truncateToWidth(left, width, "…"); + const r = truncateToWidth(right, Math.max(0, width - visibleWidth(l) - 1), "…"); + return `${l}${" ".repeat(Math.max(0, width - visibleWidth(l) - visibleWidth(r)))}${r}`; +} +const fit = (lines: string[], count: number, width: number): string[] => { + const out = lines.slice(0, count).map(l => truncateToWidth(l, width, "…")); + while (out.length < count) out.push(""); + return out; +}; + +type Headline = { value: number; estimate: boolean } | null; +function headlineOf(perf: SidebarPerf): Headline { + if (perf.live.streaming && nonneg(perf.live.rate)) return { value: perf.live.rate, estimate: true }; + if (nonneg(perf.lastRate)) return { value: perf.lastRate, estimate: false }; + return null; +} +export const hasSpeed = (perf: SidebarPerf): boolean => headlineOf(perf) !== null || perf.rates.length > 0 || nonneg(perf.turn?.rate) || nonneg(perf.peak); +const headlineText = (h: Headline): string => h ? `${h.estimate ? "~" : ""}${formatRate(h.value)}` : "—"; + +/** Graph tone is steady; only the headline and streaming marker change while live. */ +export function speedRows(i: PerfInput, count: number): string[] { + const { perf, inner, paint, heading } = i; + const h = headlineOf(perf); + const streaming = perf.live.streaming; + const label = heading("SPEED"); + if (!hasSpeed(perf)) { + return fit(i.tier === "full" ? [label, paint("dim", perf.requests > 0 ? "no eligible response yet" : "waiting for first response")] + : [label + " " + paint("dim", "waiting for first response")], count, inner); + } + const turnRate = perf.turn?.rate ?? null; + const out = perf.turn && nonneg(perf.turn.output) && perf.turn.output > 0 ? formatCompactTokenCount(perf.turn.output) : "—"; + if (i.tier === "compact") { + const head = label + " " + paint("text", `${streaming && h?.estimate ? "● " : ""}${headlineText(h)} tok/s`); + const room = inner - visibleWidth(head) - 1; + const line = room >= 6 ? `${head} ${paint("accent", sparkBlocks(perf.rates, Math.min(room, 20)))}` : head; + return fit([line, paint("muted", statsLine(turnRate, perf.peak, out, inner))], count, inner); + } + const right = streaming && h?.estimate ? paint("warning", "● streaming") : h ? paint("dim", "last response") : ""; + const rows: string[] = [pairLine(label, right, inner)]; + const digits = `${h?.estimate ? "~" : ""}${formatRate(h?.value)}`; + const unit = " tok/s"; + if (h && bigDigitsWidth(digits) <= inner) { + const [a, b, c] = bigDigits(digits) as [string, string, string]; + const withUnit = bigDigitsWidth(digits) + 1 + unit.length <= inner; + rows.push(paint("text", a), paint("text", b) + (withUnit ? " " + paint("dim", unit.trim()) : ""), paint("text", c)); + } else { + rows.push(paint("text", `${digits}`) + paint("dim", unit)); + } + if (inner >= 22) { + for (const g of brailleBars(perf.rates, inner, 2)) rows.push(paint("accent", g)); + const colW = Math.floor(inner / 3); + const cell = (t: string, w: number): string => { const x = truncateToWidth(t, w, "…"); return x + " ".repeat(Math.max(0, w - visibleWidth(x))); }; + const cols = (cells: string[]): string => cells.map((t, k) => k < 2 ? cell(t, colW) : truncateToWidth(t, inner - colW * 2, "…")).join(""); + rows.push(cols(["Turn avg", "Output", "Peak"].map(t => paint("dim", t)))); + rows.push(cols([formatRate(turnRate), out, formatRate(perf.peak)].map(t => paint("text", t)))); + } else { + rows.push(paint("muted", statsLine(turnRate, perf.peak, out, inner))); + } + return fit(rows, count, inner); +} + +function statsLine(avg: number | null, peak: number | null, out: string, inner: number): string { + const long = `avg ${formatRate(avg)} · peak ${formatRate(peak)} · out ${out}`; + return visibleWidth(long) <= inner ? long : `${formatRate(avg)} · ${formatRate(peak)} · ${out}`; +} + +const pct = (n: number): string => `${Math.round(Math.max(0, Math.min(1, n)) * 100)}%`; + +/** Longest variant that still leaves the CACHE label room; degrades hit label, then countdown. */ +function cacheRight(i: PerfInput): string { + const { perf, paint } = i; + const c = perf.cache; + const sep = paint("dim", " · "); + const hit = nonneg(c.lastHit) ? pct(c.lastHit) : null; + const w = cacheWarmth(c, i.now); + const warm = w.state === "warm" ? { tone: "success" as const, long: `◉ warm ${formatCountdown(w.remainingMs ?? 0)}`, short: `◉ ${formatCountdown(w.remainingMs ?? 0)}` } + : w.state === "cold" ? { tone: "warning" as const, long: "◌ cold", short: "◌ cold" } + : w.idleMs !== null && w.idleMs >= 60_000 ? { tone: "dim" as const, long: `idle ${formatIdle(w.idleMs)}`, short: `idle ${formatIdle(w.idleMs)}` } + : null; + const make = (hitText: string | null, warmText: string | null): string => [hitText && paint("text", hitText), warmText && warm && paint(warm.tone, warmText)].filter(Boolean).join(sep); + const variants = [make(hit && `${hit} hit`, warm?.long ?? null), make(hit, warm?.short ?? null), make(hit && `${hit} hit`, null), make(hit, null)]; + const room = i.inner - visibleWidth("CACHE") - 1; + return variants.find(v => visibleWidth(v) <= room) ?? variants[variants.length - 1]!; +} + +function tokenSummary(c: SidebarPerf["cache"], inner: number): string { + const f = formatCompactTokenCount; + const long = `read ${f(c.read)} · write ${f(c.write)} · new ${f(c.uncached)}`; + return visibleWidth(long) <= inner ? long : `r ${f(c.read)} · w ${f(c.write)} · n ${f(c.uncached)}`; +} + +export function cacheRows(i: PerfInput, count: number): string[] { + const { perf, inner, paint, heading } = i; + const c = perf.cache; + const label = heading("CACHE"); + if (!c.seen && perf.requests === 0) return fit([label, paint("dim", "no requests yet")], count, inner); + if (!c.seen) return fit([label, paint("dim", "no cache reads reported")], count, inner); + const head = pairLine(label, cacheRight(i), inner); + const spent = `spent ${sidebarCost(i.cost)}`; + const saved = nonneg(c.saved) ? ` · saved ~${sidebarCost(c.saved)}` : ""; + if (i.tier === "compact") { + const candidates = [`${tokenSummary(c, inner)} · ${sidebarCost(i.cost)}`, tokenSummary(c, inner), spent + saved, spent]; + const detail = candidates.find(t => visibleWidth(t) <= inner) ?? candidates[candidates.length - 1]!; + return fit([head, paint("muted", detail)], count, inner); + } + const parts = [c.read, c.write, c.uncached]; + const total = parts.reduce((a, b) => a + (nonneg(b) ? b : 0), 0); + const bar = total > 0 ? (() => { + const [r, w, u] = stackedBar(parts.map(p => p ?? 0), inner) as [number, number, number]; + return paint("success", "█".repeat(r)) + paint("warning", "▓".repeat(w)) + paint("dim", "░".repeat(u)); + })() : paint("dim", "—"); + return fit([head, bar, paint("muted", tokenSummary(c, inner)), paint("muted", spent) + (saved ? paint("muted", saved) : "")], count, inner); +} + +/** One row for short terminals: speed, hit rate, and cache countdown. */ +export function combinedRow(i: PerfInput): string { + const { perf, paint, inner } = i; + if (perf.requests === 0 && !perf.cache.seen) return truncateToWidth(paint("dim", "no requests yet"), inner, "…"); + const h = headlineOf(perf); + const parts = [paint("text", `↯${headlineText(h)} t/s`)]; + const c = perf.cache; + if (c.seen && nonneg(c.lastHit)) { + const w = cacheWarmth(c, i.now); + const text = `${w.state === "warm" ? "◉" : "◌"}${pct(c.lastHit)}${w.state === "warm" ? ` ${formatCountdown(w.remainingMs ?? 0)}` : w.state === "cold" ? " cold" : ""}`; + parts.push(paint(w.state === "warm" ? "success" : w.state === "cold" ? "warning" : "dim", text)); + } + return truncateToWidth(parts.join(" "), inner, "…"); +} diff --git a/pi-slate/extensions/pi-slate/perf-stats.ts b/pi-slate/extensions/pi-slate/perf-stats.ts new file mode 100644 index 0000000..9af9857 --- /dev/null +++ b/pi-slate/extensions/pi-slate/perf-stats.ts @@ -0,0 +1,215 @@ +import type { SessionEntry } from "@earendil-works/pi-coding-agent"; + +/** + * Speed and prompt-cache facts for the session rail. + * + * Accuracy contract (the rail is for glancing, so every number must be honest): + * - "Exact" values come only from finished assistant messages on the active branch: + * `usage.output`, `usage.cacheRead/cacheWrite/input`, `timestamp` (request start) and + * `durationMs` (request start → response end, monotonic). + * - A request's speed is end-to-end: output tokens ÷ (durationMs / 1000). It includes + * time to first token and hidden reasoning, both of which are real waiting time. + * - The live streaming rate is an estimate (visible chars ÷ 4) and must be labelled `~`. + * - Anything unknowable is `null`, never 0. The renderer shows `—` or omits the item. + */ + +/** Requests below either bound are latency-dominated; they count toward totals and the + * turn average but never toward the graph, the peak, or "last response". */ +export const PERF_MIN_OUTPUT_TOKENS = 32; +export const PERF_MIN_DURATION_MS = 300; +/** Bounded history so very long sessions cost constant memory in the rail. */ +export const PERF_MAX_RATES = 256; + +export type SidebarTurnPerf = { + /** Assistant requests since the last user message on the branch (the current or last turn). */ + requests: number; + /** Exact output tokens of those requests. */ + output: number; + /** Sum of their durationMs. */ + durationMs: number; + /** Token-weighted exact rate: output ÷ (durationMs / 1000); null when durationMs is 0. */ + rate: number | null; +}; + +export type SidebarCachePerf = { + /** Branch totals in tokens (same scope as SidebarUsage); null when any contributing usage is missing. */ + read: number | null; + write: number | null; + uncached: number | null; + /** cacheRead ÷ (input + cacheRead + cacheWrite) of the latest assistant request (0..1). */ + lastHit: number | null; + /** read ÷ (read + write + uncached) over the branch (0..1). */ + sessionHit: number | null; + /** Counterfactual dollars saved by cache reads; always an estimate. null when prices are unknown. */ + saved: number | null; + /** Wall-clock ms when the latest request ended (timestamp + durationMs); drives warm/cold. */ + lastActivityAt: number | null; + /** Cache lifetime that applies to the latest request; null when the provider's lifetime is unknown. */ + ttlMs: number | null; + /** True once any request on the branch read or wrote cache. */ + seen: boolean; +}; + +export type SidebarPerf = { + /** Timed assistant requests on the branch (eligible or not). */ + requests: number; + /** Exact end-to-end rates of eligible requests, oldest → newest, at most PERF_MAX_RATES. */ + rates: number[]; + /** Max of all eligible rates on the branch (not only the retained window). */ + peak: number | null; + /** Exact rate of the newest eligible request. */ + lastRate: number | null; + turn: SidebarTurnPerf | null; + cache: SidebarCachePerf; + /** Live estimate while an assistant message streams; rate is null when not streaming or no sample yet. */ + live: { streaming: boolean; rate: number | null }; +}; + +export const EMPTY_PERF: SidebarPerf = { + requests: 0, rates: [], peak: null, lastRate: null, turn: null, + cache: { read: null, write: null, uncached: null, lastHit: null, sessionHit: null, saved: null, lastActivityAt: null, ttlMs: null, seen: false }, + live: { streaming: false, rate: null }, +}; + +// --------------------------------------------------------------------------- +// Computation +// --------------------------------------------------------------------------- + +export type PerfPromptCache = { short?: number; long?: number } | undefined; +export type BranchPerfOptions = { promptCache?: PerfPromptCache; retentionLong: boolean }; + +function num(value: unknown): number | null { + return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null; +} +function obj(value: unknown): Record | null { + return typeof value === "object" && value !== null && !Array.isArray(value) ? value as Record : null; +} +function ratio(numerator: number, denominator: number): number | null { + if (!(denominator > 0)) return null; + const value = numerator / denominator; + return Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : null; +} + +/** + * One O(n) pass over the active branch. + * + * Turn rule: every timed assistant request after the last user message whose stopReason is not + * error/aborted/deferred counts, regardless of size, because tiny tool-call requests are real + * waiting time in the turn. Speed rows (rates/peak/lastRate) additionally require the minimums. + */ +export function branchPerf(entries: readonly SessionEntry[], opts: BranchPerfOptions): SidebarPerf { + let requests = 0; + let rates: number[] = []; + let peak: number | null = null; + let lastRate: number | null = null; + let turnRequests = 0; let turnOutput = 0; let turnMs = 0; + + const sums = { read: 0, write: 0, uncached: 0 }; + const missing = { read: false, write: false, uncached: false }; + let seen = false; + let saved = 0; let pricedAny = false; + let lastUsage: Record | null = null; + let lastActivityAt: number | null = null; + const ids = new Set(); + + for (const entry of entries) { + if (ids.has(entry.id)) continue; + ids.add(entry.id); + let usage: Record | null; + let expected: boolean; + let assistant: Record | null = null; + if (entry.type === "message") { + const message = obj(entry.message); + const role = message?.role; + if (role === "user") { turnRequests = 0; turnOutput = 0; turnMs = 0; continue; } + if (role === "assistant" || role === "toolResult") { + usage = obj(message?.usage); + expected = role === "assistant"; + if (role === "assistant") assistant = message; + } else continue; + } else if (entry.type === "compaction" || entry.type === "branch_summary" || entry.type === "usage") { + usage = obj((entry as { usage?: unknown }).usage); + expected = true; + } else continue; + + if (!usage) { + if (expected) { missing.read = true; missing.write = true; missing.uncached = true; } + continue; + } + const read = num(usage.cacheRead); const write = num(usage.cacheWrite); const input = num(usage.input); + if (read === null) missing.read = true; else { sums.read += read; if (read > 0) seen = true; } + if (write === null) missing.write = true; else { sums.write += write; if (write > 0) seen = true; } + if (input === null) missing.uncached = true; else sums.uncached += input; + + if (!assistant) continue; + lastUsage = usage; + const cost = obj(usage.cost); + + if (read !== null && read > 0 && input !== null && input > 0) { + const inputPrice = (num(cost?.input) ?? NaN) / input; + const readPrice = (num(cost?.cacheRead) ?? NaN) / read; + if (Number.isFinite(inputPrice) && inputPrice > 0 && Number.isFinite(readPrice)) { + const term = read * (inputPrice - readPrice); + if (Number.isFinite(term)) { saved += Math.max(0, term); pricedAny = true; } + } + } + + const timestamp = assistant.timestamp; + const durationMs = assistant.durationMs; + if (typeof timestamp !== "number" || !Number.isFinite(timestamp) + || typeof durationMs !== "number" || !Number.isFinite(durationMs) || durationMs <= 0) continue; + requests += 1; + lastActivityAt = timestamp + durationMs; + const stop = assistant.stopReason; + if (stop === "error" || stop === "aborted" || stop === "deferred") continue; + const output = num(usage.output); + if (output === null) continue; + turnRequests += 1; turnOutput += output; turnMs += durationMs; + if (output >= PERF_MIN_OUTPUT_TOKENS && durationMs >= PERF_MIN_DURATION_MS) { + const rate = output / (durationMs / 1000); + if (!Number.isFinite(rate)) continue; + rates.push(rate); + if (rates.length >= PERF_MAX_RATES * 2) rates = rates.slice(-PERF_MAX_RATES); + if (peak === null || rate > peak) peak = rate; + lastRate = rate; + } + } + if (rates.length > PERF_MAX_RATES) rates = rates.slice(-PERF_MAX_RATES); + + let lastHit: number | null = null; + let ttlMs: number | null = null; + if (lastUsage) { + const input = num(lastUsage.input); const read = num(lastUsage.cacheRead); const write = num(lastUsage.cacheWrite); + if (input !== null && read !== null && write !== null) lastHit = ratio(read, input + read + write); + const long = num(lastUsage.cacheWrite1h) !== null && (num(lastUsage.cacheWrite1h) as number) > 0; + const seconds = long || opts.retentionLong ? opts.promptCache?.long : opts.promptCache?.short; + if (typeof seconds === "number" && Number.isFinite(seconds) && seconds > 0) ttlMs = seconds * 1000; + } + const read = missing.read ? null : sums.read; + const write = missing.write ? null : sums.write; + const uncached = missing.uncached ? null : sums.uncached; + const sessionHit = read === null || write === null || uncached === null ? null : ratio(read, read + write + uncached); + + return { + requests, rates, peak, lastRate, + turn: turnRequests > 0 + ? { requests: turnRequests, output: turnOutput, durationMs: turnMs, rate: turnMs > 0 ? turnOutput / (turnMs / 1000) : null } + : null, + cache: { + read, write, uncached, lastHit, sessionHit, + saved: pricedAny && Number.isFinite(saved) ? saved : null, + lastActivityAt, ttlMs, seen, + }, + live: { streaming: false, rate: null }, + }; +} + +export type CacheWarmth = { state: "warm" | "cold" | "unknown"; remainingMs: number | null; idleMs: number | null }; + +/** Warm/cold from the provider's cache lifetime; negative gaps (clock skew) clamp to 0. */ +export function cacheWarmth(cache: SidebarCachePerf, now: number): CacheWarmth { + const idleMs = cache.lastActivityAt === null || !Number.isFinite(now) ? null : Math.max(0, now - cache.lastActivityAt); + if (cache.ttlMs === null || idleMs === null) return { state: "unknown", remainingMs: null, idleMs }; + const remainingMs = Math.max(0, cache.ttlMs - idleMs); + return { state: remainingMs > 0 ? "warm" : "cold", remainingMs, idleMs }; +} diff --git a/pi-slate/extensions/pi-slate/sidebar-data.ts b/pi-slate/extensions/pi-slate/sidebar-data.ts index 884e78f..c143056 100644 --- a/pi-slate/extensions/pi-slate/sidebar-data.ts +++ b/pi-slate/extensions/pi-slate/sidebar-data.ts @@ -2,6 +2,7 @@ import { homedir } from "node:os"; import { basename, dirname, resolve } from "node:path"; import type { SessionEntry, SlashCommandInfo, Skill } from "@earendil-works/pi-coding-agent"; import { fileURLToPath } from "node:url"; +import type { SidebarPerf } from "./perf-stats.ts"; import type { SidebarMcpResult } from "./sidebar-mcp.ts"; import { record, sidebarText } from "./sidebar-text.ts"; export { record, sidebarText } from "./sidebar-text.ts"; @@ -19,7 +20,10 @@ export type SidebarSession = { id: string; name?: string; pid: number; cwd: string; model: string; thinking: string; tokens: number | null; percent: number | null; contextWindow: number | null; estimated: boolean; rate: number | null; startedAt: number; lastTurnMs: number | null; + /** Wall-clock start of the running turn; absent or null when idle. */ + turnStartedAt?: number | null; working: boolean; turns: number; messages: number; usage: SidebarUsage; + perf: SidebarPerf; }; export type SidebarFolds = { mcp: boolean; skills: boolean; prompts: boolean }; export const DEFAULT_SIDEBAR_FOLDS: SidebarFolds = { mcp: false, skills: false, prompts: false }; diff --git a/pi-slate/extensions/pi-slate/sidebar-layout.ts b/pi-slate/extensions/pi-slate/sidebar-layout.ts index 13d322b..e8440ef 100644 --- a/pi-slate/extensions/pi-slate/sidebar-layout.ts +++ b/pi-slate/extensions/pi-slate/sidebar-layout.ts @@ -1,10 +1,22 @@ export type SidebarSlots = { header: number; middle: number; tasks: number; image: number; footer: number }; +/** How much of the session rail's top half fits; chosen from terminal rows alone. */ +export type SidebarTier = "full" | "compact" | "mini" | "micro"; +export const SIDEBAR_FULL_ROWS = 44; +export const SIDEBAR_COMPACT_ROWS = 30; +export const SIDEBAR_MINI_ROWS = 20; +export function sidebarTier(rows: number): SidebarTier { + const r = Math.floor(rows); + return r >= SIDEBAR_FULL_ROWS ? "full" : r >= SIDEBAR_COMPACT_ROWS ? "compact" : r >= SIDEBAR_MINI_ROWS ? "mini" : "micro"; +} +/** Header rows per tier, including the closing divider. Painting and hit testing both use this. */ +export const SIDEBAR_HEADER_ROWS: Record = { full: 22, compact: 14, mini: 6, micro: 4 }; + /** Allocate once for both painting and hit testing. Never depend on composer height. */ export function sessionSidebarSlots(height: number, taskCount: number, hasImage: boolean): SidebarSlots { const rows = Math.max(0, Math.floor(height)); const footer = rows >= 12 ? 1 : 0; - const header = Math.min(rows >= 30 ? 11 : 4, rows - footer); + const header = Math.min(SIDEBAR_HEADER_ROWS[sidebarTier(rows)], rows - footer); let remaining = rows - header - footer; const middleMin = Math.min(6, remaining); const taskWant = taskCount ? (rows < 30 ? 1 : 2) + Math.min(rows < 30 ? 2 : 3, taskCount) * 2 : 0; diff --git a/pi-slate/extensions/pi-slate/sidebar.ts b/pi-slate/extensions/pi-slate/sidebar.ts index 74d69fd..0afe2cd 100644 --- a/pi-slate/extensions/pi-slate/sidebar.ts +++ b/pi-slate/extensions/pi-slate/sidebar.ts @@ -7,11 +7,13 @@ import type { WorkspaceView } from "./workspace.ts"; import { chromePaint } from "./composer.ts"; import { DEFAULT_SIDEBAR_FOLDS, sidebarText, type SidebarFolds, type SidebarResources, type SidebarSession } from "./sidebar-data.ts"; import type { BackgroundTask } from "./background-tasks.ts"; -import { sessionSidebarSlots, sidebarCost, sidebarDuration, sidebarListOffset, sidebarRate, sidebarUncached } from "./sidebar-layout.ts"; +import { sessionSidebarSlots, sidebarDuration, sidebarListOffset, sidebarTier, sidebarUncached, type SidebarTier } from "./sidebar-layout.ts"; +import { cacheRows, combinedRow, formatCountdown, formatRate, hasSpeed, speedRows, type PerfInput } from "./perf-graphics.ts"; +import { cacheWarmth, EMPTY_PERF } from "./perf-stats.ts"; export const DOUBLE_CLICK_MS = 400; type ListName = "mcp" | "skills" | "prompts" | "tasks"; -type Row = { divider?: boolean; text: string; action?: () => void; list?: ListName; item?: number }; +type Row = { divider?: boolean; text: string; action?: () => void; list?: ListName; item?: number; extra?: Array<{ x0: number; x1: number; action: () => void }> }; type Hit = { y: number; x0: number; x1: number; action: () => void }; export type SidebarActions = { copy(text: string): void; @@ -26,6 +28,7 @@ const EMPTY_SESSION: SidebarSession = { percent: null, contextWindow: null, estimated: false, rate: null, startedAt: 0, lastTurnMs: null, working: false, turns: 0, messages: 0, usage: { input: null, output: null, total: null, cacheRead: null, cacheWrite: null, cost: null }, + perf: EMPTY_PERF, }; const EMPTY_RESOURCES: SidebarResources = { skills: [], commands: [], prompts: [], mcp: [] }; @@ -102,7 +105,7 @@ export class Sidebar implements Component { setActions(actions: SidebarActions): void { this.actions = actions; } setSession(session: SidebarSession): void { // Keep the full plain-text title for copying/details; truncate only its painted row. - this.session = { ...session, name: sidebarText(session.name, Infinity), usage: { ...session.usage } }; + this.session = { ...session, perf: session.perf ?? EMPTY_PERF, name: sidebarText(session.name, Infinity), usage: { ...session.usage } }; this.changed(); } setResources(resources: SidebarResources): void { @@ -160,7 +163,21 @@ export class Sidebar implements Component { `Output: ${formatCompactTokenCount(s.usage.output)} · Total: ${formatCompactTokenCount(s.usage.total)}`, `Cache read: ${formatCompactTokenCount(s.usage.cacheRead)} · Cache write: ${formatCompactTokenCount(s.usage.cacheWrite)}`, `Uncached input: ${formatCompactTokenCount(uncached)} · Cache-hit share: ${hit}`, - `Cost: ${s.usage.cost === null ? "—" : `$${s.usage.cost.toFixed(2)}`}`, `Estimated rate: ${s.rate === null ? "—" : `~${Math.round(s.rate)} tokens/sec`}`, s.cwd].join("\n"); + `Cost: ${s.usage.cost === null ? "—" : `$${s.usage.cost.toFixed(2)}`}`, `Estimated rate: ${s.rate === null ? "—" : `~${Math.round(s.rate)} tokens/sec`}`, s.cwd, ...this.speedCacheDetails()].join("\n"); + } + private speedCacheDetails(): string[] { + const perf = this.session.perf ?? EMPTY_PERF; + const c = perf.cache; + const warmth = cacheWarmth(c, this.now()); + const pct = (n: number | null): string => n === null || !Number.isFinite(n) ? "—" : `${Math.round(n * 100)}%`; + return ["", "Speed & cache", + `Speed is end-to-end: output tokens ÷ request duration (includes time to first token and hidden reasoning).`, + `Requests under 32 output tokens or 300 ms are left out of the graph, peak and last response.`, + `The live value while streaming is an estimate (visible text ÷ 4) and is marked ~.`, + `Timed requests: ${perf.requests} · last response: ${formatRate(perf.lastRate)} tok/s · peak: ${formatRate(perf.peak)} tok/s · this turn: ${formatRate(perf.turn?.rate)} tok/s`, + `Cache hit % = cache read ÷ (uncached + cache read + cache write); latest request ${pct(c.lastHit)} · session ${pct(c.sessionHit)}.`, + `Saved is an estimate of what cache reads cost less than uncached input${c.saved === null ? " (prices unknown here)" : ""}.`, + `Cache lifetime is shown only when the provider publishes it${warmth.state === "unknown" ? " (not known for this model)" : ""}.`]; } tick(): void { if (!this.hidden && this.splitActive) this.tui?.requestRender(); } invalidate(): void { @@ -218,11 +235,14 @@ export class Sidebar implements Component { const add = (row: Row): void => { const y = lines.length; lines.push(row.divider ? this.dividerLine(width, "├") : this.decorateLine(row.text, width)); + if (inner > 0) for (const e of row.extra ?? []) this.hits.push({ y, x0: 2 + e.x0, x1: 2 + e.x1, action: e.action }); if (row.action && inner > 0) this.hits.push({ y, x0: 2, x1: width - 2, action: row.action }); if (row.list) this.listRows.push({ y, list: row.list }); }; if (chrome) lines.push(this.dividerLine(width, "┌")); - for (const row of this.headerRows(inner).slice(0, slots.header)) add(row); + const header = this.headerRows(inner, sidebarTier(height)).slice(0, slots.header); + slots.middle += slots.header - header.length; slots.header = header.length; + for (const row of header) add(row); const middle = this.middle(); this.middleRows = middle.length; this.middleHeight = slots.middle; this.middleStart = lines.length; this.middleOffset = sidebarListOffset(this.middleOffset, middle.length, slots.middle); @@ -237,14 +257,35 @@ export class Sidebar implements Component { return this.cached.lines; } - private headerRows(width: number): Row[] { + private headerRows(width: number, tier: SidebarTier): Row[] { const s = this.session; + const perf = s.perf ?? EMPTY_PERF; const percent = s.percent !== null && Number.isFinite(s.percent) ? s.percent : null; const tone = percent !== null && percent >= 80 ? "warning" : "accent"; - const identity = `Session ${sidebarText(s.id).slice(0, 8) || "—"} · PID ${s.pid}`; + const branchUsage = () => this.actions?.inspect?.("Branch usage", this.sessionDetails()); const name = s.name || ""; - const occupancy = `${s.estimated ? "~" : ""}${formatCompactTokenCount(s.tokens)} / ${formatCompactTokenCount(s.contextWindow)}` - + ` · ${sidebarCost(s.usage.cost)} · ${sidebarRate(s.rate)}`; + const shortId = sidebarText(s.id).slice(0, 8) || "—"; + const idWidth = visibleWidth(shortId); + const showId = width >= idWidth + 13; + const copyName = () => { if (this.session.name) this.actions?.copy(this.session.name); }; + const copyId = () => { if (this.session.id) this.actions?.copy(this.session.id); }; + const status: Row = (() => { + const turns = s.turns === 1 ? "1 turn" : `${s.turns} turns`; + const left = s.working + ? this.paint("success", "● Working") + this.paint("muted", s.turns > 0 ? ` · turn ${s.turns}` : "") + : this.paint("dim", "○ Idle") + (s.turns > 0 ? this.paint("muted", ` · ${turns}`) : ""); + const started = s.turnStartedAt; + const right = s.working + ? typeof started === "number" && Number.isFinite(started) ? this.paint("warning", formatCountdown(Math.max(0, this.now() - started))) : "" + : s.lastTurnMs !== null ? this.paint("dim", `last ${sidebarDuration(s.lastTurnMs)}`) : ""; + return { text: this.pair(left, right, width) }; + })(); + const identity: Row = { + text: this.pair(this.heading(name || "Session", name ? "accent" : "mdHeading"), showId ? this.paint("dim", shortId) : "", width), + action: name ? copyName : undefined, + extra: showId ? [{ x0: width - idWidth, x1: width, action: copyId }] : undefined, + }; + const model: Row = { text: this.pair(this.paint("text", sidebarText(s.model)), this.paint("dim", sidebarText(s.thinking)), width) }; const meter = ((): string => { const pct = percent === null ? "—%" : `${Math.round(percent)}%`; if (width < visibleWidth(pct) + 3) return this.paint("muted", truncateToWidth(pct, width, "…")); @@ -256,22 +297,29 @@ export class Sidebar implements Component { + (filledCells ? this.paint(tone, "━".repeat(filledCells)) : "") + this.paint("dim", "─".repeat(barWidth - filledCells) + suffix); })(); - const branchUsage = () => this.actions?.inspect?.("Branch usage", this.sessionDetails()); - const stat = (label: string, value: string): string => `${this.paint("muted", label)} ${this.paint("text", value)}`; - const statRight = (label: string, value: string): string => `${this.paint("text", value)} ${this.paint("muted", label)}`; - return [ - { text: this.heading(name, "accent"), action: name ? () => { if (this.session.name) this.actions?.copy(this.session.name); } : undefined }, - { text: this.heading(visibleWidth(identity) > width ? this.pair(`Session ${sidebarText(s.id).slice(0, 8) || "—"}`, `· PID ${s.pid}`, width) : identity), action: () => { if (s.id) this.actions?.copy(s.id); } }, - { text: this.pair(this.paint("text", sidebarText(s.model)), this.paint("dim", sidebarText(s.thinking)), width) }, - { text: "" }, - { text: meter }, - { text: this.paint("dim", occupancy), action: branchUsage }, - { text: "" }, - { text: this.pair(stat("Cached", formatCompactTokenCount(s.usage.cacheRead)), statRight("In", formatCompactTokenCount(s.usage.input)), width), action: branchUsage }, - { text: this.pair(stat("Uncached", formatCompactTokenCount(sidebarUncached(s.usage))), statRight("Out", formatCompactTokenCount(s.usage.output)), width), action: branchUsage }, - { text: "" }, - { text: "", divider: true }, - ]; + const divider: Row = { text: "", divider: true }; + const input = (): PerfInput => ({ perf, cost: s.usage.cost, now: this.now(), inner: width, tier, paint: (t, x) => this.paint(t, x), heading: x => this.heading(x) }); + if (tier === "micro") return [identity, model, { text: meter, action: branchUsage }, divider]; + const combined: Row = { text: combinedRow(input()) }; + if (tier === "mini") return [status, identity, model, { text: meter, action: branchUsage }, combined, divider]; + const context: Row[] = (() => { + const pct = percent === null ? "—" : `${Math.round(percent)}%`; + const figures = `${s.estimated ? "~" : ""}${formatCompactTokenCount(s.tokens)}/${formatCompactTokenCount(s.contextWindow)}`; + const right = this.paint(tone === "warning" ? "warning" : "text", pct) + this.paint("dim", ` ${figures}`); + const filled = percent === null ? 0 : Math.round(Math.max(0, Math.min(100, percent)) * width / 100); + return [ + { text: this.pair(this.heading("CONTEXT"), right, width), action: branchUsage }, + { text: (filled ? this.paint(tone, "━".repeat(filled)) : "") + this.paint("dim", "─".repeat(Math.max(0, width - filled))), action: branchUsage }, + ]; + })(); + const rows = (lines: string[]): Row[] => lines.map(text => ({ text })); + const full = tier === "full"; + // Empty states take only their two rows; render() hands the spare rows to the middle list. + const speedCount = full && hasSpeed(perf) ? 8 : 2; + const cacheCount = full && perf.cache.seen ? 4 : 2; + return [status, identity, model, { text: "" }, ...context, { text: "" }, + ...rows(speedRows(input(), speedCount)), { text: "" }, + ...rows(cacheRows(input(), cacheCount)), { text: "" }, divider]; } private middle(): Row[] { const enabled = this.resources.mcp.filter(x => x.enabled === true).length; diff --git a/pi-slate/tests/perf-fixture.ts b/pi-slate/tests/perf-fixture.ts new file mode 100644 index 0000000..66dd7db --- /dev/null +++ b/pi-slate/tests/perf-fixture.ts @@ -0,0 +1,14 @@ +import type { SidebarPerf } from "../extensions/pi-slate/perf-stats.ts"; + +/** Realistic mid-session perf facts shared by sidebar tests. `now` is the render clock. */ +export function perfFixture(now: number): SidebarPerf { + return { + requests: 12, + rates: [18, 22, 26, 31, 24, 28, 35, 30, 22, 19, 27, 33, 38, 29, 24, 31, 36, 41, 45, 37, 30, 26, 33, 28, 21, 25, 30, 14.6], + peak: 45, lastRate: 14.6, + turn: { requests: 3, output: 12_000, durationMs: 449_000, rate: 26.7 }, + cache: { read: 1_310_000, write: 108_000, uncached: 141_000, lastHit: 0.92, sessionHit: 0.84, saved: 1.92, + lastActivityAt: now - 19_000, ttlMs: 300_000, seen: true }, + live: { streaming: false, rate: null }, + }; +} diff --git a/pi-slate/tests/perf-graphics.test.ts b/pi-slate/tests/perf-graphics.test.ts new file mode 100644 index 0000000..9c5432b --- /dev/null +++ b/pi-slate/tests/perf-graphics.test.ts @@ -0,0 +1,232 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { visibleWidth, type TUI } from "@earendil-works/pi-tui"; +import { bigDigits, brailleBars, cacheRows, combinedRow, formatCountdown, formatRate, sparkBlocks, speedRows, stackedBar, type PerfInput } from "../extensions/pi-slate/perf-graphics.ts"; +import { EMPTY_PERF, type SidebarPerf } from "../extensions/pi-slate/perf-stats.ts"; +import { Sidebar } from "../extensions/pi-slate/sidebar.ts"; +import type { SidebarSession } from "../extensions/pi-slate/sidebar-data.ts"; +import { sessionSidebarSlots, sidebarTier, SIDEBAR_HEADER_ROWS } from "../extensions/pi-slate/sidebar-layout.ts"; +import { perfFixture } from "./perf-fixture.ts"; + +const strip = (t: string) => t.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, ""); +const plainPaint = { paint: (_t: string, x: string) => x, heading: (x: string) => x }; +const input = (perf: SidebarPerf, inner = 40, tier: PerfInput["tier"] = "full", now = 1000, cost: number | null = 0.84): PerfInput => ({ perf, cost, now, inner, tier, ...plainPaint }); + +test("formatRate uses one decimal below 100, integers below 1000, then compact units", () => { + const cases: Array<[number | null, string]> = [[14.64, "14.6"], [0, "0.0"], [99.96, "100"], [100, "100"], [999.4, "999"], [999.6, "1.0k"], [1234, "1.2k"], + [12_345, "12.3k"], [123_456, "123k"], [2_500_000, "2.5M"], [null, "—"], [Number.NaN, "—"], [Infinity, "—"], [-3, "—"]]; + for (const [n, out] of cases) assert.equal(formatRate(n), out, String(n)); +}); + +test("formatCountdown is m:ss and h:mm:ss after an hour, clamped", () => { + assert.equal(formatCountdown(0), "0:00"); assert.equal(formatCountdown(221_000), "3:41"); + assert.equal(formatCountdown(59_999), "0:59"); assert.equal(formatCountdown(3_600_000), "1:00:00"); + assert.equal(formatCountdown(3_725_000), "1:02:05"); assert.equal(formatCountdown(-5), "0:00"); assert.equal(formatCountdown(Number.NaN), "0:00"); +}); + +test("bigDigits draws three equal-width rows and blanks unknown characters", () => { + const rows = bigDigits("14.6"); + assert.equal(rows.length, 3); + assert(rows.every(r => visibleWidth(r) === visibleWidth(rows[0]!))); + assert.deepEqual(bigDigits("0"), ["█▀█", "█ █", "▀▀▀"]); + assert.equal(visibleWidth(bigDigits("~1.2k")[0]!), 3 + 1 + 3 + 1 + 1 + 1 + 3 + 1 + 3); + const unknown = bigDigits("1—1"); + assert.equal(unknown[1]!.slice(4, 6), " ", "unknown glyph is blank"); + assert.deepEqual(bigDigits(""), ["", "", ""]); +}); + +test("stackedBar sums exactly to width and keeps non-zero parts visible", () => { + for (const width of [1, 2, 3, 7, 30, 44, 60]) for (const parts of [[1, 1, 1], [1.31e6, 1.08e5, 1.41e5], [1, 0, 0], [0, 0, 5], [1, 1e9, 1], [3, 2, 1], [0.1, 0.2, 0.7]]) { + const out = stackedBar(parts, width); + assert.equal(out.reduce((a, b) => a + b, 0), width, `${width} ${parts}`); + assert(out.every(n => Number.isInteger(n) && n >= 0)); + if (width >= parts.filter(p => p > 0).length) parts.forEach((p, i) => { if (p > 0) assert(out[i]! >= 1, `part ${i} visible at ${width}`); else assert.equal(out[i], 0); }); + } + assert.deepEqual(stackedBar([0, 0, 0], 10), [0, 0, 0]); + assert.deepEqual(stackedBar([1, 2, 3], 0), [0, 0, 0]); + assert.deepEqual(stackedBar([Number.NaN, -1, Infinity], 5), [0, 0, 0]); + assert.deepEqual(stackedBar([], 5), []); +}); + +test("brailleBars is zero-based, right-aligned, and always draws a positive value", () => { + assert.deepEqual(brailleBars([], 0, 2), ["", ""]); + assert.deepEqual(brailleBars([1, 2], 3, 0), []); + const one = brailleBars([5], 4, 2); + assert.equal(one.length, 2); + assert(one.every(r => r.length === 4)); + assert.equal(one[1]!.slice(0, 3), "⣀⣀⣀", "empty columns show baseline dots"); + assert.equal(one[1]![3], "⣸", "the newest rate fills the right column of the last cell"); + assert.equal(one[0]![3], "⢸"); + assert.equal(one[0]!.slice(0, 3), " "); + const tiny = brailleBars([1000, 0.001], 1, 1); + assert.notEqual(tiny[0], "⣀", "tiny but positive value is still drawn"); + // Zero-based: a flat series is full height, not half height. + assert.deepEqual(brailleBars([7, 7, 7, 7], 2, 1), ["⣿⣿"]); + // Zero-based: 50 vs 100 gives the left column half height (2 of 4 dots); min-max would give 1. + assert.equal(brailleBars([50, 100], 1, 1)[0], "⣼"); + const many = brailleBars(Array.from({ length: 500 }, (_, i) => i), 5, 2); + assert(many.every(r => r.length === 5), "only the newest 2×width values are used"); + for (const bad of [[Number.NaN, -3, Infinity], [0, 0]]) assert(brailleBars(bad, 3, 2).every(r => r.length === 3)); +}); + +test("sparkBlocks scales to the max, right-aligns, and tolerates bad input", () => { + assert.equal(sparkBlocks([], 0), ""); + assert.equal(sparkBlocks([], 3), "▁▁▁"); + assert.equal(sparkBlocks([1, 8], 4), "▁▁▂█"); + assert.equal(sparkBlocks([4, 8], 2), "▅█"); + assert.equal(sparkBlocks([1, 2, 3, 4], 2).length, 2); + assert.equal(sparkBlocks([Number.NaN, -1, 0], 3), "▁▁▁"); + assert.equal(sparkBlocks([5], 1), "█"); +}); + +test("tier thresholds are pure and the header slot follows them", () => { + assert.deepEqual([60, 44, 43, 30, 29, 20, 19, 0].map(sidebarTier), ["full", "full", "compact", "compact", "mini", "mini", "micro", "micro"]); + for (const rows of [12, 19, 20, 29, 30, 43, 44, 60, 100]) { + const slots = sessionSidebarSlots(rows, 0, false); + assert.equal(slots.header, SIDEBAR_HEADER_ROWS[sidebarTier(rows)], `header ${rows}`); + assert(slots.middle >= 6, `middle keeps 6 rows at ${rows}`); + assert(sessionSidebarSlots(rows, 4, true).tasks + sessionSidebarSlots(rows, 4, true).image >= 0); + } +}); + +test("empty perf: waiting and no-request lines, no NaN or zero percent", () => { + for (const tier of ["full", "compact"] as const) { + const lines = [...speedRows(input(EMPTY_PERF, 40, tier), tier === "full" ? 8 : 2), ...cacheRows(input(EMPTY_PERF, 40, tier), tier === "full" ? 4 : 2)].map(strip); + const text = lines.join("\n"); + assert.match(text, /waiting for first response/); assert.match(text, /no requests yet/); + assert.doesNotMatch(text, /NaN|Infinity|-\d|0%|[█▀]/); + } + assert.equal(combinedRow(input(EMPTY_PERF)), "no requests yet"); + assert.equal(speedRows(input(EMPTY_PERF, 40, "full"), 8).length, 8); +}); + +test("provider that never reports cache shows an explicit note", () => { + const perf = { ...perfFixture(1000), cache: { ...EMPTY_PERF.cache, seen: false } }; + assert.match(strip(cacheRows(input(perf), 4).join("\n")), /no cache reads reported/); + assert.doesNotMatch(strip(cacheRows(input(perf), 4).join("\n")), /[█▓░]/); +}); + +test("a single rate renders a graph with one column at the right edge", () => { + const perf: SidebarPerf = { ...EMPTY_PERF, requests: 1, rates: [30], peak: 30, lastRate: 30, turn: { requests: 1, output: 300, durationMs: 10_000, rate: 30 } }; + const rows = speedRows(input(perf, 40), 8).map(strip); + assert.equal(rows.length, 8); + const graph = rows.slice(4, 6); + assert(graph.every(r => visibleWidth(r) === 40)); + assert.match(graph[0]!, /\S$/); assert.match(graph[1]!, /^⣀+/); +}); + +test("streaming shows ~ live estimate; settled shows exact last rate", () => { + const live = { ...perfFixture(1000), live: { streaming: true, rate: 51.25 } }; + const liveText = speedRows(input(live), 8).map(strip); + assert.match(liveText[0]!, /● streaming$/); assert.match(liveText.slice(1, 4).join("\n"), /▄▀▄/, "tilde glyph precedes the digits"); + const settled = speedRows(input(perfFixture(1000)), 8).map(strip); + assert.match(settled[0]!, /last response$/); assert.doesNotMatch(settled.slice(1, 4).join(""), /▄▀▄/); + assert.match(strip(speedRows(input(live, 40, "compact"), 2)[0]!), /● ~51\.3 tok\/s|● ~51\.2 tok\/s/); +}); + +test("stats row: nulls become dashes", () => { + const perf: SidebarPerf = { ...perfFixture(1000), peak: null, turn: null }; + const rows = speedRows(input(perf), 8).map(strip); + assert.match(rows[7]!, /^—\s+—\s+—$/); +}); + +test("huge numbers stay inside the width", () => { + const perf: SidebarPerf = { ...perfFixture(1000), lastRate: 12_345, peak: 1e9, rates: [12_345, 1e9], + turn: { requests: 1, output: 9e12, durationMs: 1, rate: 1e15 }, + cache: { ...perfFixture(1000).cache, read: 1.31e6, write: 1e12, uncached: 1e15, saved: 1.2e6 } }; + for (const inner of [10, 16, 21, 22, 24, 30, 44, 60]) for (const tier of ["full", "compact"] as const) for (const cost of [1.2e6, 1e308, null]) { + const rows = [...speedRows(input(perf, inner, tier, 1000, cost), tier === "full" ? 8 : 2), ...cacheRows(input(perf, inner, tier, 1000, cost), tier === "full" ? 4 : 2), combinedRow(input(perf, inner, tier, 1000, cost))]; + for (const r of rows) { assert(visibleWidth(r) <= inner, `${inner} ${tier}: ${strip(r)}`); assert.doesNotMatch(strip(r), /NaN|Infinity/); } + } +}); + +test("width tiers: digits fall back to text, narrow rails drop the graph", () => { + const perf = perfFixture(1000); + const narrowDigits = speedRows(input(perf, 12), 8).map(strip); + assert.equal(narrowDigits[1]!.trim(), "14.6 tok/s", "big digits need more than 12 columns"); + const tiny = speedRows(input(perf, 20), 8).map(strip).join("\n"); + assert.doesNotMatch(tiny, /[⣀-⣿]/); assert.match(tiny, /26\.7 · 45\.0 · 12k/); + assert.match(speedRows(input(perf, 40), 8).map(strip).join("\n"), /[⣀-⣿]/); +}); + +test("warmth: countdown, cold, unknown lifetime and idle hint", () => { + const base = perfFixture(1_000_000); + const head = (cache: Partial, now: number) => strip(cacheRows(input({ ...base, cache: { ...base.cache, ...cache } }, 44, "full", now), 4)[0]!); + assert.match(head({}, 1_000_000), /92% hit · ◉ warm 4:41$/); + assert.match(head({}, 1_000_000 + 1000), /warm 4:40$/, "countdown moves with the clock alone"); + assert.match(head({}, 1_000_000 + 400_000), /◌ cold$/); + assert.match(head({ ttlMs: null }, 1_000_000 + 30_000), /^CACHE\s+92% hit$/, "no lifetime and recent: nothing extra"); + assert.match(head({ ttlMs: null, lastActivityAt: 1_000_000 - 4 * 60_000 }, 1_000_000), /idle 4m$/); + assert.match(head({ lastHit: null }, 1_000_000), /^CACHE\s+◉ warm/, "unknown hit is omitted, never 0%"); +}); + +test("cache rows: bar spans the width and money lines handle unknowns", () => { + const rows = cacheRows(input(perfFixture(1000), 44), 4).map(strip); + assert.equal(rows[1]!.length, 44); + assert.match(rows[2]!, /read 1\.3M · write 108k · new 141k/); + assert.equal(rows[3], "spent $0.84 · saved ~$1.92"); + const none = cacheRows(input({ ...perfFixture(1000), cache: { ...perfFixture(1000).cache, saved: null } }, 44, "full", 1000, null), 4).map(strip); + assert.equal(none[3], "spent —"); +}); + +function sidebarWith(rows: number, perf: SidebarPerf, clock: { now: number }, extra: Partial = {}) { + const sidebar = new Sidebar(() => clock.now); + sidebar.attach({ terminal: { rows, columns: 140 }, requestRender() {}, showOverlay() { return { hide() {} }; } } as unknown as TUI, undefined as never); + sidebar.setSession({ id: "01a1cd96-0000", name: "fix auth refresh", pid: 1, cwd: "/p", model: "gpt-6.1-sol (openai)", thinking: "medium", tokens: 152_000, percent: 38, + contextWindow: 400_000, estimated: false, rate: null, startedAt: 1, lastTurnMs: 39_000, working: false, turns: 7, messages: 14, + usage: { input: 1_559_000, output: 12_000, total: 1_571_000, cacheRead: 1_310_000, cacheWrite: 108_000, cost: 0.84 }, perf, ...extra }); + return sidebar; +} + +test("sidebar renders the full tier and the empty session within width", () => { + const clock = { now: 1_000_000 }; + const s = sidebarWith(60, perfFixture(clock.now), clock); + const full = s.render(44).map(strip); + assert(full.every(l => visibleWidth(l) === 44)); + const empty = sidebarWith(60, EMPTY_PERF, clock, { id: "", name: "", turns: 0, lastTurnMs: null, tokens: null, percent: null, contextWindow: null, + usage: { input: null, output: null, total: null, cacheRead: null, cacheWrite: null, cost: null } }); + const text = empty.render(44).map(strip); + assert(text.every(l => visibleWidth(l) === 44)); + assert.doesNotMatch(text.join("\n"), /NaN|Infinity|\b0%/); +}); + +test("render recomputes the countdown each second without extra timers", () => { + const clock = { now: 1_000_000 }; + const s = sidebarWith(60, perfFixture(clock.now), clock); + const a = s.render(44).map(strip).join("\n"); + assert.equal(s.render(44).map(strip).join("\n"), a); + clock.now += 1000; + const b = s.render(44).map(strip).join("\n"); + assert.notEqual(a, b); assert.match(a, /warm 4:41/); assert.match(b, /warm 4:40/); +}); + +test("every tier and width keeps rows bounded, including live streaming and long sessions", () => { + const clock = { now: 1_000_000 }; + const perf: SidebarPerf = { ...perfFixture(clock.now), rates: Array.from({ length: 256 }, (_, i) => 10 + (i % 40)), requests: 5000, live: { streaming: true, rate: 33 } }; + for (const rows of [10, 19, 20, 29, 30, 43, 44, 70]) for (const width of [0, 1, 5, 12, 20, 28, 44, 60, 90]) { + const lines = sidebarWith(rows, perf, clock, { working: true }).render(width); + assert.equal(lines.length, rows); + assert(lines.every(l => visibleWidth(l) <= width), `${width}x${rows}`); + } +}); + +test("mini tier shows the combined speed/cache row; details explain the numbers", () => { + const clock = { now: 1_000_000 }; + const s = sidebarWith(24, perfFixture(clock.now), clock); + assert.match(s.render(40).map(strip).join("\n"), /↯14\.6 t\/s ◉92% 4:41/); + assert.match(s.sessionDetails(), /Speed & cache/); + assert.match(s.sessionDetails(), /300 ms/); +}); + +test("themed render keeps tones within the theme palette", () => { + const clock = { now: 1_000_000 }; + const tones = new Set(); + const theme = { fg: (tone: string, text: string) => { tones.add(tone); return text; }, bold: (t: string) => t } as never; + const s = new Sidebar(() => clock.now); + s.attach({ terminal: { rows: 60, columns: 140 }, requestRender() {}, showOverlay() { return { hide() {} }; } } as unknown as TUI, theme); + s.setSession({ id: "a", pid: 1, cwd: "", model: "m", thinking: "low", tokens: 1, percent: 90, contextWindow: 10, estimated: true, rate: null, startedAt: 1, lastTurnMs: null, + working: true, turns: 1, messages: 1, usage: { input: 1, output: 1, total: 2, cacheRead: 0, cacheWrite: 0, cost: 0 }, perf: perfFixture(clock.now) }); + s.render(44); + for (const t of tones) assert(["text", "muted", "dim", "accent", "success", "warning", "error", "mdHeading", "border", "borderMuted", "borderAccent"].includes(t) || /^[a-zA-Z]+$/.test(t), t); + assert(tones.has("success") && tones.has("accent") && tones.has("warning")); +}); diff --git a/pi-slate/tests/perf-stats.test.ts b/pi-slate/tests/perf-stats.test.ts new file mode 100644 index 0000000..87e104d --- /dev/null +++ b/pi-slate/tests/perf-stats.test.ts @@ -0,0 +1,143 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import type { SessionEntry } from "@earendil-works/pi-coding-agent"; +import { branchPerf, cacheWarmth, EMPTY_PERF, PERF_MAX_RATES, type SidebarCachePerf } from "../extensions/pi-slate/perf-stats.ts"; + +let seq = 0; +function entry(fields: Record): SessionEntry { return { id: `e${seq++}`, parentId: null, timestamp: "0", ...fields } as unknown as SessionEntry; } +function user(): SessionEntry { return entry({ type: "message", message: { role: "user" } }); } +function usageOf(over: Record = {}, cost: Record = {}) { + return { input: 10, output: 100, cacheRead: 0, cacheWrite: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, ...cost }, ...over }; +} +function asst(over: Record = {}, usage: Record | undefined = usageOf()): SessionEntry { + const message: Record = { role: "assistant", timestamp: 1000, durationMs: 1000, stopReason: "stop", ...over }; + if (usage) message.usage = usage; + return entry({ type: "message", message }); +} +const opts = { retentionLong: false }; + +test("empty branch yields null facts", () => { + const perf = branchPerf([], opts); + assert.deepEqual(perf.rates, []); + assert.equal(perf.requests, 0); assert.equal(perf.peak, null); assert.equal(perf.turn, null); + assert.equal(perf.cache.seen, false); assert.equal(perf.cache.lastActivityAt, null); + assert.equal(perf.cache.read, 0); + assert.deepEqual(EMPTY_PERF.live, perf.live); +}); + +test("legacy messages without durationMs are not timed", () => { + const perf = branchPerf([user(), asst({ durationMs: undefined })], opts); + assert.equal(perf.requests, 0); assert.equal(perf.turn, null); assert.deepEqual(perf.rates, []); + assert.equal(perf.cache.uncached, 10); +}); + +test("error, aborted and deferred are excluded from speed and turn", () => { + const perf = branchPerf([user(), asst({ stopReason: "error" }), asst({ stopReason: "aborted" }), asst({ stopReason: "deferred" })], opts); + assert.equal(perf.requests, 3); assert.deepEqual(perf.rates, []); assert.equal(perf.peak, null); assert.equal(perf.turn, null); +}); + +test("tiny outputs count in the turn but not in rates or peak", () => { + const perf = branchPerf([user(), asst({}, usageOf({ output: 10 })), asst({ durationMs: 100 }, usageOf({ output: 500 })), asst({}, usageOf({ output: 100 }))], opts); + assert.deepEqual(perf.rates, [100]); assert.equal(perf.peak, 100); assert.equal(perf.lastRate, 100); + assert.equal(perf.turn?.requests, 3); assert.equal(perf.turn?.output, 610); +}); + +test("turn average is token weighted, not a mean of rates", () => { + const perf = branchPerf([user(), asst({ durationMs: 1000 }, usageOf({ output: 100 })), asst({ durationMs: 9000 }, usageOf({ output: 900 }))], opts); + assert.equal(perf.turn?.rate, 100); // naive mean of (100, 100) agrees; use skewed case below + const skew = branchPerf([user(), asst({ durationMs: 1000 }, usageOf({ output: 1000 })), asst({ durationMs: 9000 }, usageOf({ output: 90 }))], opts); + assert.equal(skew.turn?.rate, 109); // 1090 / 10s, naive mean would be 505 +}); + +test("turn starts after the last user message", () => { + const perf = branchPerf([user(), asst({}, usageOf({ output: 999 })), user(), asst({}, usageOf({ output: 50 }))], opts); + assert.equal(perf.turn?.output, 50); assert.equal(perf.requests, 2); + assert.equal(branchPerf([asst(), user()], opts).turn, null); +}); + +test("keeps newest PERF_MAX_RATES but peak spans all", () => { + const entries: SessionEntry[] = [asst({ durationMs: 400 }, usageOf({ output: 4000 }))]; + for (let i = 0; i < PERF_MAX_RATES + 50; i++) entries.push(asst({ durationMs: 1000 }, usageOf({ output: 100 + i }))); + const perf = branchPerf(entries, opts); + assert.equal(perf.rates.length, PERF_MAX_RATES); + assert.equal(perf.peak, 10000); + assert.equal(perf.rates.at(-1), 100 + PERF_MAX_RATES + 49); + assert.equal(perf.rates[0], 100 + 50); +}); + +test("5,000 requests process quickly", () => { + const entries: SessionEntry[] = []; + for (let i = 0; i < 5000; i++) entries.push(asst({}, usageOf({ cacheRead: 5, cost: { input: 1, cacheRead: 0.1 } }))); + const start = performance.now(); + const perf = branchPerf(entries, opts); + assert.ok(performance.now() - start < 1000); + assert.equal(perf.requests, 5000); assert.equal(perf.rates.length, PERF_MAX_RATES); +}); + +test("cache hit math uses Pi's uncached input", () => { + const perf = branchPerf([ + asst({}, usageOf({ input: 100, cacheRead: 700, cacheWrite: 200 })), + asst({}, usageOf({ input: 50, cacheRead: 150, cacheWrite: 0 })), + ], opts); + assert.equal(perf.cache.lastHit, 0.75); + assert.equal(perf.cache.read, 850); assert.equal(perf.cache.write, 200); assert.equal(perf.cache.uncached, 150); + assert.equal(perf.cache.sessionHit, 850 / 1200); + assert.equal(perf.cache.seen, true); +}); + +test("cache totals reconcile with tool results and summaries, and go null when unknown", () => { + const tool = entry({ type: "message", message: { role: "toolResult", usage: usageOf({ input: 5, cacheRead: 5, cacheWrite: 5 }) } }); + const summary = entry({ type: "compaction", usage: usageOf({ input: 1, cacheRead: 2, cacheWrite: 3 }) }); + const ok = branchPerf([asst({}, usageOf({ input: 1, cacheRead: 1, cacheWrite: 1 })), tool, summary], opts); + assert.equal(ok.cache.read, 8); assert.equal(ok.cache.write, 9); assert.equal(ok.cache.uncached, 7); + const legacy = branchPerf([asst({}, usageOf({ input: 1, cacheRead: 1 })), entry({ type: "compaction" })], opts); + assert.equal(legacy.cache.read, null); assert.equal(legacy.cache.sessionHit, null); + assert.equal(branchPerf([entry({ type: "message", message: { role: "assistant", timestamp: 1, durationMs: 1 } })], opts).cache.uncached, null); +}); + +test("saved estimates handle mixed models, skip unpriceable requests and zero prices", () => { + const a = asst({}, usageOf({ input: 100, cacheRead: 1000 }, { input: 1, cacheRead: 0.1 })); // 0.01/tok vs 0.0001 + const b = asst({}, usageOf({ input: 10, cacheRead: 200 }, { input: 0.5, cacheRead: 0.02 })); // 0.05 vs 0.0001 + const skip = asst({}, usageOf({ input: 0, cacheRead: 500 }, { input: 0, cacheRead: 1 })); + const perf = branchPerf([a, b, skip], opts); + assert.ok(Math.abs((perf.cache.saved ?? NaN) - (1000 * (0.01 - 0.0001) + 200 * (0.05 - 0.0001))) < 1e-9); + assert.equal(branchPerf([skip], opts).cache.saved, null); + assert.equal(branchPerf([asst({}, usageOf({ input: 10, cacheRead: 100 }))], opts).cache.saved, null); + // cache read priced above fresh input never yields negative savings + const inverted = branchPerf([asst({}, usageOf({ input: 10, cacheRead: 100 }, { input: 1, cacheRead: 100 }))], opts); + assert.equal(inverted.cache.saved, 0); +}); + +test("ttl selection by retention, cacheWrite1h and unknown lifetimes", () => { + const pc = { short: 300, long: 3600 }; + const e = [asst({}, usageOf({ cacheWrite: 1 }))]; + assert.equal(branchPerf(e, { promptCache: pc, retentionLong: false }).cache.ttlMs, 300_000); + assert.equal(branchPerf(e, { promptCache: pc, retentionLong: true }).cache.ttlMs, 3_600_000); + assert.equal(branchPerf([asst({}, usageOf({ cacheWrite: 1, cacheWrite1h: 1 }))], { promptCache: pc, retentionLong: false }).cache.ttlMs, 3_600_000); + assert.equal(branchPerf(e, { retentionLong: false }).cache.ttlMs, null); + assert.equal(branchPerf(e, { promptCache: { short: 0 }, retentionLong: false }).cache.ttlMs, null); + assert.equal(branchPerf(e, { promptCache: { long: 3600 }, retentionLong: false }).cache.ttlMs, null); +}); + +test("lastActivityAt is the end of the newest timed request", () => { + const perf = branchPerf([asst({ timestamp: 5000, durationMs: 2000 }), asst({ timestamp: 9000, durationMs: 500 })], opts); + assert.equal(perf.cache.lastActivityAt, 9500); +}); + +test("cacheWarmth warm, cold, unknown and clock skew", () => { + const base: SidebarCachePerf = { ...EMPTY_PERF.cache, lastActivityAt: 10_000, ttlMs: 300_000 }; + assert.deepEqual(cacheWarmth(base, 70_000), { state: "warm", remainingMs: 240_000, idleMs: 60_000 }); + assert.deepEqual(cacheWarmth(base, 310_000), { state: "cold", remainingMs: 0, idleMs: 300_000 }); + assert.equal(cacheWarmth({ ...base, ttlMs: null }, 20_000).state, "unknown"); + assert.deepEqual(cacheWarmth({ ...base, lastActivityAt: null }, 20_000), { state: "unknown", remainingMs: null, idleMs: null }); + assert.deepEqual(cacheWarmth(base, 5_000), { state: "warm", remainingMs: 300_000, idleMs: 0 }); +}); + +test("NaN, negative and infinite usage never leak", () => { + const bad = asst({}, usageOf({ input: NaN, output: -5, cacheRead: Infinity, cacheWrite: -1 }, { input: NaN })); + const perf = branchPerf([user(), bad, asst({ durationMs: NaN }), asst({ timestamp: NaN })], opts); + assert.equal(perf.cache.read, null); assert.equal(perf.cache.sessionHit, null); assert.equal(perf.cache.saved, null); + assert.equal(branchPerf([bad], opts).cache.lastHit, null); + assert.deepEqual(perf.rates, []); assert.equal(perf.turn, null); + assert.equal(perf.requests, 1); +}); diff --git a/pi-slate/tests/quiet-workbench.test.ts b/pi-slate/tests/quiet-workbench.test.ts index 49e6c58..ca8fd31 100644 --- a/pi-slate/tests/quiet-workbench.test.ts +++ b/pi-slate/tests/quiet-workbench.test.ts @@ -9,13 +9,14 @@ import { dashboardColumnWidth, formatCompactTokenCount, parseSlateArgs } from ". import { SLATE_NATIVE_THEME, SLATE_THEME } from "../extensions/pi-slate/install-defaults.ts"; import { sessionSidebarSlots, sidebarCost, sidebarRate } from "../extensions/pi-slate/sidebar-layout.ts"; import { Sidebar } from "../extensions/pi-slate/sidebar.ts"; +import { perfFixture } from "./perf-fixture.ts"; import type { SidebarSession } from "../extensions/pi-slate/sidebar-data.ts"; const theme = loadThemeFromPath(new URL("../themes/tokyo-night.json", import.meta.url).pathname, "truecolor"); const session: SidebarSession = { id: "example-session", pid: 8421, cwd: "/tmp/project", model: "sample-model", thinking: "medium", tokens: 55000, percent: 11, contextWindow: 500000, estimated: false, rate: 82, startedAt: 1000, lastTurnMs: 14000, working: true, turns: 4, messages: 8, - usage: { input: 128400, output: 6800, total: 135200, cacheRead: 94000, cacheWrite: 22000, cost: 1.24 } }; + usage: { input: 128400, output: 6800, total: 135200, cacheRead: 94000, cacheWrite: 22000, cost: 1.24 }, perf: perfFixture(1000) }; test("bundled default Tokyo Night loads with the native validator and restrained backgrounds", () => { assert.equal(SLATE_THEME, "tokyo-night"); assert.equal(theme.name, SLATE_THEME); @@ -65,20 +66,10 @@ test("growing usage and money keep a stable label lane and value edge with the r for (const value of [0, 999, 128400, 999900000, 1e12, 1e20, 1e308, null]) { sidebar.setSession({ ...session, usage: { ...session.usage, input: value, output: value, cost: value } }); const rows = sidebar.render(width).map(stripVTControlCharacters); - const stats: string[] = []; - for (const label of ["Cached", "Uncached"]) { - const line = rows.find(row => row.startsWith("│ " + label + " "))!; - assert(line, label); assert.equal(visibleWidth(line), width); - assert.equal(visibleWidth(line.trimEnd()), width, "right edge must not move"); - stats.push(line); - } - const occupancy = rows.find(row => row.includes("/ 500k"))!; - assert(occupancy, "occupancy line"); - if (width > 28) { // Below this, bounded values truncate instead of moving edges. - for (const line of stats) assert.doesNotMatch(line, /…/, "values must not consume the label lane"); - assert(occupancy.includes(`${sidebarCost(value)} · ~82 t/s`), `${sidebarCost(value)} on the occupancy line`); - assert.doesNotMatch(occupancy, /…/); - } + assert(rows.every(row => visibleWidth(row) === width), `bounded rows at ${width} for ${value}`); + const spent = rows.find(row => row.includes("spent"))!; + assert(spent, "spent line"); + if (width > 28) assert(spent.includes(`spent ${sidebarCost(value)}`), `${sidebarCost(value)} on the spent line`); } } assert.equal(formatCompactTokenCount(1e9), "1B"); assert.equal(formatCompactTokenCount(1e12), "1T"); @@ -93,8 +84,8 @@ test("growing usage and money keep a stable label lane and value edge with the r test("context meter keeps a thin track and dim separator with the real theme", () => { const sidebar = new Sidebar(() => 10000); - sidebar.attach({ terminal: { rows: 50, columns: 140 }, requestRender() {} } as unknown as TUI, theme); - assert.equal(sessionSidebarSlots(50, 0, false).header, 11, "single identity row removes the section/name rows"); + sidebar.attach({ terminal: { rows: 24, columns: 140 }, requestRender() {} } as unknown as TUI, theme); + assert.equal(sessionSidebarSlots(24, 0, false).header, 6, "mini tier keeps the one-row context meter"); for (const width of [28, 40, 80]) { sidebar.setSession(session); const rows = sidebar.render(width); diff --git a/pi-slate/tests/sidebar-preview.test.ts b/pi-slate/tests/sidebar-preview.test.ts index 8fafd20..d749cfc 100644 --- a/pi-slate/tests/sidebar-preview.test.ts +++ b/pi-slate/tests/sidebar-preview.test.ts @@ -6,6 +6,8 @@ import test from "node:test"; import type { Theme } from "@earendil-works/pi-coding-agent"; import { visibleWidth, type TUI, type TuiMouseEvent } from "@earendil-works/pi-tui"; import { Sidebar, DOUBLE_CLICK_MS } from "../extensions/pi-slate/sidebar.ts"; +import { perfFixture } from "./perf-fixture.ts"; +import { EMPTY_PERF } from "../extensions/pi-slate/perf-stats.ts"; import { SidebarMcpFiles, type SidebarResources, type SidebarSession } from "../extensions/pi-slate/sidebar-data.ts"; import { sessionSidebarSlots } from "../extensions/pi-slate/sidebar-layout.ts"; import { DiffWorkspaceView, type WorkspaceView } from "../extensions/pi-slate/workspace.ts"; @@ -14,7 +16,7 @@ import type { BackgroundTask } from "../extensions/pi-slate/background-tasks.ts" const theme = (code = 32) => ({ fg: (_tone: string, text: string) => `\x1b[${code}m${text}\x1b[0m`, bold: (text: string) => text }) as Theme; const stripAnsi = (text: string) => text.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, ""); const plain = (lines: string[]) => lines.map(line => stripAnsi(line).replace(/^│ ?/, "").replace(/ ?│$/, "").trimEnd()); -const session: SidebarSession = { id: "session-a", pid: 8421, cwd: "/tmp/project", model: "sonnet-4.6", thinking: "medium", tokens: 31600, percent: 16, contextWindow: 200000, estimated: false, rate: 82, startedAt: 1000, lastTurnMs: 5000, working: true, turns: 2, messages: 5, usage: { input: 61400, output: 876, total: 62276, cacheRead: 48000, cacheWrite: 6100, cost: 0.12 } }; +const session: SidebarSession = { id: "session-a", pid: 8421, cwd: "/tmp/project", model: "sonnet-4.6", thinking: "medium", tokens: 31600, percent: 16, contextWindow: 200000, estimated: false, rate: 82, startedAt: 1000, lastTurnMs: 5000, working: true, turns: 2, messages: 5, usage: { input: 61400, output: 876, total: 62276, cacheRead: 48000, cacheWrite: 6100, cost: 0.12 }, perf: perfFixture(1000) }; const resources: SidebarResources = { mcp: Array.from({ length: 7 }, (_, i) => ({ name: `server-${i}`, enabled: i !== 2, source: "global" })), skills: Array.from({ length: 6 }, (_, i) => ({ name: `skill-${i}`, path: `/tmp/skills/${i}/SKILL.md`, loaded: i === 0, source: "project" })), @@ -46,7 +48,7 @@ function task(i: number): BackgroundTask { test("quiet session rail merges usage into context and hides empty shelves", () => { const { sidebar } = fixture(); const lines = plain(sidebar.render(80)); - for (const label of ["Session session- · PID 8421", "sonnet-4.6", "16%", "31.6k / 200k · $0.12 · ~82 t/s", "61.4k In", "876 Out", "Cached 48k", "Uncached 7.3k", "MCP · 6 Enabled", "Skills · 1 Loaded", "Prompts · 6"]) + for (const label of ["Working · turn 2", "session-", "sonnet-4.6", "16%", "31.6k/200k", "SPEED", "CACHE", "92% hit", "spent $0.12", "MCP · 6 Enabled", "Skills · 1 Loaded", "Prompts · 6"]) assert(lines.some(line => line.includes(label)), label); for (const label of ["Stats", "Tokens · branch", "Commands ·", "Tasks", "Preview", "no selection", "/run-0", "prompt-0"]) assert(!lines.some(line => line.includes(label)), label); @@ -61,16 +63,14 @@ test("session identity keeps the ID while a separate title copies the full name" sidebar.setSession({ ...session, id, name }); sidebar.setActions({ copy: (value) => copied.push(value), openFile() {} }); const lines = plain(sidebar.render(40)); - assert.equal(lines[1], name, "title is the first content row"); - assert.equal(lines[2], "Session 01234567 · PID 8421", "identity follows the title"); - sidebar.handleMouse(mouse(row(sidebar, "Session 01234567"))); - sidebar.handleMouse(mouse(row(sidebar, name))); + assert(lines[2]!.startsWith(name) && lines[2]!.endsWith("01234567"), "title left, short ID right, on one row"); + sidebar.handleMouse(mouse(2, { x: 37 })); + sidebar.handleMouse(mouse(2)); assert.deepEqual(copied, [id, name]); assert.ok(sidebar.sessionDetails().startsWith(`Session ${id} · PID 8421\n`)); assert.match(sidebar.sessionDetails(), /Title: Slate 的会话标题/); sidebar.setSession({ ...session, id: "" }); - assert.equal(plain(sidebar.render(40))[1], "", "unnamed sessions retain the title spacer"); - assert.equal(plain(sidebar.render(40))[2], "Session — · PID 8421"); + assert.match(plain(sidebar.render(40))[2]!, /^Session\s+—$/, "unnamed sessions fall back to a Session heading"); assert.match(sidebar.sessionDetails(), /Title: —/); }); @@ -82,24 +82,24 @@ test("long titles stay bounded, copy without ellipsis, and refresh on same-sessi sidebar.setActions({ copy: value => copied.push(value), openFile() {} }); sidebar.setSession({ ...session, name: `\x1b[31m${name}\x1b[0m\n` }); const before = sidebar.render(28); - const title = plain(before)[1]!; - assert.match(title, /…$/); + const title = plain(before)[2]!; + assert.match(title, /…/); assert(before.every(line => visibleWidth(line) <= 28)); assert(!before.some(line => line.includes("\x1b[31m") || line.includes("\n")), "untrusted title styling and line breaks are removed"); - sidebar.handleMouse(mouse(1, { width: 28 })); + sidebar.handleMouse(mouse(2, { width: 28 })); assert.deepEqual(copied, [name], "copy uses the complete sanitized title, not its painted ellipsis"); assert(sidebar.sessionDetails().includes(`Title: ${name}\n`)); sidebar.setSession({ ...session, name: "改名后的会话" }); - sidebar.handleMouse(mouse(1, { width: 28 })); + sidebar.handleMouse(mouse(2, { width: 28 })); assert.deepEqual(copied, [name, "改名后的会话"], "a click before repaint never copies the previous title"); const after = sidebar.render(28); assert.notEqual(after, before, "renaming invalidates cached rows even with the same clock and ID"); - assert.equal(plain(after)[1], "改名后的会话"); + assert(plain(after)[2]!.startsWith("改名后的会话")); sidebar.setSession({ ...session, name: " \n\x1b[2J" }); - sidebar.handleMouse(mouse(1, { width: 28 })); + sidebar.handleMouse(mouse(2, { width: 28 })); assert.deepEqual(copied, [name, "改名后的会话"], "clearing a title disables copying before repaint"); - assert.equal(plain(sidebar.render(28))[1], ""); - assert.equal(sidebar.handleMouse(mouse(1, { width: 28 })), undefined, "an empty title has no stale copy hit"); + assert.match(plain(sidebar.render(28))[2]!, /^Session/); + assert.equal(sidebar.handleMouse(mouse(2, { width: 28 })), undefined, "an empty title has no stale copy hit"); assert.deepEqual(copied, [name, "改名后的会话"]); }); @@ -117,19 +117,18 @@ test("top title uses bold theme accent and follows theme changes independently o sidebar.setActions({ copy: value => copied.push(value), openFile() {} }); for (const width of [8, 28, 40, 80]) { const lines = sidebar.render(width); - assert.match(lines[1]!, /\x1b\[36m/, "title uses accent rather than body text or heading color"); - assert.match(lines[1]!, /\x1b\[1m/, "title is bold"); - assert.match(lines[2]!, /\x1b\[33m/, "Session ID retains its heading color"); + assert.match(lines[2]!, /\x1b\[36m/, "title uses accent rather than body text or heading color"); + assert.match(lines[2]!, /\x1b\[1m/, "title is bold"); assert(lines.every(line => visibleWidth(line) <= width)); } const before = sidebar.render(40); current = titleTheme(35); const after = sidebar.render(40); assert.notEqual(after, before, "theme changes refresh the cached title"); - assert.match(after[1]!, /\x1b\[35m/); - assert.doesNotMatch(after[1]!, /\x1b\[36m/); - assert.match(after[1]!, /\x1b\[1m/); - sidebar.handleMouse(mouse(1)); + assert.match(after[2]!, /\x1b\[35m/); + assert.doesNotMatch(after[2]!, /\x1b\[36m/); + assert.match(after[2]!, /\x1b\[1m/); + sidebar.handleMouse(mouse(2)); assert.deepEqual(copied, [name], "copy contains no styling"); }); @@ -151,41 +150,39 @@ test("all sizes allocate exact bounded rows, including zero, Unicode, and tiny t } }); -test("usage is a single stable label/value lane; full accounting stays in details", () => { +test("speed and cache replace the usage lane; full accounting stays in details", () => { const { sidebar } = fixture(); for (const width of [18, 28, 40, 80]) { const text = plain(sidebar.render(width)).join("\n"); - assert(text.includes("PID 8421")); - if (width >= 28) for (const value of ["61.4k", "876", "48k", "7.3k", "$0.12"]) assert(text.includes(value), value); - if (width >= 40) assert(text.includes("~82 t/s")); // Narrow rails truncate the merged occupancy tail first. + assert(text.includes("CACHE") && text.includes("SPEED")); + if (width >= 28) for (const value of ["108k", "$0.12", "92%"]) assert(text.includes(value), value); + assert(!/\bCached\b|Uncached|\bPID\b/.test(text), "old usage rows are gone"); } assert.match(sidebar.sessionDetails(), /Cache read: 48k · Cache write: 6.1k/); assert.match(sidebar.sessionDetails(), /~82 tokens\/sec/); + assert.match(sidebar.sessionDetails(), /PID 8421/); + assert.match(sidebar.sessionDetails(), /Speed & cache\n.*end-to-end: output tokens ÷ request duration/); + assert.match(sidebar.sessionDetails(), /Cache hit % = cache read ÷ \(uncached \+ cache read \+ cache write\)/); }); -test("title precedes the session identity and the 11-row header matches its slots", () => { +test("header height follows the terminal tier and its divider closes the header", () => { const { sidebar } = fixture(); sidebar.setSession({ ...session, name: "Slate session title" }); - assert.equal(sessionSidebarSlots(60, 0, false).header, 11); - assert.equal(sessionSidebarSlots(30, 0, false).header, 11); - assert.equal(sessionSidebarSlots(29, 0, false).header, 4, "compact header also releases the removed rows"); + for (const [rows, header] of [[60, 22], [44, 22], [43, 14], [30, 14], [29, 6], [20, 6], [19, 4]] as const) + assert.equal(sessionSidebarSlots(rows, 0, false).header, header, `rows ${rows}`); const lines = plain(sidebar.render(40)); assert.match(lines[0]!, /^┌─+┐$/, "top bar"); assert.match(lines.at(-1)!, /^└─+┘$/, "bottom bar"); const hairline = lines.findIndex((line, i) => i > 0 && i < lines.length - 1 && /^├─+┤$/.test(line)); - assert.equal(hairline, 11, "hairline closes an 11-row header under the top bar"); - assert.equal(lines[1], "Slate session title"); - assert.equal(lines[2], "Session session- · PID 8421"); - assert(/^Context [━─]+ │ 16%$/.test(lines[5]!), "single context meter row"); - assert(lines[6]!.includes("31.6k / 200k · $0.12 · ~82 t/s"), "merged occupancy line"); - assert(lines[8]!.includes("61.4k In") && lines[8]!.includes("Cached 48k")); - assert(lines[8]!.indexOf("Cached 48k") < lines[8]!.indexOf("61.4k In"), "Cached lanes left, In right with value first"); - assert(lines[9]!.includes("876 Out") && lines[9]!.includes("Uncached 7.3k")); - assert(lines[9]!.indexOf("Uncached 7.3k") < lines[9]!.indexOf("876 Out"), "Uncached lanes left, Out right with value first"); + assert.equal(hairline, 22, "hairline closes a 22-row header under the top bar"); + assert.match(lines[1]!, /^○ Idle|^● Working/); + assert(lines[2]!.startsWith("Slate session title") && lines[2]!.endsWith("session-")); + assert(lines[5]!.startsWith("CONTEXT") && lines[5]!.includes("16%") && lines[5]!.includes("31.6k/200k")); + assert(/^[━─]+$/.test(lines[6]!), "single full-width context bar"); }); test("context meter fills the rail with a thin track and degrades gracefully when narrow", () => { - const { sidebar } = fixture(); + const { sidebar } = fixture(24); const meter = (width: number) => { const line = plain(sidebar.render(width)).find(line => line.startsWith("Context") || line.endsWith("%")); assert(line, `meter at width ${width}`); assert.doesNotMatch(line, /[█░]/, "meter avoids block glyphs"); return line; @@ -212,28 +209,30 @@ test("context meter fills the rail with a thin track and degrades gracefully whe test("context meter fill follows the theme accent and shifts to the warning tone at 80% and above", () => { const codes: Record = { muted: 90, dim: 2, accent: 36, warning: 33, text: 37 }; const toneTheme = { fg: (tone: string, text: string) => `\x1b[${codes[tone] ?? 0}m${text}\x1b[0m`, bold: (text: string) => text } as Theme; - const { sidebar } = fixture(); - sidebar.setThemeProvider(() => toneTheme); sidebar.invalidate(); - const meterLine = () => sidebar.render(40).find(line => stripAnsi(line).includes("Context"))!; - for (const [percent, code] of [[0, 36], [79, 36], [80, 33], [100, 33]] as const) { - sidebar.setSession({ ...session, percent }); sidebar.invalidate(); - const line = meterLine(); - const fill = line.match(/━+/)?.[0] ?? ""; - if (fill) assert(line.includes(`\x1b[${code}m${fill}\x1b[0m`), `${percent}% fills with code ${code}`); - assert(line.includes("\x1b[2m"), "track and separator stay dim"); + for (const rows of [24, 60]) { + const { sidebar } = fixture(rows); + sidebar.setThemeProvider(() => toneTheme); sidebar.invalidate(); + const meterLine = () => sidebar.render(40).find(line => /^│ ?(Context )?[━─]{4}/.test(stripAnsi(line)))!; + for (const [percent, code] of [[0, 36], [79, 36], [80, 33], [100, 33]] as const) { + sidebar.setSession({ ...session, percent }); sidebar.invalidate(); + const line = meterLine(); + const fill = line.match(/━+/)?.[0] ?? ""; + if (fill) assert(line.includes(`\x1b[${code}m${fill}\x1b[0m`), `${rows} rows: ${percent}% fills with code ${code}`); + assert(line.includes("\x1b[2m"), "track stays dim"); + } + sidebar.setSession({ ...session, percent: null }); sidebar.invalidate(); + assert(!/━/.test(stripAnsi(meterLine())), "null percent fills nothing"); } - sidebar.setSession({ ...session, percent: null }); sidebar.invalidate(); - assert(!/━/.test(stripAnsi(meterLine())), "null percent fills nothing"); }); -test("occupancy and stat rows keep the branch usage inspect action; nulls render as dashes", () => { +test("context rows keep the branch usage inspect action; nulls render as dashes", () => { const { sidebar } = fixture(); const inspected: string[] = []; sidebar.setActions({ copy() {}, openFile() {}, inspect: title => inspected.push(title) }); sidebar.setSession({ ...session, estimated: true, usage: { input: null, output: null, total: null, cacheRead: null, cacheWrite: null, cost: null } }); - sidebar.handleMouse(mouse(row(sidebar, "~31.6k / 200k · — · ~82 t/s"))); - sidebar.handleMouse(mouse(row(sidebar, "— In"))); - sidebar.handleMouse(mouse(row(sidebar, "Uncached —"))); - assert.deepEqual(inspected, ["Branch usage", "Branch usage", "Branch usage"]); + const heading = row(sidebar, "~31.6k/200k"); + sidebar.handleMouse(mouse(heading)); + sidebar.handleMouse(mouse(heading + 1)); + assert.deepEqual(inspected, ["Branch usage", "Branch usage"]); }); test("a 24-row terminal still renders an image body; a very short one prioritizes tasks", () => { @@ -421,7 +420,7 @@ test("unknown values and invalid MCP config remain explicit even when folded", ( sidebar.setSession({ ...session, percent: null, tokens: null, contextWindow: null, usage: { input: null, output: null, total: null, cacheRead: null, cacheWrite: null, cost: null } }); sidebar.setResources({ ...resources, mcpError: "MCP config unreadable" }); const lines = plain(sidebar.render(80)); - assert(lines.some(line => line.includes("—%"))); + assert(lines.some(line => /^CONTEXT\s+—\s+—\/—$/.test(line))); assert.match(sidebar.sessionDetails(), /Cache read: —/); assert(lines.some(line => line.includes("MCP · 6 Enabled · 1 Error"))); assert(!lines.some(line => line.includes("MCP config unreadable") || line.includes("config error"))); @@ -443,7 +442,7 @@ test("unknown MCP declarations are neutral when folded or expanded and inspectio assert(expanded.some(line => line.includes("⌄ MCP · —"))); assert(expanded.some(line => line.trim() === "— unknown-server")); sidebar.setThemeProvider(() => ({ fg: (tone: string, text: string) => tone === "warning" ? `\x1b[33m${text}\x1b[0m` : tone === "error" ? `\x1b[31m${text}\x1b[0m` : text, bold: (text: string) => text }) as Theme); - assert(!/\x1b\[(?:33|31)m/.test(sidebar.render(80).join("\n"))); + assert(!/\x1b\[(?:33|31)m/.test(sidebar.render(80).filter(line => /MCP|unknown-server/.test(stripAnsi(line))).join("\n"))); sidebar.handleMouse(mouse(row(sidebar, "unknown-server"))); assert.match(details[0]!, /Slate does not validate MCP/); assert.match(details[0]!, /Use \/mcp/); @@ -493,7 +492,7 @@ test("sidebar closes both rails and joins every horizontal divider at the right const lines = sidebar.render(width).map(stripAnsi); assert.equal(lines[0], "┌" + "─".repeat(width - 2) + "┐"); assert.equal(lines.at(-1), "└" + "─".repeat(width - 2) + "┘"); - assert.equal(lines[11], "├" + "─".repeat(width - 2) + "┤"); + assert.equal(lines[22], "├" + "─".repeat(width - 2) + "┤"); for (const line of lines) { assert.equal(visibleWidth(line), width); assert.match(line, /^[│┌├└]/); @@ -503,3 +502,26 @@ test("sidebar closes both rails and joins every horizontal divider at the right sidebar.setView(image()); for (const line of sidebar.render(40).map(stripAnsi)) assert.match(line, /[│┐┤┘]$/, "preview rows keep the right border"); }); + +test("working status shows the running turn's elapsed time and ticks each second", () => { + const { sidebar, advance } = fixture(); + sidebar.setSession({ ...session, working: true, turnStartedAt: 4000 - 42_000 }); + assert.match(plain(sidebar.render(44))[1]!, /● Working · turn 2\s+0:42$/); + advance(1000); + assert.match(plain(sidebar.render(44))[1]!, /0:43$/); + sidebar.setSession({ ...session, working: false, turnStartedAt: null }); + assert.match(plain(sidebar.render(44))[1]!, /○ Idle · 2 turns\s+last 5s$/); +}); + +test("empty speed and cache sections collapse and give their rows to the resource list", () => { + const { sidebar } = fixture(46); + sidebar.setSession({ ...session, perf: EMPTY_PERF }); + const empty = plain(sidebar.render(44)); + const mcpEmpty = empty.findIndex(line => line.includes("MCP")); + assert(empty.some(line => line.includes("waiting for first response"))); + assert(empty.some(line => line.includes("no requests yet"))); + sidebar.setSession(session); + const full = plain(sidebar.render(44)); + assert.equal(full.findIndex(line => line.includes("MCP")) - mcpEmpty, 8, "6 speed + 2 cache rows are reclaimed"); + assert.equal(empty.length, full.length, "the rail still fills the terminal"); +}); diff --git a/pi-slate/tests/surfaces-install.test.ts b/pi-slate/tests/surfaces-install.test.ts index 57c7d08..431579d 100644 --- a/pi-slate/tests/surfaces-install.test.ts +++ b/pi-slate/tests/surfaces-install.test.ts @@ -488,9 +488,9 @@ test("dashboard uses live branch facts and session-scoped tasks; commands preser await f.emit("session_info_changed"); assert.match(rail(), /Dashboard test/); assert.doesNotMatch(rail(), /Unnamed session|Untitled session/); - assert.ok(rail().includes(`Session ${f.manager.getSessionId().slice(0, 8)} · PID ${process.pid}`)); + assert.ok(rail().includes(f.manager.getSessionId().slice(0, 8))); assert.match(railOf(f).sessionDetails(), /Title: Dashboard test/); - assert.ok(railOf(f).sessionDetails().startsWith(`Session ${f.manager.getSessionId()} · PID ${process.pid}`)); assert.match(rail(), /450\s+In/); assert.match(rail(), /Uncached\s+100/); assert.match(rail(), /\$0.35/); + assert.ok(railOf(f).sessionDetails().startsWith(`Session ${f.manager.getSessionId()} · PID ${process.pid}`)); assert.match(rail(), /new 100/); assert.match(rail(), /\$0\.35/); assert(!/Summary|Activity Preview|Context\s*\n/.test(rail())); f.extraCommands.push({ name: "skill:review", source: "skill", sourceInfo: { path: "/skills/review/SKILL.md", scope: "user" } }); await f.emit("message_end", { message: { role: "toolResult", toolName: "codemode", toolCallId: "outer", content: [], isError: false, nestedCalls: { calls: [{ id: "nested-read", name: "read", arguments: { path: "/skills/review/SKILL.md" }, status: "ok" }], complete: true } } }); @@ -531,7 +531,7 @@ test("session titles restore, repaint on rename/clear events, and clear when swi assert(rows().some(row => row.includes("手动固定的标题"))); f.manager.appendSessionInfo(""); await f.emit("session_info_changed", { name: "" }); - assert.match(rows()[1]!, /^│\s+│$/, "clearing the stored name restores the blank title row"); + assert.match(rows()[2]!, /^│ Session/, "clearing the stored name restores the Session heading"); assert.match(sidebar.sessionDetails(), /Title: —/); const restored = SessionManager.inMemory(f.ctx.cwd); restored.appendSessionInfo("已恢复的标题"); From c20256d24d423d609b2d265e0f49772f534cb1d6 Mon Sep 17 00:00:00 2001 From: GaganSD Date: Thu, 12 Nov 2026 08:52:36 +0530 Subject: [PATCH 02/15] fix(slate): give sidebar sections one consistent layout CONTEXT, SPEED and CACHE now share a heading row (label left, key figure right), one full-width visual row using the same bar glyphs, and labelled detail rows. Speed shows only exact per-response figures and the turn average uses the same eligible responses as the peak. Short terminals keep the CONTEXT heading row instead of the legacy meter. --- pi-slate/extensions/pi-slate/perf-graphics.ts | 228 +++++++++--------- pi-slate/extensions/pi-slate/perf-stats.ts | 26 +- .../extensions/pi-slate/sidebar-layout.ts | 2 +- pi-slate/extensions/pi-slate/sidebar.ts | 41 +--- pi-slate/tests/perf-graphics.test.ts | 180 ++++++++------ pi-slate/tests/perf-stats.test.ts | 3 + pi-slate/tests/quiet-workbench.test.ts | 25 +- pi-slate/tests/sidebar-preview.test.ts | 36 ++- pi-slate/tests/surfaces-install.test.ts | 2 +- 9 files changed, 271 insertions(+), 272 deletions(-) diff --git a/pi-slate/extensions/pi-slate/perf-graphics.ts b/pi-slate/extensions/pi-slate/perf-graphics.ts index 375d2b6..8188bd8 100644 --- a/pi-slate/extensions/pi-slate/perf-graphics.ts +++ b/pi-slate/extensions/pi-slate/perf-graphics.ts @@ -66,8 +66,8 @@ const DOT = [[0x01, 0x08], [0x02, 0x10], [0x04, 0x20], [0x40, 0x80]] as const; /** * Zero-based braille bar graph, `rows` cells tall and `width` cells wide (2 columns per cell). - * Right-aligned: the newest value is the right-most column. Columns without data show baseline dots. - * A positive value always draws at least the bottom dot. + * Left-aligned: history fills in from the left; once there are more values than columns the + * newest `2 × width` are shown. Unused columns are blank. A positive value draws at least one dot. */ export function brailleBars(values: readonly number[], width: number, rows: number): string[] { const w = Math.max(0, Math.floor(width)); @@ -75,13 +75,11 @@ export function brailleBars(values: readonly number[], width: number, rows: numb if (r === 0) return []; if (w === 0) return Array.from({ length: r }, () => ""); const columns = w * 2; - const shown = values.slice(-columns); - const offset = columns - shown.length; - const clean = shown.map(v => nonneg(v) ? v : 0); - const max = clean.reduce((a, b) => Math.max(a, b), 0); + const shown = values.slice(-columns).map(v => nonneg(v) ? v : 0); + const max = shown.reduce((a, b) => Math.max(a, b), 0); const total = r * 4; const heights = Array.from({ length: columns }, (_, c) => { - const v = c < offset ? 0 : clean[c - offset]!; + const v = c < shown.length ? shown[c]! : 0; return v > 0 && max > 0 ? Math.max(1, Math.min(total, Math.round(v / max * total))) : 0; }); const lines: string[] = []; @@ -90,9 +88,7 @@ export function brailleBars(values: readonly number[], width: number, rows: numb for (let cell = 0; cell < w; cell++) { let code = 0; for (let k = 0; k < 2; k++) for (let d = 0; d < 4; d++) { - const level = (r - row) * 4 - d; - const h = heights[cell * 2 + k]!; - if (level <= h || (level === 1 && h === 0)) code |= DOT[d]![k]!; + if ((r - row) * 4 - d <= heights[cell * 2 + k]!) code |= DOT[d]![k]!; } s += code === 0 ? " " : String.fromCharCode(0x2800 + code); } @@ -102,14 +98,14 @@ export function brailleBars(values: readonly number[], width: number, rows: numb } const BLOCKS = "▁▂▃▄▅▆▇█"; -/** One-row zero-based sparkline of the newest `width` values, right-aligned; gaps show the baseline. */ +/** One-row zero-based sparkline, left-aligned, padded with spaces; shows the newest `width` values. */ export function sparkBlocks(values: readonly number[], width: number): string { const w = Math.max(0, Math.floor(width)); if (w === 0) return ""; const shown = values.slice(-w).map(v => nonneg(v) ? v : 0); const max = shown.reduce((a, b) => Math.max(a, b), 0); const body = shown.map(v => v > 0 && max > 0 ? BLOCKS[Math.max(0, Math.min(7, Math.round(v / max * 7)))]! : BLOCKS[0]!).join(""); - return BLOCKS[0]!.repeat(w - shown.length) + body; + return body + " ".repeat(w - shown.length); } /** @@ -145,137 +141,131 @@ export function formatIdle(ms: number): string { } // ---- row composition ------------------------------------------------------------------------- +// One grammar for CONTEXT, SPEED and CACHE: heading row (label left, key figure right), one +// full-width visual row, then `label value · label value` detail rows. Padding is always spaces. export type PerfInput = { perf: SidebarPerf; cost: number | null; now: number; inner: number; tier: SidebarTier } & PerfPaint; +type Seg = readonly [Tone, string]; + +const fit = (lines: string[], width: number): string[] => lines.map(l => truncateToWidth(l, width, "…")); +const paintSegs = (i: PerfPaint, segs: readonly Seg[]): string => segs.map(([t, x]) => i.paint(t, x)).join(""); +const segWidth = (segs: readonly Seg[]): number => segs.reduce((n, [, x]) => n + visibleWidth(x), 0); -/** Left text wins: headings never get squeezed out by a long right-hand status. */ -function pairLine(left: string, right: string, width: number): string { - if (width <= 0) return ""; - const l = truncateToWidth(left, width, "…"); - const r = truncateToWidth(right, Math.max(0, width - visibleWidth(l) - 1), "…"); - return `${l}${" ".repeat(Math.max(0, width - visibleWidth(l) - visibleWidth(r)))}${r}`; +/** Heading row: bold label left, longest right-hand variant that still leaves the label room. */ +function headingRow(i: PerfInput, label: string, variants: ReadonlyArray): string { + const left = i.heading(label); + const room = i.inner - visibleWidth(label) - 1; + const right = variants.find(v => segWidth(v) <= room) ?? []; + const gap = Math.max(1, i.inner - visibleWidth(label) - segWidth(right)); + return truncateToWidth(left + (right.length ? " ".repeat(gap) + paintSegs(i, right) : ""), i.inner, "…"); } -const fit = (lines: string[], count: number, width: number): string[] => { - const out = lines.slice(0, count).map(l => truncateToWidth(l, width, "…")); - while (out.length < count) out.push(""); - return out; -}; -type Headline = { value: number; estimate: boolean } | null; -function headlineOf(perf: SidebarPerf): Headline { - if (perf.live.streaming && nonneg(perf.live.rate)) return { value: perf.live.rate, estimate: true }; - if (nonneg(perf.lastRate)) return { value: perf.lastRate, estimate: false }; - return null; +/** Detail row: `label value · label value`, dropping trailing pairs until it fits. */ +function detailRow(i: PerfInput, pairs: ReadonlyArray): string { + const render = (n: number): string => pairs.slice(0, n).map(([l, v]) => i.paint("dim", l + " ") + i.paint("text", v)).join(i.paint("dim", " · ")); + for (let n = pairs.length; n >= 1; n--) { + const text = render(n); + if (visibleWidth(text) <= i.inner) return text; + } + return truncateToWidth(render(1), i.inner, "…"); +} +const noteRow = (i: PerfInput, text: string): string => truncateToWidth(i.paint("dim", text), i.inner, "…"); +const baseline = (i: PerfInput): string => i.paint("dim", "─".repeat(Math.max(0, i.inner))); +const DASH: Seg = ["dim", "—"]; + +/** CONTEXT: heading + a single filled/empty bar. */ +export function contextRows(i: PerfInput, c: { percent: number | null; tokens: number | null; window: number | null; estimated: boolean }): string[] { + const percent = c.percent !== null && Number.isFinite(c.percent) ? Math.max(0, Math.min(100, c.percent)) : null; + const tone: Tone = percent !== null && percent >= 80 ? "warning" : "accent"; + const pctSeg: Seg = percent === null ? DASH : [percent >= 80 ? "warning" : "text", `${Math.round(percent)}%`]; + const figures: Seg = ["dim", `${c.estimated ? "~" : ""}${formatCompactTokenCount(c.tokens)}/${formatCompactTokenCount(c.window)}`]; + const filled = percent === null ? 0 : Math.round(percent * i.inner / 100); + return [ + headingRow(i, "CONTEXT", [[pctSeg, ["dim", " "], figures], [pctSeg]]), + i.paint(tone, "━".repeat(filled)) + i.paint("dim", "─".repeat(Math.max(0, i.inner - filled))), + ]; } -export const hasSpeed = (perf: SidebarPerf): boolean => headlineOf(perf) !== null || perf.rates.length > 0 || nonneg(perf.turn?.rate) || nonneg(perf.peak); -const headlineText = (h: Headline): string => h ? `${h.estimate ? "~" : ""}${formatRate(h.value)}` : "—"; -/** Graph tone is steady; only the headline and streaming marker change while live. */ -export function speedRows(i: PerfInput, count: number): string[] { - const { perf, inner, paint, heading } = i; - const h = headlineOf(perf); - const streaming = perf.live.streaming; - const label = heading("SPEED"); +/** Headline is always the exact last response; the live chars÷4 estimate is not shown here. */ +export const hasSpeed = (perf: SidebarPerf): boolean => nonneg(perf.lastRate) || perf.rates.length > 0 || nonneg(perf.turn?.rate) || nonneg(perf.peak); + +export function speedRows(i: PerfInput): string[] { + const { perf, inner, paint } = i; + const streaming: readonly Seg[] = perf.live.streaming ? [["warning", "● streaming"]] : []; if (!hasSpeed(perf)) { - return fit(i.tier === "full" ? [label, paint("dim", perf.requests > 0 ? "no eligible response yet" : "waiting for first response")] - : [label + " " + paint("dim", "waiting for first response")], count, inner); + return [headingRow(i, "SPEED", [[...streaming, ...(streaming.length ? [["text", " "] as Seg] : []), DASH], [DASH]]), + noteRow(i, perf.requests > 0 ? "replies too short to time" : "waiting for first response")]; } - const turnRate = perf.turn?.rate ?? null; - const out = perf.turn && nonneg(perf.turn.output) && perf.turn.output > 0 ? formatCompactTokenCount(perf.turn.output) : "—"; - if (i.tier === "compact") { - const head = label + " " + paint("text", `${streaming && h?.estimate ? "● " : ""}${headlineText(h)} tok/s`); - const room = inner - visibleWidth(head) - 1; - const line = room >= 6 ? `${head} ${paint("accent", sparkBlocks(perf.rates, Math.min(room, 20)))}` : head; - return fit([line, paint("muted", statsLine(turnRate, perf.peak, out, inner))], count, inner); + const rate = nonneg(perf.lastRate) ? perf.lastRate : null; + const value: Seg = rate === null ? DASH : ["text", formatRate(rate)]; + const unit: Seg = ["dim", " tok/s"]; + const out = perf.turn && perf.turn.output > 0 ? formatCompactTokenCount(perf.turn.output) : "—"; + const detail = detailRow(i, [["avg", formatRate(perf.turn?.rate)], ["peak", formatRate(perf.peak)], ["out", out]]); + const gap: Seg = ["text", " "]; + if (i.tier !== "full") { + const lead = streaming.length ? [...streaming, gap] : []; + const visual = perf.rates.length ? paint("accent", sparkBlocks(perf.rates, inner)) : baseline(i); + return [headingRow(i, "SPEED", [[...lead, value, unit], [...lead, value], [value, unit], [value]]), visual, detail]; } - const right = streaming && h?.estimate ? paint("warning", "● streaming") : h ? paint("dim", "last response") : ""; - const rows: string[] = [pairLine(label, right, inner)]; - const digits = `${h?.estimate ? "~" : ""}${formatRate(h?.value)}`; - const unit = " tok/s"; - if (h && bigDigitsWidth(digits) <= inner) { + const right: Seg[][] = [streaming.length ? [...streaming] : [["dim", "last response"]], streaming.length ? [["warning", "●"]] : []]; + const rows = [headingRow(i, "SPEED", right)]; + const digits = rate === null ? "—" : formatRate(rate); + if (rate !== null && bigDigitsWidth(digits) <= inner) { const [a, b, c] = bigDigits(digits) as [string, string, string]; - const withUnit = bigDigitsWidth(digits) + 1 + unit.length <= inner; - rows.push(paint("text", a), paint("text", b) + (withUnit ? " " + paint("dim", unit.trim()) : ""), paint("text", c)); - } else { - rows.push(paint("text", `${digits}`) + paint("dim", unit)); - } - if (inner >= 22) { - for (const g of brailleBars(perf.rates, inner, 2)) rows.push(paint("accent", g)); - const colW = Math.floor(inner / 3); - const cell = (t: string, w: number): string => { const x = truncateToWidth(t, w, "…"); return x + " ".repeat(Math.max(0, w - visibleWidth(x))); }; - const cols = (cells: string[]): string => cells.map((t, k) => k < 2 ? cell(t, colW) : truncateToWidth(t, inner - colW * 2, "…")).join(""); - rows.push(cols(["Turn avg", "Output", "Peak"].map(t => paint("dim", t)))); - rows.push(cols([formatRate(turnRate), out, formatRate(perf.peak)].map(t => paint("text", t)))); - } else { - rows.push(paint("muted", statsLine(turnRate, perf.peak, out, inner))); - } - return fit(rows, count, inner); -} - -function statsLine(avg: number | null, peak: number | null, out: string, inner: number): string { - const long = `avg ${formatRate(avg)} · peak ${formatRate(peak)} · out ${out}`; - return visibleWidth(long) <= inner ? long : `${formatRate(avg)} · ${formatRate(peak)} · ${out}`; + const withUnit = bigDigitsWidth(digits) + 1 + "tok/s".length <= inner; + rows.push(paint("text", a), paint("text", b) + (withUnit ? " " + paint("dim", "tok/s") : ""), paint("text", c)); + } else rows.push(paintSegs(i, [value, unit])); + if (inner >= 22) rows.push(...brailleBars(perf.rates, inner, 2).map(g => paint("accent", g))); + rows.push(detail); + return fit(rows, inner); } const pct = (n: number): string => `${Math.round(Math.max(0, Math.min(1, n)) * 100)}%`; -/** Longest variant that still leaves the CACHE label room; degrades hit label, then countdown. */ -function cacheRight(i: PerfInput): string { - const { perf, paint } = i; - const c = perf.cache; - const sep = paint("dim", " · "); +/** Right-hand key figure of the CACHE heading and the mini row: hit rate then warmth. */ +function cacheSegs(i: PerfInput, full: boolean): Seg[][] { + const { cache: c } = i.perf; const hit = nonneg(c.lastHit) ? pct(c.lastHit) : null; const w = cacheWarmth(c, i.now); - const warm = w.state === "warm" ? { tone: "success" as const, long: `◉ warm ${formatCountdown(w.remainingMs ?? 0)}`, short: `◉ ${formatCountdown(w.remainingMs ?? 0)}` } - : w.state === "cold" ? { tone: "warning" as const, long: "◌ cold", short: "◌ cold" } - : w.idleMs !== null && w.idleMs >= 60_000 ? { tone: "dim" as const, long: `idle ${formatIdle(w.idleMs)}`, short: `idle ${formatIdle(w.idleMs)}` } - : null; - const make = (hitText: string | null, warmText: string | null): string => [hitText && paint("text", hitText), warmText && warm && paint(warm.tone, warmText)].filter(Boolean).join(sep); - const variants = [make(hit && `${hit} hit`, warm?.long ?? null), make(hit, warm?.short ?? null), make(hit && `${hit} hit`, null), make(hit, null)]; - const room = i.inner - visibleWidth("CACHE") - 1; - return variants.find(v => visibleWidth(v) <= room) ?? variants[variants.length - 1]!; -} - -function tokenSummary(c: SidebarPerf["cache"], inner: number): string { - const f = formatCompactTokenCount; - const long = `read ${f(c.read)} · write ${f(c.write)} · new ${f(c.uncached)}`; - return visibleWidth(long) <= inner ? long : `r ${f(c.read)} · w ${f(c.write)} · n ${f(c.uncached)}`; + const warm: Seg | null = w.state === "warm" ? ["success", full ? `◉ ${formatCountdown(w.remainingMs ?? 0)}` : `warm ${formatCountdown(w.remainingMs ?? 0)}`] + : w.state === "cold" ? ["warning", "cold"] + : w.idleMs !== null && w.idleMs >= 60_000 ? ["dim", `idle ${formatIdle(w.idleMs)}`] : null; + const sep: Seg = ["dim", " · "]; + const hitSegs = (long: boolean): Seg[] => hit === null ? [] : long ? [["text", hit], ["dim", " hit"]] : [["text", hit]]; + const join = (a: Seg[], b: Seg | null): Seg[] => b ? (a.length ? [...a, sep, b] : [b]) : a; + return [join(hitSegs(true), warm), join(hitSegs(false), warm), hitSegs(true), hitSegs(false)]; } -export function cacheRows(i: PerfInput, count: number): string[] { - const { perf, inner, paint, heading } = i; +export function cacheRows(i: PerfInput): string[] { + const { perf, inner, paint } = i; const c = perf.cache; - const label = heading("CACHE"); - if (!c.seen && perf.requests === 0) return fit([label, paint("dim", "no requests yet")], count, inner); - if (!c.seen) return fit([label, paint("dim", "no cache reads reported")], count, inner); - const head = pairLine(label, cacheRight(i), inner); - const spent = `spent ${sidebarCost(i.cost)}`; - const saved = nonneg(c.saved) ? ` · saved ~${sidebarCost(c.saved)}` : ""; - if (i.tier === "compact") { - const candidates = [`${tokenSummary(c, inner)} · ${sidebarCost(i.cost)}`, tokenSummary(c, inner), spent + saved, spent]; - const detail = candidates.find(t => visibleWidth(t) <= inner) ?? candidates[candidates.length - 1]!; - return fit([head, paint("muted", detail)], count, inner); - } + if (!c.seen) return [headingRow(i, "CACHE", [[DASH]]), noteRow(i, perf.requests === 0 ? "no requests yet" : "no cache reads reported")]; const parts = [c.read, c.write, c.uncached]; const total = parts.reduce((a, b) => a + (nonneg(b) ? b : 0), 0); - const bar = total > 0 ? (() => { + const bar = (() => { + if (total <= 0) return baseline(i); const [r, w, u] = stackedBar(parts.map(p => p ?? 0), inner) as [number, number, number]; - return paint("success", "█".repeat(r)) + paint("warning", "▓".repeat(w)) + paint("dim", "░".repeat(u)); - })() : paint("dim", "—"); - return fit([head, bar, paint("muted", tokenSummary(c, inner)), paint("muted", spent) + (saved ? paint("muted", saved) : "")], count, inner); + return paint("success", "━".repeat(r)) + paint("warning", "━".repeat(w)) + paint("muted", "━".repeat(u)); + })(); + const f = formatCompactTokenCount; + const spent: [string, string] = ["spent", sidebarCost(i.cost)]; + const tokens: Array<[string, string]> = [["read", f(c.read)], ["write", f(c.write)], ["new", f(c.uncached)]]; + const rows = [headingRow(i, "CACHE", cacheSegs(i, true)), bar]; + if (i.tier === "full") { + rows.push(detailRow(i, tokens), detailRow(i, nonneg(c.saved) ? [spent, ["saved", `~${sidebarCost(c.saved)}`]] : [spent])); + } else rows.push(detailRow(i, [...tokens, spent])); + return fit(rows, inner); } -/** One row for short terminals: speed, hit rate, and cache countdown. */ +/** One row for short terminals: `23.5 tok/s · 62% hit · idle 1m`, shedding trailing parts to fit. */ export function combinedRow(i: PerfInput): string { - const { perf, paint, inner } = i; - if (perf.requests === 0 && !perf.cache.seen) return truncateToWidth(paint("dim", "no requests yet"), inner, "…"); - const h = headlineOf(perf); - const parts = [paint("text", `↯${headlineText(h)} t/s`)]; - const c = perf.cache; - if (c.seen && nonneg(c.lastHit)) { - const w = cacheWarmth(c, i.now); - const text = `${w.state === "warm" ? "◉" : "◌"}${pct(c.lastHit)}${w.state === "warm" ? ` ${formatCountdown(w.remainingMs ?? 0)}` : w.state === "cold" ? " cold" : ""}`; - parts.push(paint(w.state === "warm" ? "success" : w.state === "cold" ? "warning" : "dim", text)); - } - return truncateToWidth(parts.join(" "), inner, "…"); + const { perf } = i; + if (perf.requests === 0 && !perf.cache.seen) return noteRow(i, "no requests yet"); + const speed: Seg[] = nonneg(perf.lastRate) ? [["text", formatRate(perf.lastRate)], ["dim", " tok/s"]] : [DASH]; + const cache = perf.cache.seen ? cacheSegs(i, false) : [[]]; + const sep: Seg = ["dim", " · "]; + const variants = cache.map(c => c.length ? [...speed, sep, ...c] : speed); + variants.push(speed); + const pick = variants.find(v => segWidth(v) <= i.inner) ?? speed; + return truncateToWidth(paintSegs(i, pick), i.inner, "…"); } diff --git a/pi-slate/extensions/pi-slate/perf-stats.ts b/pi-slate/extensions/pi-slate/perf-stats.ts index 9af9857..ab9f6d1 100644 --- a/pi-slate/extensions/pi-slate/perf-stats.ts +++ b/pi-slate/extensions/pi-slate/perf-stats.ts @@ -9,12 +9,13 @@ import type { SessionEntry } from "@earendil-works/pi-coding-agent"; * `durationMs` (request start → response end, monotonic). * - A request's speed is end-to-end: output tokens ÷ (durationMs / 1000). It includes * time to first token and hidden reasoning, both of which are real waiting time. - * - The live streaming rate is an estimate (visible chars ÷ 4) and must be labelled `~`. + * - The live streaming rate is an estimate (visible chars ÷ 4) and must be labelled `~`; the rail no + * longer shows it (the composer's working message does). * - Anything unknowable is `null`, never 0. The renderer shows `—` or omits the item. */ -/** Requests below either bound are latency-dominated; they count toward totals and the - * turn average but never toward the graph, the peak, or "last response". */ +/** Requests below either bound are latency-dominated; they count toward totals and the turn's + * output, but never toward the graph, the peak, the turn average, or "last response". */ export const PERF_MIN_OUTPUT_TOKENS = 32; export const PERF_MIN_DURATION_MS = 300; /** Bounded history so very long sessions cost constant memory in the rail. */ @@ -23,11 +24,12 @@ export const PERF_MAX_RATES = 256; export type SidebarTurnPerf = { /** Assistant requests since the last user message on the branch (the current or last turn). */ requests: number; - /** Exact output tokens of those requests. */ + /** Exact output tokens of all those requests (including tiny ones). */ output: number; - /** Sum of their durationMs. */ + /** Sum of all their durationMs. */ durationMs: number; - /** Token-weighted exact rate: output ÷ (durationMs / 1000); null when durationMs is 0. */ + /** Token-weighted exact rate over the ELIGIBLE requests of the turn only (same rule as rates/peak): + * eligible output ÷ eligible seconds; null when none are eligible, so avg/peak/headline are known together. */ rate: number | null; }; @@ -94,15 +96,16 @@ function ratio(numerator: number, denominator: number): number | null { * One O(n) pass over the active branch. * * Turn rule: every timed assistant request after the last user message whose stopReason is not - * error/aborted/deferred counts, regardless of size, because tiny tool-call requests are real - * waiting time in the turn. Speed rows (rates/peak/lastRate) additionally require the minimums. + * error/aborted/deferred counts toward `turn.requests/output/durationMs`. `turn.rate` and the speed + * rows (rates/peak/lastRate) share one eligibility rule: output >= PERF_MIN_OUTPUT_TOKENS and + * duration >= PERF_MIN_DURATION_MS. */ export function branchPerf(entries: readonly SessionEntry[], opts: BranchPerfOptions): SidebarPerf { let requests = 0; let rates: number[] = []; let peak: number | null = null; let lastRate: number | null = null; - let turnRequests = 0; let turnOutput = 0; let turnMs = 0; + let turnRequests = 0; let turnOutput = 0; let turnMs = 0; let turnRateOut = 0; let turnRateMs = 0; const sums = { read: 0, write: 0, uncached: 0 }; const missing = { read: false, write: false, uncached: false }; @@ -121,7 +124,7 @@ export function branchPerf(entries: readonly SessionEntry[], opts: BranchPerfOpt if (entry.type === "message") { const message = obj(entry.message); const role = message?.role; - if (role === "user") { turnRequests = 0; turnOutput = 0; turnMs = 0; continue; } + if (role === "user") { turnRequests = 0; turnOutput = 0; turnMs = 0; turnRateOut = 0; turnRateMs = 0; continue; } if (role === "assistant" || role === "toolResult") { usage = obj(message?.usage); expected = role === "assistant"; @@ -168,6 +171,7 @@ export function branchPerf(entries: readonly SessionEntry[], opts: BranchPerfOpt if (output >= PERF_MIN_OUTPUT_TOKENS && durationMs >= PERF_MIN_DURATION_MS) { const rate = output / (durationMs / 1000); if (!Number.isFinite(rate)) continue; + turnRateOut += output; turnRateMs += durationMs; rates.push(rate); if (rates.length >= PERF_MAX_RATES * 2) rates = rates.slice(-PERF_MAX_RATES); if (peak === null || rate > peak) peak = rate; @@ -193,7 +197,7 @@ export function branchPerf(entries: readonly SessionEntry[], opts: BranchPerfOpt return { requests, rates, peak, lastRate, turn: turnRequests > 0 - ? { requests: turnRequests, output: turnOutput, durationMs: turnMs, rate: turnMs > 0 ? turnOutput / (turnMs / 1000) : null } + ? { requests: turnRequests, output: turnOutput, durationMs: turnMs, rate: turnRateMs > 0 ? turnRateOut / (turnRateMs / 1000) : null } : null, cache: { read, write, uncached, lastHit, sessionHit, diff --git a/pi-slate/extensions/pi-slate/sidebar-layout.ts b/pi-slate/extensions/pi-slate/sidebar-layout.ts index e8440ef..6587c98 100644 --- a/pi-slate/extensions/pi-slate/sidebar-layout.ts +++ b/pi-slate/extensions/pi-slate/sidebar-layout.ts @@ -10,7 +10,7 @@ export function sidebarTier(rows: number): SidebarTier { return r >= SIDEBAR_FULL_ROWS ? "full" : r >= SIDEBAR_COMPACT_ROWS ? "compact" : r >= SIDEBAR_MINI_ROWS ? "mini" : "micro"; } /** Header rows per tier, including the closing divider. Painting and hit testing both use this. */ -export const SIDEBAR_HEADER_ROWS: Record = { full: 22, compact: 14, mini: 6, micro: 4 }; +export const SIDEBAR_HEADER_ROWS: Record = { full: 21, compact: 16, mini: 6, micro: 4 }; /** Allocate once for both painting and hit testing. Never depend on composer height. */ export function sessionSidebarSlots(height: number, taskCount: number, hasImage: boolean): SidebarSlots { diff --git a/pi-slate/extensions/pi-slate/sidebar.ts b/pi-slate/extensions/pi-slate/sidebar.ts index 0afe2cd..a749664 100644 --- a/pi-slate/extensions/pi-slate/sidebar.ts +++ b/pi-slate/extensions/pi-slate/sidebar.ts @@ -8,7 +8,7 @@ import { chromePaint } from "./composer.ts"; import { DEFAULT_SIDEBAR_FOLDS, sidebarText, type SidebarFolds, type SidebarResources, type SidebarSession } from "./sidebar-data.ts"; import type { BackgroundTask } from "./background-tasks.ts"; import { sessionSidebarSlots, sidebarDuration, sidebarListOffset, sidebarTier, sidebarUncached, type SidebarTier } from "./sidebar-layout.ts"; -import { cacheRows, combinedRow, formatCountdown, formatRate, hasSpeed, speedRows, type PerfInput } from "./perf-graphics.ts"; +import { cacheRows, combinedRow, contextRows, formatCountdown, formatRate, speedRows, type PerfInput } from "./perf-graphics.ts"; import { cacheWarmth, EMPTY_PERF } from "./perf-stats.ts"; export const DOUBLE_CLICK_MS = 400; @@ -261,7 +261,6 @@ export class Sidebar implements Component { const s = this.session; const perf = s.perf ?? EMPTY_PERF; const percent = s.percent !== null && Number.isFinite(s.percent) ? s.percent : null; - const tone = percent !== null && percent >= 80 ? "warning" : "accent"; const branchUsage = () => this.actions?.inspect?.("Branch usage", this.sessionDetails()); const name = s.name || ""; const shortId = sidebarText(s.id).slice(0, 8) || "—"; @@ -286,40 +285,18 @@ export class Sidebar implements Component { extra: showId ? [{ x0: width - idWidth, x1: width, action: copyId }] : undefined, }; const model: Row = { text: this.pair(this.paint("text", sidebarText(s.model)), this.paint("dim", sidebarText(s.thinking)), width) }; - const meter = ((): string => { - const pct = percent === null ? "—%" : `${Math.round(percent)}%`; - if (width < visibleWidth(pct) + 3) return this.paint("muted", truncateToWidth(pct, width, "…")); - const suffix = ` │ ${pct}`; - const barWidth = Math.max(0, width - "Context ".length - visibleWidth(suffix)); - const filledCells = percent === null ? 0 : Math.round(Math.max(0, Math.min(100, percent)) * barWidth / 100); - const label = truncateToWidth("Context ", Math.max(0, width - barWidth - visibleWidth(suffix)), "…"); - return this.paint("muted", label) - + (filledCells ? this.paint(tone, "━".repeat(filledCells)) : "") - + this.paint("dim", "─".repeat(barWidth - filledCells) + suffix); - })(); const divider: Row = { text: "", divider: true }; const input = (): PerfInput => ({ perf, cost: s.usage.cost, now: this.now(), inner: width, tier, paint: (t, x) => this.paint(t, x), heading: x => this.heading(x) }); - if (tier === "micro") return [identity, model, { text: meter, action: branchUsage }, divider]; - const combined: Row = { text: combinedRow(input()) }; - if (tier === "mini") return [status, identity, model, { text: meter, action: branchUsage }, combined, divider]; - const context: Row[] = (() => { - const pct = percent === null ? "—" : `${Math.round(percent)}%`; - const figures = `${s.estimated ? "~" : ""}${formatCompactTokenCount(s.tokens)}/${formatCompactTokenCount(s.contextWindow)}`; - const right = this.paint(tone === "warning" ? "warning" : "text", pct) + this.paint("dim", ` ${figures}`); - const filled = percent === null ? 0 : Math.round(Math.max(0, Math.min(100, percent)) * width / 100); - return [ - { text: this.pair(this.heading("CONTEXT"), right, width), action: branchUsage }, - { text: (filled ? this.paint(tone, "━".repeat(filled)) : "") + this.paint("dim", "─".repeat(Math.max(0, width - filled))), action: branchUsage }, - ]; - })(); + const context: Row[] = contextRows(input(), { percent, tokens: s.tokens, window: s.contextWindow, estimated: s.estimated }) + .map(text => ({ text, action: branchUsage })); + // Short terminals keep the same CONTEXT heading row (label left, figures right) without the bar. + if (tier === "micro") return [identity, model, context[0]!, divider]; + if (tier === "mini") return [status, identity, model, context[0]!, { text: combinedRow(input()) }, divider]; const rows = (lines: string[]): Row[] => lines.map(text => ({ text })); - const full = tier === "full"; - // Empty states take only their two rows; render() hands the spare rows to the middle list. - const speedCount = full && hasSpeed(perf) ? 8 : 2; - const cacheCount = full && perf.cache.seen ? 4 : 2; + // Empty states collapse to their own natural height; render() hands spare rows to the middle list. return [status, identity, model, { text: "" }, ...context, { text: "" }, - ...rows(speedRows(input(), speedCount)), { text: "" }, - ...rows(cacheRows(input(), cacheCount)), { text: "" }, divider]; + ...rows(speedRows(input())), { text: "" }, + ...rows(cacheRows(input())), { text: "" }, divider]; } private middle(): Row[] { const enabled = this.resources.mcp.filter(x => x.enabled === true).length; diff --git a/pi-slate/tests/perf-graphics.test.ts b/pi-slate/tests/perf-graphics.test.ts index 9c5432b..9e60edf 100644 --- a/pi-slate/tests/perf-graphics.test.ts +++ b/pi-slate/tests/perf-graphics.test.ts @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; import { visibleWidth, type TUI } from "@earendil-works/pi-tui"; -import { bigDigits, brailleBars, cacheRows, combinedRow, formatCountdown, formatRate, sparkBlocks, speedRows, stackedBar, type PerfInput } from "../extensions/pi-slate/perf-graphics.ts"; +import { bigDigits, brailleBars, cacheRows, combinedRow, contextRows, formatCountdown, formatRate, sparkBlocks, speedRows, stackedBar, type PerfInput } from "../extensions/pi-slate/perf-graphics.ts"; import { EMPTY_PERF, type SidebarPerf } from "../extensions/pi-slate/perf-stats.ts"; import { Sidebar } from "../extensions/pi-slate/sidebar.ts"; import type { SidebarSession } from "../extensions/pi-slate/sidebar-data.ts"; @@ -48,125 +48,167 @@ test("stackedBar sums exactly to width and keeps non-zero parts visible", () => assert.deepEqual(stackedBar([], 5), []); }); -test("brailleBars is zero-based, right-aligned, and always draws a positive value", () => { +test("brailleBars is zero-based, left-aligned with blank padding, and always draws a positive value", () => { assert.deepEqual(brailleBars([], 0, 2), ["", ""]); assert.deepEqual(brailleBars([1, 2], 3, 0), []); const one = brailleBars([5], 4, 2); assert.equal(one.length, 2); assert(one.every(r => r.length === 4)); - assert.equal(one[1]!.slice(0, 3), "⣀⣀⣀", "empty columns show baseline dots"); - assert.equal(one[1]![3], "⣸", "the newest rate fills the right column of the last cell"); - assert.equal(one[0]![3], "⢸"); - assert.equal(one[0]!.slice(0, 3), " "); + assert.deepEqual(one, ["⡇ ", "⡇ "].map(x => x), "one value is the left column of the first cell; no baseline dots"); + assert.deepEqual(brailleBars([], 3, 2), [" ", " "]); const tiny = brailleBars([1000, 0.001], 1, 1); - assert.notEqual(tiny[0], "⣀", "tiny but positive value is still drawn"); - // Zero-based: a flat series is full height, not half height. - assert.deepEqual(brailleBars([7, 7, 7, 7], 2, 1), ["⣿⣿"]); - // Zero-based: 50 vs 100 gives the left column half height (2 of 4 dots); min-max would give 1. - assert.equal(brailleBars([50, 100], 1, 1)[0], "⣼"); + assert.notEqual(tiny[0], " ", "tiny but positive value is still drawn"); + assert.deepEqual(brailleBars([7, 7, 7, 7], 2, 1), ["⣿⣿"], "flat series is full height"); + assert.equal(brailleBars([50, 100], 1, 1)[0], "⣼", "zero-based: 50 vs 100 is half height, not min-max"); const many = brailleBars(Array.from({ length: 500 }, (_, i) => i), 5, 2); assert(many.every(r => r.length === 5), "only the newest 2×width values are used"); + assert.equal(many[1]![4], "⣿", "newest value is the right edge once full"); for (const bad of [[Number.NaN, -3, Infinity], [0, 0]]) assert(brailleBars(bad, 3, 2).every(r => r.length === 3)); }); -test("sparkBlocks scales to the max, right-aligns, and tolerates bad input", () => { +test("sparkBlocks scales to the max, left-aligns, pads with spaces, and tolerates bad input", () => { assert.equal(sparkBlocks([], 0), ""); - assert.equal(sparkBlocks([], 3), "▁▁▁"); - assert.equal(sparkBlocks([1, 8], 4), "▁▁▂█"); + assert.equal(sparkBlocks([], 3), " "); + assert.equal(sparkBlocks([1, 8], 4), "▂█ "); assert.equal(sparkBlocks([4, 8], 2), "▅█"); - assert.equal(sparkBlocks([1, 2, 3, 4], 2).length, 2); + assert.equal(sparkBlocks([1, 2, 3, 4], 2), "▆█", "newest values win when there are more than columns"); assert.equal(sparkBlocks([Number.NaN, -1, 0], 3), "▁▁▁"); assert.equal(sparkBlocks([5], 1), "█"); }); test("tier thresholds are pure and the header slot follows them", () => { assert.deepEqual([60, 44, 43, 30, 29, 20, 19, 0].map(sidebarTier), ["full", "full", "compact", "compact", "mini", "mini", "micro", "micro"]); - for (const rows of [12, 19, 20, 29, 30, 43, 44, 60, 100]) { + for (let rows = 12; rows <= 100; rows++) { const slots = sessionSidebarSlots(rows, 0, false); assert.equal(slots.header, SIDEBAR_HEADER_ROWS[sidebarTier(rows)], `header ${rows}`); assert(slots.middle >= 6, `middle keeps 6 rows at ${rows}`); - assert(sessionSidebarSlots(rows, 4, true).tasks + sessionSidebarSlots(rows, 4, true).image >= 0); } }); -test("empty perf: waiting and no-request lines, no NaN or zero percent", () => { +const SECTIONS = (perf: SidebarPerf, inner = 40, tier: PerfInput["tier"] = "compact", now = 1000, cost: number | null = 0.84) => { + const i = input(perf, inner, tier, now, cost); + return { speed: speedRows(i).map(strip), cache: cacheRows(i).map(strip), combined: strip(combinedRow(i)) }; +}; + +test("empty perf: sections keep the grammar, collapse to two rows, and never print NaN or 0%", () => { for (const tier of ["full", "compact"] as const) { - const lines = [...speedRows(input(EMPTY_PERF, 40, tier), tier === "full" ? 8 : 2), ...cacheRows(input(EMPTY_PERF, 40, tier), tier === "full" ? 4 : 2)].map(strip); - const text = lines.join("\n"); - assert.match(text, /waiting for first response/); assert.match(text, /no requests yet/); - assert.doesNotMatch(text, /NaN|Infinity|-\d|0%|[█▀]/); + const { speed, cache } = SECTIONS(EMPTY_PERF, 40, tier); + assert.equal(speed.length, 2); assert.equal(cache.length, 2); + assert.match(speed[0]!, /^SPEED\s+—$/); assert.equal(speed[1], "waiting for first response"); + assert.match(cache[0]!, /^CACHE\s+—$/); assert.equal(cache[1], "no requests yet"); + assert.doesNotMatch([...speed, ...cache].join("\n"), /NaN|Infinity|-\d|0%|[█▀]/); } - assert.equal(combinedRow(input(EMPTY_PERF)), "no requests yet"); - assert.equal(speedRows(input(EMPTY_PERF, 40, "full"), 8).length, 8); + assert.equal(strip(combinedRow(input(EMPTY_PERF))), "no requests yet"); }); -test("provider that never reports cache shows an explicit note", () => { +test("provider that never reports cache shows an explicit note and no bar", () => { const perf = { ...perfFixture(1000), cache: { ...EMPTY_PERF.cache, seen: false } }; - assert.match(strip(cacheRows(input(perf), 4).join("\n")), /no cache reads reported/); - assert.doesNotMatch(strip(cacheRows(input(perf), 4).join("\n")), /[█▓░]/); + const { cache } = SECTIONS(perf); + assert.equal(cache.length, 2); assert.equal(cache[1], "no cache reads reported"); assert.doesNotMatch(cache.join(""), /━/); +}); + +test("compact SPEED: heading, left-aligned sparkline, labelled detail row; padding is spaces", () => { + const perf: SidebarPerf = { ...perfFixture(1000), rates: [10, 20, 23.5, 15, 18], lastRate: 23.5, peak: 23.5, turn: { requests: 2, output: 214, durationMs: 15_000, rate: 13.9 } }; + const { speed } = SECTIONS(perf); + assert.equal(speed.length, 3); + assert.match(speed[0]!, /^SPEED\s+23\.5 tok\/s$/); + assert.match(speed[1]!, /^[▁-█]{5} +$/); assert.equal(speed[1]!.length, 40); + assert.equal(speed[2], "avg 13.9 · peak 23.5 · out 214"); }); -test("a single rate renders a graph with one column at the right edge", () => { +test("a single rate renders one sparkline cell at the left; no rates draws a dim baseline", () => { const perf: SidebarPerf = { ...EMPTY_PERF, requests: 1, rates: [30], peak: 30, lastRate: 30, turn: { requests: 1, output: 300, durationMs: 10_000, rate: 30 } }; - const rows = speedRows(input(perf, 40), 8).map(strip); - assert.equal(rows.length, 8); - const graph = rows.slice(4, 6); - assert(graph.every(r => visibleWidth(r) === 40)); - assert.match(graph[0]!, /\S$/); assert.match(graph[1]!, /^⣀+/); + assert.match(SECTIONS(perf).speed[1]!, /^█ +$/); + const noRates = { ...perf, rates: [] }; + assert.equal(SECTIONS(noRates).speed[1], "─".repeat(40)); }); -test("streaming shows ~ live estimate; settled shows exact last rate", () => { - const live = { ...perfFixture(1000), live: { streaming: true, rate: 51.25 } }; - const liveText = speedRows(input(live), 8).map(strip); - assert.match(liveText[0]!, /● streaming$/); assert.match(liveText.slice(1, 4).join("\n"), /▄▀▄/, "tilde glyph precedes the digits"); - const settled = speedRows(input(perfFixture(1000)), 8).map(strip); - assert.match(settled[0]!, /last response$/); assert.doesNotMatch(settled.slice(1, 4).join(""), /▄▀▄/); - assert.match(strip(speedRows(input(live, 40, "compact"), 2)[0]!), /● ~51\.3 tok\/s|● ~51\.2 tok\/s/); +test("streaming adds a marker but the headline stays the exact last rate", () => { + const perf = { ...perfFixture(1000), lastRate: 14.6, live: { streaming: true, rate: 999 } }; + const compact = SECTIONS(perf).speed; + assert.match(compact[0]!, /^SPEED\s+● streaming {2}14\.6 tok\/s$/); + assert.doesNotMatch(compact.join("\n"), /~|999/); + const full = SECTIONS(perf, 40, "full").speed; + assert.match(full[0]!, /^SPEED\s+● streaming$/); + assert.match(SECTIONS(perfFixture(1000), 40, "full").speed[0]!, /^SPEED\s+last response$/); + const first = SECTIONS({ ...EMPTY_PERF, live: { streaming: true, rate: 20 } }).speed; + assert.match(first[0]!, /^SPEED\s+● streaming {2}—$/); assert.equal(first[1], "waiting for first response"); }); -test("stats row: nulls become dashes", () => { - const perf: SidebarPerf = { ...perfFixture(1000), peak: null, turn: null }; - const rows = speedRows(input(perf), 8).map(strip); - assert.match(rows[7]!, /^—\s+—\s+—$/); +test("full SPEED: big digits, two braille rows, then the same detail row", () => { + const rows = SECTIONS(perfFixture(1000), 40, "full").speed; + assert.equal(rows.length, 7); + assert.equal(rows[2], " █ ▀▀█ █▀█ tok/s"); + assert.match(rows[4]!, /[⠁-⣿]/); assert.match(rows[5]!, /[⠁-⣿]/); + assert.equal(rows[6], "avg 26.7 · peak 45.0 · out 12k"); + assert(!rows.join("").includes("Turn avg"), "the 3-column table is gone"); }); -test("huge numbers stay inside the width", () => { +test("avg, peak and headline are known together", () => { + const perf: SidebarPerf = { ...perfFixture(1000), peak: null, lastRate: null, rates: [], turn: { requests: 1, output: 10, durationMs: 100, rate: null } }; + const rows = SECTIONS(perf).speed; + assert.equal(rows.length, 2, "no eligible rates: collapsed waiting state"); + assert.equal(rows[1], "replies too short to time"); +}); + +test("huge numbers and tiny widths stay inside the width", () => { const perf: SidebarPerf = { ...perfFixture(1000), lastRate: 12_345, peak: 1e9, rates: [12_345, 1e9], turn: { requests: 1, output: 9e12, durationMs: 1, rate: 1e15 }, cache: { ...perfFixture(1000).cache, read: 1.31e6, write: 1e12, uncached: 1e15, saved: 1.2e6 } }; - for (const inner of [10, 16, 21, 22, 24, 30, 44, 60]) for (const tier of ["full", "compact"] as const) for (const cost of [1.2e6, 1e308, null]) { - const rows = [...speedRows(input(perf, inner, tier, 1000, cost), tier === "full" ? 8 : 2), ...cacheRows(input(perf, inner, tier, 1000, cost), tier === "full" ? 4 : 2), combinedRow(input(perf, inner, tier, 1000, cost))]; - for (const r of rows) { assert(visibleWidth(r) <= inner, `${inner} ${tier}: ${strip(r)}`); assert.doesNotMatch(strip(r), /NaN|Infinity/); } + for (const inner of [1, 4, 10, 16, 21, 22, 24, 30, 44, 60]) for (const tier of ["full", "compact"] as const) for (const cost of [1.2e6, 1e308, null]) { + const i = input({ ...perf, live: { streaming: true, rate: 5 } }, inner, tier, 1000, cost); + for (const r of [...speedRows(i), ...cacheRows(i), combinedRow(i), ...contextRows(i, { percent: 91, tokens: 1e12, window: 1e15, estimated: true })]) { + assert(visibleWidth(r) <= inner, `${inner} ${tier}: ${strip(r)}`); assert.doesNotMatch(strip(r), /NaN|Infinity/); + } } }); -test("width tiers: digits fall back to text, narrow rails drop the graph", () => { +test("width tiers: digits fall back to text; narrow rails drop the graph", () => { const perf = perfFixture(1000); - const narrowDigits = speedRows(input(perf, 12), 8).map(strip); - assert.equal(narrowDigits[1]!.trim(), "14.6 tok/s", "big digits need more than 12 columns"); - const tiny = speedRows(input(perf, 20), 8).map(strip).join("\n"); - assert.doesNotMatch(tiny, /[⣀-⣿]/); assert.match(tiny, /26\.7 · 45\.0 · 12k/); - assert.match(speedRows(input(perf, 40), 8).map(strip).join("\n"), /[⣀-⣿]/); + assert.equal(SECTIONS(perf, 12, "full").speed[1]!.trim(), "14.6 tok/s", "big digits need more than 12 columns"); + const tiny = SECTIONS(perf, 20, "full").speed.join("\n"); + assert.doesNotMatch(tiny, /[⠁-⣿]/); + assert.match(tiny, /avg 26\.7 · peak 45\.0/); + assert.match(SECTIONS(perf, 40, "full").speed.join("\n"), /[⠁-⣿]/); }); -test("warmth: countdown, cold, unknown lifetime and idle hint", () => { +test("CACHE heading: hit, warmth countdown, cold, unknown lifetime and idle hint", () => { const base = perfFixture(1_000_000); - const head = (cache: Partial, now: number) => strip(cacheRows(input({ ...base, cache: { ...base.cache, ...cache } }, 44, "full", now), 4)[0]!); - assert.match(head({}, 1_000_000), /92% hit · ◉ warm 4:41$/); - assert.match(head({}, 1_000_000 + 1000), /warm 4:40$/, "countdown moves with the clock alone"); - assert.match(head({}, 1_000_000 + 400_000), /◌ cold$/); + const head = (cache: Partial, now: number, tier: PerfInput["tier"] = "full") => + strip(cacheRows(input({ ...base, cache: { ...base.cache, ...cache } }, 40, tier, now))[0]!); + assert.match(head({}, 1_000_000), /^CACHE\s+92% hit · ◉ 4:41$/); + assert.match(head({}, 1_000_000 + 1000), /◉ 4:40$/, "countdown moves with the clock alone"); + assert.match(head({}, 1_000_000 + 400_000), /92% hit · cold$/); assert.match(head({ ttlMs: null }, 1_000_000 + 30_000), /^CACHE\s+92% hit$/, "no lifetime and recent: nothing extra"); - assert.match(head({ ttlMs: null, lastActivityAt: 1_000_000 - 4 * 60_000 }, 1_000_000), /idle 4m$/); - assert.match(head({ lastHit: null }, 1_000_000), /^CACHE\s+◉ warm/, "unknown hit is omitted, never 0%"); + assert.match(head({ ttlMs: null, lastActivityAt: 1_000_000 - 62_000 }, 1_000_000, "compact"), /^CACHE\s+92% hit · idle 1m$/); + assert.match(head({ lastHit: null }, 1_000_000), /^CACHE\s+◉ 4:41$/, "unknown hit is omitted, never 0%"); }); -test("cache rows: bar spans the width and money lines handle unknowns", () => { - const rows = cacheRows(input(perfFixture(1000), 44), 4).map(strip); - assert.equal(rows[1]!.length, 44); - assert.match(rows[2]!, /read 1\.3M · write 108k · new 141k/); - assert.equal(rows[3], "spent $0.84 · saved ~$1.92"); - const none = cacheRows(input({ ...perfFixture(1000), cache: { ...perfFixture(1000).cache, saved: null } }, 44, "full", 1000, null), 4).map(strip); +test("CACHE bars use the context glyph in three tones; money rows handle unknowns", () => { + const themed: string[] = []; + const paint = { paint: (t: string, x: string) => { themed.push(`${t}:${x}`); return x; }, heading: (x: string) => x }; + const full = cacheRows({ ...input(perfFixture(1000), 40, "full"), ...paint }).map(strip); + assert.equal(full.length, 4); + assert.equal(full[1], "━".repeat(40)); assert(!/[█▓░]/.test(full.join(""))); + const bar = themed.filter(t => /^(success|warning|muted):━/.test(t)).map(t => t.split(":")[0]); + assert.deepEqual(bar, ["success", "warning", "muted"]); + assert.equal(themed.find(t => t.startsWith("success:━"))!.length - "success:".length + themed.find(t => t.startsWith("warning:━"))!.length - "warning:".length + themed.find(t => t.startsWith("muted:━"))!.length - "muted:".length, 40, "segments sum to the width"); + assert.equal(full[2], "read 1.3M · write 108k · new 141k"); + assert.equal(full[3], "spent $0.84 · saved ~$1.92"); + const none = SECTIONS({ ...perfFixture(1000), cache: { ...perfFixture(1000).cache, saved: null } }, 40, "full", 1000, null).cache; assert.equal(none[3], "spent —"); + const compact = SECTIONS(perfFixture(1000), 48).cache; + assert.equal(compact.length, 3); assert.equal(compact[2], "read 1.3M · write 108k · new 141k · spent $0.84"); + assert.equal(SECTIONS(perfFixture(1000), 40).cache[2], "read 1.3M · write 108k · new 141k", "spent is dropped when it does not fit"); + const zero = SECTIONS({ ...perfFixture(1000), cache: { ...perfFixture(1000).cache, read: 0, write: 0, uncached: 0 } }).cache; + assert.equal(zero[1], "─".repeat(40)); +}); + +test("CONTEXT uses the same grammar", () => { + const i = input(EMPTY_PERF, 40); + const rows = contextRows(i, { percent: 2, tokens: 8100, window: 400_000, estimated: false }).map(strip); + assert.match(rows[0]!, /^CONTEXT\s+2% {2}8\.1k\/400k$/); assert.equal(rows[1], "━" + "─".repeat(39)); + assert.match(strip(contextRows(i, { percent: null, tokens: null, window: null, estimated: true })[0]!), /^CONTEXT\s+— {2}~—\/—$/); }); function sidebarWith(rows: number, perf: SidebarPerf, clock: { now: number }, extra: Partial = {}) { @@ -197,7 +239,7 @@ test("render recomputes the countdown each second without extra timers", () => { assert.equal(s.render(44).map(strip).join("\n"), a); clock.now += 1000; const b = s.render(44).map(strip).join("\n"); - assert.notEqual(a, b); assert.match(a, /warm 4:41/); assert.match(b, /warm 4:40/); + assert.notEqual(a, b); assert.match(a, /◉ 4:41/); assert.match(b, /◉ 4:40/); }); test("every tier and width keeps rows bounded, including live streaming and long sessions", () => { @@ -213,7 +255,7 @@ test("every tier and width keeps rows bounded, including live streaming and long test("mini tier shows the combined speed/cache row; details explain the numbers", () => { const clock = { now: 1_000_000 }; const s = sidebarWith(24, perfFixture(clock.now), clock); - assert.match(s.render(40).map(strip).join("\n"), /↯14\.6 t\/s ◉92% 4:41/); + assert.match(s.render(40).map(strip).join("\n"), /14\.6 tok\/s · 92% hit · warm 4:41/); assert.match(s.sessionDetails(), /Speed & cache/); assert.match(s.sessionDetails(), /300 ms/); }); diff --git a/pi-slate/tests/perf-stats.test.ts b/pi-slate/tests/perf-stats.test.ts index 87e104d..36e861c 100644 --- a/pi-slate/tests/perf-stats.test.ts +++ b/pi-slate/tests/perf-stats.test.ts @@ -40,6 +40,9 @@ test("tiny outputs count in the turn but not in rates or peak", () => { const perf = branchPerf([user(), asst({}, usageOf({ output: 10 })), asst({ durationMs: 100 }, usageOf({ output: 500 })), asst({}, usageOf({ output: 100 }))], opts); assert.deepEqual(perf.rates, [100]); assert.equal(perf.peak, 100); assert.equal(perf.lastRate, 100); assert.equal(perf.turn?.requests, 3); assert.equal(perf.turn?.output, 610); + assert.equal(perf.turn?.rate, 100, "turn average uses the same eligibility as rates and peak"); + const onlyTiny = branchPerf([user(), asst({}, usageOf({ output: 10 }))], opts); + assert.equal(onlyTiny.turn?.output, 10); assert.equal(onlyTiny.turn?.rate, null); assert.equal(onlyTiny.peak, null); }); test("turn average is token weighted, not a mean of rates", () => { diff --git a/pi-slate/tests/quiet-workbench.test.ts b/pi-slate/tests/quiet-workbench.test.ts index ca8fd31..98fea2e 100644 --- a/pi-slate/tests/quiet-workbench.test.ts +++ b/pi-slate/tests/quiet-workbench.test.ts @@ -82,30 +82,19 @@ test("growing usage and money keep a stable label lane and value edge with the r sidebar.dispose(); }); -test("context meter keeps a thin track and dim separator with the real theme", () => { +test("short terminals keep the CONTEXT heading row grammar with the real theme", () => { const sidebar = new Sidebar(() => 10000); sidebar.attach({ terminal: { rows: 24, columns: 140 }, requestRender() {} } as unknown as TUI, theme); - assert.equal(sessionSidebarSlots(24, 0, false).header, 6, "mini tier keeps the one-row context meter"); + assert.equal(sessionSidebarSlots(24, 0, false).header, 6, "mini tier keeps a one-row context summary"); for (const width of [28, 40, 80]) { sidebar.setSession(session); const rows = sidebar.render(width); - const meter = rows.find(row => stripVTControlCharacters(row).includes("Context"))!; - assert(meter, `meter at ${width}`); - assert.match(stripVTControlCharacters(meter), /^│ Context [━─]+ │ 11% │$/, `structure at ${width}`); - assert.doesNotMatch(stripVTControlCharacters(meter), /[█░]/, "no solid or shaded blocks"); - assert.equal(visibleWidth(meter), width); - const track = stripVTControlCharacters(meter).match(/─+/)![0]; - const dimOpen = theme.fg("dim", "").replace(/\u001b\[39m$/, ""); - assert(meter.includes(`${dimOpen}${track}`), "empty cells use the dim thin track"); + const line = rows.find(row => stripVTControlCharacters(row).includes("CONTEXT"))!; + assert(line, `context row at ${width}`); + assert.match(stripVTControlCharacters(line), /^│ CONTEXT +11% /, `label left, percent right at ${width}`); + assert.doesNotMatch(stripVTControlCharacters(line), /[█░│]{2}|Context /, "no legacy inline meter"); + assert.equal(visibleWidth(line), width); } - sidebar.setSession({ ...session, percent: 83 }); - const warning = sidebar.render(40); - const fill = stripVTControlCharacters(warning.find(row => stripVTControlCharacters(row).includes("Context"))!).match(/━+/)![0]; - assert(warning.some(row => row.includes(theme.fg("warning", fill))), "fill shifts to the warning tone at >= 80%"); - sidebar.setSession({ ...session, percent: null }); - const empty = stripVTControlCharacters(sidebar.render(40).find(row => stripVTControlCharacters(row).includes("Context"))!); - assert(empty.includes("─") && !empty.includes("━") && empty.endsWith("—% │"), "null percent is an empty track with a dash"); - sidebar.dispose(); }); test("quiet editor avoids duplicate identity/model and restores compact facts without losing its draft", () => { diff --git a/pi-slate/tests/sidebar-preview.test.ts b/pi-slate/tests/sidebar-preview.test.ts index d749cfc..a6499dc 100644 --- a/pi-slate/tests/sidebar-preview.test.ts +++ b/pi-slate/tests/sidebar-preview.test.ts @@ -168,40 +168,34 @@ test("speed and cache replace the usage lane; full accounting stays in details", test("header height follows the terminal tier and its divider closes the header", () => { const { sidebar } = fixture(); sidebar.setSession({ ...session, name: "Slate session title" }); - for (const [rows, header] of [[60, 22], [44, 22], [43, 14], [30, 14], [29, 6], [20, 6], [19, 4]] as const) + for (const [rows, header] of [[60, 21], [44, 21], [43, 16], [30, 16], [29, 6], [20, 6], [19, 4]] as const) assert.equal(sessionSidebarSlots(rows, 0, false).header, header, `rows ${rows}`); const lines = plain(sidebar.render(40)); assert.match(lines[0]!, /^┌─+┐$/, "top bar"); assert.match(lines.at(-1)!, /^└─+┘$/, "bottom bar"); const hairline = lines.findIndex((line, i) => i > 0 && i < lines.length - 1 && /^├─+┤$/.test(line)); - assert.equal(hairline, 22, "hairline closes a 22-row header under the top bar"); + assert.equal(hairline, 21, "hairline closes a 21-row header under the top bar"); assert.match(lines[1]!, /^○ Idle|^● Working/); assert(lines[2]!.startsWith("Slate session title") && lines[2]!.endsWith("session-")); assert(lines[5]!.startsWith("CONTEXT") && lines[5]!.includes("16%") && lines[5]!.includes("31.6k/200k")); assert(/^[━─]+$/.test(lines[6]!), "single full-width context bar"); }); -test("context meter fills the rail with a thin track and degrades gracefully when narrow", () => { +test("context row keeps the heading grammar and degrades gracefully when narrow", () => { const { sidebar } = fixture(24); - const meter = (width: number) => { - const line = plain(sidebar.render(width)).find(line => line.startsWith("Context") || line.endsWith("%")); - assert(line, `meter at width ${width}`); assert.doesNotMatch(line, /[█░]/, "meter avoids block glyphs"); return line; + const context = (width: number) => { + const line = plain(sidebar.render(width)).find(line => line.startsWith("CONTEXT") || /\d+%|—/.test(line) && !line.includes("tok/s") && !line.includes("Idle") && !line.includes("Working")); + assert(line, `context at width ${width}`); return line; }; - assert.equal(meter(80), `Context ${"━".repeat(10)}${"─".repeat(52)} │ 16%`); - assert.equal(meter(40), `Context ${"━".repeat(4)}${"─".repeat(18)} │ 16%`); - assert.equal(meter(28), `Context ${"━".repeat(2)}${"─".repeat(8)} │ 16%`); + assert.match(context(80), /^CONTEXT {2,}16% {2}31\.6k\/200k$/); + assert.match(context(40), /^CONTEXT {2,}16% {2}31\.6k\/200k$/); sidebar.setSession({ ...session, percent: null }); - assert.equal(meter(40), `Context ${"─".repeat(23)} │ —%`, "null percent is an empty track"); - sidebar.setSession({ ...session, percent: 0 }); - assert.equal(meter(40), `Context ${"─".repeat(23)} │ 0%`); - sidebar.setSession({ ...session, percent: 100 }); - assert.equal(meter(40), `Context ${"━".repeat(21)} │ 100%`); + assert.match(context(40), /^CONTEXT .*—/, "unknown percent shows a dash"); sidebar.setSession(session); - for (const width of [8, 12, 20]) { - const line = meter(width); + for (const width of [20, 28]) { + const line = context(width); assert(visibleWidth(line) <= width - 4, `bounded at ${width}`); assert(line.includes("16%"), `percent survives at ${width}`); - if (width < 16) assert(!line.includes("Context"), `label yields before the percent at ${width}`); } for (const line of sidebar.render(3)) assert(visibleWidth(line) <= 3, "degenerate rail stays bounded"); }); @@ -209,10 +203,10 @@ test("context meter fills the rail with a thin track and degrades gracefully whe test("context meter fill follows the theme accent and shifts to the warning tone at 80% and above", () => { const codes: Record = { muted: 90, dim: 2, accent: 36, warning: 33, text: 37 }; const toneTheme = { fg: (tone: string, text: string) => `\x1b[${codes[tone] ?? 0}m${text}\x1b[0m`, bold: (text: string) => text } as Theme; - for (const rows of [24, 60]) { + for (const rows of [60]) { const { sidebar } = fixture(rows); sidebar.setThemeProvider(() => toneTheme); sidebar.invalidate(); - const meterLine = () => sidebar.render(40).find(line => /^│ ?(Context )?[━─]{4}/.test(stripAnsi(line)))!; + const meterLine = () => sidebar.render(40).find(line => /^│ ?[━─]{4}/.test(stripAnsi(line)))!; for (const [percent, code] of [[0, 36], [79, 36], [80, 33], [100, 33]] as const) { sidebar.setSession({ ...session, percent }); sidebar.invalidate(); const line = meterLine(); @@ -492,7 +486,7 @@ test("sidebar closes both rails and joins every horizontal divider at the right const lines = sidebar.render(width).map(stripAnsi); assert.equal(lines[0], "┌" + "─".repeat(width - 2) + "┐"); assert.equal(lines.at(-1), "└" + "─".repeat(width - 2) + "┘"); - assert.equal(lines[22], "├" + "─".repeat(width - 2) + "┤"); + assert.equal(lines.find((l, i) => i > 0 && l.startsWith("├")), "├" + "─".repeat(width - 2) + "┤", "header divider joins both rails"); for (const line of lines) { assert.equal(visibleWidth(line), width); assert.match(line, /^[│┌├└]/); @@ -522,6 +516,6 @@ test("empty speed and cache sections collapse and give their rows to the resourc assert(empty.some(line => line.includes("no requests yet"))); sidebar.setSession(session); const full = plain(sidebar.render(44)); - assert.equal(full.findIndex(line => line.includes("MCP")) - mcpEmpty, 8, "6 speed + 2 cache rows are reclaimed"); + assert.equal(full.findIndex(line => line.includes("MCP")) - mcpEmpty, 7, "5 speed + 2 cache rows are reclaimed"); assert.equal(empty.length, full.length, "the rail still fills the terminal"); }); diff --git a/pi-slate/tests/surfaces-install.test.ts b/pi-slate/tests/surfaces-install.test.ts index 431579d..2e58b92 100644 --- a/pi-slate/tests/surfaces-install.test.ts +++ b/pi-slate/tests/surfaces-install.test.ts @@ -490,7 +490,7 @@ test("dashboard uses live branch facts and session-scoped tasks; commands preser assert.doesNotMatch(rail(), /Unnamed session|Untitled session/); assert.ok(rail().includes(f.manager.getSessionId().slice(0, 8))); assert.match(railOf(f).sessionDetails(), /Title: Dashboard test/); - assert.ok(railOf(f).sessionDetails().startsWith(`Session ${f.manager.getSessionId()} · PID ${process.pid}`)); assert.match(rail(), /new 100/); assert.match(rail(), /\$0\.35/); + assert.ok(railOf(f).sessionDetails().startsWith(`Session ${f.manager.getSessionId()} · PID ${process.pid}`)); assert.match(rail(), /new 100/); assert.match(rail(), /read 300 · write 50 · new 100/); assert(!/Summary|Activity Preview|Context\s*\n/.test(rail())); f.extraCommands.push({ name: "skill:review", source: "skill", sourceInfo: { path: "/skills/review/SKILL.md", scope: "user" } }); await f.emit("message_end", { message: { role: "toolResult", toolName: "codemode", toolCallId: "outer", content: [], isError: false, nestedCalls: { calls: [{ id: "nested-read", name: "read", arguments: { path: "/skills/review/SKILL.md" }, status: "ok" }], complete: true } } }); From 22d2490399b26635a53ef83cc26487526b0cf16c Mon Sep 17 00:00:00 2001 From: GaganSD Date: Thu, 12 Nov 2026 08:52:43 +0530 Subject: [PATCH 03/15] docs(slate): describe the sidebar speed and cache sections --- pi-slate/CHANGELOG.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pi-slate/CHANGELOG.md b/pi-slate/CHANGELOG.md index e1f114e..f75a02b 100644 --- a/pi-slate/CHANGELOG.md +++ b/pi-slate/CHANGELOG.md @@ -4,13 +4,13 @@ ### Added -- Sidebar SPEED card: a large tok/s figure, a graph of recent responses, turn average, output and peak. A finished response's speed is exact (output tokens ÷ response time); the live value while streaming is marked `~`. -- Sidebar CACHE section: hit % of the latest request, read/write/new split, spend and estimated savings. A warm/cold countdown appears only when the model publishes its cache lifetime. +- Sidebar SPEED section: tok/s of the latest response (exact: output tokens ÷ response time), a graph of recent responses, turn average, output and peak. Responses under 32 tokens or 300 ms are not timed. On tall terminals the figure is drawn in large digits. +- Sidebar CACHE section: hit % of the latest request, a read/write/new bar, spend and estimated savings. A warm/cold countdown appears only when the model publishes its cache lifetime. - The status row shows Working/Idle, the turn number, and the running turn's elapsed time. ### Changed -- The sidebar header is reorganised into status, CONTEXT, SPEED and CACHE, and adapts to terminal height (full, compact, mini). CONTEXT is a single bar; use pi-context-view for the category breakdown. +- The sidebar header is reorganised into status, CONTEXT, SPEED and CACHE, which share one layout (heading with the key figure on the right, one bar or graph row, labelled details), and adapts to terminal height (full, compact, mini). CONTEXT is a single bar; use pi-context-view for the category breakdown. - Live speed updates to the sidebar are throttled to about 4 per second. ## 0.2.1 From e9778c6d32692cd3b3cd3492b42d8bcf5fd6eb6f Mon Sep 17 00:00:00 2001 From: GaganSD Date: Thu, 12 Nov 2026 09:29:13 +0530 Subject: [PATCH 04/15] feat(slate): draw the context bar as a two-row battery MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The thin ━ line read as a section divider. CONTEXT now fills a two-row battery body with an eighth-step charging edge and a centred terminal nub that lights up at 100%. --- pi-slate/CHANGELOG.md | 2 +- pi-slate/extensions/pi-slate/perf-graphics.ts | 28 +++++++++++++++++-- .../extensions/pi-slate/sidebar-layout.ts | 2 +- pi-slate/tests/perf-graphics.test.ts | 23 +++++++++++++-- pi-slate/tests/sidebar-preview.test.ts | 14 +++++----- 5 files changed, 55 insertions(+), 14 deletions(-) diff --git a/pi-slate/CHANGELOG.md b/pi-slate/CHANGELOG.md index f75a02b..a01e9e0 100644 --- a/pi-slate/CHANGELOG.md +++ b/pi-slate/CHANGELOG.md @@ -10,7 +10,7 @@ ### Changed -- The sidebar header is reorganised into status, CONTEXT, SPEED and CACHE, which share one layout (heading with the key figure on the right, one bar or graph row, labelled details), and adapts to terminal height (full, compact, mini). CONTEXT is a single bar; use pi-context-view for the category breakdown. +- The sidebar header is reorganised into status, CONTEXT, SPEED and CACHE, which share one layout (heading with the key figure on the right, one bar or graph row, labelled details), and adapts to terminal height (full, compact, mini). CONTEXT is a two-row battery bar; use pi-context-view for the category breakdown. - Live speed updates to the sidebar are throttled to about 4 per second. ## 0.2.1 diff --git a/pi-slate/extensions/pi-slate/perf-graphics.ts b/pi-slate/extensions/pi-slate/perf-graphics.ts index 8188bd8..031348c 100644 --- a/pi-slate/extensions/pi-slate/perf-graphics.ts +++ b/pi-slate/extensions/pi-slate/perf-graphics.ts @@ -173,16 +173,38 @@ const noteRow = (i: PerfInput, text: string): string => truncateToWidth(i.paint( const baseline = (i: PerfInput): string => i.paint("dim", "─".repeat(Math.max(0, i.inner))); const DASH: Seg = ["dim", "—"]; -/** CONTEXT: heading + a single filled/empty bar. */ +const EIGHTHS = ["", "▏", "▎", "▍", "▌", "▋", "▊", "▉"]; + +/** + * Two-row battery: solid fill on a light-shaded track, with a half-height nub on the right + * (▄ over ▀ centres it on the body). The fill edge advances in eighth-cell steps; any + * non-zero percent shows at least one eighth so a fresh session never reads as empty. + */ +export function batteryRows(width: number, percent: number | null, paint: PerfInput["paint"], tone: Tone): string[] { + const w = Math.max(0, Math.floor(width)); + if (w === 0) return ["", ""]; + if (w < 3) return [paint("dim", "░".repeat(w)), paint("dim", "░".repeat(w))]; + const body = w - 1; + const p = percent === null || !Number.isFinite(percent) ? 0 : Math.max(0, Math.min(100, percent)); + let eighths = Math.round(p * body * 8 / 100); + if (p > 0 && eighths === 0) eighths = 1; + const full = Math.floor(eighths / 8), part = eighths % 8; + const fill = "█".repeat(full) + EIGHTHS[part]!; + const track = "░".repeat(Math.max(0, body - full - (part ? 1 : 0))); + const nubTone: Tone = p >= 100 ? tone : "dim"; + const row = (nub: string) => (fill ? paint(tone, fill) : "") + (track ? paint("dim", track) : "") + paint(nubTone, nub); + return [row("▄"), row("▀")]; +} + +/** CONTEXT: heading + a two-row battery bar. */ export function contextRows(i: PerfInput, c: { percent: number | null; tokens: number | null; window: number | null; estimated: boolean }): string[] { const percent = c.percent !== null && Number.isFinite(c.percent) ? Math.max(0, Math.min(100, c.percent)) : null; const tone: Tone = percent !== null && percent >= 80 ? "warning" : "accent"; const pctSeg: Seg = percent === null ? DASH : [percent >= 80 ? "warning" : "text", `${Math.round(percent)}%`]; const figures: Seg = ["dim", `${c.estimated ? "~" : ""}${formatCompactTokenCount(c.tokens)}/${formatCompactTokenCount(c.window)}`]; - const filled = percent === null ? 0 : Math.round(percent * i.inner / 100); return [ headingRow(i, "CONTEXT", [[pctSeg, ["dim", " "], figures], [pctSeg]]), - i.paint(tone, "━".repeat(filled)) + i.paint("dim", "─".repeat(Math.max(0, i.inner - filled))), + ...batteryRows(i.inner, percent, i.paint, tone), ]; } diff --git a/pi-slate/extensions/pi-slate/sidebar-layout.ts b/pi-slate/extensions/pi-slate/sidebar-layout.ts index 6587c98..b07c88a 100644 --- a/pi-slate/extensions/pi-slate/sidebar-layout.ts +++ b/pi-slate/extensions/pi-slate/sidebar-layout.ts @@ -10,7 +10,7 @@ export function sidebarTier(rows: number): SidebarTier { return r >= SIDEBAR_FULL_ROWS ? "full" : r >= SIDEBAR_COMPACT_ROWS ? "compact" : r >= SIDEBAR_MINI_ROWS ? "mini" : "micro"; } /** Header rows per tier, including the closing divider. Painting and hit testing both use this. */ -export const SIDEBAR_HEADER_ROWS: Record = { full: 21, compact: 16, mini: 6, micro: 4 }; +export const SIDEBAR_HEADER_ROWS: Record = { full: 22, compact: 17, mini: 6, micro: 4 }; /** Allocate once for both painting and hit testing. Never depend on composer height. */ export function sessionSidebarSlots(height: number, taskCount: number, hasImage: boolean): SidebarSlots { diff --git a/pi-slate/tests/perf-graphics.test.ts b/pi-slate/tests/perf-graphics.test.ts index 9e60edf..25cbab6 100644 --- a/pi-slate/tests/perf-graphics.test.ts +++ b/pi-slate/tests/perf-graphics.test.ts @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; import { visibleWidth, type TUI } from "@earendil-works/pi-tui"; -import { bigDigits, brailleBars, cacheRows, combinedRow, contextRows, formatCountdown, formatRate, sparkBlocks, speedRows, stackedBar, type PerfInput } from "../extensions/pi-slate/perf-graphics.ts"; +import { batteryRows, bigDigits, brailleBars, cacheRows, combinedRow, contextRows, formatCountdown, formatRate, sparkBlocks, speedRows, stackedBar, type PerfInput } from "../extensions/pi-slate/perf-graphics.ts"; import { EMPTY_PERF, type SidebarPerf } from "../extensions/pi-slate/perf-stats.ts"; import { Sidebar } from "../extensions/pi-slate/sidebar.ts"; import type { SidebarSession } from "../extensions/pi-slate/sidebar-data.ts"; @@ -207,7 +207,9 @@ test("CACHE bars use the context glyph in three tones; money rows handle unknown test("CONTEXT uses the same grammar", () => { const i = input(EMPTY_PERF, 40); const rows = contextRows(i, { percent: 2, tokens: 8100, window: 400_000, estimated: false }).map(strip); - assert.match(rows[0]!, /^CONTEXT\s+2% {2}8\.1k\/400k$/); assert.equal(rows[1], "━" + "─".repeat(39)); + assert.match(rows[0]!, /^CONTEXT\s+2% {2}8\.1k\/400k$/); + // 2% of a 39-cell body = 6.24 eighths → 6 → one ▊ edge, then track, then the half-height nub. + assert.equal(rows[1], "▊" + "░".repeat(38) + "▄"); assert.equal(rows[2], "▊" + "░".repeat(38) + "▀"); assert.match(strip(contextRows(i, { percent: null, tokens: null, window: null, estimated: true })[0]!), /^CONTEXT\s+— {2}~—\/—$/); }); @@ -272,3 +274,20 @@ test("themed render keeps tones within the theme palette", () => { for (const t of tones) assert(["text", "muted", "dim", "accent", "success", "warning", "error", "mdHeading", "border", "borderMuted", "borderAccent"].includes(t) || /^[a-zA-Z]+$/.test(t), t); assert(tones.has("success") && tones.has("accent") && tones.has("warning")); }); + +test("battery bar: two rows, exact width, eighth-step fill, visible at tiny percents, centred nub", () => { + const paint = (_t: string, x: string) => x; + for (const width of [0, 1, 2, 3, 10, 41]) for (const pct of [null, 0, 0.01, 2, 50, 99.9, 100, 140, NaN]) { + const rows = batteryRows(width, pct as number | null, paint, "accent"); + assert.equal(rows.length, 2); + for (const r of rows) assert.equal(visibleWidth(r), width, `width ${width} pct ${pct}`); + } + assert.deepEqual(batteryRows(11, 0, paint, "accent"), ["░".repeat(10) + "▄", "░".repeat(10) + "▀"]); + assert.deepEqual(batteryRows(11, null, paint, "accent"), ["░".repeat(10) + "▄", "░".repeat(10) + "▀"]); + assert.equal(batteryRows(11, 0.01, paint, "accent")[0], "▏" + "░".repeat(9) + "▄", "any usage is visible"); + assert.equal(batteryRows(11, 50, paint, "accent")[0], "█████" + "░".repeat(5) + "▄"); + assert.equal(batteryRows(11, 100, paint, "accent")[1], "█".repeat(10) + "▀"); + const tones: string[] = []; + batteryRows(11, 100, (t, x) => { tones.push(`${t}:${x}`); return x; }, "warning"); + assert(tones.includes("warning:▄"), "a full battery lights its nub in the fill tone"); +}); diff --git a/pi-slate/tests/sidebar-preview.test.ts b/pi-slate/tests/sidebar-preview.test.ts index a6499dc..65ae8ac 100644 --- a/pi-slate/tests/sidebar-preview.test.ts +++ b/pi-slate/tests/sidebar-preview.test.ts @@ -168,17 +168,17 @@ test("speed and cache replace the usage lane; full accounting stays in details", test("header height follows the terminal tier and its divider closes the header", () => { const { sidebar } = fixture(); sidebar.setSession({ ...session, name: "Slate session title" }); - for (const [rows, header] of [[60, 21], [44, 21], [43, 16], [30, 16], [29, 6], [20, 6], [19, 4]] as const) + for (const [rows, header] of [[60, 22], [44, 22], [43, 17], [30, 17], [29, 6], [20, 6], [19, 4]] as const) assert.equal(sessionSidebarSlots(rows, 0, false).header, header, `rows ${rows}`); const lines = plain(sidebar.render(40)); assert.match(lines[0]!, /^┌─+┐$/, "top bar"); assert.match(lines.at(-1)!, /^└─+┘$/, "bottom bar"); const hairline = lines.findIndex((line, i) => i > 0 && i < lines.length - 1 && /^├─+┤$/.test(line)); - assert.equal(hairline, 21, "hairline closes a 21-row header under the top bar"); + assert.equal(hairline, 22, "hairline closes a 22-row header under the top bar"); assert.match(lines[1]!, /^○ Idle|^● Working/); assert(lines[2]!.startsWith("Slate session title") && lines[2]!.endsWith("session-")); assert(lines[5]!.startsWith("CONTEXT") && lines[5]!.includes("16%") && lines[5]!.includes("31.6k/200k")); - assert(/^[━─]+$/.test(lines[6]!), "single full-width context bar"); + assert(/^[█-▏░]+▄$/.test(lines[6]!) && /^[█-▏░]+▀$/.test(lines[7]!), "two-row battery with a centred nub"); }); test("context row keeps the heading grammar and degrades gracefully when narrow", () => { @@ -206,16 +206,16 @@ test("context meter fill follows the theme accent and shifts to the warning tone for (const rows of [60]) { const { sidebar } = fixture(rows); sidebar.setThemeProvider(() => toneTheme); sidebar.invalidate(); - const meterLine = () => sidebar.render(40).find(line => /^│ ?[━─]{4}/.test(stripAnsi(line)))!; + const meterLine = () => sidebar.render(40).find(line => /▄ ?│$/.test(stripAnsi(line)))!; for (const [percent, code] of [[0, 36], [79, 36], [80, 33], [100, 33]] as const) { sidebar.setSession({ ...session, percent }); sidebar.invalidate(); const line = meterLine(); - const fill = line.match(/━+/)?.[0] ?? ""; + const fill = stripAnsi(line).match(/[█-▏]+/)?.[0] ?? ""; if (fill) assert(line.includes(`\x1b[${code}m${fill}\x1b[0m`), `${rows} rows: ${percent}% fills with code ${code}`); - assert(line.includes("\x1b[2m"), "track stays dim"); + if (percent < 100) assert(line.includes("\x1b[2m"), "track stays dim"); } sidebar.setSession({ ...session, percent: null }); sidebar.invalidate(); - assert(!/━/.test(stripAnsi(meterLine())), "null percent fills nothing"); + assert(!/[█-▏]/.test(stripAnsi(meterLine())), "null percent fills nothing"); } }); From 83e69e32ae80ab92c5684bc0926497e2c756b020 Mon Sep 17 00:00:00 2001 From: GaganSD Date: Thu, 12 Nov 2026 09:31:59 +0530 Subject: [PATCH 05/15] fix(slate): make the context bar a single row without a nub --- pi-slate/CHANGELOG.md | 2 +- pi-slate/extensions/pi-slate/perf-graphics.ts | 23 ++++++--------- .../extensions/pi-slate/sidebar-layout.ts | 2 +- pi-slate/tests/perf-graphics.test.ts | 28 ++++++++----------- pi-slate/tests/sidebar-preview.test.ts | 8 +++--- 5 files changed, 26 insertions(+), 37 deletions(-) diff --git a/pi-slate/CHANGELOG.md b/pi-slate/CHANGELOG.md index a01e9e0..f75a02b 100644 --- a/pi-slate/CHANGELOG.md +++ b/pi-slate/CHANGELOG.md @@ -10,7 +10,7 @@ ### Changed -- The sidebar header is reorganised into status, CONTEXT, SPEED and CACHE, which share one layout (heading with the key figure on the right, one bar or graph row, labelled details), and adapts to terminal height (full, compact, mini). CONTEXT is a two-row battery bar; use pi-context-view for the category breakdown. +- The sidebar header is reorganised into status, CONTEXT, SPEED and CACHE, which share one layout (heading with the key figure on the right, one bar or graph row, labelled details), and adapts to terminal height (full, compact, mini). CONTEXT is a single bar; use pi-context-view for the category breakdown. - Live speed updates to the sidebar are throttled to about 4 per second. ## 0.2.1 diff --git a/pi-slate/extensions/pi-slate/perf-graphics.ts b/pi-slate/extensions/pi-slate/perf-graphics.ts index 031348c..c817fdc 100644 --- a/pi-slate/extensions/pi-slate/perf-graphics.ts +++ b/pi-slate/extensions/pi-slate/perf-graphics.ts @@ -176,27 +176,22 @@ const DASH: Seg = ["dim", "—"]; const EIGHTHS = ["", "▏", "▎", "▍", "▌", "▋", "▊", "▉"]; /** - * Two-row battery: solid fill on a light-shaded track, with a half-height nub on the right - * (▄ over ▀ centres it on the body). The fill edge advances in eighth-cell steps; any - * non-zero percent shows at least one eighth so a fresh session never reads as empty. + * One-row context bar: solid fill on a light-shaded track. The fill edge advances in + * eighth-cell steps; any non-zero percent shows at least one eighth so usage never reads as empty. */ -export function batteryRows(width: number, percent: number | null, paint: PerfInput["paint"], tone: Tone): string[] { +export function contextBar(width: number, percent: number | null, paint: PerfInput["paint"], tone: Tone): string { const w = Math.max(0, Math.floor(width)); - if (w === 0) return ["", ""]; - if (w < 3) return [paint("dim", "░".repeat(w)), paint("dim", "░".repeat(w))]; - const body = w - 1; + if (w === 0) return ""; const p = percent === null || !Number.isFinite(percent) ? 0 : Math.max(0, Math.min(100, percent)); - let eighths = Math.round(p * body * 8 / 100); + let eighths = Math.round(p * w * 8 / 100); if (p > 0 && eighths === 0) eighths = 1; const full = Math.floor(eighths / 8), part = eighths % 8; const fill = "█".repeat(full) + EIGHTHS[part]!; - const track = "░".repeat(Math.max(0, body - full - (part ? 1 : 0))); - const nubTone: Tone = p >= 100 ? tone : "dim"; - const row = (nub: string) => (fill ? paint(tone, fill) : "") + (track ? paint("dim", track) : "") + paint(nubTone, nub); - return [row("▄"), row("▀")]; + const track = "░".repeat(Math.max(0, w - full - (part ? 1 : 0))); + return (fill ? paint(tone, fill) : "") + (track ? paint("dim", track) : ""); } -/** CONTEXT: heading + a two-row battery bar. */ +/** CONTEXT: heading + a one-row bar. */ export function contextRows(i: PerfInput, c: { percent: number | null; tokens: number | null; window: number | null; estimated: boolean }): string[] { const percent = c.percent !== null && Number.isFinite(c.percent) ? Math.max(0, Math.min(100, c.percent)) : null; const tone: Tone = percent !== null && percent >= 80 ? "warning" : "accent"; @@ -204,7 +199,7 @@ export function contextRows(i: PerfInput, c: { percent: number | null; tokens: n const figures: Seg = ["dim", `${c.estimated ? "~" : ""}${formatCompactTokenCount(c.tokens)}/${formatCompactTokenCount(c.window)}`]; return [ headingRow(i, "CONTEXT", [[pctSeg, ["dim", " "], figures], [pctSeg]]), - ...batteryRows(i.inner, percent, i.paint, tone), + contextBar(i.inner, percent, i.paint, tone), ]; } diff --git a/pi-slate/extensions/pi-slate/sidebar-layout.ts b/pi-slate/extensions/pi-slate/sidebar-layout.ts index b07c88a..6587c98 100644 --- a/pi-slate/extensions/pi-slate/sidebar-layout.ts +++ b/pi-slate/extensions/pi-slate/sidebar-layout.ts @@ -10,7 +10,7 @@ export function sidebarTier(rows: number): SidebarTier { return r >= SIDEBAR_FULL_ROWS ? "full" : r >= SIDEBAR_COMPACT_ROWS ? "compact" : r >= SIDEBAR_MINI_ROWS ? "mini" : "micro"; } /** Header rows per tier, including the closing divider. Painting and hit testing both use this. */ -export const SIDEBAR_HEADER_ROWS: Record = { full: 22, compact: 17, mini: 6, micro: 4 }; +export const SIDEBAR_HEADER_ROWS: Record = { full: 21, compact: 16, mini: 6, micro: 4 }; /** Allocate once for both painting and hit testing. Never depend on composer height. */ export function sessionSidebarSlots(height: number, taskCount: number, hasImage: boolean): SidebarSlots { diff --git a/pi-slate/tests/perf-graphics.test.ts b/pi-slate/tests/perf-graphics.test.ts index 25cbab6..d08ba56 100644 --- a/pi-slate/tests/perf-graphics.test.ts +++ b/pi-slate/tests/perf-graphics.test.ts @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; import { visibleWidth, type TUI } from "@earendil-works/pi-tui"; -import { batteryRows, bigDigits, brailleBars, cacheRows, combinedRow, contextRows, formatCountdown, formatRate, sparkBlocks, speedRows, stackedBar, type PerfInput } from "../extensions/pi-slate/perf-graphics.ts"; +import { bigDigits, contextBar, brailleBars, cacheRows, combinedRow, contextRows, formatCountdown, formatRate, sparkBlocks, speedRows, stackedBar, type PerfInput } from "../extensions/pi-slate/perf-graphics.ts"; import { EMPTY_PERF, type SidebarPerf } from "../extensions/pi-slate/perf-stats.ts"; import { Sidebar } from "../extensions/pi-slate/sidebar.ts"; import type { SidebarSession } from "../extensions/pi-slate/sidebar-data.ts"; @@ -208,8 +208,8 @@ test("CONTEXT uses the same grammar", () => { const i = input(EMPTY_PERF, 40); const rows = contextRows(i, { percent: 2, tokens: 8100, window: 400_000, estimated: false }).map(strip); assert.match(rows[0]!, /^CONTEXT\s+2% {2}8\.1k\/400k$/); - // 2% of a 39-cell body = 6.24 eighths → 6 → one ▊ edge, then track, then the half-height nub. - assert.equal(rows[1], "▊" + "░".repeat(38) + "▄"); assert.equal(rows[2], "▊" + "░".repeat(38) + "▀"); + // 2% of 40 cells = 6.4 eighths → 6 → one ▊ edge, then the track. + assert.equal(rows.length, 2); assert.equal(rows[1], "▊" + "░".repeat(39)); assert.match(strip(contextRows(i, { percent: null, tokens: null, window: null, estimated: true })[0]!), /^CONTEXT\s+— {2}~—\/—$/); }); @@ -275,19 +275,13 @@ test("themed render keeps tones within the theme palette", () => { assert(tones.has("success") && tones.has("accent") && tones.has("warning")); }); -test("battery bar: two rows, exact width, eighth-step fill, visible at tiny percents, centred nub", () => { +test("context bar: one row, exact width, eighth-step fill, visible at tiny percents", () => { const paint = (_t: string, x: string) => x; - for (const width of [0, 1, 2, 3, 10, 41]) for (const pct of [null, 0, 0.01, 2, 50, 99.9, 100, 140, NaN]) { - const rows = batteryRows(width, pct as number | null, paint, "accent"); - assert.equal(rows.length, 2); - for (const r of rows) assert.equal(visibleWidth(r), width, `width ${width} pct ${pct}`); - } - assert.deepEqual(batteryRows(11, 0, paint, "accent"), ["░".repeat(10) + "▄", "░".repeat(10) + "▀"]); - assert.deepEqual(batteryRows(11, null, paint, "accent"), ["░".repeat(10) + "▄", "░".repeat(10) + "▀"]); - assert.equal(batteryRows(11, 0.01, paint, "accent")[0], "▏" + "░".repeat(9) + "▄", "any usage is visible"); - assert.equal(batteryRows(11, 50, paint, "accent")[0], "█████" + "░".repeat(5) + "▄"); - assert.equal(batteryRows(11, 100, paint, "accent")[1], "█".repeat(10) + "▀"); - const tones: string[] = []; - batteryRows(11, 100, (t, x) => { tones.push(`${t}:${x}`); return x; }, "warning"); - assert(tones.includes("warning:▄"), "a full battery lights its nub in the fill tone"); + for (const width of [0, 1, 2, 3, 10, 41]) for (const pct of [null, 0, 0.01, 2, 50, 99.9, 100, 140, NaN]) + assert.equal(visibleWidth(contextBar(width, pct as number | null, paint, "accent")), width, `width ${width} pct ${pct}`); + assert.equal(contextBar(10, 0, paint, "accent"), "░".repeat(10)); + assert.equal(contextBar(10, null, paint, "accent"), "░".repeat(10)); + assert.equal(contextBar(10, 0.01, paint, "accent"), "▏" + "░".repeat(9), "any usage is visible"); + assert.equal(contextBar(10, 50, paint, "accent"), "█████" + "░".repeat(5)); + assert.equal(contextBar(10, 100, paint, "accent"), "█".repeat(10)); }); diff --git a/pi-slate/tests/sidebar-preview.test.ts b/pi-slate/tests/sidebar-preview.test.ts index 65ae8ac..b789255 100644 --- a/pi-slate/tests/sidebar-preview.test.ts +++ b/pi-slate/tests/sidebar-preview.test.ts @@ -168,17 +168,17 @@ test("speed and cache replace the usage lane; full accounting stays in details", test("header height follows the terminal tier and its divider closes the header", () => { const { sidebar } = fixture(); sidebar.setSession({ ...session, name: "Slate session title" }); - for (const [rows, header] of [[60, 22], [44, 22], [43, 17], [30, 17], [29, 6], [20, 6], [19, 4]] as const) + for (const [rows, header] of [[60, 21], [44, 21], [43, 16], [30, 16], [29, 6], [20, 6], [19, 4]] as const) assert.equal(sessionSidebarSlots(rows, 0, false).header, header, `rows ${rows}`); const lines = plain(sidebar.render(40)); assert.match(lines[0]!, /^┌─+┐$/, "top bar"); assert.match(lines.at(-1)!, /^└─+┘$/, "bottom bar"); const hairline = lines.findIndex((line, i) => i > 0 && i < lines.length - 1 && /^├─+┤$/.test(line)); - assert.equal(hairline, 22, "hairline closes a 22-row header under the top bar"); + assert.equal(hairline, 21, "hairline closes a 21-row header under the top bar"); assert.match(lines[1]!, /^○ Idle|^● Working/); assert(lines[2]!.startsWith("Slate session title") && lines[2]!.endsWith("session-")); assert(lines[5]!.startsWith("CONTEXT") && lines[5]!.includes("16%") && lines[5]!.includes("31.6k/200k")); - assert(/^[█-▏░]+▄$/.test(lines[6]!) && /^[█-▏░]+▀$/.test(lines[7]!), "two-row battery with a centred nub"); + assert(/^[█-▏░]+$/.test(lines[6]!) && lines[7] === "", "one-row context bar"); }); test("context row keeps the heading grammar and degrades gracefully when narrow", () => { @@ -206,7 +206,7 @@ test("context meter fill follows the theme accent and shifts to the warning tone for (const rows of [60]) { const { sidebar } = fixture(rows); sidebar.setThemeProvider(() => toneTheme); sidebar.invalidate(); - const meterLine = () => sidebar.render(40).find(line => /▄ ?│$/.test(stripAnsi(line)))!; + const meterLine = () => sidebar.render(40).find(line => /^│ ?[█-▏░]{4}/.test(stripAnsi(line)))!; for (const [percent, code] of [[0, 36], [79, 36], [80, 33], [100, 33]] as const) { sidebar.setSession({ ...session, percent }); sidebar.invalidate(); const line = meterLine(); From 227e55dd9899b7cfae42d9e323c9e49fb2bfe643 Mon Sep 17 00:00:00 2001 From: GaganSD Date: Wed, 18 Nov 2026 05:53:48 +0000 Subject: [PATCH 06/15] refactor(slate): simplify sidebar performance cards --- pi-slate/extensions/pi-slate/index.ts | 8 +- pi-slate/extensions/pi-slate/perf-graphics.ts | 123 ++++++---------- pi-slate/extensions/pi-slate/perf-stats.ts | 136 +++++------------- pi-slate/extensions/pi-slate/sidebar-data.ts | 17 ++- .../extensions/pi-slate/sidebar-layout.ts | 23 +-- pi-slate/extensions/pi-slate/sidebar.ts | 38 +++-- pi-slate/tests/perf-fixture.ts | 8 +- pi-slate/tests/perf-graphics.test.ts | 96 +++++-------- pi-slate/tests/perf-stats.test.ts | 33 ++--- pi-slate/tests/quiet-workbench.test.ts | 14 +- pi-slate/tests/sidebar-data.test.ts | 15 +- pi-slate/tests/sidebar-preview.test.ts | 28 ++-- 12 files changed, 188 insertions(+), 351 deletions(-) diff --git a/pi-slate/extensions/pi-slate/index.ts b/pi-slate/extensions/pi-slate/index.ts index bf2ab0e..d2bb68f 100644 --- a/pi-slate/extensions/pi-slate/index.ts +++ b/pi-slate/extensions/pi-slate/index.ts @@ -336,7 +336,7 @@ export default function piSlate(pi: ExtensionAPI): void { branchFacts = { leaf, counts: sidebarMessageCounts(entries), usage: sidebarUsage(entries), perf: branchPerf(entries, { promptCache: ctx.model?.promptCache, retentionLong: process.env.PI_CACHE_RETENTION === "long" }) }; } - const liveRate = tokenRate.rate(); + const rate = tokenRate.rate(); const mcpCount = resources.mcp.filter(server => server.enabled === true).length; if (owns("sidebar") && !sidebarYielded) { sidebar.setSession({ @@ -344,13 +344,13 @@ export default function piSlate(pi: ExtensionAPI): void { name: ctx.sessionManager.getSessionName?.(), pid: process.pid, cwd: ctx.cwd, model: modelStatusLabel(ctx.model, config.modelDisplay), thinking: ctx.thinkingLevel ?? "—", tokens, percent, contextWindow, estimated, - rate: tokenRate.rate() > 0 ? tokenRate.rate() : null, startedAt: sessionStartedAt, lastTurnMs, turnStartedAt: turnStartedAt ?? null, + rate: rate > 0 ? rate : null, startedAt: sessionStartedAt, lastTurnMs, turnStartedAt: turnStartedAt ?? null, working: typeof ctx.isIdle === "function" && !ctx.isIdle(), ...branchFacts.counts, usage: branchFacts.usage, - perf: { ...branchFacts.perf, live: { streaming: liveStreaming, rate: liveStreaming && liveRate > 0 ? liveRate : null } }, + perf: branchFacts.perf, streaming: liveStreaming, }); } contextEdge = { - tokens: formatFocusedContextTokens(percent, tokenRate.rate(), contextWindow), + tokens: formatFocusedContextTokens(percent, rate, contextWindow), resources: formatFocusedContextResources(percent, estimated, mcpCount), }; }; diff --git a/pi-slate/extensions/pi-slate/perf-graphics.ts b/pi-slate/extensions/pi-slate/perf-graphics.ts index c817fdc..b23f1c7 100644 --- a/pi-slate/extensions/pi-slate/perf-graphics.ts +++ b/pi-slate/extensions/pi-slate/perf-graphics.ts @@ -5,6 +5,7 @@ */ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui"; import { formatCompactTokenCount } from "./layout.ts"; +import type { SidebarUsage } from "./sidebar-data.ts"; import { sidebarCost, type SidebarTier } from "./sidebar-layout.ts"; import { cacheWarmth, type SidebarPerf } from "./perf-stats.ts"; @@ -17,24 +18,11 @@ export type PerfPaint = { const finite = (n: number | null | undefined): n is number => typeof n === "number" && Number.isFinite(n); const nonneg = (n: number | null | undefined): n is number => finite(n) && n >= 0; -/** tok/s: <100 one decimal, <1000 integer, then compact (1.2k, 12.3k, 123k, 1.2M). */ +/** tok/s: one decimal below 100, otherwise use the session's compact token notation. */ export function formatRate(n: number | null | undefined): string { if (!nonneg(n)) return "—"; const tenth = Math.round(n * 10) / 10; - if (tenth < 100) return tenth.toFixed(1); - const whole = Math.round(n); - if (whole < 1000) return `${whole}`; - if (whole < 999_500) { - const k = whole / 1000; - return `${k >= 100 ? Math.round(k) : (Math.round(k * 10) / 10).toFixed(1)}k`; - } - if (whole < 1e15) { - const unit = whole >= 1e12 ? 1e12 : whole >= 1e9 ? 1e9 : 1e6; - const suffix = unit === 1e12 ? "T" : unit === 1e9 ? "B" : "M"; - const v = whole / unit; - return `${v >= 100 ? Math.round(v) : (Math.round(v * 10) / 10).toFixed(1)}${suffix}`; - } - return whole.toExponential(1); + return tenth < 100 ? tenth.toFixed(1) : formatCompactTokenCount(n); } /** m:ss, or h:mm:ss from one hour. Unknown/negative clamps to 0:00. */ @@ -50,7 +38,7 @@ const FONT: Record = { "0": ["█▀█", "█ █", "▀▀▀"], "1": ["▀█ ", " █ ", "▀▀▀"], "2": ["▀▀█", "█▀▀", "▀▀▀"], "3": ["▀▀█", " ▀█", "▀▀▀"], "4": ["█ █", "▀▀█", " ▀"], "5": ["█▀▀", "▀▀█", "▀▀▀"], "6": ["█▀▀", "█▀█", "▀▀▀"], "7": ["▀▀█", " █", " ▀"], "8": ["█▀█", "█▀█", "▀▀▀"], "9": ["█▀█", "▀▀█", "▀▀▀"], ".": [" ", " ", "▀"], - "k": ["█ ▄", "██ ", "█ ▀"], "~": [" ", "▄▀▄", " "], " ": [" ", " ", " "], + "k": ["█ ▄", "██ ", "█ ▀"], " ": [" ", " ", " "], }; /** Three rows of block-drawn text; unknown characters render as blank. Glyphs joined by one space. */ @@ -58,10 +46,6 @@ export function bigDigits(text: string): string[] { const glyphs = [...text].map(ch => FONT[ch] ?? FONT[" "]!); return [0, 1, 2].map(r => glyphs.map(g => g[r]!).join(" ")); } -export function bigDigitsWidth(text: string): number { - return visibleWidth(bigDigits(text)[0]!); -} - const DOT = [[0x01, 0x08], [0x02, 0x10], [0x04, 0x20], [0x40, 0x80]] as const; /** @@ -97,40 +81,22 @@ export function brailleBars(values: readonly number[], width: number, rows: numb return lines; } -const BLOCKS = "▁▂▃▄▅▆▇█"; -/** One-row zero-based sparkline, left-aligned, padded with spaces; shows the newest `width` values. */ -export function sparkBlocks(values: readonly number[], width: number): string { - const w = Math.max(0, Math.floor(width)); - if (w === 0) return ""; - const shown = values.slice(-w).map(v => nonneg(v) ? v : 0); - const max = shown.reduce((a, b) => Math.max(a, b), 0); - const body = shown.map(v => v > 0 && max > 0 ? BLOCKS[Math.max(0, Math.min(7, Math.round(v / max * 7)))]! : BLOCKS[0]!).join(""); - return body + " ".repeat(w - shown.length); -} - -/** - * Split `width` cells among `parts` by largest remainder: counts sum exactly to `width` (when any part is - * positive) and every positive part gets at least one cell when the width allows. - */ +/** Reserve a cell per positive segment if possible, then round the proportional boundaries. */ export function stackedBar(parts: readonly number[], width: number): number[] { const w = Math.max(0, Math.floor(width)); - const p = parts.map(v => nonneg(v) ? v : 0); - const sum = p.reduce((a, b) => a + b, 0); - const out = p.map(() => 0); - if (w === 0 || sum <= 0) return out; - const exact = p.map(v => v / sum * w); - exact.forEach((v, i) => { out[i] = Math.floor(v); }); - let left = w - out.reduce((a, b) => a + b, 0); - const order = exact.map((v, i) => ({ i, frac: v - Math.floor(v) })).sort((a, b) => b.frac - a.frac || a.i - b.i); - for (let k = 0; left > 0; k = (k + 1) % order.length) { out[order[k]!.i]! += 1; left -= 1; } - const positive = p.map((v, i) => v > 0 ? i : -1).filter(i => i >= 0); - if (w >= positive.length) for (const i of positive) { - if (out[i]! > 0) continue; - let donor = -1; - for (let j = 0; j < out.length; j++) if (out[j]! > 1 && (donor < 0 || out[j]! > out[donor]!)) donor = j; - if (donor >= 0) { out[donor]! -= 1; out[i] = 1; } - } - return out; + const values = parts.map(v => nonneg(v) ? v : 0); + const max = Math.max(0, ...values); + if (!w || !max) return values.map(() => 0); + const total = values.reduce((sum, v) => sum + v / max, 0); + const positive = values.filter(v => v > 0).length; + const spare = w >= positive ? w - positive : w; + let cumulative = 0; let boundary = 0; + return values.map(v => { + const next = Math.round((cumulative += v / max) / total * spare); + const cells = next - boundary + (w >= positive && v > 0 ? 1 : 0); + boundary = next; + return cells; + }); } export function formatIdle(ms: number): string { @@ -144,7 +110,7 @@ export function formatIdle(ms: number): string { // One grammar for CONTEXT, SPEED and CACHE: heading row (label left, key figure right), one // full-width visual row, then `label value · label value` detail rows. Padding is always spaces. -export type PerfInput = { perf: SidebarPerf; cost: number | null; now: number; inner: number; tier: SidebarTier } & PerfPaint; +export type PerfInput = { perf: SidebarPerf; usage: SidebarUsage; streaming: boolean; now: number; inner: number; tier: SidebarTier } & PerfPaint; type Seg = readonly [Tone, string]; const fit = (lines: string[], width: number): string[] => lines.map(l => truncateToWidth(l, width, "…")); @@ -203,33 +169,32 @@ export function contextRows(i: PerfInput, c: { percent: number | null; tokens: n ]; } -/** Headline is always the exact last response; the live chars÷4 estimate is not shown here. */ -export const hasSpeed = (perf: SidebarPerf): boolean => nonneg(perf.lastRate) || perf.rates.length > 0 || nonneg(perf.turn?.rate) || nonneg(perf.peak); - +/** Headline is always the exact last eligible response. */ export function speedRows(i: PerfInput): string[] { const { perf, inner, paint } = i; - const streaming: readonly Seg[] = perf.live.streaming ? [["warning", "● streaming"]] : []; - if (!hasSpeed(perf)) { + const streaming: readonly Seg[] = i.streaming ? [["warning", "● streaming"]] : []; + const rate = perf.rates.at(-1); + if (rate === undefined) { return [headingRow(i, "SPEED", [[...streaming, ...(streaming.length ? [["text", " "] as Seg] : []), DASH], [DASH]]), noteRow(i, perf.requests > 0 ? "replies too short to time" : "waiting for first response")]; } - const rate = nonneg(perf.lastRate) ? perf.lastRate : null; - const value: Seg = rate === null ? DASH : ["text", formatRate(rate)]; + const digits = formatRate(rate); + const value: Seg = ["text", digits]; const unit: Seg = ["dim", " tok/s"]; const out = perf.turn && perf.turn.output > 0 ? formatCompactTokenCount(perf.turn.output) : "—"; const detail = detailRow(i, [["avg", formatRate(perf.turn?.rate)], ["peak", formatRate(perf.peak)], ["out", out]]); const gap: Seg = ["text", " "]; if (i.tier !== "full") { const lead = streaming.length ? [...streaming, gap] : []; - const visual = perf.rates.length ? paint("accent", sparkBlocks(perf.rates, inner)) : baseline(i); + const visual = paint("accent", brailleBars(perf.rates, inner, 1)[0]!); return [headingRow(i, "SPEED", [[...lead, value, unit], [...lead, value], [value, unit], [value]]), visual, detail]; } const right: Seg[][] = [streaming.length ? [...streaming] : [["dim", "last response"]], streaming.length ? [["warning", "●"]] : []]; const rows = [headingRow(i, "SPEED", right)]; - const digits = rate === null ? "—" : formatRate(rate); - if (rate !== null && bigDigitsWidth(digits) <= inner) { - const [a, b, c] = bigDigits(digits) as [string, string, string]; - const withUnit = bigDigitsWidth(digits) + 1 + "tok/s".length <= inner; + const [a, b, c] = bigDigits(digits) as [string, string, string]; + const digitWidth = visibleWidth(a); + if (digitWidth <= inner && [...digits].every(ch => ch in FONT)) { + const withUnit = digitWidth + 1 + "tok/s".length <= inner; rows.push(paint("text", a), paint("text", b) + (withUnit ? " " + paint("dim", "tok/s") : ""), paint("text", c)); } else rows.push(paintSegs(i, [value, unit])); if (inner >= 22) rows.push(...brailleBars(perf.rates, inner, 2).map(g => paint("accent", g))); @@ -254,22 +219,17 @@ function cacheSegs(i: PerfInput, full: boolean): Seg[][] { } export function cacheRows(i: PerfInput): string[] { - const { perf, inner, paint } = i; - const c = perf.cache; - if (!c.seen) return [headingRow(i, "CACHE", [[DASH]]), noteRow(i, perf.requests === 0 ? "no requests yet" : "no cache reads reported")]; - const parts = [c.read, c.write, c.uncached]; - const total = parts.reduce((a, b) => a + (nonneg(b) ? b : 0), 0); - const bar = (() => { - if (total <= 0) return baseline(i); - const [r, w, u] = stackedBar(parts.map(p => p ?? 0), inner) as [number, number, number]; - return paint("success", "━".repeat(r)) + paint("warning", "━".repeat(w)) + paint("muted", "━".repeat(u)); - })(); + const { perf, usage, inner, paint } = i; + if (!usage.cacheSeen) return [headingRow(i, "CACHE", [[DASH]]), noteRow(i, perf.requests === 0 ? "no requests yet" : "no cache reads reported")]; + const [r = 0, w = 0, u = 0] = stackedBar([usage.cacheRead ?? 0, usage.cacheWrite ?? 0, usage.uncached ?? 0], inner); + const bar = r || w || u ? paint("success", "━".repeat(r)) + paint("warning", "━".repeat(w)) + paint("muted", "━".repeat(u)) : baseline(i); const f = formatCompactTokenCount; - const spent: [string, string] = ["spent", sidebarCost(i.cost)]; - const tokens: Array<[string, string]> = [["read", f(c.read)], ["write", f(c.write)], ["new", f(c.uncached)]]; + const spent: [string, string] = ["spent", sidebarCost(usage.cost)]; + const tokens: Array<[string, string]> = [["read", f(usage.cacheRead)], ["write", f(usage.cacheWrite)], ["new", f(usage.uncached)]]; const rows = [headingRow(i, "CACHE", cacheSegs(i, true)), bar]; if (i.tier === "full") { - rows.push(detailRow(i, tokens), detailRow(i, nonneg(c.saved) ? [spent, ["saved", `~${sidebarCost(c.saved)}`]] : [spent])); + const saved = perf.cache.saved; + rows.push(detailRow(i, tokens), detailRow(i, nonneg(saved) ? [spent, ["saved", `~${sidebarCost(saved)}`]] : [spent])); } else rows.push(detailRow(i, [...tokens, spent])); return fit(rows, inner); } @@ -277,9 +237,10 @@ export function cacheRows(i: PerfInput): string[] { /** One row for short terminals: `23.5 tok/s · 62% hit · idle 1m`, shedding trailing parts to fit. */ export function combinedRow(i: PerfInput): string { const { perf } = i; - if (perf.requests === 0 && !perf.cache.seen) return noteRow(i, "no requests yet"); - const speed: Seg[] = nonneg(perf.lastRate) ? [["text", formatRate(perf.lastRate)], ["dim", " tok/s"]] : [DASH]; - const cache = perf.cache.seen ? cacheSegs(i, false) : [[]]; + if (perf.requests === 0 && !i.usage.cacheSeen) return noteRow(i, "no requests yet"); + const rate = perf.rates.at(-1); + const speed: Seg[] = rate === undefined ? [DASH] : [["text", formatRate(rate)], ["dim", " tok/s"]]; + const cache = i.usage.cacheSeen ? cacheSegs(i, false) : [[]]; const sep: Seg = ["dim", " · "]; const variants = cache.map(c => c.length ? [...speed, sep, ...c] : speed); variants.push(speed); diff --git a/pi-slate/extensions/pi-slate/perf-stats.ts b/pi-slate/extensions/pi-slate/perf-stats.ts index ab9f6d1..224aa30 100644 --- a/pi-slate/extensions/pi-slate/perf-stats.ts +++ b/pi-slate/extensions/pi-slate/perf-stats.ts @@ -1,4 +1,5 @@ import type { SessionEntry } from "@earendil-works/pi-coding-agent"; +import { nonnegative, record } from "./sidebar-data.ts"; /** * Speed and prompt-cache facts for the session rail. @@ -9,8 +10,6 @@ import type { SessionEntry } from "@earendil-works/pi-coding-agent"; * `durationMs` (request start → response end, monotonic). * - A request's speed is end-to-end: output tokens ÷ (durationMs / 1000). It includes * time to first token and hidden reasoning, both of which are real waiting time. - * - The live streaming rate is an estimate (visible chars ÷ 4) and must be labelled `~`; the rail no - * longer shows it (the composer's working message does). * - Anything unknowable is `null`, never 0. The renderer shows `—` or omits the item. */ @@ -22,34 +21,21 @@ export const PERF_MIN_DURATION_MS = 300; export const PERF_MAX_RATES = 256; export type SidebarTurnPerf = { - /** Assistant requests since the last user message on the branch (the current or last turn). */ - requests: number; - /** Exact output tokens of all those requests (including tiny ones). */ + /** Exact output tokens since the last user message, including tiny replies. */ output: number; - /** Sum of all their durationMs. */ - durationMs: number; - /** Token-weighted exact rate over the ELIGIBLE requests of the turn only (same rule as rates/peak): - * eligible output ÷ eligible seconds; null when none are eligible, so avg/peak/headline are known together. */ + /** Eligible output ÷ eligible seconds for this turn; null if no replies qualify. */ rate: number | null; }; export type SidebarCachePerf = { - /** Branch totals in tokens (same scope as SidebarUsage); null when any contributing usage is missing. */ - read: number | null; - write: number | null; - uncached: number | null; /** cacheRead ÷ (input + cacheRead + cacheWrite) of the latest assistant request (0..1). */ lastHit: number | null; - /** read ÷ (read + write + uncached) over the branch (0..1). */ - sessionHit: number | null; /** Counterfactual dollars saved by cache reads; always an estimate. null when prices are unknown. */ saved: number | null; /** Wall-clock ms when the latest request ended (timestamp + durationMs); drives warm/cold. */ lastActivityAt: number | null; /** Cache lifetime that applies to the latest request; null when the provider's lifetime is unknown. */ ttlMs: number | null; - /** True once any request on the branch read or wrote cache. */ - seen: boolean; }; export type SidebarPerf = { @@ -59,18 +45,13 @@ export type SidebarPerf = { rates: number[]; /** Max of all eligible rates on the branch (not only the retained window). */ peak: number | null; - /** Exact rate of the newest eligible request. */ - lastRate: number | null; turn: SidebarTurnPerf | null; cache: SidebarCachePerf; - /** Live estimate while an assistant message streams; rate is null when not streaming or no sample yet. */ - live: { streaming: boolean; rate: number | null }; }; export const EMPTY_PERF: SidebarPerf = { - requests: 0, rates: [], peak: null, lastRate: null, turn: null, - cache: { read: null, write: null, uncached: null, lastHit: null, sessionHit: null, saved: null, lastActivityAt: null, ttlMs: null, seen: false }, - live: { streaming: false, rate: null }, + requests: 0, rates: [], peak: null, turn: null, + cache: { lastHit: null, saved: null, lastActivityAt: null, ttlMs: null }, }; // --------------------------------------------------------------------------- @@ -80,94 +61,55 @@ export const EMPTY_PERF: SidebarPerf = { export type PerfPromptCache = { short?: number; long?: number } | undefined; export type BranchPerfOptions = { promptCache?: PerfPromptCache; retentionLong: boolean }; -function num(value: unknown): number | null { - return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null; -} -function obj(value: unknown): Record | null { - return typeof value === "object" && value !== null && !Array.isArray(value) ? value as Record : null; -} -function ratio(numerator: number, denominator: number): number | null { - if (!(denominator > 0)) return null; - const value = numerator / denominator; - return Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : null; -} - /** * One O(n) pass over the active branch. * * Turn rule: every timed assistant request after the last user message whose stopReason is not - * error/aborted/deferred counts toward `turn.requests/output/durationMs`. `turn.rate` and the speed - * rows (rates/peak/lastRate) share one eligibility rule: output >= PERF_MIN_OUTPUT_TOKENS and - * duration >= PERF_MIN_DURATION_MS. + * error/aborted/deferred counts toward `turn.output`. The turn rate and speed graph both + * require output >= PERF_MIN_OUTPUT_TOKENS and duration >= PERF_MIN_DURATION_MS. */ export function branchPerf(entries: readonly SessionEntry[], opts: BranchPerfOptions): SidebarPerf { let requests = 0; let rates: number[] = []; let peak: number | null = null; - let lastRate: number | null = null; - let turnRequests = 0; let turnOutput = 0; let turnMs = 0; let turnRateOut = 0; let turnRateMs = 0; - - const sums = { read: 0, write: 0, uncached: 0 }; - const missing = { read: false, write: false, uncached: false }; - let seen = false; + let turnOutput: number | null = null; + let turnRateOut = 0; let turnRateMs = 0; let saved = 0; let pricedAny = false; - let lastUsage: Record | null = null; + let lastUsage: Record | undefined; let lastActivityAt: number | null = null; const ids = new Set(); for (const entry of entries) { - if (ids.has(entry.id)) continue; + if (entry.type !== "message" || ids.has(entry.id)) continue; ids.add(entry.id); - let usage: Record | null; - let expected: boolean; - let assistant: Record | null = null; - if (entry.type === "message") { - const message = obj(entry.message); - const role = message?.role; - if (role === "user") { turnRequests = 0; turnOutput = 0; turnMs = 0; turnRateOut = 0; turnRateMs = 0; continue; } - if (role === "assistant" || role === "toolResult") { - usage = obj(message?.usage); - expected = role === "assistant"; - if (role === "assistant") assistant = message; - } else continue; - } else if (entry.type === "compaction" || entry.type === "branch_summary" || entry.type === "usage") { - usage = obj((entry as { usage?: unknown }).usage); - expected = true; - } else continue; - - if (!usage) { - if (expected) { missing.read = true; missing.write = true; missing.uncached = true; } - continue; - } - const read = num(usage.cacheRead); const write = num(usage.cacheWrite); const input = num(usage.input); - if (read === null) missing.read = true; else { sums.read += read; if (read > 0) seen = true; } - if (write === null) missing.write = true; else { sums.write += write; if (write > 0) seen = true; } - if (input === null) missing.uncached = true; else sums.uncached += input; - - if (!assistant) continue; + const message = entry.message; + if (message.role === "user") { turnOutput = null; turnRateOut = 0; turnRateMs = 0; continue; } + if (message.role !== "assistant") continue; + const usage = record(message.usage); + if (!usage) continue; lastUsage = usage; - const cost = obj(usage.cost); - + const read = nonnegative(usage.cacheRead); const input = nonnegative(usage.input); if (read !== null && read > 0 && input !== null && input > 0) { - const inputPrice = (num(cost?.input) ?? NaN) / input; - const readPrice = (num(cost?.cacheRead) ?? NaN) / read; + const cost = record(usage.cost); + const inputPrice = (nonnegative(cost?.input) ?? NaN) / input; + const readPrice = (nonnegative(cost?.cacheRead) ?? NaN) / read; if (Number.isFinite(inputPrice) && inputPrice > 0 && Number.isFinite(readPrice)) { const term = read * (inputPrice - readPrice); if (Number.isFinite(term)) { saved += Math.max(0, term); pricedAny = true; } } } - const timestamp = assistant.timestamp; - const durationMs = assistant.durationMs; + const timestamp = message.timestamp; + const durationMs = message.durationMs; if (typeof timestamp !== "number" || !Number.isFinite(timestamp) || typeof durationMs !== "number" || !Number.isFinite(durationMs) || durationMs <= 0) continue; requests += 1; lastActivityAt = timestamp + durationMs; - const stop = assistant.stopReason; + const stop = message.stopReason; if (stop === "error" || stop === "aborted" || stop === "deferred") continue; - const output = num(usage.output); + const output = nonnegative(usage.output); if (output === null) continue; - turnRequests += 1; turnOutput += output; turnMs += durationMs; + turnOutput = (turnOutput ?? 0) + output; if (output >= PERF_MIN_OUTPUT_TOKENS && durationMs >= PERF_MIN_DURATION_MS) { const rate = output / (durationMs / 1000); if (!Number.isFinite(rate)) continue; @@ -175,7 +117,6 @@ export function branchPerf(entries: readonly SessionEntry[], opts: BranchPerfOpt rates.push(rate); if (rates.length >= PERF_MAX_RATES * 2) rates = rates.slice(-PERF_MAX_RATES); if (peak === null || rate > peak) peak = rate; - lastRate = rate; } } if (rates.length > PERF_MAX_RATES) rates = rates.slice(-PERF_MAX_RATES); @@ -183,28 +124,19 @@ export function branchPerf(entries: readonly SessionEntry[], opts: BranchPerfOpt let lastHit: number | null = null; let ttlMs: number | null = null; if (lastUsage) { - const input = num(lastUsage.input); const read = num(lastUsage.cacheRead); const write = num(lastUsage.cacheWrite); - if (input !== null && read !== null && write !== null) lastHit = ratio(read, input + read + write); - const long = num(lastUsage.cacheWrite1h) !== null && (num(lastUsage.cacheWrite1h) as number) > 0; + const input = nonnegative(lastUsage.input); const read = nonnegative(lastUsage.cacheRead); const write = nonnegative(lastUsage.cacheWrite); + if (input !== null && read !== null && write !== null) { + const total = input + read + write; + if (total > 0) lastHit = read / total; + } + const long = (nonnegative(lastUsage.cacheWrite1h) ?? 0) > 0; const seconds = long || opts.retentionLong ? opts.promptCache?.long : opts.promptCache?.short; if (typeof seconds === "number" && Number.isFinite(seconds) && seconds > 0) ttlMs = seconds * 1000; } - const read = missing.read ? null : sums.read; - const write = missing.write ? null : sums.write; - const uncached = missing.uncached ? null : sums.uncached; - const sessionHit = read === null || write === null || uncached === null ? null : ratio(read, read + write + uncached); - return { - requests, rates, peak, lastRate, - turn: turnRequests > 0 - ? { requests: turnRequests, output: turnOutput, durationMs: turnMs, rate: turnRateMs > 0 ? turnRateOut / (turnRateMs / 1000) : null } - : null, - cache: { - read, write, uncached, lastHit, sessionHit, - saved: pricedAny && Number.isFinite(saved) ? saved : null, - lastActivityAt, ttlMs, seen, - }, - live: { streaming: false, rate: null }, + requests, rates, peak, + turn: turnOutput === null ? null : { output: turnOutput, rate: turnRateMs > 0 ? turnRateOut / (turnRateMs / 1000) : null }, + cache: { lastHit, saved: pricedAny && Number.isFinite(saved) ? saved : null, lastActivityAt, ttlMs }, }; } diff --git a/pi-slate/extensions/pi-slate/sidebar-data.ts b/pi-slate/extensions/pi-slate/sidebar-data.ts index c143056..14f87f0 100644 --- a/pi-slate/extensions/pi-slate/sidebar-data.ts +++ b/pi-slate/extensions/pi-slate/sidebar-data.ts @@ -10,7 +10,8 @@ export { parseMcpFile, sidebarMcp, SidebarMcpFiles, type SidebarMcp, type Sideba export type SidebarUsage = { input: number | null; output: number | null; cacheRead: number | null; - cacheWrite: number | null; total: number | null; cost: number | null; + cacheWrite: number | null; uncached: number | null; total: number | null; cost: number | null; + cacheSeen: boolean; }; export type SidebarSkill = { name: string; path: string; source: string; loaded: boolean }; export type SidebarCommand = { name: string; source: string; description?: string }; @@ -19,7 +20,7 @@ export type SidebarResources = { skills: SidebarSkill[]; commands: SidebarComman export type SidebarSession = { id: string; name?: string; pid: number; cwd: string; model: string; thinking: string; tokens: number | null; percent: number | null; contextWindow: number | null; - estimated: boolean; rate: number | null; startedAt: number; lastTurnMs: number | null; + estimated: boolean; rate: number | null; startedAt: number; lastTurnMs: number | null; streaming: boolean; /** Wall-clock start of the running turn; absent or null when idle. */ turnStartedAt?: number | null; working: boolean; turns: number; messages: number; usage: SidebarUsage; @@ -32,7 +33,7 @@ export function parseSidebarFolds(value: unknown): SidebarFolds { const raw = record(value); return { mcp: raw?.mcp === true, skills: raw?.skills === true, prompts: raw?.prompts === true }; } -function nonnegative(value: unknown): number | null { +export function nonnegative(value: unknown): number | null { return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null; } @@ -41,6 +42,7 @@ export function sidebarUsage(entries: readonly SessionEntry[]): SidebarUsage { const sums = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 }; const missing = new Set(); const seen = new Set(); + let cacheSeen = false; for (const entry of entries) { if (seen.has(entry.id)) continue; seen.add(entry.id); @@ -61,7 +63,11 @@ export function sidebarUsage(entries: readonly SessionEntry[]): SidebarUsage { for (const key of Object.keys(sums) as Array) { const value = nonnegative(key === "cost" ? record(raw.cost)?.total : raw[key]); if (value === null) missing.add(key); - else { sums[key] += value; if (!Number.isFinite(sums[key])) missing.add(key); } + else { + sums[key] += value; + if (!Number.isFinite(sums[key])) missing.add(key); + if ((key === "cacheRead" || key === "cacheWrite") && value > 0) cacheSeen = true; + } } } // Pi's input is uncached input; cacheRead/cacheWrite are separate categories. @@ -69,7 +75,8 @@ export function sidebarUsage(entries: readonly SessionEntry[]): SidebarUsage { ? null : nonnegative(sums.input + sums.cacheRead + sums.cacheWrite); const output = missing.has("output") ? null : sums.output; return { - input: inbound, output, + input: inbound, output, cacheSeen, + uncached: missing.has("input") ? null : sums.input, cacheRead: missing.has("cacheRead") ? null : sums.cacheRead, cacheWrite: missing.has("cacheWrite") ? null : sums.cacheWrite, total: inbound === null || output === null ? null : nonnegative(inbound + output), diff --git a/pi-slate/extensions/pi-slate/sidebar-layout.ts b/pi-slate/extensions/pi-slate/sidebar-layout.ts index 6587c98..f3beea7 100644 --- a/pi-slate/extensions/pi-slate/sidebar-layout.ts +++ b/pi-slate/extensions/pi-slate/sidebar-layout.ts @@ -2,21 +2,15 @@ export type SidebarSlots = { header: number; middle: number; tasks: number; imag /** How much of the session rail's top half fits; chosen from terminal rows alone. */ export type SidebarTier = "full" | "compact" | "mini" | "micro"; -export const SIDEBAR_FULL_ROWS = 44; -export const SIDEBAR_COMPACT_ROWS = 30; -export const SIDEBAR_MINI_ROWS = 20; export function sidebarTier(rows: number): SidebarTier { - const r = Math.floor(rows); - return r >= SIDEBAR_FULL_ROWS ? "full" : r >= SIDEBAR_COMPACT_ROWS ? "compact" : r >= SIDEBAR_MINI_ROWS ? "mini" : "micro"; + return rows >= 44 ? "full" : rows >= 30 ? "compact" : rows >= 20 ? "mini" : "micro"; } -/** Header rows per tier, including the closing divider. Painting and hit testing both use this. */ -export const SIDEBAR_HEADER_ROWS: Record = { full: 21, compact: 16, mini: 6, micro: 4 }; /** Allocate once for both painting and hit testing. Never depend on composer height. */ -export function sessionSidebarSlots(height: number, taskCount: number, hasImage: boolean): SidebarSlots { +export function sessionSidebarSlots(height: number, headerRows: number, taskCount: number, hasImage: boolean): SidebarSlots { const rows = Math.max(0, Math.floor(height)); const footer = rows >= 12 ? 1 : 0; - const header = Math.min(SIDEBAR_HEADER_ROWS[sidebarTier(rows)], rows - footer); + const header = Math.min(headerRows, rows - footer); let remaining = rows - header - footer; const middleMin = Math.min(6, remaining); const taskWant = taskCount ? (rows < 30 ? 1 : 2) + Math.min(rows < 30 ? 2 : 3, taskCount) * 2 : 0; @@ -41,17 +35,6 @@ export function sidebarCost(cost: number | null): string { return `$${(cost / unit).toFixed(1)}${suffix}`; } -/** Input is inbound (uncached + cache read + cache write). */ -export function sidebarUncached(usage: { input: number | null; cacheRead: number | null; cacheWrite: number | null }): number | null { - if (usage.input === null || usage.cacheRead === null || usage.cacheWrite === null) return null; - return Math.max(0, usage.input - usage.cacheRead - usage.cacheWrite); -} - -export function sidebarRate(rate: number | null): string { - if (rate === null || !Number.isFinite(rate) || rate < 0) return "—"; - return `~${Math.round(rate)} t/s`; -} - export function sidebarDuration(ms: number | null): string { if (ms === null || !Number.isFinite(ms)) return "—"; const seconds = Math.max(0, Math.floor(ms / 1000)); diff --git a/pi-slate/extensions/pi-slate/sidebar.ts b/pi-slate/extensions/pi-slate/sidebar.ts index a749664..d2f0c07 100644 --- a/pi-slate/extensions/pi-slate/sidebar.ts +++ b/pi-slate/extensions/pi-slate/sidebar.ts @@ -7,7 +7,7 @@ import type { WorkspaceView } from "./workspace.ts"; import { chromePaint } from "./composer.ts"; import { DEFAULT_SIDEBAR_FOLDS, sidebarText, type SidebarFolds, type SidebarResources, type SidebarSession } from "./sidebar-data.ts"; import type { BackgroundTask } from "./background-tasks.ts"; -import { sessionSidebarSlots, sidebarDuration, sidebarListOffset, sidebarTier, sidebarUncached, type SidebarTier } from "./sidebar-layout.ts"; +import { sessionSidebarSlots, sidebarDuration, sidebarListOffset, sidebarTier, type SidebarTier } from "./sidebar-layout.ts"; import { cacheRows, combinedRow, contextRows, formatCountdown, formatRate, speedRows, type PerfInput } from "./perf-graphics.ts"; import { cacheWarmth, EMPTY_PERF } from "./perf-stats.ts"; @@ -26,8 +26,8 @@ export type SidebarActions = { const EMPTY_SESSION: SidebarSession = { id: "", name: "", pid: process.pid, cwd: "", model: "—", thinking: "—", tokens: null, percent: null, contextWindow: null, estimated: false, rate: null, startedAt: 0, - lastTurnMs: null, working: false, turns: 0, messages: 0, - usage: { input: null, output: null, total: null, cacheRead: null, cacheWrite: null, cost: null }, + lastTurnMs: null, working: false, streaming: false, turns: 0, messages: 0, + usage: { input: null, output: null, total: null, cacheRead: null, cacheWrite: null, uncached: null, cacheSeen: false, cost: null }, perf: EMPTY_PERF, }; const EMPTY_RESOURCES: SidebarResources = { skills: [], commands: [], prompts: [], mcp: [] }; @@ -105,7 +105,7 @@ export class Sidebar implements Component { setActions(actions: SidebarActions): void { this.actions = actions; } setSession(session: SidebarSession): void { // Keep the full plain-text title for copying/details; truncate only its painted row. - this.session = { ...session, perf: session.perf ?? EMPTY_PERF, name: sidebarText(session.name, Infinity), usage: { ...session.usage } }; + this.session = { ...session, name: sidebarText(session.name, Infinity), usage: { ...session.usage } }; this.changed(); } setResources(resources: SidebarResources): void { @@ -153,7 +153,6 @@ export class Sidebar implements Component { isImagePinned(): boolean { return this.pinned; } sessionDetails(): string { const s = this.session; - const uncached = sidebarUncached(s.usage); const hit = s.usage.input !== null && s.usage.cacheRead !== null && s.usage.input > 0 ? `${Math.round(s.usage.cacheRead / s.usage.input * 100)}%` : "—"; return [`Session ${sidebarText(s.id) || "—"} · PID ${s.pid}`, `Title: ${s.name || "—"}`, `Model: ${s.model} · ${s.thinking}`, `Context: ${formatCompactTokenCount(s.tokens)} / ${formatCompactTokenCount(s.contextWindow)}${s.estimated ? " (estimated)" : ""}`, @@ -162,11 +161,11 @@ export class Sidebar implements Component { `Active-branch usage:`, `Input (uncached + cache read + cache write): ${formatCompactTokenCount(s.usage.input)}`, `Output: ${formatCompactTokenCount(s.usage.output)} · Total: ${formatCompactTokenCount(s.usage.total)}`, `Cache read: ${formatCompactTokenCount(s.usage.cacheRead)} · Cache write: ${formatCompactTokenCount(s.usage.cacheWrite)}`, - `Uncached input: ${formatCompactTokenCount(uncached)} · Cache-hit share: ${hit}`, + `Uncached input: ${formatCompactTokenCount(s.usage.uncached)} · Cache-hit share: ${hit}`, `Cost: ${s.usage.cost === null ? "—" : `$${s.usage.cost.toFixed(2)}`}`, `Estimated rate: ${s.rate === null ? "—" : `~${Math.round(s.rate)} tokens/sec`}`, s.cwd, ...this.speedCacheDetails()].join("\n"); } private speedCacheDetails(): string[] { - const perf = this.session.perf ?? EMPTY_PERF; + const perf = this.session.perf; const c = perf.cache; const warmth = cacheWarmth(c, this.now()); const pct = (n: number | null): string => n === null || !Number.isFinite(n) ? "—" : `${Math.round(n * 100)}%`; @@ -174,8 +173,8 @@ export class Sidebar implements Component { `Speed is end-to-end: output tokens ÷ request duration (includes time to first token and hidden reasoning).`, `Requests under 32 output tokens or 300 ms are left out of the graph, peak and last response.`, `The live value while streaming is an estimate (visible text ÷ 4) and is marked ~.`, - `Timed requests: ${perf.requests} · last response: ${formatRate(perf.lastRate)} tok/s · peak: ${formatRate(perf.peak)} tok/s · this turn: ${formatRate(perf.turn?.rate)} tok/s`, - `Cache hit % = cache read ÷ (uncached + cache read + cache write); latest request ${pct(c.lastHit)} · session ${pct(c.sessionHit)}.`, + `Timed requests: ${perf.requests} · last response: ${formatRate(perf.rates.at(-1))} tok/s · peak: ${formatRate(perf.peak)} tok/s · this turn: ${formatRate(perf.turn?.rate)} tok/s`, + `Cache hit % = cache read ÷ (uncached + cache read + cache write); latest request ${pct(c.lastHit)}.`, `Saved is an estimate of what cache reads cost less than uncached input${c.saved === null ? " (prices unknown here)" : ""}.`, `Cache lifetime is shown only when the provider publishes it${warmth.state === "unknown" ? " (not known for this model)" : ""}.`]; } @@ -228,9 +227,10 @@ export class Sidebar implements Component { if (this.cached?.key === key) return this.cached.lines; this.hits = []; this.listRows = []; const chrome = height >= 12 ? 1 : 0; - const slots = sessionSidebarSlots(height, this.tasks.length, Boolean(this.imageView())); - if (chrome) slots.middle = Math.max(0, slots.middle - 2); const inner = Math.max(0, width - 4); + const header = this.headerRows(inner, sidebarTier(height)); + const slots = sessionSidebarSlots(height, header.length, this.tasks.length, Boolean(this.imageView())); + if (chrome) slots.middle = Math.max(0, slots.middle - 2); const lines: string[] = []; const add = (row: Row): void => { const y = lines.length; @@ -240,9 +240,7 @@ export class Sidebar implements Component { if (row.list) this.listRows.push({ y, list: row.list }); }; if (chrome) lines.push(this.dividerLine(width, "┌")); - const header = this.headerRows(inner, sidebarTier(height)).slice(0, slots.header); - slots.middle += slots.header - header.length; slots.header = header.length; - for (const row of header) add(row); + for (const row of header.slice(0, slots.header)) add(row); const middle = this.middle(); this.middleRows = middle.length; this.middleHeight = slots.middle; this.middleStart = lines.length; this.middleOffset = sidebarListOffset(this.middleOffset, middle.length, slots.middle); @@ -259,7 +257,6 @@ export class Sidebar implements Component { private headerRows(width: number, tier: SidebarTier): Row[] { const s = this.session; - const perf = s.perf ?? EMPTY_PERF; const percent = s.percent !== null && Number.isFinite(s.percent) ? s.percent : null; const branchUsage = () => this.actions?.inspect?.("Branch usage", this.sessionDetails()); const name = s.name || ""; @@ -286,17 +283,16 @@ export class Sidebar implements Component { }; const model: Row = { text: this.pair(this.paint("text", sidebarText(s.model)), this.paint("dim", sidebarText(s.thinking)), width) }; const divider: Row = { text: "", divider: true }; - const input = (): PerfInput => ({ perf, cost: s.usage.cost, now: this.now(), inner: width, tier, paint: (t, x) => this.paint(t, x), heading: x => this.heading(x) }); - const context: Row[] = contextRows(input(), { percent, tokens: s.tokens, window: s.contextWindow, estimated: s.estimated }) + const input: PerfInput = { perf: s.perf, usage: s.usage, streaming: s.streaming, now: this.now(), inner: width, tier, paint: (t, x) => this.paint(t, x), heading: x => this.heading(x) }; + const context: Row[] = contextRows(input, { percent, tokens: s.tokens, window: s.contextWindow, estimated: s.estimated }) .map(text => ({ text, action: branchUsage })); // Short terminals keep the same CONTEXT heading row (label left, figures right) without the bar. if (tier === "micro") return [identity, model, context[0]!, divider]; - if (tier === "mini") return [status, identity, model, context[0]!, { text: combinedRow(input()) }, divider]; + if (tier === "mini") return [status, identity, model, context[0]!, { text: combinedRow(input) }, divider]; const rows = (lines: string[]): Row[] => lines.map(text => ({ text })); - // Empty states collapse to their own natural height; render() hands spare rows to the middle list. return [status, identity, model, { text: "" }, ...context, { text: "" }, - ...rows(speedRows(input())), { text: "" }, - ...rows(cacheRows(input())), { text: "" }, divider]; + ...rows(speedRows(input)), { text: "" }, + ...rows(cacheRows(input)), { text: "" }, divider]; } private middle(): Row[] { const enabled = this.resources.mcp.filter(x => x.enabled === true).length; diff --git a/pi-slate/tests/perf-fixture.ts b/pi-slate/tests/perf-fixture.ts index 66dd7db..f83b57e 100644 --- a/pi-slate/tests/perf-fixture.ts +++ b/pi-slate/tests/perf-fixture.ts @@ -5,10 +5,8 @@ export function perfFixture(now: number): SidebarPerf { return { requests: 12, rates: [18, 22, 26, 31, 24, 28, 35, 30, 22, 19, 27, 33, 38, 29, 24, 31, 36, 41, 45, 37, 30, 26, 33, 28, 21, 25, 30, 14.6], - peak: 45, lastRate: 14.6, - turn: { requests: 3, output: 12_000, durationMs: 449_000, rate: 26.7 }, - cache: { read: 1_310_000, write: 108_000, uncached: 141_000, lastHit: 0.92, sessionHit: 0.84, saved: 1.92, - lastActivityAt: now - 19_000, ttlMs: 300_000, seen: true }, - live: { streaming: false, rate: null }, + peak: 45, + turn: { output: 12_000, rate: 26.7 }, + cache: { lastHit: 0.92, saved: 1.92, lastActivityAt: now - 19_000, ttlMs: 300_000 }, }; } diff --git a/pi-slate/tests/perf-graphics.test.ts b/pi-slate/tests/perf-graphics.test.ts index d08ba56..26d0d1b 100644 --- a/pi-slate/tests/perf-graphics.test.ts +++ b/pi-slate/tests/perf-graphics.test.ts @@ -1,19 +1,20 @@ import assert from "node:assert/strict"; import test from "node:test"; import { visibleWidth, type TUI } from "@earendil-works/pi-tui"; -import { bigDigits, contextBar, brailleBars, cacheRows, combinedRow, contextRows, formatCountdown, formatRate, sparkBlocks, speedRows, stackedBar, type PerfInput } from "../extensions/pi-slate/perf-graphics.ts"; +import { bigDigits, contextBar, brailleBars, cacheRows, combinedRow, contextRows, formatCountdown, formatRate, speedRows, stackedBar, type PerfInput } from "../extensions/pi-slate/perf-graphics.ts"; import { EMPTY_PERF, type SidebarPerf } from "../extensions/pi-slate/perf-stats.ts"; import { Sidebar } from "../extensions/pi-slate/sidebar.ts"; -import type { SidebarSession } from "../extensions/pi-slate/sidebar-data.ts"; -import { sessionSidebarSlots, sidebarTier, SIDEBAR_HEADER_ROWS } from "../extensions/pi-slate/sidebar-layout.ts"; +import type { SidebarSession, SidebarUsage } from "../extensions/pi-slate/sidebar-data.ts"; import { perfFixture } from "./perf-fixture.ts"; const strip = (t: string) => t.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, ""); const plainPaint = { paint: (_t: string, x: string) => x, heading: (x: string) => x }; -const input = (perf: SidebarPerf, inner = 40, tier: PerfInput["tier"] = "full", now = 1000, cost: number | null = 0.84): PerfInput => ({ perf, cost, now, inner, tier, ...plainPaint }); +const usage: SidebarUsage = { input: 1_559_000, output: 12_000, total: 1_571_000, cacheRead: 1_310_000, cacheWrite: 108_000, uncached: 141_000, cacheSeen: true, cost: 0.84 }; +const noUsage: SidebarUsage = { input: null, output: null, total: null, cacheRead: null, cacheWrite: null, uncached: null, cacheSeen: false, cost: null }; +const input = (perf: SidebarPerf, inner = 40, tier: PerfInput["tier"] = "full", now = 1000, totals = usage): PerfInput => ({ perf, usage: totals, streaming: false, now, inner, tier, ...plainPaint }); test("formatRate uses one decimal below 100, integers below 1000, then compact units", () => { - const cases: Array<[number | null, string]> = [[14.64, "14.6"], [0, "0.0"], [99.96, "100"], [100, "100"], [999.4, "999"], [999.6, "1.0k"], [1234, "1.2k"], + const cases: Array<[number | null, string]> = [[14.64, "14.6"], [0, "0.0"], [99.96, "100"], [100, "100"], [999.4, "999"], [999.6, "1k"], [1234, "1.2k"], [12_345, "12.3k"], [123_456, "123k"], [2_500_000, "2.5M"], [null, "—"], [Number.NaN, "—"], [Infinity, "—"], [-3, "—"]]; for (const [n, out] of cases) assert.equal(formatRate(n), out, String(n)); }); @@ -29,14 +30,14 @@ test("bigDigits draws three equal-width rows and blanks unknown characters", () assert.equal(rows.length, 3); assert(rows.every(r => visibleWidth(r) === visibleWidth(rows[0]!))); assert.deepEqual(bigDigits("0"), ["█▀█", "█ █", "▀▀▀"]); - assert.equal(visibleWidth(bigDigits("~1.2k")[0]!), 3 + 1 + 3 + 1 + 1 + 1 + 3 + 1 + 3); + assert.equal(visibleWidth(bigDigits("1.2k")[0]!), 3 + 1 + 1 + 1 + 3 + 1 + 3); const unknown = bigDigits("1—1"); assert.equal(unknown[1]!.slice(4, 6), " ", "unknown glyph is blank"); assert.deepEqual(bigDigits(""), ["", "", ""]); }); test("stackedBar sums exactly to width and keeps non-zero parts visible", () => { - for (const width of [1, 2, 3, 7, 30, 44, 60]) for (const parts of [[1, 1, 1], [1.31e6, 1.08e5, 1.41e5], [1, 0, 0], [0, 0, 5], [1, 1e9, 1], [3, 2, 1], [0.1, 0.2, 0.7]]) { + for (const width of [1, 2, 3, 7, 30, 44, 60]) for (const parts of [[1, 1, 1], [1.31e6, 1.08e5, 1.41e5], [1, 0, 0], [0, 0, 5], [1, 1e9, 1], [3, 2, 1], [0.1, 0.2, 0.7], [1e308, 1e308, 1e308]]) { const out = stackedBar(parts, width); assert.equal(out.reduce((a, b) => a + b, 0), width, `${width} ${parts}`); assert(out.every(n => Number.isInteger(n) && n >= 0)); @@ -66,72 +67,49 @@ test("brailleBars is zero-based, left-aligned with blank padding, and always dra for (const bad of [[Number.NaN, -3, Infinity], [0, 0]]) assert(brailleBars(bad, 3, 2).every(r => r.length === 3)); }); -test("sparkBlocks scales to the max, left-aligns, pads with spaces, and tolerates bad input", () => { - assert.equal(sparkBlocks([], 0), ""); - assert.equal(sparkBlocks([], 3), " "); - assert.equal(sparkBlocks([1, 8], 4), "▂█ "); - assert.equal(sparkBlocks([4, 8], 2), "▅█"); - assert.equal(sparkBlocks([1, 2, 3, 4], 2), "▆█", "newest values win when there are more than columns"); - assert.equal(sparkBlocks([Number.NaN, -1, 0], 3), "▁▁▁"); - assert.equal(sparkBlocks([5], 1), "█"); -}); - -test("tier thresholds are pure and the header slot follows them", () => { - assert.deepEqual([60, 44, 43, 30, 29, 20, 19, 0].map(sidebarTier), ["full", "full", "compact", "compact", "mini", "mini", "micro", "micro"]); - for (let rows = 12; rows <= 100; rows++) { - const slots = sessionSidebarSlots(rows, 0, false); - assert.equal(slots.header, SIDEBAR_HEADER_ROWS[sidebarTier(rows)], `header ${rows}`); - assert(slots.middle >= 6, `middle keeps 6 rows at ${rows}`); - } -}); - -const SECTIONS = (perf: SidebarPerf, inner = 40, tier: PerfInput["tier"] = "compact", now = 1000, cost: number | null = 0.84) => { - const i = input(perf, inner, tier, now, cost); - return { speed: speedRows(i).map(strip), cache: cacheRows(i).map(strip), combined: strip(combinedRow(i)) }; +const SECTIONS = (perf: SidebarPerf, inner = 40, tier: PerfInput["tier"] = "compact", totals = usage) => { + const i = input(perf, inner, tier, 1000, totals); + return { speed: speedRows(i).map(strip), cache: cacheRows(i).map(strip) }; }; test("empty perf: sections keep the grammar, collapse to two rows, and never print NaN or 0%", () => { for (const tier of ["full", "compact"] as const) { - const { speed, cache } = SECTIONS(EMPTY_PERF, 40, tier); + const { speed, cache } = SECTIONS(EMPTY_PERF, 40, tier, noUsage); assert.equal(speed.length, 2); assert.equal(cache.length, 2); assert.match(speed[0]!, /^SPEED\s+—$/); assert.equal(speed[1], "waiting for first response"); assert.match(cache[0]!, /^CACHE\s+—$/); assert.equal(cache[1], "no requests yet"); assert.doesNotMatch([...speed, ...cache].join("\n"), /NaN|Infinity|-\d|0%|[█▀]/); } - assert.equal(strip(combinedRow(input(EMPTY_PERF))), "no requests yet"); + assert.equal(strip(combinedRow(input(EMPTY_PERF, 40, "mini", 1000, noUsage))), "no requests yet"); }); test("provider that never reports cache shows an explicit note and no bar", () => { - const perf = { ...perfFixture(1000), cache: { ...EMPTY_PERF.cache, seen: false } }; - const { cache } = SECTIONS(perf); + const { cache } = SECTIONS(perfFixture(1000), 40, "compact", noUsage); assert.equal(cache.length, 2); assert.equal(cache[1], "no cache reads reported"); assert.doesNotMatch(cache.join(""), /━/); }); test("compact SPEED: heading, left-aligned sparkline, labelled detail row; padding is spaces", () => { - const perf: SidebarPerf = { ...perfFixture(1000), rates: [10, 20, 23.5, 15, 18], lastRate: 23.5, peak: 23.5, turn: { requests: 2, output: 214, durationMs: 15_000, rate: 13.9 } }; + const perf: SidebarPerf = { ...perfFixture(1000), rates: [10, 20, 15, 18, 23.5], peak: 23.5, turn: { output: 214, rate: 13.9 } }; const { speed } = SECTIONS(perf); assert.equal(speed.length, 3); assert.match(speed[0]!, /^SPEED\s+23\.5 tok\/s$/); - assert.match(speed[1]!, /^[▁-█]{5} +$/); assert.equal(speed[1]!.length, 40); + assert.match(speed[1]!, /^[⠁-⣿]{3} +$/); assert.equal(speed[1]!.length, 40); assert.equal(speed[2], "avg 13.9 · peak 23.5 · out 214"); }); -test("a single rate renders one sparkline cell at the left; no rates draws a dim baseline", () => { - const perf: SidebarPerf = { ...EMPTY_PERF, requests: 1, rates: [30], peak: 30, lastRate: 30, turn: { requests: 1, output: 300, durationMs: 10_000, rate: 30 } }; - assert.match(SECTIONS(perf).speed[1]!, /^█ +$/); - const noRates = { ...perf, rates: [] }; - assert.equal(SECTIONS(noRates).speed[1], "─".repeat(40)); +test("a single rate renders one braille column at the left", () => { + const perf: SidebarPerf = { ...EMPTY_PERF, requests: 1, rates: [30], peak: 30, turn: { output: 300, rate: 30 } }; + assert.match(SECTIONS(perf).speed[1]!, /^⡇ +$/); }); test("streaming adds a marker but the headline stays the exact last rate", () => { - const perf = { ...perfFixture(1000), lastRate: 14.6, live: { streaming: true, rate: 999 } }; - const compact = SECTIONS(perf).speed; + const perf = perfFixture(1000); + const compact = speedRows({ ...input(perf, 40, "compact"), streaming: true }); assert.match(compact[0]!, /^SPEED\s+● streaming {2}14\.6 tok\/s$/); - assert.doesNotMatch(compact.join("\n"), /~|999/); - const full = SECTIONS(perf, 40, "full").speed; + const full = speedRows({ ...input(perf), streaming: true }); assert.match(full[0]!, /^SPEED\s+● streaming$/); - assert.match(SECTIONS(perfFixture(1000), 40, "full").speed[0]!, /^SPEED\s+last response$/); - const first = SECTIONS({ ...EMPTY_PERF, live: { streaming: true, rate: 20 } }).speed; + assert.match(SECTIONS(perf, 40, "full").speed[0]!, /^SPEED\s+last response$/); + const first = speedRows({ ...input(EMPTY_PERF, 40, "compact"), streaming: true }); assert.match(first[0]!, /^SPEED\s+● streaming {2}—$/); assert.equal(first[1], "waiting for first response"); }); @@ -145,18 +123,18 @@ test("full SPEED: big digits, two braille rows, then the same detail row", () => }); test("avg, peak and headline are known together", () => { - const perf: SidebarPerf = { ...perfFixture(1000), peak: null, lastRate: null, rates: [], turn: { requests: 1, output: 10, durationMs: 100, rate: null } }; + const perf: SidebarPerf = { ...perfFixture(1000), peak: null, rates: [], turn: { output: 10, rate: null } }; const rows = SECTIONS(perf).speed; assert.equal(rows.length, 2, "no eligible rates: collapsed waiting state"); assert.equal(rows[1], "replies too short to time"); }); test("huge numbers and tiny widths stay inside the width", () => { - const perf: SidebarPerf = { ...perfFixture(1000), lastRate: 12_345, peak: 1e9, rates: [12_345, 1e9], - turn: { requests: 1, output: 9e12, durationMs: 1, rate: 1e15 }, - cache: { ...perfFixture(1000).cache, read: 1.31e6, write: 1e12, uncached: 1e15, saved: 1.2e6 } }; + const base = perfFixture(1000); + const perf: SidebarPerf = { ...base, peak: 1e9, rates: [12_345, 1e9], turn: { output: 9e12, rate: 1e15 }, cache: { ...base.cache, saved: 1.2e6 } }; + assert.equal(SECTIONS(perf, 40, "full").speed[1], "1B tok/s", "unsupported big glyphs fall back to text"); for (const inner of [1, 4, 10, 16, 21, 22, 24, 30, 44, 60]) for (const tier of ["full", "compact"] as const) for (const cost of [1.2e6, 1e308, null]) { - const i = input({ ...perf, live: { streaming: true, rate: 5 } }, inner, tier, 1000, cost); + const i = { ...input(perf, inner, tier, 1000, { ...usage, cacheWrite: 1e12, uncached: 1e15, cost }), streaming: true }; for (const r of [...speedRows(i), ...cacheRows(i), combinedRow(i), ...contextRows(i, { percent: 91, tokens: 1e12, window: 1e15, estimated: true })]) { assert(visibleWidth(r) <= inner, `${inner} ${tier}: ${strip(r)}`); assert.doesNotMatch(strip(r), /NaN|Infinity/); } @@ -195,12 +173,12 @@ test("CACHE bars use the context glyph in three tones; money rows handle unknown assert.equal(themed.find(t => t.startsWith("success:━"))!.length - "success:".length + themed.find(t => t.startsWith("warning:━"))!.length - "warning:".length + themed.find(t => t.startsWith("muted:━"))!.length - "muted:".length, 40, "segments sum to the width"); assert.equal(full[2], "read 1.3M · write 108k · new 141k"); assert.equal(full[3], "spent $0.84 · saved ~$1.92"); - const none = SECTIONS({ ...perfFixture(1000), cache: { ...perfFixture(1000).cache, saved: null } }, 40, "full", 1000, null).cache; + const none = SECTIONS({ ...perfFixture(1000), cache: { ...perfFixture(1000).cache, saved: null } }, 40, "full", { ...usage, cost: null }).cache; assert.equal(none[3], "spent —"); const compact = SECTIONS(perfFixture(1000), 48).cache; assert.equal(compact.length, 3); assert.equal(compact[2], "read 1.3M · write 108k · new 141k · spent $0.84"); assert.equal(SECTIONS(perfFixture(1000), 40).cache[2], "read 1.3M · write 108k · new 141k", "spent is dropped when it does not fit"); - const zero = SECTIONS({ ...perfFixture(1000), cache: { ...perfFixture(1000).cache, read: 0, write: 0, uncached: 0 } }).cache; + const zero = SECTIONS(perfFixture(1000), 40, "compact", { ...usage, cacheRead: 0, cacheWrite: 0, uncached: 0 }).cache; assert.equal(zero[1], "─".repeat(40)); }); @@ -217,8 +195,8 @@ function sidebarWith(rows: number, perf: SidebarPerf, clock: { now: number }, ex const sidebar = new Sidebar(() => clock.now); sidebar.attach({ terminal: { rows, columns: 140 }, requestRender() {}, showOverlay() { return { hide() {} }; } } as unknown as TUI, undefined as never); sidebar.setSession({ id: "01a1cd96-0000", name: "fix auth refresh", pid: 1, cwd: "/p", model: "gpt-6.1-sol (openai)", thinking: "medium", tokens: 152_000, percent: 38, - contextWindow: 400_000, estimated: false, rate: null, startedAt: 1, lastTurnMs: 39_000, working: false, turns: 7, messages: 14, - usage: { input: 1_559_000, output: 12_000, total: 1_571_000, cacheRead: 1_310_000, cacheWrite: 108_000, cost: 0.84 }, perf, ...extra }); + contextWindow: 400_000, estimated: false, rate: null, startedAt: 1, lastTurnMs: 39_000, working: false, streaming: false, turns: 7, messages: 14, + usage, perf, ...extra }); return sidebar; } @@ -228,7 +206,7 @@ test("sidebar renders the full tier and the empty session within width", () => { const full = s.render(44).map(strip); assert(full.every(l => visibleWidth(l) === 44)); const empty = sidebarWith(60, EMPTY_PERF, clock, { id: "", name: "", turns: 0, lastTurnMs: null, tokens: null, percent: null, contextWindow: null, - usage: { input: null, output: null, total: null, cacheRead: null, cacheWrite: null, cost: null } }); + usage: noUsage }); const text = empty.render(44).map(strip); assert(text.every(l => visibleWidth(l) === 44)); assert.doesNotMatch(text.join("\n"), /NaN|Infinity|\b0%/); @@ -246,9 +224,9 @@ test("render recomputes the countdown each second without extra timers", () => { test("every tier and width keeps rows bounded, including live streaming and long sessions", () => { const clock = { now: 1_000_000 }; - const perf: SidebarPerf = { ...perfFixture(clock.now), rates: Array.from({ length: 256 }, (_, i) => 10 + (i % 40)), requests: 5000, live: { streaming: true, rate: 33 } }; + const perf: SidebarPerf = { ...perfFixture(clock.now), rates: Array.from({ length: 256 }, (_, i) => 10 + (i % 40)), requests: 5000 }; for (const rows of [10, 19, 20, 29, 30, 43, 44, 70]) for (const width of [0, 1, 5, 12, 20, 28, 44, 60, 90]) { - const lines = sidebarWith(rows, perf, clock, { working: true }).render(width); + const lines = sidebarWith(rows, perf, clock, { working: true, streaming: true }).render(width); assert.equal(lines.length, rows); assert(lines.every(l => visibleWidth(l) <= width), `${width}x${rows}`); } @@ -269,7 +247,7 @@ test("themed render keeps tones within the theme palette", () => { const s = new Sidebar(() => clock.now); s.attach({ terminal: { rows: 60, columns: 140 }, requestRender() {}, showOverlay() { return { hide() {} }; } } as unknown as TUI, theme); s.setSession({ id: "a", pid: 1, cwd: "", model: "m", thinking: "low", tokens: 1, percent: 90, contextWindow: 10, estimated: true, rate: null, startedAt: 1, lastTurnMs: null, - working: true, turns: 1, messages: 1, usage: { input: 1, output: 1, total: 2, cacheRead: 0, cacheWrite: 0, cost: 0 }, perf: perfFixture(clock.now) }); + working: true, streaming: false, turns: 1, messages: 1, usage, perf: perfFixture(clock.now) }); s.render(44); for (const t of tones) assert(["text", "muted", "dim", "accent", "success", "warning", "error", "mdHeading", "border", "borderMuted", "borderAccent"].includes(t) || /^[a-zA-Z]+$/.test(t), t); assert(tones.has("success") && tones.has("accent") && tones.has("warning")); diff --git a/pi-slate/tests/perf-stats.test.ts b/pi-slate/tests/perf-stats.test.ts index 36e861c..11833a6 100644 --- a/pi-slate/tests/perf-stats.test.ts +++ b/pi-slate/tests/perf-stats.test.ts @@ -20,15 +20,13 @@ test("empty branch yields null facts", () => { const perf = branchPerf([], opts); assert.deepEqual(perf.rates, []); assert.equal(perf.requests, 0); assert.equal(perf.peak, null); assert.equal(perf.turn, null); - assert.equal(perf.cache.seen, false); assert.equal(perf.cache.lastActivityAt, null); - assert.equal(perf.cache.read, 0); - assert.deepEqual(EMPTY_PERF.live, perf.live); + assert.deepEqual(perf.cache, EMPTY_PERF.cache); }); test("legacy messages without durationMs are not timed", () => { const perf = branchPerf([user(), asst({ durationMs: undefined })], opts); assert.equal(perf.requests, 0); assert.equal(perf.turn, null); assert.deepEqual(perf.rates, []); - assert.equal(perf.cache.uncached, 10); + assert.equal(perf.cache.lastHit, 0); }); test("error, aborted and deferred are excluded from speed and turn", () => { @@ -38,8 +36,8 @@ test("error, aborted and deferred are excluded from speed and turn", () => { test("tiny outputs count in the turn but not in rates or peak", () => { const perf = branchPerf([user(), asst({}, usageOf({ output: 10 })), asst({ durationMs: 100 }, usageOf({ output: 500 })), asst({}, usageOf({ output: 100 }))], opts); - assert.deepEqual(perf.rates, [100]); assert.equal(perf.peak, 100); assert.equal(perf.lastRate, 100); - assert.equal(perf.turn?.requests, 3); assert.equal(perf.turn?.output, 610); + assert.deepEqual(perf.rates, [100]); assert.equal(perf.peak, 100); + assert.equal(perf.turn?.output, 610); assert.equal(perf.turn?.rate, 100, "turn average uses the same eligibility as rates and peak"); const onlyTiny = branchPerf([user(), asst({}, usageOf({ output: 10 }))], opts); assert.equal(onlyTiny.turn?.output, 10); assert.equal(onlyTiny.turn?.rate, null); assert.equal(onlyTiny.peak, null); @@ -77,25 +75,14 @@ test("5,000 requests process quickly", () => { assert.equal(perf.requests, 5000); assert.equal(perf.rates.length, PERF_MAX_RATES); }); -test("cache hit math uses Pi's uncached input", () => { +test("cache hit uses the latest assistant's uncached input, cache read and write", () => { + const tool = entry({ type: "message", message: { role: "toolResult", usage: usageOf({ cacheRead: 99 }) } }); const perf = branchPerf([ asst({}, usageOf({ input: 100, cacheRead: 700, cacheWrite: 200 })), - asst({}, usageOf({ input: 50, cacheRead: 150, cacheWrite: 0 })), + asst({}, usageOf({ input: 50, cacheRead: 150, cacheWrite: 50 })), + tool, entry({ type: "compaction" }), ], opts); - assert.equal(perf.cache.lastHit, 0.75); - assert.equal(perf.cache.read, 850); assert.equal(perf.cache.write, 200); assert.equal(perf.cache.uncached, 150); - assert.equal(perf.cache.sessionHit, 850 / 1200); - assert.equal(perf.cache.seen, true); -}); - -test("cache totals reconcile with tool results and summaries, and go null when unknown", () => { - const tool = entry({ type: "message", message: { role: "toolResult", usage: usageOf({ input: 5, cacheRead: 5, cacheWrite: 5 }) } }); - const summary = entry({ type: "compaction", usage: usageOf({ input: 1, cacheRead: 2, cacheWrite: 3 }) }); - const ok = branchPerf([asst({}, usageOf({ input: 1, cacheRead: 1, cacheWrite: 1 })), tool, summary], opts); - assert.equal(ok.cache.read, 8); assert.equal(ok.cache.write, 9); assert.equal(ok.cache.uncached, 7); - const legacy = branchPerf([asst({}, usageOf({ input: 1, cacheRead: 1 })), entry({ type: "compaction" })], opts); - assert.equal(legacy.cache.read, null); assert.equal(legacy.cache.sessionHit, null); - assert.equal(branchPerf([entry({ type: "message", message: { role: "assistant", timestamp: 1, durationMs: 1 } })], opts).cache.uncached, null); + assert.equal(perf.cache.lastHit, 0.6); }); test("saved estimates handle mixed models, skip unpriceable requests and zero prices", () => { @@ -139,7 +126,7 @@ test("cacheWarmth warm, cold, unknown and clock skew", () => { test("NaN, negative and infinite usage never leak", () => { const bad = asst({}, usageOf({ input: NaN, output: -5, cacheRead: Infinity, cacheWrite: -1 }, { input: NaN })); const perf = branchPerf([user(), bad, asst({ durationMs: NaN }), asst({ timestamp: NaN })], opts); - assert.equal(perf.cache.read, null); assert.equal(perf.cache.sessionHit, null); assert.equal(perf.cache.saved, null); + assert.equal(perf.cache.saved, null); assert.equal(branchPerf([bad], opts).cache.lastHit, null); assert.deepEqual(perf.rates, []); assert.equal(perf.turn, null); assert.equal(perf.requests, 1); diff --git a/pi-slate/tests/quiet-workbench.test.ts b/pi-slate/tests/quiet-workbench.test.ts index 98fea2e..f2629e8 100644 --- a/pi-slate/tests/quiet-workbench.test.ts +++ b/pi-slate/tests/quiet-workbench.test.ts @@ -7,7 +7,7 @@ import { loadThemeFromPath, SYSTEM_THEME_NAME } from "../node_modules/@earendil- import { ComposerEditor, type ComposerSource } from "../extensions/pi-slate/composer.ts"; import { dashboardColumnWidth, formatCompactTokenCount, parseSlateArgs } from "../extensions/pi-slate/layout.ts"; import { SLATE_NATIVE_THEME, SLATE_THEME } from "../extensions/pi-slate/install-defaults.ts"; -import { sessionSidebarSlots, sidebarCost, sidebarRate } from "../extensions/pi-slate/sidebar-layout.ts"; +import { sessionSidebarSlots, sidebarCost } from "../extensions/pi-slate/sidebar-layout.ts"; import { Sidebar } from "../extensions/pi-slate/sidebar.ts"; import { perfFixture } from "./perf-fixture.ts"; import type { SidebarSession } from "../extensions/pi-slate/sidebar-data.ts"; @@ -15,8 +15,8 @@ import type { SidebarSession } from "../extensions/pi-slate/sidebar-data.ts"; const theme = loadThemeFromPath(new URL("../themes/tokyo-night.json", import.meta.url).pathname, "truecolor"); const session: SidebarSession = { id: "example-session", pid: 8421, cwd: "/tmp/project", model: "sample-model", thinking: "medium", tokens: 55000, percent: 11, contextWindow: 500000, - estimated: false, rate: 82, startedAt: 1000, lastTurnMs: 14000, working: true, turns: 4, messages: 8, - usage: { input: 128400, output: 6800, total: 135200, cacheRead: 94000, cacheWrite: 22000, cost: 1.24 }, perf: perfFixture(1000) }; + estimated: false, rate: 82, startedAt: 1000, lastTurnMs: 14000, working: true, streaming: false, turns: 4, messages: 8, + usage: { input: 128400, output: 6800, total: 135200, cacheRead: 94000, cacheWrite: 22000, uncached: 12400, cacheSeen: true, cost: 1.24 }, perf: perfFixture(1000) }; test("bundled default Tokyo Night loads with the native validator and restrained backgrounds", () => { assert.equal(SLATE_THEME, "tokyo-night"); assert.equal(theme.name, SLATE_THEME); @@ -49,10 +49,10 @@ test("compact viewport hides the rail without changing stored width or focus", ( test("empty shelves allocate zero rows and all allocations remain bounded", () => { for (let height = 0; height < 80; height++) { - const empty = sessionSidebarSlots(height, 0, false); + const empty = sessionSidebarSlots(height, 11, 0, false); assert.equal(empty.tasks, 0); assert.equal(empty.image, 0); for (const tasks of [0, 1, 10]) for (const image of [false, true]) { - const values = Object.values(sessionSidebarSlots(height, tasks, image)); + const values = Object.values(sessionSidebarSlots(height, 11, tasks, image)); assert.equal(values.reduce((a, b) => a + b, 0), height); assert(values.every(n => n >= 0)); } @@ -76,16 +76,12 @@ test("growing usage and money keep a stable label lane and value edge with the r assert.equal(sidebarCost(null), "—"); assert.equal(sidebarCost(Number.NaN), "—"); assert.equal(sidebarCost(-1), "—"); assert.equal(sidebarCost(1.24), "$1.24"); assert.equal(sidebarCost(1e308), "$1.0e+308"); - assert.equal(sidebarRate(33.4), "~33 t/s"); assert.equal(sidebarRate(300), "~300 t/s"); - assert.equal(sidebarRate(null), "—"); assert.equal(sidebarRate(Number.NaN), "—"); - assert.equal(sidebarRate(-1), "—"); assert.equal(sidebarRate(Infinity), "—"); sidebar.dispose(); }); test("short terminals keep the CONTEXT heading row grammar with the real theme", () => { const sidebar = new Sidebar(() => 10000); sidebar.attach({ terminal: { rows: 24, columns: 140 }, requestRender() {} } as unknown as TUI, theme); - assert.equal(sessionSidebarSlots(24, 0, false).header, 6, "mini tier keeps a one-row context summary"); for (const width of [28, 40, 80]) { sidebar.setSession(session); const rows = sidebar.render(width); diff --git a/pi-slate/tests/sidebar-data.test.ts b/pi-slate/tests/sidebar-data.test.ts index f02636a..e691231 100644 --- a/pi-slate/tests/sidebar-data.test.ts +++ b/pi-slate/tests/sidebar-data.test.ts @@ -16,36 +16,37 @@ function skill(name: string): Skill { return { name, filePath: `/skills/${name}/ test("usage input includes cache categories once; reasoning is already part of output", () => { const a = message("a", "assistant", { usage }); const result = sidebarUsage([a, a]); - assert.deepEqual(result, { input: 450, output: 20, cacheRead: 300, cacheWrite: 50, total: 470, cost: 0.25 }); + assert.deepEqual(result, { input: 450, output: 20, cacheRead: 300, cacheWrite: 50, uncached: 100, cacheSeen: true, total: 470, cost: 0.25 }); }); test("tool nested usage, compaction, branch summaries and cache warming each count once", () => { const entries = [message("a", "assistant", { usage }), message("t", "toolResult", { usage, nestedCalls: { calls: [{ usage }], complete: true } }), entry("c", { type: "compaction", usage }), entry("b", { type: "branch_summary", usage }), entry("w", { type: "usage", kind: "cache_warm", usage })]; const result = sidebarUsage(entries); - assert.equal(result.input, 2250); assert.equal(result.output, 100); assert.equal(result.cost, 1.25); + assert.deepEqual(result, { input: 2250, output: 100, cacheRead: 1500, cacheWrite: 250, uncached: 500, cacheSeen: true, total: 2350, cost: 1.25 }); }); test("ordinary tool results without usage are not invented model requests", () => { - assert.deepEqual(sidebarUsage([message("t", "toolResult")]), { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, cost: 0 }); + assert.deepEqual(sidebarUsage([message("t", "toolResult")]), { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, uncached: 0, cacheSeen: false, total: 0, cost: 0 }); }); test("missing or invalid provider facts show unknown rather than fake zero", () => { - assert.deepEqual(sidebarUsage([message("a", "assistant")]), { input: null, output: null, cacheRead: null, cacheWrite: null, total: null, cost: null }); + assert.deepEqual(sidebarUsage([message("a", "assistant")]), { input: null, output: null, cacheRead: null, cacheWrite: null, uncached: null, cacheSeen: false, total: null, cost: null }); const result = sidebarUsage([message("a", "assistant", { usage: { ...usage, cacheRead: NaN, cost: { total: -1 } } })]); - assert.equal(result.input, null); assert.equal(result.output, 20); assert.equal(result.cacheWrite, 50); assert.equal(result.total, null); assert.equal(result.cost, null); + assert.deepEqual(result, { input: null, output: 20, cacheRead: null, cacheWrite: 50, uncached: 100, cacheSeen: true, total: null, cost: null }); }); test("legacy summaries without usage make billed totals unknown rather than silently free", () => { for (const type of ["compaction", "branch_summary"]) { const result = sidebarUsage([message("a", "assistant", { usage }), entry("summary", { type })]); - assert.equal(result.input, null); assert.equal(result.cost, null); + assert.equal(result.input, null); assert.equal(result.uncached, null); assert.equal(result.cost, null); + assert.equal(result.cacheSeen, true); } }); test("overflow in otherwise finite usage never manufactures Infinity metrics", () => { const huge = { ...usage, input: 1e308, output: 1e308, cacheRead: 1e308, cacheWrite: 1e308, cost: { total: 1e308 } }; const result = sidebarUsage([message("a", "assistant", { usage: huge }), message("b", "assistant", { usage: huge })]); - assert(Object.values(result).every(value => value === null || Number.isFinite(value))); + assert(Object.values(result).every(value => typeof value !== "number" || Number.isFinite(value))); assert.equal(result.input, null); assert.equal(result.cost, null); }); diff --git a/pi-slate/tests/sidebar-preview.test.ts b/pi-slate/tests/sidebar-preview.test.ts index b789255..d11db50 100644 --- a/pi-slate/tests/sidebar-preview.test.ts +++ b/pi-slate/tests/sidebar-preview.test.ts @@ -8,15 +8,15 @@ import { visibleWidth, type TUI, type TuiMouseEvent } from "@earendil-works/pi-t import { Sidebar, DOUBLE_CLICK_MS } from "../extensions/pi-slate/sidebar.ts"; import { perfFixture } from "./perf-fixture.ts"; import { EMPTY_PERF } from "../extensions/pi-slate/perf-stats.ts"; -import { SidebarMcpFiles, type SidebarResources, type SidebarSession } from "../extensions/pi-slate/sidebar-data.ts"; -import { sessionSidebarSlots } from "../extensions/pi-slate/sidebar-layout.ts"; +import { SidebarMcpFiles, type SidebarResources, type SidebarSession, type SidebarUsage } from "../extensions/pi-slate/sidebar-data.ts"; import { DiffWorkspaceView, type WorkspaceView } from "../extensions/pi-slate/workspace.ts"; import type { BackgroundTask } from "../extensions/pi-slate/background-tasks.ts"; const theme = (code = 32) => ({ fg: (_tone: string, text: string) => `\x1b[${code}m${text}\x1b[0m`, bold: (text: string) => text }) as Theme; const stripAnsi = (text: string) => text.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, ""); const plain = (lines: string[]) => lines.map(line => stripAnsi(line).replace(/^│ ?/, "").replace(/ ?│$/, "").trimEnd()); -const session: SidebarSession = { id: "session-a", pid: 8421, cwd: "/tmp/project", model: "sonnet-4.6", thinking: "medium", tokens: 31600, percent: 16, contextWindow: 200000, estimated: false, rate: 82, startedAt: 1000, lastTurnMs: 5000, working: true, turns: 2, messages: 5, usage: { input: 61400, output: 876, total: 62276, cacheRead: 48000, cacheWrite: 6100, cost: 0.12 }, perf: perfFixture(1000) }; +const session: SidebarSession = { id: "session-a", pid: 8421, cwd: "/tmp/project", model: "sonnet-4.6", thinking: "medium", tokens: 31600, percent: 16, contextWindow: 200000, estimated: false, rate: 82, startedAt: 1000, lastTurnMs: 5000, working: true, streaming: false, turns: 2, messages: 5, usage: { input: 61400, output: 876, total: 62276, cacheRead: 48000, cacheWrite: 6100, uncached: 7300, cacheSeen: true, cost: 0.12 }, perf: perfFixture(1000) }; +const noUsage: SidebarUsage = { input: null, output: null, total: null, cacheRead: null, cacheWrite: null, uncached: null, cacheSeen: false, cost: null }; const resources: SidebarResources = { mcp: Array.from({ length: 7 }, (_, i) => ({ name: `server-${i}`, enabled: i !== 2, source: "global" })), skills: Array.from({ length: 6 }, (_, i) => ({ name: `skill-${i}`, path: `/tmp/skills/${i}/SKILL.md`, loaded: i === 0, source: "project" })), @@ -143,9 +143,6 @@ test("all sizes allocate exact bounded rows, including zero, Unicode, and tiny t assert.equal(lines.length, height); assert(lines.every(line => visibleWidth(line) <= width), `${width}×${height}`); assert(lines.every(line => !line.includes("\x1b[2J") && !line.includes("\n"))); - const slots = sessionSidebarSlots(height, 4, true); - assert.equal(Object.values(slots).reduce((a, b) => a + b, 0), height); - assert(Object.values(slots).every(x => x >= 0)); } } }); @@ -155,7 +152,7 @@ test("speed and cache replace the usage lane; full accounting stays in details", for (const width of [18, 28, 40, 80]) { const text = plain(sidebar.render(width)).join("\n"); assert(text.includes("CACHE") && text.includes("SPEED")); - if (width >= 28) for (const value of ["108k", "$0.12", "92%"]) assert(text.includes(value), value); + if (width >= 28) for (const value of ["6.1k", "$0.12", "92%"]) assert(text.includes(value), value); assert(!/\bCached\b|Uncached|\bPID\b/.test(text), "old usage rows are gone"); } assert.match(sidebar.sessionDetails(), /Cache read: 48k · Cache write: 6.1k/); @@ -166,15 +163,16 @@ test("speed and cache replace the usage lane; full accounting stays in details", }); test("header height follows the terminal tier and its divider closes the header", () => { - const { sidebar } = fixture(); + const { sidebar, terminal } = fixture(); sidebar.setSession({ ...session, name: "Slate session title" }); - for (const [rows, header] of [[60, 21], [44, 21], [43, 16], [30, 16], [29, 6], [20, 6], [19, 4]] as const) - assert.equal(sessionSidebarSlots(rows, 0, false).header, header, `rows ${rows}`); + for (const [rows, header] of [[60, 21], [44, 21], [43, 16], [30, 16], [29, 6], [20, 6], [19, 4]] as const) { + terminal.rows = rows; + assert.equal(plain(sidebar.render(40)).findIndex(line => /^├─+┤$/.test(line)), header, `rows ${rows}`); + } + terminal.rows = 60; const lines = plain(sidebar.render(40)); assert.match(lines[0]!, /^┌─+┐$/, "top bar"); assert.match(lines.at(-1)!, /^└─+┘$/, "bottom bar"); - const hairline = lines.findIndex((line, i) => i > 0 && i < lines.length - 1 && /^├─+┤$/.test(line)); - assert.equal(hairline, 21, "hairline closes a 21-row header under the top bar"); assert.match(lines[1]!, /^○ Idle|^● Working/); assert(lines[2]!.startsWith("Slate session title") && lines[2]!.endsWith("session-")); assert(lines[5]!.startsWith("CONTEXT") && lines[5]!.includes("16%") && lines[5]!.includes("31.6k/200k")); @@ -222,7 +220,7 @@ test("context meter fill follows the theme accent and shifts to the warning tone test("context rows keep the branch usage inspect action; nulls render as dashes", () => { const { sidebar } = fixture(); const inspected: string[] = []; sidebar.setActions({ copy() {}, openFile() {}, inspect: title => inspected.push(title) }); - sidebar.setSession({ ...session, estimated: true, usage: { input: null, output: null, total: null, cacheRead: null, cacheWrite: null, cost: null } }); + sidebar.setSession({ ...session, estimated: true, usage: noUsage }); const heading = row(sidebar, "~31.6k/200k"); sidebar.handleMouse(mouse(heading)); sidebar.handleMouse(mouse(heading + 1)); @@ -411,7 +409,7 @@ test("clock and theme changes invalidate cached output; pure repeated render is test("unknown values and invalid MCP config remain explicit even when folded", () => { const { sidebar } = fixture(); - sidebar.setSession({ ...session, percent: null, tokens: null, contextWindow: null, usage: { input: null, output: null, total: null, cacheRead: null, cacheWrite: null, cost: null } }); + sidebar.setSession({ ...session, percent: null, tokens: null, contextWindow: null, usage: noUsage }); sidebar.setResources({ ...resources, mcpError: "MCP config unreadable" }); const lines = plain(sidebar.render(80)); assert(lines.some(line => /^CONTEXT\s+—\s+—\/—$/.test(line))); @@ -509,7 +507,7 @@ test("working status shows the running turn's elapsed time and ticks each second test("empty speed and cache sections collapse and give their rows to the resource list", () => { const { sidebar } = fixture(46); - sidebar.setSession({ ...session, perf: EMPTY_PERF }); + sidebar.setSession({ ...session, usage: noUsage, perf: EMPTY_PERF }); const empty = plain(sidebar.render(44)); const mcpEmpty = empty.findIndex(line => line.includes("MCP")); assert(empty.some(line => line.includes("waiting for first response"))); From 5bec7aae56d337972e4568bab5724632db76f646 Mon Sep 17 00:00:00 2001 From: GaganSD Date: Wed, 18 Nov 2026 06:18:12 +0000 Subject: [PATCH 07/15] fix(slate): align cache hit rate with the sidebar bar --- pi-slate/CHANGELOG.md | 2 +- pi-slate/extensions/pi-slate/perf-graphics.ts | 28 +++++++++------ pi-slate/extensions/pi-slate/sidebar-data.ts | 4 +++ pi-slate/extensions/pi-slate/sidebar.ts | 9 +++-- pi-slate/tests/perf-graphics.test.ts | 34 ++++++++++++++----- pi-slate/tests/sidebar-preview.test.ts | 4 +-- 6 files changed, 55 insertions(+), 26 deletions(-) diff --git a/pi-slate/CHANGELOG.md b/pi-slate/CHANGELOG.md index f75a02b..8e1de78 100644 --- a/pi-slate/CHANGELOG.md +++ b/pi-slate/CHANGELOG.md @@ -5,7 +5,7 @@ ### Added - Sidebar SPEED section: tok/s of the latest response (exact: output tokens ÷ response time), a graph of recent responses, turn average, output and peak. Responses under 32 tokens or 300 ms are not timed. On tall terminals the figure is drawn in large digits. -- Sidebar CACHE section: hit % of the latest request, a read/write/new bar, spend and estimated savings. A warm/cold countdown appears only when the model publishes its cache lifetime. +- Sidebar CACHE section: active-branch hit % matching the read/write/new bar, spend and estimated savings. Session details also show the latest request's hit %. A warm/cold countdown appears only when the model publishes its cache lifetime. - The status row shows Working/Idle, the turn number, and the running turn's elapsed time. ### Changed diff --git a/pi-slate/extensions/pi-slate/perf-graphics.ts b/pi-slate/extensions/pi-slate/perf-graphics.ts index b23f1c7..14fce5c 100644 --- a/pi-slate/extensions/pi-slate/perf-graphics.ts +++ b/pi-slate/extensions/pi-slate/perf-graphics.ts @@ -5,7 +5,7 @@ */ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui"; import { formatCompactTokenCount } from "./layout.ts"; -import type { SidebarUsage } from "./sidebar-data.ts"; +import { sidebarCacheHit, type SidebarUsage } from "./sidebar-data.ts"; import { sidebarCost, type SidebarTier } from "./sidebar-layout.ts"; import { cacheWarmth, type SidebarPerf } from "./perf-stats.ts"; @@ -81,19 +81,22 @@ export function brailleBars(values: readonly number[], width: number, rows: numb return lines; } -/** Reserve a cell per positive segment if possible, then round the proportional boundaries. */ +/** Round proportional boundaries; keep positive segments visible when they fit. */ export function stackedBar(parts: readonly number[], width: number): number[] { const w = Math.max(0, Math.floor(width)); const values = parts.map(v => nonneg(v) ? v : 0); const max = Math.max(0, ...values); if (!w || !max) return values.map(() => 0); const total = values.reduce((sum, v) => sum + v / max, 0); - const positive = values.filter(v => v > 0).length; - const spare = w >= positive ? w - positive : w; + let remaining = values.filter(v => v > 0).length; + const min = w >= remaining ? 1 : 0; let cumulative = 0; let boundary = 0; return values.map(v => { - const next = Math.round((cumulative += v / max) / total * spare); - const cells = next - boundary + (w >= positive && v > 0 ? 1 : 0); + if (!v) return 0; + remaining--; + const rounded = Math.round((cumulative += v / max) / total * w); + const next = Math.max(boundary + min, Math.min(w - remaining * min, rounded)); + const cells = next - boundary; boundary = next; return cells; }); @@ -202,12 +205,17 @@ export function speedRows(i: PerfInput): string[] { return fit(rows, inner); } -const pct = (n: number): string => `${Math.round(Math.max(0, Math.min(1, n)) * 100)}%`; +export function formatCacheHit(rate: number | null): string { + if (rate === null) return "—"; + const rounded = Math.round(rate * 100); + return rounded === 100 && rate < 1 ? ">99%" : `${rounded}%`; +} -/** Right-hand key figure of the CACHE heading and the mini row: hit rate then warmth. */ +/** Headline uses the same branch totals as the bar; warmth is based on the latest request. */ function cacheSegs(i: PerfInput, full: boolean): Seg[][] { const { cache: c } = i.perf; - const hit = nonneg(c.lastHit) ? pct(c.lastHit) : null; + const rate = sidebarCacheHit(i.usage); + const hit = rate === null ? null : formatCacheHit(rate); const w = cacheWarmth(c, i.now); const warm: Seg | null = w.state === "warm" ? ["success", full ? `◉ ${formatCountdown(w.remainingMs ?? 0)}` : `warm ${formatCountdown(w.remainingMs ?? 0)}`] : w.state === "cold" ? ["warning", "cold"] @@ -221,7 +229,7 @@ function cacheSegs(i: PerfInput, full: boolean): Seg[][] { export function cacheRows(i: PerfInput): string[] { const { perf, usage, inner, paint } = i; if (!usage.cacheSeen) return [headingRow(i, "CACHE", [[DASH]]), noteRow(i, perf.requests === 0 ? "no requests yet" : "no cache reads reported")]; - const [r = 0, w = 0, u = 0] = stackedBar([usage.cacheRead ?? 0, usage.cacheWrite ?? 0, usage.uncached ?? 0], inner); + const [r = 0, w = 0, u = 0] = usage.input === null ? [] : stackedBar([usage.cacheRead ?? 0, usage.cacheWrite ?? 0, usage.uncached ?? 0], inner); const bar = r || w || u ? paint("success", "━".repeat(r)) + paint("warning", "━".repeat(w)) + paint("muted", "━".repeat(u)) : baseline(i); const f = formatCompactTokenCount; const spent: [string, string] = ["spent", sidebarCost(usage.cost)]; diff --git a/pi-slate/extensions/pi-slate/sidebar-data.ts b/pi-slate/extensions/pi-slate/sidebar-data.ts index 14f87f0..1b12101 100644 --- a/pi-slate/extensions/pi-slate/sidebar-data.ts +++ b/pi-slate/extensions/pi-slate/sidebar-data.ts @@ -84,6 +84,10 @@ export function sidebarUsage(entries: readonly SessionEntry[]): SidebarUsage { }; } +export function sidebarCacheHit({ input, cacheRead }: SidebarUsage): number | null { + return input !== null && input > 0 && cacheRead !== null ? cacheRead / input : null; +} + export function sidebarMessageCounts(entries: readonly SessionEntry[]): { turns: number; messages: number } { let turns = 0; let messages = 0; for (const entry of entries) { diff --git a/pi-slate/extensions/pi-slate/sidebar.ts b/pi-slate/extensions/pi-slate/sidebar.ts index d2f0c07..0b21604 100644 --- a/pi-slate/extensions/pi-slate/sidebar.ts +++ b/pi-slate/extensions/pi-slate/sidebar.ts @@ -5,10 +5,10 @@ import { installSidebarSplit, type SidebarSplitLease } from "./sidebar-split.ts" import { mcpDetails } from "./sidebar-mcp.ts"; import type { WorkspaceView } from "./workspace.ts"; import { chromePaint } from "./composer.ts"; -import { DEFAULT_SIDEBAR_FOLDS, sidebarText, type SidebarFolds, type SidebarResources, type SidebarSession } from "./sidebar-data.ts"; +import { DEFAULT_SIDEBAR_FOLDS, sidebarCacheHit, sidebarText, type SidebarFolds, type SidebarResources, type SidebarSession } from "./sidebar-data.ts"; import type { BackgroundTask } from "./background-tasks.ts"; import { sessionSidebarSlots, sidebarDuration, sidebarListOffset, sidebarTier, type SidebarTier } from "./sidebar-layout.ts"; -import { cacheRows, combinedRow, contextRows, formatCountdown, formatRate, speedRows, type PerfInput } from "./perf-graphics.ts"; +import { cacheRows, combinedRow, contextRows, formatCacheHit, formatCountdown, formatRate, speedRows, type PerfInput } from "./perf-graphics.ts"; import { cacheWarmth, EMPTY_PERF } from "./perf-stats.ts"; export const DOUBLE_CLICK_MS = 400; @@ -153,7 +153,7 @@ export class Sidebar implements Component { isImagePinned(): boolean { return this.pinned; } sessionDetails(): string { const s = this.session; - const hit = s.usage.input !== null && s.usage.cacheRead !== null && s.usage.input > 0 ? `${Math.round(s.usage.cacheRead / s.usage.input * 100)}%` : "—"; + const hit = formatCacheHit(sidebarCacheHit(s.usage)); return [`Session ${sidebarText(s.id) || "—"} · PID ${s.pid}`, `Title: ${s.name || "—"}`, `Model: ${s.model} · ${s.thinking}`, `Context: ${formatCompactTokenCount(s.tokens)} / ${formatCompactTokenCount(s.contextWindow)}${s.estimated ? " (estimated)" : ""}`, `Wall time (this runtime): ${sidebarDuration(s.startedAt > 0 ? this.now() - s.startedAt : null)}`, @@ -168,13 +168,12 @@ export class Sidebar implements Component { const perf = this.session.perf; const c = perf.cache; const warmth = cacheWarmth(c, this.now()); - const pct = (n: number | null): string => n === null || !Number.isFinite(n) ? "—" : `${Math.round(n * 100)}%`; return ["", "Speed & cache", `Speed is end-to-end: output tokens ÷ request duration (includes time to first token and hidden reasoning).`, `Requests under 32 output tokens or 300 ms are left out of the graph, peak and last response.`, `The live value while streaming is an estimate (visible text ÷ 4) and is marked ~.`, `Timed requests: ${perf.requests} · last response: ${formatRate(perf.rates.at(-1))} tok/s · peak: ${formatRate(perf.peak)} tok/s · this turn: ${formatRate(perf.turn?.rate)} tok/s`, - `Cache hit % = cache read ÷ (uncached + cache read + cache write); latest request ${pct(c.lastHit)}.`, + `Cache hit % = cache read ÷ (uncached + cache read + cache write); latest request ${formatCacheHit(c.lastHit)}.`, `Saved is an estimate of what cache reads cost less than uncached input${c.saved === null ? " (prices unknown here)" : ""}.`, `Cache lifetime is shown only when the provider publishes it${warmth.state === "unknown" ? " (not known for this model)" : ""}.`]; } diff --git a/pi-slate/tests/perf-graphics.test.ts b/pi-slate/tests/perf-graphics.test.ts index 26d0d1b..5012e47 100644 --- a/pi-slate/tests/perf-graphics.test.ts +++ b/pi-slate/tests/perf-graphics.test.ts @@ -154,12 +154,27 @@ test("CACHE heading: hit, warmth countdown, cold, unknown lifetime and idle hint const base = perfFixture(1_000_000); const head = (cache: Partial, now: number, tier: PerfInput["tier"] = "full") => strip(cacheRows(input({ ...base, cache: { ...base.cache, ...cache } }, 40, tier, now))[0]!); - assert.match(head({}, 1_000_000), /^CACHE\s+92% hit · ◉ 4:41$/); + assert.match(head({}, 1_000_000), /^CACHE\s+84% hit · ◉ 4:41$/); assert.match(head({}, 1_000_000 + 1000), /◉ 4:40$/, "countdown moves with the clock alone"); - assert.match(head({}, 1_000_000 + 400_000), /92% hit · cold$/); - assert.match(head({ ttlMs: null }, 1_000_000 + 30_000), /^CACHE\s+92% hit$/, "no lifetime and recent: nothing extra"); - assert.match(head({ ttlMs: null, lastActivityAt: 1_000_000 - 62_000 }, 1_000_000, "compact"), /^CACHE\s+92% hit · idle 1m$/); - assert.match(head({ lastHit: null }, 1_000_000), /^CACHE\s+◉ 4:41$/, "unknown hit is omitted, never 0%"); + assert.match(head({}, 1_000_000 + 400_000), /84% hit · cold$/); + assert.match(head({ ttlMs: null }, 1_000_000 + 30_000), /^CACHE\s+84% hit$/, "no lifetime and recent: nothing extra"); + assert.match(head({ ttlMs: null, lastActivityAt: 1_000_000 - 62_000 }, 1_000_000, "compact"), /^CACHE\s+84% hit · idle 1m$/); +}); + +test("CACHE headline and bar use branch totals and distinguish near-perfect from exact hits", () => { + const base = perfFixture(1000); + const perf = { ...base, cache: { ...base.cache, lastHit: 0.9956 } }; + for (const [read, label, cells] of [[8600, "86%", 34], [9500, "95%", 38], [9956, ">99%", 39], [10000, "100%", 40]] as const) { + const totals = { ...usage, input: 10000, cacheRead: read, cacheWrite: 0, uncached: 10000 - read }; + const i = input(perf, 40, "compact", 1000, totals); + const [heading, bar] = cacheRows({ ...i, paint: (t, x) => t === "success" ? x.replaceAll("━", "█") : x }); + assert(heading?.includes(`${label} hit`)); + assert.equal(bar, "█".repeat(cells) + "━".repeat(40 - cells)); + assert(combinedRow(i).includes(`${label} hit`)); + } + const unknown = SECTIONS(perf, 40, "full", { ...usage, input: null, uncached: null }).cache; + assert.match(unknown[0]!, /^CACHE\s+◉ 4:41$/, "unknown totals omit the hit rate"); + assert.equal(unknown[1], "─".repeat(40), "missing input is not treated as all cached"); }); test("CACHE bars use the context glyph in three tones; money rows handle unknowns", () => { @@ -178,7 +193,7 @@ test("CACHE bars use the context glyph in three tones; money rows handle unknown const compact = SECTIONS(perfFixture(1000), 48).cache; assert.equal(compact.length, 3); assert.equal(compact[2], "read 1.3M · write 108k · new 141k · spent $0.84"); assert.equal(SECTIONS(perfFixture(1000), 40).cache[2], "read 1.3M · write 108k · new 141k", "spent is dropped when it does not fit"); - const zero = SECTIONS(perfFixture(1000), 40, "compact", { ...usage, cacheRead: 0, cacheWrite: 0, uncached: 0 }).cache; + const zero = SECTIONS(perfFixture(1000), 40, "compact", { ...usage, input: 0, cacheRead: 0, cacheWrite: 0, uncached: 0 }).cache; assert.equal(zero[1], "─".repeat(40)); }); @@ -234,10 +249,13 @@ test("every tier and width keeps rows bounded, including live streaming and long test("mini tier shows the combined speed/cache row; details explain the numbers", () => { const clock = { now: 1_000_000 }; - const s = sidebarWith(24, perfFixture(clock.now), clock); - assert.match(s.render(40).map(strip).join("\n"), /14\.6 tok\/s · 92% hit · warm 4:41/); + const base = perfFixture(clock.now); + const s = sidebarWith(24, { ...base, cache: { ...base.cache, lastHit: 0.9956 } }, clock); + assert.match(s.render(40).map(strip).join("\n"), /14\.6 tok\/s · 84% hit · warm 4:41/); assert.match(s.sessionDetails(), /Speed & cache/); assert.match(s.sessionDetails(), /300 ms/); + assert.match(s.sessionDetails(), /Cache-hit share: 84%/); + assert.match(s.sessionDetails(), /latest request >99%\./); }); test("themed render keeps tones within the theme palette", () => { diff --git a/pi-slate/tests/sidebar-preview.test.ts b/pi-slate/tests/sidebar-preview.test.ts index d11db50..3abcd1c 100644 --- a/pi-slate/tests/sidebar-preview.test.ts +++ b/pi-slate/tests/sidebar-preview.test.ts @@ -48,7 +48,7 @@ function task(i: number): BackgroundTask { test("quiet session rail merges usage into context and hides empty shelves", () => { const { sidebar } = fixture(); const lines = plain(sidebar.render(80)); - for (const label of ["Working · turn 2", "session-", "sonnet-4.6", "16%", "31.6k/200k", "SPEED", "CACHE", "92% hit", "spent $0.12", "MCP · 6 Enabled", "Skills · 1 Loaded", "Prompts · 6"]) + for (const label of ["Working · turn 2", "session-", "sonnet-4.6", "16%", "31.6k/200k", "SPEED", "CACHE", "78% hit", "spent $0.12", "MCP · 6 Enabled", "Skills · 1 Loaded", "Prompts · 6"]) assert(lines.some(line => line.includes(label)), label); for (const label of ["Stats", "Tokens · branch", "Commands ·", "Tasks", "Preview", "no selection", "/run-0", "prompt-0"]) assert(!lines.some(line => line.includes(label)), label); @@ -152,7 +152,7 @@ test("speed and cache replace the usage lane; full accounting stays in details", for (const width of [18, 28, 40, 80]) { const text = plain(sidebar.render(width)).join("\n"); assert(text.includes("CACHE") && text.includes("SPEED")); - if (width >= 28) for (const value of ["6.1k", "$0.12", "92%"]) assert(text.includes(value), value); + if (width >= 28) for (const value of ["6.1k", "$0.12", "78%"]) assert(text.includes(value), value); assert(!/\bCached\b|Uncached|\bPID\b/.test(text), "old usage rows are gone"); } assert.match(sidebar.sessionDetails(), /Cache read: 48k · Cache write: 6.1k/); From f4c1774bff6fd28fc95fb79627dc088ee5d8e1d2 Mon Sep 17 00:00:00 2001 From: GaganSD Date: Wed, 18 Nov 2026 06:24:08 +0000 Subject: [PATCH 08/15] fix(slate): show cache hit rates to two decimal places --- pi-slate/CHANGELOG.md | 2 +- pi-slate/extensions/pi-slate/perf-graphics.ts | 6 ++--- pi-slate/tests/perf-graphics.test.ts | 22 +++++++++---------- pi-slate/tests/sidebar-preview.test.ts | 4 ++-- 4 files changed, 17 insertions(+), 17 deletions(-) diff --git a/pi-slate/CHANGELOG.md b/pi-slate/CHANGELOG.md index 8e1de78..376f1f1 100644 --- a/pi-slate/CHANGELOG.md +++ b/pi-slate/CHANGELOG.md @@ -5,7 +5,7 @@ ### Added - Sidebar SPEED section: tok/s of the latest response (exact: output tokens ÷ response time), a graph of recent responses, turn average, output and peak. Responses under 32 tokens or 300 ms are not timed. On tall terminals the figure is drawn in large digits. -- Sidebar CACHE section: active-branch hit % matching the read/write/new bar, spend and estimated savings. Session details also show the latest request's hit %. A warm/cold countdown appears only when the model publishes its cache lifetime. +- Sidebar CACHE section: active-branch hit % matching the read/write/new bar, spend and estimated savings. Session details also show the latest request's hit %. Hit rates use up to two decimal places and show “all cached” instead of 100%. A warm/cold countdown appears only when the model publishes its cache lifetime. - The status row shows Working/Idle, the turn number, and the running turn's elapsed time. ### Changed diff --git a/pi-slate/extensions/pi-slate/perf-graphics.ts b/pi-slate/extensions/pi-slate/perf-graphics.ts index 14fce5c..762baa8 100644 --- a/pi-slate/extensions/pi-slate/perf-graphics.ts +++ b/pi-slate/extensions/pi-slate/perf-graphics.ts @@ -207,8 +207,8 @@ export function speedRows(i: PerfInput): string[] { export function formatCacheHit(rate: number | null): string { if (rate === null) return "—"; - const rounded = Math.round(rate * 100); - return rounded === 100 && rate < 1 ? ">99%" : `${rounded}%`; + if (rate === 1) return "all cached"; + return `${Math.min(99.99, Math.round(rate * 10_000) / 100)}%`; } /** Headline uses the same branch totals as the bar; warmth is based on the latest request. */ @@ -221,7 +221,7 @@ function cacheSegs(i: PerfInput, full: boolean): Seg[][] { : w.state === "cold" ? ["warning", "cold"] : w.idleMs !== null && w.idleMs >= 60_000 ? ["dim", `idle ${formatIdle(w.idleMs)}`] : null; const sep: Seg = ["dim", " · "]; - const hitSegs = (long: boolean): Seg[] => hit === null ? [] : long ? [["text", hit], ["dim", " hit"]] : [["text", hit]]; + const hitSegs = (long: boolean): Seg[] => hit === null ? [] : long && rate !== 1 ? [["text", hit], ["dim", " hit"]] : [["text", hit]]; const join = (a: Seg[], b: Seg | null): Seg[] => b ? (a.length ? [...a, sep, b] : [b]) : a; return [join(hitSegs(true), warm), join(hitSegs(false), warm), hitSegs(true), hitSegs(false)]; } diff --git a/pi-slate/tests/perf-graphics.test.ts b/pi-slate/tests/perf-graphics.test.ts index 5012e47..b1a722a 100644 --- a/pi-slate/tests/perf-graphics.test.ts +++ b/pi-slate/tests/perf-graphics.test.ts @@ -154,23 +154,23 @@ test("CACHE heading: hit, warmth countdown, cold, unknown lifetime and idle hint const base = perfFixture(1_000_000); const head = (cache: Partial, now: number, tier: PerfInput["tier"] = "full") => strip(cacheRows(input({ ...base, cache: { ...base.cache, ...cache } }, 40, tier, now))[0]!); - assert.match(head({}, 1_000_000), /^CACHE\s+84% hit · ◉ 4:41$/); + assert.match(head({}, 1_000_000), /^CACHE\s+84\.03% hit · ◉ 4:41$/); assert.match(head({}, 1_000_000 + 1000), /◉ 4:40$/, "countdown moves with the clock alone"); - assert.match(head({}, 1_000_000 + 400_000), /84% hit · cold$/); - assert.match(head({ ttlMs: null }, 1_000_000 + 30_000), /^CACHE\s+84% hit$/, "no lifetime and recent: nothing extra"); - assert.match(head({ ttlMs: null, lastActivityAt: 1_000_000 - 62_000 }, 1_000_000, "compact"), /^CACHE\s+84% hit · idle 1m$/); + assert.match(head({}, 1_000_000 + 400_000), /84\.03% hit · cold$/); + assert.match(head({ ttlMs: null }, 1_000_000 + 30_000), /^CACHE\s+84\.03% hit$/, "no lifetime and recent: nothing extra"); + assert.match(head({ ttlMs: null, lastActivityAt: 1_000_000 - 62_000 }, 1_000_000, "compact"), /^CACHE\s+84\.03% hit · idle 1m$/); }); test("CACHE headline and bar use branch totals and distinguish near-perfect from exact hits", () => { const base = perfFixture(1000); const perf = { ...base, cache: { ...base.cache, lastHit: 0.9956 } }; - for (const [read, label, cells] of [[8600, "86%", 34], [9500, "95%", 38], [9956, ">99%", 39], [10000, "100%", 40]] as const) { - const totals = { ...usage, input: 10000, cacheRead: read, cacheWrite: 0, uncached: 10000 - read }; + for (const [read, label, cells] of [[86_000, "86% hit", 34], [95_200, "95.2% hit", 38], [99_560, "99.56% hit", 39], [99_999, "99.99% hit", 39], [100_000, "all cached", 40]] as const) { + const totals = { ...usage, input: 100_000, cacheRead: read, cacheWrite: 0, uncached: 100_000 - read }; const i = input(perf, 40, "compact", 1000, totals); const [heading, bar] = cacheRows({ ...i, paint: (t, x) => t === "success" ? x.replaceAll("━", "█") : x }); - assert(heading?.includes(`${label} hit`)); + assert(heading?.includes(label)); assert.equal(bar, "█".repeat(cells) + "━".repeat(40 - cells)); - assert(combinedRow(i).includes(`${label} hit`)); + assert(combinedRow(i).includes(label)); } const unknown = SECTIONS(perf, 40, "full", { ...usage, input: null, uncached: null }).cache; assert.match(unknown[0]!, /^CACHE\s+◉ 4:41$/, "unknown totals omit the hit rate"); @@ -251,11 +251,11 @@ test("mini tier shows the combined speed/cache row; details explain the numbers" const clock = { now: 1_000_000 }; const base = perfFixture(clock.now); const s = sidebarWith(24, { ...base, cache: { ...base.cache, lastHit: 0.9956 } }, clock); - assert.match(s.render(40).map(strip).join("\n"), /14\.6 tok\/s · 84% hit · warm 4:41/); + assert.match(s.render(40).map(strip).join("\n"), /14\.6 tok\/s · 84\.03% hit · warm 4:41/); assert.match(s.sessionDetails(), /Speed & cache/); assert.match(s.sessionDetails(), /300 ms/); - assert.match(s.sessionDetails(), /Cache-hit share: 84%/); - assert.match(s.sessionDetails(), /latest request >99%\./); + assert.match(s.sessionDetails(), /Cache-hit share: 84\.03%/); + assert.match(s.sessionDetails(), /latest request 99\.56%\./); }); test("themed render keeps tones within the theme palette", () => { diff --git a/pi-slate/tests/sidebar-preview.test.ts b/pi-slate/tests/sidebar-preview.test.ts index 3abcd1c..d8dd8eb 100644 --- a/pi-slate/tests/sidebar-preview.test.ts +++ b/pi-slate/tests/sidebar-preview.test.ts @@ -48,7 +48,7 @@ function task(i: number): BackgroundTask { test("quiet session rail merges usage into context and hides empty shelves", () => { const { sidebar } = fixture(); const lines = plain(sidebar.render(80)); - for (const label of ["Working · turn 2", "session-", "sonnet-4.6", "16%", "31.6k/200k", "SPEED", "CACHE", "78% hit", "spent $0.12", "MCP · 6 Enabled", "Skills · 1 Loaded", "Prompts · 6"]) + for (const label of ["Working · turn 2", "session-", "sonnet-4.6", "16%", "31.6k/200k", "SPEED", "CACHE", "78.18% hit", "spent $0.12", "MCP · 6 Enabled", "Skills · 1 Loaded", "Prompts · 6"]) assert(lines.some(line => line.includes(label)), label); for (const label of ["Stats", "Tokens · branch", "Commands ·", "Tasks", "Preview", "no selection", "/run-0", "prompt-0"]) assert(!lines.some(line => line.includes(label)), label); @@ -152,7 +152,7 @@ test("speed and cache replace the usage lane; full accounting stays in details", for (const width of [18, 28, 40, 80]) { const text = plain(sidebar.render(width)).join("\n"); assert(text.includes("CACHE") && text.includes("SPEED")); - if (width >= 28) for (const value of ["6.1k", "$0.12", "78%"]) assert(text.includes(value), value); + if (width >= 28) for (const value of ["6.1k", "$0.12", "78.18%"]) assert(text.includes(value), value); assert(!/\bCached\b|Uncached|\bPID\b/.test(text), "old usage rows are gone"); } assert.match(sidebar.sessionDetails(), /Cache read: 48k · Cache write: 6.1k/); From 32d896f35bba0b7656a9da56ba6210f2ff53f49c Mon Sep 17 00:00:00 2001 From: GaganSD Date: Wed, 18 Nov 2026 06:34:29 +0000 Subject: [PATCH 09/15] fix(slate): restore compact speed sparkline without streaming badge --- pi-slate/CHANGELOG.md | 4 +-- pi-slate/extensions/pi-slate/index.ts | 11 +++---- pi-slate/extensions/pi-slate/perf-graphics.ts | 21 +++++++------ pi-slate/extensions/pi-slate/sidebar-data.ts | 2 +- pi-slate/extensions/pi-slate/sidebar.ts | 6 ++-- pi-slate/tests/perf-graphics.test.ts | 31 +++++++------------ pi-slate/tests/quiet-workbench.test.ts | 2 +- pi-slate/tests/sidebar-preview.test.ts | 3 +- 8 files changed, 36 insertions(+), 44 deletions(-) diff --git a/pi-slate/CHANGELOG.md b/pi-slate/CHANGELOG.md index 376f1f1..ada1b89 100644 --- a/pi-slate/CHANGELOG.md +++ b/pi-slate/CHANGELOG.md @@ -4,14 +4,14 @@ ### Added -- Sidebar SPEED section: tok/s of the latest response (exact: output tokens ÷ response time), a graph of recent responses, turn average, output and peak. Responses under 32 tokens or 300 ms are not timed. On tall terminals the figure is drawn in large digits. +- Sidebar SPEED section: tok/s of the latest response (exact: output tokens ÷ response time), a graph of recent responses, turn average, output and peak. Responses under 32 tokens or 300 ms are not timed. Compact terminals use a block sparkline; tall terminals show large digits and a Braille graph. - Sidebar CACHE section: active-branch hit % matching the read/write/new bar, spend and estimated savings. Session details also show the latest request's hit %. Hit rates use up to two decimal places and show “all cached” instead of 100%. A warm/cold countdown appears only when the model publishes its cache lifetime. - The status row shows Working/Idle, the turn number, and the running turn's elapsed time. ### Changed - The sidebar header is reorganised into status, CONTEXT, SPEED and CACHE, which share one layout (heading with the key figure on the right, one bar or graph row, labelled details), and adapts to terminal height (full, compact, mini). CONTEXT is a single bar; use pi-context-view for the category breakdown. -- Live speed updates to the sidebar are throttled to about 4 per second. +- The SPEED card shows completed replies. The live rate estimate remains in the composer. ## 0.2.1 diff --git a/pi-slate/extensions/pi-slate/index.ts b/pi-slate/extensions/pi-slate/index.ts index d2bb68f..60dc5c3 100644 --- a/pi-slate/extensions/pi-slate/index.ts +++ b/pi-slate/extensions/pi-slate/index.ts @@ -231,7 +231,6 @@ export default function piSlate(pi: ExtensionAPI): void { let dashboardClock: ReturnType | undefined; const dashboardSubscriptions: Array<() => void> = []; let branchFacts: { leaf?: string | null; counts: ReturnType; usage: ReturnType; perf: ReturnType } | undefined; - let liveStreaming = false; let lastLiveSync = 0; let liveSyncTimer: ReturnType | undefined; let inspectingSidebar = false; @@ -346,7 +345,7 @@ export default function piSlate(pi: ExtensionAPI): void { tokens, percent, contextWindow, estimated, rate: rate > 0 ? rate : null, startedAt: sessionStartedAt, lastTurnMs, turnStartedAt: turnStartedAt ?? null, working: typeof ctx.isIdle === "function" && !ctx.isIdle(), ...branchFacts.counts, usage: branchFacts.usage, - perf: branchFacts.perf, streaming: liveStreaming, + perf: branchFacts.perf, }); } contextEdge = { @@ -436,7 +435,7 @@ export default function piSlate(pi: ExtensionAPI): void { }, () => {}); } if (owns("editor")) branch.start(ctx.cwd); - sessionStartedAt = Date.now(); turnStartedAt = undefined; lastTurnMs = null; branchFacts = undefined; liveStreaming = false; + sessionStartedAt = Date.now(); turnStartedAt = undefined; lastTurnMs = null; branchFacts = undefined; if (owns("editor") || owns("sidebar")) { skills.reset([]); skills.restore(ctx.sessionManager.getBranch(), ctx.cwd); @@ -725,7 +724,6 @@ export default function piSlate(pi: ExtensionAPI): void { currentContext = ctx; if (event.message.role === "assistant") { thinkingFold.stop(); - liveStreaming = true; if (ctx.mode === "tui" && (owns("editor") || owns("sidebar"))) tokenRate.startMessage(); } }); @@ -743,7 +741,6 @@ export default function piSlate(pi: ExtensionAPI): void { currentContext = ctx; if (event.message.role === "assistant") { thinkingFold.stop(); - liveStreaming = false; if (ctx.mode === "tui" && (owns("editor") || owns("sidebar"))) tokenRate.endMessage(); } else if (owns("sidebar") && ctx.mode === "tui" && event.message.role === "toolResult") { skills.observeNested(event.message.nestedCalls?.calls ?? [], ctx.cwd); @@ -790,7 +787,7 @@ export default function piSlate(pi: ExtensionAPI): void { currentContext = ctx; thinkingFold.stop(); if (owns("sidebar") && ctx.mode === "tui") { - branchFacts = undefined; liveStreaming = false; skills.restore(ctx.sessionManager.getBranch(), ctx.cwd); + branchFacts = undefined; skills.restore(ctx.sessionManager.getBranch(), ctx.cwd); background.reset(ctx.sessionManager.getSessionId?.() ?? ""); sidebar.setTasks([]); pi.events.emit?.(BACKGROUND_TASKS_REQUEST, { version: 1, sessionId: ctx.sessionManager.getSessionId?.() ?? "" }); refreshResources(ctx); syncSidebar(ctx); @@ -799,7 +796,7 @@ export default function piSlate(pi: ExtensionAPI): void { }); pi.on("session_shutdown", (_event, ctx) => { sessionEpoch += 1; - liveStreaming = false; if (liveSyncTimer) { clearTimeout(liveSyncTimer); liveSyncTimer = undefined; } + if (liveSyncTimer) { clearTimeout(liveSyncTimer); liveSyncTimer = undefined; } workingWord = undefined; stopWave(); thinkingFold.stop(); diff --git a/pi-slate/extensions/pi-slate/perf-graphics.ts b/pi-slate/extensions/pi-slate/perf-graphics.ts index 762baa8..f746cb1 100644 --- a/pi-slate/extensions/pi-slate/perf-graphics.ts +++ b/pi-slate/extensions/pi-slate/perf-graphics.ts @@ -113,7 +113,7 @@ export function formatIdle(ms: number): string { // One grammar for CONTEXT, SPEED and CACHE: heading row (label left, key figure right), one // full-width visual row, then `label value · label value` detail rows. Padding is always spaces. -export type PerfInput = { perf: SidebarPerf; usage: SidebarUsage; streaming: boolean; now: number; inner: number; tier: SidebarTier } & PerfPaint; +export type PerfInput = { perf: SidebarPerf; usage: SidebarUsage; now: number; inner: number; tier: SidebarTier } & PerfPaint; type Seg = readonly [Tone, string]; const fit = (lines: string[], width: number): string[] => lines.map(l => truncateToWidth(l, width, "…")); @@ -172,13 +172,19 @@ export function contextRows(i: PerfInput, c: { percent: number | null; tokens: n ]; } +function speedSparkline(rates: readonly number[], width: number): string { + if (width <= 0) return ""; + const shown = rates.slice(-width); + const peak = Math.max(...shown); + return shown.map(rate => "▁▂▃▄▅▆▇█"[Math.round(rate / peak * 7)]).join("").padEnd(width); +} + /** Headline is always the exact last eligible response. */ export function speedRows(i: PerfInput): string[] { const { perf, inner, paint } = i; - const streaming: readonly Seg[] = i.streaming ? [["warning", "● streaming"]] : []; const rate = perf.rates.at(-1); if (rate === undefined) { - return [headingRow(i, "SPEED", [[...streaming, ...(streaming.length ? [["text", " "] as Seg] : []), DASH], [DASH]]), + return [headingRow(i, "SPEED", [[DASH]]), noteRow(i, perf.requests > 0 ? "replies too short to time" : "waiting for first response")]; } const digits = formatRate(rate); @@ -186,14 +192,11 @@ export function speedRows(i: PerfInput): string[] { const unit: Seg = ["dim", " tok/s"]; const out = perf.turn && perf.turn.output > 0 ? formatCompactTokenCount(perf.turn.output) : "—"; const detail = detailRow(i, [["avg", formatRate(perf.turn?.rate)], ["peak", formatRate(perf.peak)], ["out", out]]); - const gap: Seg = ["text", " "]; if (i.tier !== "full") { - const lead = streaming.length ? [...streaming, gap] : []; - const visual = paint("accent", brailleBars(perf.rates, inner, 1)[0]!); - return [headingRow(i, "SPEED", [[...lead, value, unit], [...lead, value], [value, unit], [value]]), visual, detail]; + const visual = paint("accent", speedSparkline(perf.rates, inner)); + return [headingRow(i, "SPEED", [[value, unit], [value]]), visual, detail]; } - const right: Seg[][] = [streaming.length ? [...streaming] : [["dim", "last response"]], streaming.length ? [["warning", "●"]] : []]; - const rows = [headingRow(i, "SPEED", right)]; + const rows = [headingRow(i, "SPEED", [[["dim", "last response"]]])]; const [a, b, c] = bigDigits(digits) as [string, string, string]; const digitWidth = visibleWidth(a); if (digitWidth <= inner && [...digits].every(ch => ch in FONT)) { diff --git a/pi-slate/extensions/pi-slate/sidebar-data.ts b/pi-slate/extensions/pi-slate/sidebar-data.ts index 1b12101..287886b 100644 --- a/pi-slate/extensions/pi-slate/sidebar-data.ts +++ b/pi-slate/extensions/pi-slate/sidebar-data.ts @@ -20,7 +20,7 @@ export type SidebarResources = { skills: SidebarSkill[]; commands: SidebarComman export type SidebarSession = { id: string; name?: string; pid: number; cwd: string; model: string; thinking: string; tokens: number | null; percent: number | null; contextWindow: number | null; - estimated: boolean; rate: number | null; startedAt: number; lastTurnMs: number | null; streaming: boolean; + estimated: boolean; rate: number | null; startedAt: number; lastTurnMs: number | null; /** Wall-clock start of the running turn; absent or null when idle. */ turnStartedAt?: number | null; working: boolean; turns: number; messages: number; usage: SidebarUsage; diff --git a/pi-slate/extensions/pi-slate/sidebar.ts b/pi-slate/extensions/pi-slate/sidebar.ts index 0b21604..092b3e1 100644 --- a/pi-slate/extensions/pi-slate/sidebar.ts +++ b/pi-slate/extensions/pi-slate/sidebar.ts @@ -26,7 +26,7 @@ export type SidebarActions = { const EMPTY_SESSION: SidebarSession = { id: "", name: "", pid: process.pid, cwd: "", model: "—", thinking: "—", tokens: null, percent: null, contextWindow: null, estimated: false, rate: null, startedAt: 0, - lastTurnMs: null, working: false, streaming: false, turns: 0, messages: 0, + lastTurnMs: null, working: false, turns: 0, messages: 0, usage: { input: null, output: null, total: null, cacheRead: null, cacheWrite: null, uncached: null, cacheSeen: false, cost: null }, perf: EMPTY_PERF, }; @@ -171,7 +171,7 @@ export class Sidebar implements Component { return ["", "Speed & cache", `Speed is end-to-end: output tokens ÷ request duration (includes time to first token and hidden reasoning).`, `Requests under 32 output tokens or 300 ms are left out of the graph, peak and last response.`, - `The live value while streaming is an estimate (visible text ÷ 4) and is marked ~.`, + `The composer's live rate is an estimate (visible text ÷ 4) and is marked ~.`, `Timed requests: ${perf.requests} · last response: ${formatRate(perf.rates.at(-1))} tok/s · peak: ${formatRate(perf.peak)} tok/s · this turn: ${formatRate(perf.turn?.rate)} tok/s`, `Cache hit % = cache read ÷ (uncached + cache read + cache write); latest request ${formatCacheHit(c.lastHit)}.`, `Saved is an estimate of what cache reads cost less than uncached input${c.saved === null ? " (prices unknown here)" : ""}.`, @@ -282,7 +282,7 @@ export class Sidebar implements Component { }; const model: Row = { text: this.pair(this.paint("text", sidebarText(s.model)), this.paint("dim", sidebarText(s.thinking)), width) }; const divider: Row = { text: "", divider: true }; - const input: PerfInput = { perf: s.perf, usage: s.usage, streaming: s.streaming, now: this.now(), inner: width, tier, paint: (t, x) => this.paint(t, x), heading: x => this.heading(x) }; + const input: PerfInput = { perf: s.perf, usage: s.usage, now: this.now(), inner: width, tier, paint: (t, x) => this.paint(t, x), heading: x => this.heading(x) }; const context: Row[] = contextRows(input, { percent, tokens: s.tokens, window: s.contextWindow, estimated: s.estimated }) .map(text => ({ text, action: branchUsage })); // Short terminals keep the same CONTEXT heading row (label left, figures right) without the bar. diff --git a/pi-slate/tests/perf-graphics.test.ts b/pi-slate/tests/perf-graphics.test.ts index b1a722a..7cd5d6c 100644 --- a/pi-slate/tests/perf-graphics.test.ts +++ b/pi-slate/tests/perf-graphics.test.ts @@ -11,7 +11,7 @@ const strip = (t: string) => t.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, ""); const plainPaint = { paint: (_t: string, x: string) => x, heading: (x: string) => x }; const usage: SidebarUsage = { input: 1_559_000, output: 12_000, total: 1_571_000, cacheRead: 1_310_000, cacheWrite: 108_000, uncached: 141_000, cacheSeen: true, cost: 0.84 }; const noUsage: SidebarUsage = { input: null, output: null, total: null, cacheRead: null, cacheWrite: null, uncached: null, cacheSeen: false, cost: null }; -const input = (perf: SidebarPerf, inner = 40, tier: PerfInput["tier"] = "full", now = 1000, totals = usage): PerfInput => ({ perf, usage: totals, streaming: false, now, inner, tier, ...plainPaint }); +const input = (perf: SidebarPerf, inner = 40, tier: PerfInput["tier"] = "full", now = 1000, totals = usage): PerfInput => ({ perf, usage: totals, now, inner, tier, ...plainPaint }); test("formatRate uses one decimal below 100, integers below 1000, then compact units", () => { const cases: Array<[number | null, string]> = [[14.64, "14.6"], [0, "0.0"], [99.96, "100"], [100, "100"], [999.4, "999"], [999.6, "1k"], [1234, "1.2k"], @@ -93,29 +93,20 @@ test("compact SPEED: heading, left-aligned sparkline, labelled detail row; paddi const { speed } = SECTIONS(perf); assert.equal(speed.length, 3); assert.match(speed[0]!, /^SPEED\s+23\.5 tok\/s$/); - assert.match(speed[1]!, /^[⠁-⣿]{3} +$/); assert.equal(speed[1]!.length, 40); + assert.equal(speed[1], "▄▇▅▆█".padEnd(40)); + assert.equal(SECTIONS(perf, 3).speed[1], "▅▆█", "show the newest sample per column"); assert.equal(speed[2], "avg 13.9 · peak 23.5 · out 214"); }); -test("a single rate renders one braille column at the left", () => { +test("a single rate renders one block at the left", () => { const perf: SidebarPerf = { ...EMPTY_PERF, requests: 1, rates: [30], peak: 30, turn: { output: 300, rate: 30 } }; - assert.match(SECTIONS(perf).speed[1]!, /^⡇ +$/); -}); - -test("streaming adds a marker but the headline stays the exact last rate", () => { - const perf = perfFixture(1000); - const compact = speedRows({ ...input(perf, 40, "compact"), streaming: true }); - assert.match(compact[0]!, /^SPEED\s+● streaming {2}14\.6 tok\/s$/); - const full = speedRows({ ...input(perf), streaming: true }); - assert.match(full[0]!, /^SPEED\s+● streaming$/); - assert.match(SECTIONS(perf, 40, "full").speed[0]!, /^SPEED\s+last response$/); - const first = speedRows({ ...input(EMPTY_PERF, 40, "compact"), streaming: true }); - assert.match(first[0]!, /^SPEED\s+● streaming {2}—$/); assert.equal(first[1], "waiting for first response"); + assert.match(SECTIONS(perf).speed[1]!, /^█ +$/); }); test("full SPEED: big digits, two braille rows, then the same detail row", () => { const rows = SECTIONS(perfFixture(1000), 40, "full").speed; assert.equal(rows.length, 7); + assert.match(rows[0]!, /^SPEED\s+last response$/); assert.equal(rows[2], " █ ▀▀█ █▀█ tok/s"); assert.match(rows[4]!, /[⠁-⣿]/); assert.match(rows[5]!, /[⠁-⣿]/); assert.equal(rows[6], "avg 26.7 · peak 45.0 · out 12k"); @@ -134,7 +125,7 @@ test("huge numbers and tiny widths stay inside the width", () => { const perf: SidebarPerf = { ...base, peak: 1e9, rates: [12_345, 1e9], turn: { output: 9e12, rate: 1e15 }, cache: { ...base.cache, saved: 1.2e6 } }; assert.equal(SECTIONS(perf, 40, "full").speed[1], "1B tok/s", "unsupported big glyphs fall back to text"); for (const inner of [1, 4, 10, 16, 21, 22, 24, 30, 44, 60]) for (const tier of ["full", "compact"] as const) for (const cost of [1.2e6, 1e308, null]) { - const i = { ...input(perf, inner, tier, 1000, { ...usage, cacheWrite: 1e12, uncached: 1e15, cost }), streaming: true }; + const i = input(perf, inner, tier, 1000, { ...usage, cacheWrite: 1e12, uncached: 1e15, cost }); for (const r of [...speedRows(i), ...cacheRows(i), combinedRow(i), ...contextRows(i, { percent: 91, tokens: 1e12, window: 1e15, estimated: true })]) { assert(visibleWidth(r) <= inner, `${inner} ${tier}: ${strip(r)}`); assert.doesNotMatch(strip(r), /NaN|Infinity/); } @@ -210,7 +201,7 @@ function sidebarWith(rows: number, perf: SidebarPerf, clock: { now: number }, ex const sidebar = new Sidebar(() => clock.now); sidebar.attach({ terminal: { rows, columns: 140 }, requestRender() {}, showOverlay() { return { hide() {} }; } } as unknown as TUI, undefined as never); sidebar.setSession({ id: "01a1cd96-0000", name: "fix auth refresh", pid: 1, cwd: "/p", model: "gpt-6.1-sol (openai)", thinking: "medium", tokens: 152_000, percent: 38, - contextWindow: 400_000, estimated: false, rate: null, startedAt: 1, lastTurnMs: 39_000, working: false, streaming: false, turns: 7, messages: 14, + contextWindow: 400_000, estimated: false, rate: null, startedAt: 1, lastTurnMs: 39_000, working: false, turns: 7, messages: 14, usage, perf, ...extra }); return sidebar; } @@ -237,11 +228,11 @@ test("render recomputes the countdown each second without extra timers", () => { assert.notEqual(a, b); assert.match(a, /◉ 4:41/); assert.match(b, /◉ 4:40/); }); -test("every tier and width keeps rows bounded, including live streaming and long sessions", () => { +test("every tier and width keeps rows bounded, during working turns and long sessions", () => { const clock = { now: 1_000_000 }; const perf: SidebarPerf = { ...perfFixture(clock.now), rates: Array.from({ length: 256 }, (_, i) => 10 + (i % 40)), requests: 5000 }; for (const rows of [10, 19, 20, 29, 30, 43, 44, 70]) for (const width of [0, 1, 5, 12, 20, 28, 44, 60, 90]) { - const lines = sidebarWith(rows, perf, clock, { working: true, streaming: true }).render(width); + const lines = sidebarWith(rows, perf, clock, { working: true }).render(width); assert.equal(lines.length, rows); assert(lines.every(l => visibleWidth(l) <= width), `${width}x${rows}`); } @@ -265,7 +256,7 @@ test("themed render keeps tones within the theme palette", () => { const s = new Sidebar(() => clock.now); s.attach({ terminal: { rows: 60, columns: 140 }, requestRender() {}, showOverlay() { return { hide() {} }; } } as unknown as TUI, theme); s.setSession({ id: "a", pid: 1, cwd: "", model: "m", thinking: "low", tokens: 1, percent: 90, contextWindow: 10, estimated: true, rate: null, startedAt: 1, lastTurnMs: null, - working: true, streaming: false, turns: 1, messages: 1, usage, perf: perfFixture(clock.now) }); + working: true, turns: 1, messages: 1, usage, perf: perfFixture(clock.now) }); s.render(44); for (const t of tones) assert(["text", "muted", "dim", "accent", "success", "warning", "error", "mdHeading", "border", "borderMuted", "borderAccent"].includes(t) || /^[a-zA-Z]+$/.test(t), t); assert(tones.has("success") && tones.has("accent") && tones.has("warning")); diff --git a/pi-slate/tests/quiet-workbench.test.ts b/pi-slate/tests/quiet-workbench.test.ts index f2629e8..134e207 100644 --- a/pi-slate/tests/quiet-workbench.test.ts +++ b/pi-slate/tests/quiet-workbench.test.ts @@ -15,7 +15,7 @@ import type { SidebarSession } from "../extensions/pi-slate/sidebar-data.ts"; const theme = loadThemeFromPath(new URL("../themes/tokyo-night.json", import.meta.url).pathname, "truecolor"); const session: SidebarSession = { id: "example-session", pid: 8421, cwd: "/tmp/project", model: "sample-model", thinking: "medium", tokens: 55000, percent: 11, contextWindow: 500000, - estimated: false, rate: 82, startedAt: 1000, lastTurnMs: 14000, working: true, streaming: false, turns: 4, messages: 8, + estimated: false, rate: 82, startedAt: 1000, lastTurnMs: 14000, working: true, turns: 4, messages: 8, usage: { input: 128400, output: 6800, total: 135200, cacheRead: 94000, cacheWrite: 22000, uncached: 12400, cacheSeen: true, cost: 1.24 }, perf: perfFixture(1000) }; test("bundled default Tokyo Night loads with the native validator and restrained backgrounds", () => { diff --git a/pi-slate/tests/sidebar-preview.test.ts b/pi-slate/tests/sidebar-preview.test.ts index d8dd8eb..40a2c88 100644 --- a/pi-slate/tests/sidebar-preview.test.ts +++ b/pi-slate/tests/sidebar-preview.test.ts @@ -15,7 +15,7 @@ import type { BackgroundTask } from "../extensions/pi-slate/background-tasks.ts" const theme = (code = 32) => ({ fg: (_tone: string, text: string) => `\x1b[${code}m${text}\x1b[0m`, bold: (text: string) => text }) as Theme; const stripAnsi = (text: string) => text.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, ""); const plain = (lines: string[]) => lines.map(line => stripAnsi(line).replace(/^│ ?/, "").replace(/ ?│$/, "").trimEnd()); -const session: SidebarSession = { id: "session-a", pid: 8421, cwd: "/tmp/project", model: "sonnet-4.6", thinking: "medium", tokens: 31600, percent: 16, contextWindow: 200000, estimated: false, rate: 82, startedAt: 1000, lastTurnMs: 5000, working: true, streaming: false, turns: 2, messages: 5, usage: { input: 61400, output: 876, total: 62276, cacheRead: 48000, cacheWrite: 6100, uncached: 7300, cacheSeen: true, cost: 0.12 }, perf: perfFixture(1000) }; +const session: SidebarSession = { id: "session-a", pid: 8421, cwd: "/tmp/project", model: "sonnet-4.6", thinking: "medium", tokens: 31600, percent: 16, contextWindow: 200000, estimated: false, rate: 82, startedAt: 1000, lastTurnMs: 5000, working: true, turns: 2, messages: 5, usage: { input: 61400, output: 876, total: 62276, cacheRead: 48000, cacheWrite: 6100, uncached: 7300, cacheSeen: true, cost: 0.12 }, perf: perfFixture(1000) }; const noUsage: SidebarUsage = { input: null, output: null, total: null, cacheRead: null, cacheWrite: null, uncached: null, cacheSeen: false, cost: null }; const resources: SidebarResources = { mcp: Array.from({ length: 7 }, (_, i) => ({ name: `server-${i}`, enabled: i !== 2, source: "global" })), @@ -152,6 +152,7 @@ test("speed and cache replace the usage lane; full accounting stays in details", for (const width of [18, 28, 40, 80]) { const text = plain(sidebar.render(width)).join("\n"); assert(text.includes("CACHE") && text.includes("SPEED")); + assert.doesNotMatch(text, /● streaming/); if (width >= 28) for (const value of ["6.1k", "$0.12", "78.18%"]) assert(text.includes(value), value); assert(!/\bCached\b|Uncached|\bPID\b/.test(text), "old usage rows are gone"); } From 1c0f33dfd215739db0c56132a721ad83fea90595 Mon Sep 17 00:00:00 2001 From: GaganSD Date: Wed, 18 Nov 2026 07:06:40 +0000 Subject: [PATCH 10/15] fix(slate): tighten performance accounting and sidebar layout --- pi-slate/CHANGELOG.md | 8 +- pi-slate/extensions/pi-slate/index.ts | 57 +++--- pi-slate/extensions/pi-slate/perf-graphics.ts | 37 ++-- pi-slate/extensions/pi-slate/perf-stats.ts | 169 +++++++---------- pi-slate/extensions/pi-slate/sidebar-data.ts | 21 ++- .../extensions/pi-slate/sidebar-layout.ts | 36 ++-- pi-slate/extensions/pi-slate/sidebar.ts | 42 ++--- pi-slate/tests/perf-fixture.ts | 4 +- pi-slate/tests/perf-graphics.test.ts | 49 +++-- pi-slate/tests/perf-stats.test.ts | 171 +++++++----------- pi-slate/tests/quiet-workbench.test.ts | 4 +- pi-slate/tests/sidebar-data.test.ts | 23 ++- pi-slate/tests/sidebar-preview.test.ts | 37 ++-- pi-slate/tests/surfaces-install.test.ts | 52 +++++- 14 files changed, 335 insertions(+), 375 deletions(-) diff --git a/pi-slate/CHANGELOG.md b/pi-slate/CHANGELOG.md index ada1b89..0b11018 100644 --- a/pi-slate/CHANGELOG.md +++ b/pi-slate/CHANGELOG.md @@ -4,13 +4,13 @@ ### Added -- Sidebar SPEED section: tok/s of the latest response (exact: output tokens ÷ response time), a graph of recent responses, turn average, output and peak. Responses under 32 tokens or 300 ms are not timed. Compact terminals use a block sparkline; tall terminals show large digits and a Braille graph. -- Sidebar CACHE section: active-branch hit % matching the read/write/new bar, spend and estimated savings. Session details also show the latest request's hit %. Hit rates use up to two decimal places and show “all cached” instead of 100%. A warm/cold countdown appears only when the model publishes its cache lifetime. -- The status row shows Working/Idle, the turn number, and the running turn's elapsed time. +- Sidebar SPEED section: tok/s of the latest eligible reply (output tokens ÷ Pi's recorded provider-stream duration), a graph of recent responses, turn average, output and peak. Responses under 32 tokens or 300 ms are not timed. Compact terminals use a block sparkline; tall terminals show large digits and a Braille graph. +- Sidebar CACHE section: active-branch hit % matching the read/write/new bar, spend and estimated savings. Session details also show the latest request's hit %. Hit rates use up to two decimal places and show “all cached” instead of 100%. An estimated expiry countdown appears only when the last reported cache activity and its retention tier are known. +- The status row shows Working/Idle, elapsed time while working, and the branch turn count when idle. ### Changed -- The sidebar header is reorganised into status, CONTEXT, SPEED and CACHE, which share one layout (heading with the key figure on the right, one bar or graph row, labelled details), and adapts to terminal height (full, compact, mini). CONTEXT is a single bar; use pi-context-view for the category breakdown. +- The sidebar header is reorganised into status, CONTEXT, SPEED and CACHE, which share one layout (heading with the key figure on the right, one bar or graph row, labelled details), and adapts to terminal height (full and compact). CONTEXT is a single bar; use pi-context-view for the category breakdown. - The SPEED card shows completed replies. The live rate estimate remains in the composer. ## 0.2.1 diff --git a/pi-slate/extensions/pi-slate/index.ts b/pi-slate/extensions/pi-slate/index.ts index 60dc5c3..d084585 100644 --- a/pi-slate/extensions/pi-slate/index.ts +++ b/pi-slate/extensions/pi-slate/index.ts @@ -231,8 +231,6 @@ export default function piSlate(pi: ExtensionAPI): void { let dashboardClock: ReturnType | undefined; const dashboardSubscriptions: Array<() => void> = []; let branchFacts: { leaf?: string | null; counts: ReturnType; usage: ReturnType; perf: ReturnType } | undefined; - let lastLiveSync = 0; - let liveSyncTimer: ReturnType | undefined; let inspectingSidebar = false; let sidebarYielded = false; let sessionEpoch = 0; @@ -270,9 +268,8 @@ export default function piSlate(pi: ExtensionAPI): void { const tokenRate = new TokenRateTracker(); const thinkingFold = new ThinkingFoldTracker({ onChange: () => syncThinkingStatus() }); const branch = new GitBranchPoller(pi, (next) => { gitBranch = next; requestRender(); }); - let contextEdge = { - tokens: formatFocusedContextTokens(null, null, null), - resources: formatFocusedContextResources(null, false, 0), + let contextEdge: { percent: number | null; window: number | null; resources: string } = { + percent: null, window: null, resources: formatFocusedContextResources(null, false, 0), }; let requestRender = (_force = false) => {}; @@ -329,15 +326,14 @@ export default function piSlate(pi: ExtensionAPI): void { percent = resolved.percent; contextWindow = usage?.contextWindow ?? ctx.model?.contextWindow ?? null; } catch { /* Context can be temporarily unavailable; keep identity and other facts fresh. */ } - const leaf = ctx.sessionManager.getLeafId?.(); - if (!branchFacts || leaf === undefined || leaf !== branchFacts.leaf) { - const entries = ctx.sessionManager.getBranch(); - branchFacts = { leaf, counts: sidebarMessageCounts(entries), usage: sidebarUsage(entries), - perf: branchPerf(entries, { promptCache: ctx.model?.promptCache, retentionLong: process.env.PI_CACHE_RETENTION === "long" }) }; - } - const rate = tokenRate.rate(); - const mcpCount = resources.mcp.filter(server => server.enabled === true).length; if (owns("sidebar") && !sidebarYielded) { + const leaf = ctx.sessionManager.getLeafId?.(); + if (!branchFacts || leaf === undefined || leaf !== branchFacts.leaf) { + const entries = ctx.sessionManager.getBranch(); + branchFacts = { leaf, counts: sidebarMessageCounts(entries), usage: sidebarUsage(entries), + perf: branchPerf(entries, (provider, model) => ctx.modelRegistry.find(provider, model)?.promptCache) }; + } + const rate = tokenRate.rate(); sidebar.setSession({ id: ctx.sessionManager.getSessionId?.() ?? "", name: ctx.sessionManager.getSessionName?.(), @@ -348,10 +344,8 @@ export default function piSlate(pi: ExtensionAPI): void { perf: branchFacts.perf, }); } - contextEdge = { - tokens: formatFocusedContextTokens(percent, rate, contextWindow), - resources: formatFocusedContextResources(percent, estimated, mcpCount), - }; + contextEdge = { percent, window: contextWindow, + resources: formatFocusedContextResources(percent, estimated, resources.mcp.filter(server => server.enabled === true).length) }; }; const refreshResources = (ctx: ExtensionContext): void => { if (ctx.mode !== "tui" || !ctx.sessionManager || (!owns("sidebar") && !owns("editor")) || (sidebarYielded && !editorActive())) return; @@ -440,18 +434,7 @@ export default function piSlate(pi: ExtensionAPI): void { skills.reset([]); skills.restore(ctx.sessionManager.getBranch(), ctx.cwd); refreshResources(ctx); - tokenRate.setOnChange(() => { - // Per-token updates reach the sidebar at most ~4/s; a trailing sync keeps the last one. - const flush = (): void => { - liveSyncTimer = undefined; lastLiveSync = Date.now(); - const live = liveContext(); - if (live) syncSidebar(live); - }; - const wait = 250 - (Date.now() - lastLiveSync); - if (wait <= 0) { if (liveSyncTimer) clearTimeout(liveSyncTimer); flush(); } - else if (!liveSyncTimer) liveSyncTimer = setTimeout(flush, wait); - if (thinkingFold.elapsedMs() !== null) syncThinkingStatus(); - }); + tokenRate.setOnChange(() => { if (thinkingFold.elapsedMs() !== null) syncThinkingStatus(); }); syncSidebar(ctx); } @@ -546,8 +529,9 @@ export default function piSlate(pi: ExtensionAPI): void { const ctx = liveContext(); if (!ctx || ctx.mode !== "tui" || !sidebar.splitActive) return; diagnostics.attempt("dashboard", "Last dashboard snapshot retained; a background refresh failed.", () => { - sidebar.tick(); if (++ticks % 5 === 0) { refreshResources(ctx); syncSidebar(ctx); } + else if (ctx.sessionManager.getLeafId() !== branchFacts?.leaf) syncSidebar(ctx); + sidebar.tick(); }, () => {}); }, 1000); dashboardClock.unref?.(); @@ -592,7 +576,9 @@ export default function piSlate(pi: ExtensionAPI): void { working: typeof current.isIdle === "function" && !current.isIdle(), workspaceHeader: owns("header"), dashboardVisible: sidebar.isVisible(tui.terminal.columns, tui.terminal.rows), - ...(!sidebar.isVisible(tui.terminal.columns, tui.terminal.rows) ? { context: contextEdge } : {}), + ...(!sidebar.isVisible(tui.terminal.columns, tui.terminal.rows) ? { context: { + tokens: formatFocusedContextTokens(contextEdge.percent, tokenRate.rate(), contextEdge.window), resources: contextEdge.resources, + } } : {}), }); let cachedMetadata = metadata(ctx); activeEditor = new ComposerEditor( @@ -712,7 +698,6 @@ export default function piSlate(pi: ExtensionAPI): void { }); pi.on("model_select", (_event, ctx) => { currentContext = ctx; - branchFacts = undefined; // cache lifetime depends on the selected model syncSidebar(ctx); }); pi.on("thinking_level_select", (_event, ctx) => { @@ -724,7 +709,10 @@ export default function piSlate(pi: ExtensionAPI): void { currentContext = ctx; if (event.message.role === "assistant") { thinkingFold.stop(); - if (ctx.mode === "tui" && (owns("editor") || owns("sidebar"))) tokenRate.startMessage(); + if (ctx.mode === "tui" && (owns("editor") || owns("sidebar"))) { + tokenRate.startMessage(); + syncSidebar(ctx); // Pi has persisted the input that started this request. + } } }); pi.on("message_update", (event, ctx) => { @@ -746,7 +734,6 @@ export default function piSlate(pi: ExtensionAPI): void { skills.observeNested(event.message.nestedCalls?.calls ?? [], ctx.cwd); } refreshResources(ctx); - syncSidebar(ctx); syncVisibleMessages(); }); pi.on("session_info_changed", (_event, ctx) => { currentContext = ctx; syncSidebar(ctx); }); @@ -762,6 +749,7 @@ export default function piSlate(pi: ExtensionAPI): void { skills.readStart(event.toolCallId, event.toolName, event.args, ctx.cwd); background.shellStart(event.toolCallId, event.toolName, event.args, Date.now()); sidebar.setTasks(background.snapshot()); + syncSidebar(ctx); // message_end precedes persistence; the tool starts after it. }); pi.on("tool_execution_end", (event, ctx) => { if (ctx.mode !== "tui") return; @@ -796,7 +784,6 @@ export default function piSlate(pi: ExtensionAPI): void { }); pi.on("session_shutdown", (_event, ctx) => { sessionEpoch += 1; - if (liveSyncTimer) { clearTimeout(liveSyncTimer); liveSyncTimer = undefined; } workingWord = undefined; stopWave(); thinkingFold.stop(); diff --git a/pi-slate/extensions/pi-slate/perf-graphics.ts b/pi-slate/extensions/pi-slate/perf-graphics.ts index f746cb1..e3cda6a 100644 --- a/pi-slate/extensions/pi-slate/perf-graphics.ts +++ b/pi-slate/extensions/pi-slate/perf-graphics.ts @@ -184,19 +184,17 @@ export function speedRows(i: PerfInput): string[] { const { perf, inner, paint } = i; const rate = perf.rates.at(-1); if (rate === undefined) { - return [headingRow(i, "SPEED", [[DASH]]), - noteRow(i, perf.requests > 0 ? "replies too short to time" : "waiting for first response")]; + return [headingRow(i, "SPEED", [[DASH]]), noteRow(i, "no timed replies")]; } const digits = formatRate(rate); const value: Seg = ["text", digits]; const unit: Seg = ["dim", " tok/s"]; - const out = perf.turn && perf.turn.output > 0 ? formatCompactTokenCount(perf.turn.output) : "—"; - const detail = detailRow(i, [["avg", formatRate(perf.turn?.rate)], ["peak", formatRate(perf.peak)], ["out", out]]); + const detail = detailRow(i, [["avg", formatRate(perf.turn.rate)], ["peak", formatRate(perf.peak)], ["out", formatCompactTokenCount(perf.turn.output)]]); if (i.tier !== "full") { const visual = paint("accent", speedSparkline(perf.rates, inner)); return [headingRow(i, "SPEED", [[value, unit], [value]]), visual, detail]; } - const rows = [headingRow(i, "SPEED", [[["dim", "last response"]]])]; + const rows = [headingRow(i, "SPEED", [[["dim", "last timed reply"]]])]; const [a, b, c] = bigDigits(digits) as [string, string, string]; const digitWidth = visibleWidth(a); if (digitWidth <= inner && [...digits].every(ch => ch in FONT)) { @@ -215,12 +213,12 @@ export function formatCacheHit(rate: number | null): string { } /** Headline uses the same branch totals as the bar; warmth is based on the latest request. */ -function cacheSegs(i: PerfInput, full: boolean): Seg[][] { +function cacheSegs(i: PerfInput): Seg[][] { const { cache: c } = i.perf; const rate = sidebarCacheHit(i.usage); const hit = rate === null ? null : formatCacheHit(rate); const w = cacheWarmth(c, i.now); - const warm: Seg | null = w.state === "warm" ? ["success", full ? `◉ ${formatCountdown(w.remainingMs ?? 0)}` : `warm ${formatCountdown(w.remainingMs ?? 0)}`] + const warm: Seg | null = w.state === "warm" ? ["success", `◉ ${formatCountdown(w.remainingMs ?? 0)}`] : w.state === "cold" ? ["warning", "cold"] : w.idleMs !== null && w.idleMs >= 60_000 ? ["dim", `idle ${formatIdle(w.idleMs)}`] : null; const sep: Seg = ["dim", " · "]; @@ -230,31 +228,18 @@ function cacheSegs(i: PerfInput, full: boolean): Seg[][] { } export function cacheRows(i: PerfInput): string[] { - const { perf, usage, inner, paint } = i; - if (!usage.cacheSeen) return [headingRow(i, "CACHE", [[DASH]]), noteRow(i, perf.requests === 0 ? "no requests yet" : "no cache reads reported")]; + const { usage, inner, paint } = i; + const spent: [string, string] = ["spent", sidebarCost(usage.cost)]; + if (!usage.cacheSeen) return [headingRow(i, "CACHE", [[DASH]]), noteRow(i, "no cache activity reported"), + ...(usage.cost !== null && (usage.cost > 0 || (usage.input ?? 0) > 0) ? [detailRow(i, [spent])] : [])]; const [r = 0, w = 0, u = 0] = usage.input === null ? [] : stackedBar([usage.cacheRead ?? 0, usage.cacheWrite ?? 0, usage.uncached ?? 0], inner); const bar = r || w || u ? paint("success", "━".repeat(r)) + paint("warning", "━".repeat(w)) + paint("muted", "━".repeat(u)) : baseline(i); const f = formatCompactTokenCount; - const spent: [string, string] = ["spent", sidebarCost(usage.cost)]; const tokens: Array<[string, string]> = [["read", f(usage.cacheRead)], ["write", f(usage.cacheWrite)], ["new", f(usage.uncached)]]; - const rows = [headingRow(i, "CACHE", cacheSegs(i, true)), bar]; + const rows = [headingRow(i, "CACHE", cacheSegs(i)), bar]; if (i.tier === "full") { - const saved = perf.cache.saved; + const saved = usage.saved; rows.push(detailRow(i, tokens), detailRow(i, nonneg(saved) ? [spent, ["saved", `~${sidebarCost(saved)}`]] : [spent])); } else rows.push(detailRow(i, [...tokens, spent])); return fit(rows, inner); } - -/** One row for short terminals: `23.5 tok/s · 62% hit · idle 1m`, shedding trailing parts to fit. */ -export function combinedRow(i: PerfInput): string { - const { perf } = i; - if (perf.requests === 0 && !i.usage.cacheSeen) return noteRow(i, "no requests yet"); - const rate = perf.rates.at(-1); - const speed: Seg[] = rate === undefined ? [DASH] : [["text", formatRate(rate)], ["dim", " tok/s"]]; - const cache = i.usage.cacheSeen ? cacheSegs(i, false) : [[]]; - const sep: Seg = ["dim", " · "]; - const variants = cache.map(c => c.length ? [...speed, sep, ...c] : speed); - variants.push(speed); - const pick = variants.find(v => segWidth(v) <= i.inner) ?? speed; - return truncateToWidth(paintSegs(i, pick), i.inner, "…"); -} diff --git a/pi-slate/extensions/pi-slate/perf-stats.ts b/pi-slate/extensions/pi-slate/perf-stats.ts index 224aa30..abd909e 100644 --- a/pi-slate/extensions/pi-slate/perf-stats.ts +++ b/pi-slate/extensions/pi-slate/perf-stats.ts @@ -1,148 +1,109 @@ import type { SessionEntry } from "@earendil-works/pi-coding-agent"; import { nonnegative, record } from "./sidebar-data.ts"; -/** - * Speed and prompt-cache facts for the session rail. - * - * Accuracy contract (the rail is for glancing, so every number must be honest): - * - "Exact" values come only from finished assistant messages on the active branch: - * `usage.output`, `usage.cacheRead/cacheWrite/input`, `timestamp` (request start) and - * `durationMs` (request start → response end, monotonic). - * - A request's speed is end-to-end: output tokens ÷ (durationMs / 1000). It includes - * time to first token and hidden reasoning, both of which are real waiting time. - * - Anything unknowable is `null`, never 0. The renderer shows `—` or omits the item. - */ - -/** Requests below either bound are latency-dominated; they count toward totals and the turn's - * output, but never toward the graph, the peak, the turn average, or "last response". */ export const PERF_MIN_OUTPUT_TOKENS = 32; export const PERF_MIN_DURATION_MS = 300; -/** Bounded history so very long sessions cost constant memory in the rail. */ export const PERF_MAX_RATES = 256; -export type SidebarTurnPerf = { - /** Exact output tokens since the last user message, including tiny replies. */ - output: number; - /** Eligible output ÷ eligible seconds for this turn; null if no replies qualify. */ - rate: number | null; -}; - export type SidebarCachePerf = { - /** cacheRead ÷ (input + cacheRead + cacheWrite) of the latest assistant request (0..1). */ lastHit: number | null; - /** Counterfactual dollars saved by cache reads; always an estimate. null when prices are unknown. */ - saved: number | null; - /** Wall-clock ms when the latest request ended (timestamp + durationMs); drives warm/cold. */ lastActivityAt: number | null; - /** Cache lifetime that applies to the latest request; null when the provider's lifetime is unknown. */ ttlMs: number | null; }; export type SidebarPerf = { - /** Timed assistant requests on the branch (eligible or not). */ - requests: number; - /** Exact end-to-end rates of eligible requests, oldest → newest, at most PERF_MAX_RATES. */ + timedReplies: number; + /** Eligible output rates, oldest first. Peak includes replies outside this window. */ rates: number[]; - /** Max of all eligible rates on the branch (not only the retained window). */ peak: number | null; - turn: SidebarTurnPerf | null; + turn: { output: number | null; rate: number | null }; cache: SidebarCachePerf; }; export const EMPTY_PERF: SidebarPerf = { - requests: 0, rates: [], peak: null, turn: null, - cache: { lastHit: null, saved: null, lastActivityAt: null, ttlMs: null }, + timedReplies: 0, rates: [], peak: null, turn: { output: 0, rate: null }, + cache: { lastHit: null, lastActivityAt: null, ttlMs: null }, }; -// --------------------------------------------------------------------------- -// Computation -// --------------------------------------------------------------------------- +type CacheProducer = { provider: string; model: string }; +type CacheActivity = CacheProducer & { at: number | null; writes: number | null; hourWrites: number | null }; +type PromptCacheLookup = (provider: string, model: string) => { short?: number; long?: number } | undefined; + +function cacheActivity(producer: CacheProducer & { responseModel?: string }, usage: Record | undefined, at: number | null): CacheActivity | undefined { + const writes = nonnegative(usage?.cacheWrite); + if (!(writes || (nonnegative(usage?.cacheRead) ?? 0) > 0)) return; + return { provider: producer.provider, model: producer.responseModel ?? producer.model, at, writes, hourWrites: nonnegative(usage?.cacheWrite1h) }; +} + +function cacheLifetime(activity: CacheActivity, lookup: PromptCacheLookup): number | null { + const { short, long } = lookup(activity.provider, activity.model) ?? {}; + // Neither the current selection nor a zero 1h split proves what a past request used: + // the Anthropic adapter also reports zero when the split is absent. + const { writes, hourWrites } = activity; + const seconds = short === long ? short : writes && hourWrites === writes ? long : undefined; + const ms = nonnegative((seconds ?? 0) * 1000); + return ms || null; +} -export type PerfPromptCache = { short?: number; long?: number } | undefined; -export type BranchPerfOptions = { promptCache?: PerfPromptCache; retentionLong: boolean }; +function reportedHit(usage: Record | undefined): number | null { + const read = nonnegative(usage?.cacheRead); + const write = nonnegative(usage?.cacheWrite); + const input = nonnegative(usage?.input); + if (read === null || write === null || input === null) return null; + const total = read + write + input; + return total > 0 && Number.isFinite(total) ? read / total : null; +} -/** - * One O(n) pass over the active branch. - * - * Turn rule: every timed assistant request after the last user message whose stopReason is not - * error/aborted/deferred counts toward `turn.output`. The turn rate and speed graph both - * require output >= PERF_MIN_OUTPUT_TOKENS and duration >= PERF_MIN_DURATION_MS. - */ -export function branchPerf(entries: readonly SessionEntry[], opts: BranchPerfOptions): SidebarPerf { - let requests = 0; +/** Completed output does not require timing. Rates use Pi's recorded provider-stream duration. */ +export function branchPerf(entries: readonly SessionEntry[], promptCacheFor: PromptCacheLookup = () => undefined): SidebarPerf { + let timedReplies = 0; let rates: number[] = []; let peak: number | null = null; - let turnOutput: number | null = null; + let turnOutput: number | null = 0; let turnRateOut = 0; let turnRateMs = 0; - let saved = 0; let pricedAny = false; - let lastUsage: Record | undefined; - let lastActivityAt: number | null = null; + let lastHit: number | null = null; + let latestCache: CacheActivity | undefined; const ids = new Set(); for (const entry of entries) { - if (entry.type !== "message" || ids.has(entry.id)) continue; + if (ids.has(entry.id)) continue; ids.add(entry.id); - const message = entry.message; - if (message.role === "user") { turnOutput = null; turnRateOut = 0; turnRateMs = 0; continue; } - if (message.role !== "assistant") continue; - const usage = record(message.usage); - if (!usage) continue; - lastUsage = usage; - const read = nonnegative(usage.cacheRead); const input = nonnegative(usage.input); - if (read !== null && read > 0 && input !== null && input > 0) { - const cost = record(usage.cost); - const inputPrice = (nonnegative(cost?.input) ?? NaN) / input; - const readPrice = (nonnegative(cost?.cacheRead) ?? NaN) / read; - if (Number.isFinite(inputPrice) && inputPrice > 0 && Number.isFinite(readPrice)) { - const term = read * (inputPrice - readPrice); - if (Number.isFinite(term)) { saved += Math.max(0, term); pricedAny = true; } - } + if (entry.type === "usage" && entry.kind === "cache_warm") { + latestCache = cacheActivity(entry, record(entry.usage), nonnegative(Date.parse(entry.timestamp))) ?? latestCache; } + if (entry.type !== "message") continue; + const { message } = entry; + if (message.role === "user") { turnOutput = 0; turnRateOut = 0; turnRateMs = 0; continue; } + if (message.role !== "assistant" || message.stopReason === "error" || message.stopReason === "aborted" || message.stopReason === "deferred") continue; - const timestamp = message.timestamp; - const durationMs = message.durationMs; - if (typeof timestamp !== "number" || !Number.isFinite(timestamp) - || typeof durationMs !== "number" || !Number.isFinite(durationMs) || durationMs <= 0) continue; - requests += 1; - lastActivityAt = timestamp + durationMs; - const stop = message.stopReason; - if (stop === "error" || stop === "aborted" || stop === "deferred") continue; - const output = nonnegative(usage.output); - if (output === null) continue; - turnOutput = (turnOutput ?? 0) + output; - if (output >= PERF_MIN_OUTPUT_TOKENS && durationMs >= PERF_MIN_DURATION_MS) { - const rate = output / (durationMs / 1000); - if (!Number.isFinite(rate)) continue; - turnRateOut += output; turnRateMs += durationMs; - rates.push(rate); - if (rates.length >= PERF_MAX_RATES * 2) rates = rates.slice(-PERF_MAX_RATES); - if (peak === null || rate > peak) peak = rate; - } - } - if (rates.length > PERF_MAX_RATES) rates = rates.slice(-PERF_MAX_RATES); + const usage = record(message.usage); + const duration = nonnegative(message.durationMs); + const timestamp = nonnegative(message.timestamp); + const endedAt = timestamp === null || duration === null ? null : nonnegative(timestamp + duration); + latestCache = cacheActivity(message, usage, endedAt); + lastHit = reportedHit(usage); + const output = nonnegative(usage?.output); + turnOutput = output === null || turnOutput === null ? null : nonnegative(turnOutput + output); + if (output === null || output < PERF_MIN_OUTPUT_TOKENS || duration === null || duration < PERF_MIN_DURATION_MS) continue; - let lastHit: number | null = null; - let ttlMs: number | null = null; - if (lastUsage) { - const input = nonnegative(lastUsage.input); const read = nonnegative(lastUsage.cacheRead); const write = nonnegative(lastUsage.cacheWrite); - if (input !== null && read !== null && write !== null) { - const total = input + read + write; - if (total > 0) lastHit = read / total; - } - const long = (nonnegative(lastUsage.cacheWrite1h) ?? 0) > 0; - const seconds = long || opts.retentionLong ? opts.promptCache?.long : opts.promptCache?.short; - if (typeof seconds === "number" && Number.isFinite(seconds) && seconds > 0) ttlMs = seconds * 1000; + const rate = output / (duration / 1000); + if (!Number.isFinite(rate)) continue; + timedReplies += 1; + turnRateOut += output; turnRateMs += duration; + rates.push(rate); + if (rates.length >= PERF_MAX_RATES * 2) rates = rates.slice(-PERF_MAX_RATES); + if (peak === null || rate > peak) peak = rate; } + return { - requests, rates, peak, - turn: turnOutput === null ? null : { output: turnOutput, rate: turnRateMs > 0 ? turnRateOut / (turnRateMs / 1000) : null }, - cache: { lastHit, saved: pricedAny && Number.isFinite(saved) ? saved : null, lastActivityAt, ttlMs }, + timedReplies, rates: rates.slice(-PERF_MAX_RATES), peak, + turn: { output: turnOutput, rate: turnRateMs > 0 ? nonnegative(turnRateOut / (turnRateMs / 1000)) : null }, + cache: { lastHit, lastActivityAt: latestCache?.at ?? null, ttlMs: latestCache ? cacheLifetime(latestCache, promptCacheFor) : null }, }; } export type CacheWarmth = { state: "warm" | "cold" | "unknown"; remainingMs: number | null; idleMs: number | null }; -/** Warm/cold from the provider's cache lifetime; negative gaps (clock skew) clamp to 0. */ export function cacheWarmth(cache: SidebarCachePerf, now: number): CacheWarmth { const idleMs = cache.lastActivityAt === null || !Number.isFinite(now) ? null : Math.max(0, now - cache.lastActivityAt); if (cache.ttlMs === null || idleMs === null) return { state: "unknown", remainingMs: null, idleMs }; diff --git a/pi-slate/extensions/pi-slate/sidebar-data.ts b/pi-slate/extensions/pi-slate/sidebar-data.ts index 287886b..f29f492 100644 --- a/pi-slate/extensions/pi-slate/sidebar-data.ts +++ b/pi-slate/extensions/pi-slate/sidebar-data.ts @@ -12,6 +12,8 @@ export type SidebarUsage = { input: number | null; output: number | null; cacheRead: number | null; cacheWrite: number | null; uncached: number | null; total: number | null; cost: number | null; cacheSeen: boolean; + /** Branch-wide read savings estimate; unknown unless every cached read is priceable. */ + saved: number | null; }; export type SidebarSkill = { name: string; path: string; source: string; loaded: boolean }; export type SidebarCommand = { name: string; source: string; description?: string }; @@ -37,12 +39,20 @@ export function nonnegative(value: unknown): number | null { return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null; } +function cacheReadSavings(raw: Record, cost: Record | undefined, read: number): number | null { + const input = nonnegative(raw.input); + const inputCost = nonnegative(cost?.input); + const readCost = nonnegative(cost?.cacheRead); + return input && inputCost && readCost !== null ? nonnegative(Math.max(0, read * (inputCost / input) - readCost)) : null; +} + /** Active-branch usage, including nested tools and summaries, once per owning entry. */ export function sidebarUsage(entries: readonly SessionEntry[]): SidebarUsage { const sums = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 }; const missing = new Set(); const seen = new Set(); let cacheSeen = false; + let saved: number | null = 0; for (const entry of entries) { if (seen.has(entry.id)) continue; seen.add(entry.id); @@ -60,8 +70,16 @@ export function sidebarUsage(entries: readonly SessionEntry[]): SidebarUsage { if (expected) for (const key of Object.keys(sums) as Array) missing.add(key); continue; } + const cost = record(raw.cost); + const read = nonnegative(raw.cacheRead); + if (read && saved !== null) { + // Summary and tool ledgers may blend distinct requests and prices. + const singleRequest = entry.type === "usage" && entry.kind === "cache_warm" || entry.type === "message" && entry.message.role === "assistant"; + const estimate = singleRequest ? cacheReadSavings(raw, cost, read) : null; + saved = estimate === null ? null : nonnegative(saved + estimate); + } for (const key of Object.keys(sums) as Array) { - const value = nonnegative(key === "cost" ? record(raw.cost)?.total : raw[key]); + const value = nonnegative(key === "cost" ? cost?.total : raw[key]); if (value === null) missing.add(key); else { sums[key] += value; @@ -81,6 +99,7 @@ export function sidebarUsage(entries: readonly SessionEntry[]): SidebarUsage { cacheWrite: missing.has("cacheWrite") ? null : sums.cacheWrite, total: inbound === null || output === null ? null : nonnegative(inbound + output), cost: missing.has("cost") ? null : sums.cost, + saved: missing.has("cacheRead") || !sums.cacheRead ? null : saved, }; } diff --git a/pi-slate/extensions/pi-slate/sidebar-layout.ts b/pi-slate/extensions/pi-slate/sidebar-layout.ts index f3beea7..a2418a9 100644 --- a/pi-slate/extensions/pi-slate/sidebar-layout.ts +++ b/pi-slate/extensions/pi-slate/sidebar-layout.ts @@ -1,24 +1,22 @@ -export type SidebarSlots = { header: number; middle: number; tasks: number; image: number; footer: number }; +export type SidebarSlots = { frame: number; header: number; middle: number; tasks: number; image: number; footer: number }; +export type SidebarTier = "full" | "compact"; -/** How much of the session rail's top half fits; chosen from terminal rows alone. */ -export type SidebarTier = "full" | "compact" | "mini" | "micro"; -export function sidebarTier(rows: number): SidebarTier { - return rows >= 44 ? "full" : rows >= 30 ? "compact" : rows >= 20 ? "mini" : "micro"; -} - -/** Allocate once for both painting and hit testing. Never depend on composer height. */ -export function sessionSidebarSlots(height: number, headerRows: number, taskCount: number, hasImage: boolean): SidebarSlots { +/** Budget borders, content and hit regions together. Shed header gaps before squeezing a preview. */ +export function sessionSidebarSlots(height: number, headerRows: number, taskCount: number, hasImage: boolean, gaps = 0): SidebarSlots { const rows = Math.max(0, Math.floor(height)); - const footer = rows >= 12 ? 1 : 0; - const header = Math.min(headerRows, rows - footer); - let remaining = rows - header - footer; - const middleMin = Math.min(6, remaining); - const taskWant = taskCount ? (rows < 30 ? 1 : 2) + Math.min(rows < 30 ? 2 : 3, taskCount) * 2 : 0; - const tasks = Math.min(taskWant, Math.max(0, remaining - middleMin)); - remaining -= tasks; - const imageWant = hasImage ? rows < 20 ? 2 : Math.min(10, Math.max(4, Math.floor(rows / 5))) : 0; - const image = Math.min(imageWant, Math.max(0, remaining - middleMin)); - return { header, middle: remaining - image, tasks, image, footer }; + const frame = rows >= 12 ? 2 : 0; + const footer = frame ? 1 : 0; + const available = rows - frame - footer; + const taskWant = taskCount ? 2 + Math.min(3, taskCount) * 2 : 0; + const previewMin = hasImage ? 4 : 0; + const headerWant = hasImage ? Math.max(headerRows - gaps, Math.min(headerRows, available - 6 - taskWant - previewMin)) : headerRows; + const header = Math.min(available, headerWant); + const body = available - header; + const spare = Math.max(0, body - 6); + const tasks = Math.min(taskWant, spare - Math.min(previewMin, spare)); + const imageWant = hasImage ? Math.min(10, Math.max(previewMin, Math.floor(rows / 5))) : 0; + const image = Math.min(imageWant, spare - tasks); + return { frame, header, middle: body - tasks - image, tasks, image, footer }; } export function sidebarListOffset(offset: number, count: number, visible: number): number { diff --git a/pi-slate/extensions/pi-slate/sidebar.ts b/pi-slate/extensions/pi-slate/sidebar.ts index 092b3e1..591ebec 100644 --- a/pi-slate/extensions/pi-slate/sidebar.ts +++ b/pi-slate/extensions/pi-slate/sidebar.ts @@ -7,14 +7,15 @@ import type { WorkspaceView } from "./workspace.ts"; import { chromePaint } from "./composer.ts"; import { DEFAULT_SIDEBAR_FOLDS, sidebarCacheHit, sidebarText, type SidebarFolds, type SidebarResources, type SidebarSession } from "./sidebar-data.ts"; import type { BackgroundTask } from "./background-tasks.ts"; -import { sessionSidebarSlots, sidebarDuration, sidebarListOffset, sidebarTier, type SidebarTier } from "./sidebar-layout.ts"; -import { cacheRows, combinedRow, contextRows, formatCacheHit, formatCountdown, formatRate, speedRows, type PerfInput } from "./perf-graphics.ts"; +import { sessionSidebarSlots, sidebarDuration, sidebarListOffset, type SidebarTier } from "./sidebar-layout.ts"; +import { cacheRows, contextRows, formatCacheHit, formatCountdown, formatRate, speedRows, type PerfInput } from "./perf-graphics.ts"; import { cacheWarmth, EMPTY_PERF } from "./perf-stats.ts"; export const DOUBLE_CLICK_MS = 400; type ListName = "mcp" | "skills" | "prompts" | "tasks"; type Row = { divider?: boolean; text: string; action?: () => void; list?: ListName; item?: number; extra?: Array<{ x0: number; x1: number; action: () => void }> }; type Hit = { y: number; x0: number; x1: number; action: () => void }; +const HEADER_GAP: Row = { text: "" }; export type SidebarActions = { copy(text: string): void; openFile(filePath: string): void; @@ -27,7 +28,7 @@ const EMPTY_SESSION: SidebarSession = { id: "", name: "", pid: process.pid, cwd: "", model: "—", thinking: "—", tokens: null, percent: null, contextWindow: null, estimated: false, rate: null, startedAt: 0, lastTurnMs: null, working: false, turns: 0, messages: 0, - usage: { input: null, output: null, total: null, cacheRead: null, cacheWrite: null, uncached: null, cacheSeen: false, cost: null }, + usage: { input: null, output: null, total: null, cacheRead: null, cacheWrite: null, uncached: null, cacheSeen: false, cost: null, saved: null }, perf: EMPTY_PERF, }; const EMPTY_RESOURCES: SidebarResources = { skills: [], commands: [], prompts: [], mcp: [] }; @@ -169,13 +170,13 @@ export class Sidebar implements Component { const c = perf.cache; const warmth = cacheWarmth(c, this.now()); return ["", "Speed & cache", - `Speed is end-to-end: output tokens ÷ request duration (includes time to first token and hidden reasoning).`, - `Requests under 32 output tokens or 300 ms are left out of the graph, peak and last response.`, + `Speed is output tokens ÷ Pi's recorded provider-stream duration, not total turn time.`, + `Replies with less than 32 output tokens, less than 300 ms, or missing timing are excluded from speed.`, `The composer's live rate is an estimate (visible text ÷ 4) and is marked ~.`, - `Timed requests: ${perf.requests} · last response: ${formatRate(perf.rates.at(-1))} tok/s · peak: ${formatRate(perf.peak)} tok/s · this turn: ${formatRate(perf.turn?.rate)} tok/s`, + `Timed replies: ${perf.timedReplies} · last timed reply: ${formatRate(perf.rates.at(-1))} tok/s · peak: ${formatRate(perf.peak)} tok/s · this turn: ${formatRate(perf.turn.rate)} tok/s`, `Cache hit % = cache read ÷ (uncached + cache read + cache write); latest request ${formatCacheHit(c.lastHit)}.`, - `Saved is an estimate of what cache reads cost less than uncached input${c.saved === null ? " (prices unknown here)" : ""}.`, - `Cache lifetime is shown only when the provider publishes it${warmth.state === "unknown" ? " (not known for this model)" : ""}.`]; + `Saved is estimated from recorded prices only when all branch cache reads are priceable.`, + `Cache expiry is estimated from the last reported cache activity when its retention tier is known${warmth.state === "unknown" ? " (not established here)" : ""}.`]; } tick(): void { if (!this.hidden && this.splitActive) this.tui?.requestRender(); } invalidate(): void { @@ -225,11 +226,10 @@ export class Sidebar implements Component { const key = `${width}:${height}:${this.revision}:${Math.floor(this.now() / 1000)}`; if (this.cached?.key === key) return this.cached.lines; this.hits = []; this.listRows = []; - const chrome = height >= 12 ? 1 : 0; const inner = Math.max(0, width - 4); - const header = this.headerRows(inner, sidebarTier(height)); - const slots = sessionSidebarSlots(height, header.length, this.tasks.length, Boolean(this.imageView())); - if (chrome) slots.middle = Math.max(0, slots.middle - 2); + const header = this.headerRows(inner, height >= 44 ? "full" : "compact"); + const slots = sessionSidebarSlots(height, header.length, this.tasks.length, Boolean(this.imageView()), header.filter(row => row === HEADER_GAP).length); + let dropGaps = header.length - slots.header; const lines: string[] = []; const add = (row: Row): void => { const y = lines.length; @@ -238,8 +238,8 @@ export class Sidebar implements Component { if (row.action && inner > 0) this.hits.push({ y, x0: 2, x1: width - 2, action: row.action }); if (row.list) this.listRows.push({ y, list: row.list }); }; - if (chrome) lines.push(this.dividerLine(width, "┌")); - for (const row of header.slice(0, slots.header)) add(row); + if (slots.frame) lines.push(this.dividerLine(width, "┌")); + for (const row of header.filter(row => row !== HEADER_GAP || dropGaps-- <= 0).slice(0, slots.header)) add(row); const middle = this.middle(); this.middleRows = middle.length; this.middleHeight = slots.middle; this.middleStart = lines.length; this.middleOffset = sidebarListOffset(this.middleOffset, middle.length, slots.middle); @@ -248,8 +248,7 @@ export class Sidebar implements Component { this.imageStart = lines.length; this.imageHeight = slots.image; lines.push(...this.imageLines(width, slots.image, lines.length)); if (slots.footer) add({ text: this.paint("dim", "/slate session · details"), action: () => this.actions?.inspect?.("Session", this.sessionDetails()) }); - while (lines.length < height - chrome) lines.push(this.decorateLine("", width)); - if (chrome) lines.push(this.dividerLine(width, "└")); + if (slots.frame) lines.push(this.dividerLine(width, "└")); this.cached = { key, lines: lines.slice(0, height) }; return this.cached.lines; } @@ -267,7 +266,7 @@ export class Sidebar implements Component { const status: Row = (() => { const turns = s.turns === 1 ? "1 turn" : `${s.turns} turns`; const left = s.working - ? this.paint("success", "● Working") + this.paint("muted", s.turns > 0 ? ` · turn ${s.turns}` : "") + ? this.paint("success", "● Working") : this.paint("dim", "○ Idle") + (s.turns > 0 ? this.paint("muted", ` · ${turns}`) : ""); const started = s.turnStartedAt; const right = s.working @@ -285,13 +284,10 @@ export class Sidebar implements Component { const input: PerfInput = { perf: s.perf, usage: s.usage, now: this.now(), inner: width, tier, paint: (t, x) => this.paint(t, x), heading: x => this.heading(x) }; const context: Row[] = contextRows(input, { percent, tokens: s.tokens, window: s.contextWindow, estimated: s.estimated }) .map(text => ({ text, action: branchUsage })); - // Short terminals keep the same CONTEXT heading row (label left, figures right) without the bar. - if (tier === "micro") return [identity, model, context[0]!, divider]; - if (tier === "mini") return [status, identity, model, context[0]!, { text: combinedRow(input) }, divider]; const rows = (lines: string[]): Row[] => lines.map(text => ({ text })); - return [status, identity, model, { text: "" }, ...context, { text: "" }, - ...rows(speedRows(input)), { text: "" }, - ...rows(cacheRows(input)), { text: "" }, divider]; + return [status, identity, model, HEADER_GAP, ...context, HEADER_GAP, + ...rows(speedRows(input)), HEADER_GAP, + ...rows(cacheRows(input)), HEADER_GAP, divider]; } private middle(): Row[] { const enabled = this.resources.mcp.filter(x => x.enabled === true).length; diff --git a/pi-slate/tests/perf-fixture.ts b/pi-slate/tests/perf-fixture.ts index f83b57e..cfcad2d 100644 --- a/pi-slate/tests/perf-fixture.ts +++ b/pi-slate/tests/perf-fixture.ts @@ -3,10 +3,10 @@ import type { SidebarPerf } from "../extensions/pi-slate/perf-stats.ts"; /** Realistic mid-session perf facts shared by sidebar tests. `now` is the render clock. */ export function perfFixture(now: number): SidebarPerf { return { - requests: 12, + timedReplies: 28, rates: [18, 22, 26, 31, 24, 28, 35, 30, 22, 19, 27, 33, 38, 29, 24, 31, 36, 41, 45, 37, 30, 26, 33, 28, 21, 25, 30, 14.6], peak: 45, turn: { output: 12_000, rate: 26.7 }, - cache: { lastHit: 0.92, saved: 1.92, lastActivityAt: now - 19_000, ttlMs: 300_000 }, + cache: { lastHit: 0.92, lastActivityAt: now - 19_000, ttlMs: 300_000 }, }; } diff --git a/pi-slate/tests/perf-graphics.test.ts b/pi-slate/tests/perf-graphics.test.ts index 7cd5d6c..103206d 100644 --- a/pi-slate/tests/perf-graphics.test.ts +++ b/pi-slate/tests/perf-graphics.test.ts @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; import { visibleWidth, type TUI } from "@earendil-works/pi-tui"; -import { bigDigits, contextBar, brailleBars, cacheRows, combinedRow, contextRows, formatCountdown, formatRate, speedRows, stackedBar, type PerfInput } from "../extensions/pi-slate/perf-graphics.ts"; +import { bigDigits, contextBar, brailleBars, cacheRows, contextRows, formatCountdown, formatRate, speedRows, stackedBar, type PerfInput } from "../extensions/pi-slate/perf-graphics.ts"; import { EMPTY_PERF, type SidebarPerf } from "../extensions/pi-slate/perf-stats.ts"; import { Sidebar } from "../extensions/pi-slate/sidebar.ts"; import type { SidebarSession, SidebarUsage } from "../extensions/pi-slate/sidebar-data.ts"; @@ -9,8 +9,8 @@ import { perfFixture } from "./perf-fixture.ts"; const strip = (t: string) => t.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, ""); const plainPaint = { paint: (_t: string, x: string) => x, heading: (x: string) => x }; -const usage: SidebarUsage = { input: 1_559_000, output: 12_000, total: 1_571_000, cacheRead: 1_310_000, cacheWrite: 108_000, uncached: 141_000, cacheSeen: true, cost: 0.84 }; -const noUsage: SidebarUsage = { input: null, output: null, total: null, cacheRead: null, cacheWrite: null, uncached: null, cacheSeen: false, cost: null }; +const usage: SidebarUsage = { input: 1_559_000, output: 12_000, total: 1_571_000, cacheRead: 1_310_000, cacheWrite: 108_000, uncached: 141_000, cacheSeen: true, cost: 0.84, saved: 1.92 }; +const noUsage: SidebarUsage = { input: null, output: null, total: null, cacheRead: null, cacheWrite: null, uncached: null, cacheSeen: false, cost: null, saved: null }; const input = (perf: SidebarPerf, inner = 40, tier: PerfInput["tier"] = "full", now = 1000, totals = usage): PerfInput => ({ perf, usage: totals, now, inner, tier, ...plainPaint }); test("formatRate uses one decimal below 100, integers below 1000, then compact units", () => { @@ -76,16 +76,15 @@ test("empty perf: sections keep the grammar, collapse to two rows, and never pri for (const tier of ["full", "compact"] as const) { const { speed, cache } = SECTIONS(EMPTY_PERF, 40, tier, noUsage); assert.equal(speed.length, 2); assert.equal(cache.length, 2); - assert.match(speed[0]!, /^SPEED\s+—$/); assert.equal(speed[1], "waiting for first response"); - assert.match(cache[0]!, /^CACHE\s+—$/); assert.equal(cache[1], "no requests yet"); + assert.match(speed[0]!, /^SPEED\s+—$/); assert.equal(speed[1], "no timed replies"); + assert.match(cache[0]!, /^CACHE\s+—$/); assert.equal(cache[1], "no cache activity reported"); assert.doesNotMatch([...speed, ...cache].join("\n"), /NaN|Infinity|-\d|0%|[█▀]/); } - assert.equal(strip(combinedRow(input(EMPTY_PERF, 40, "mini", 1000, noUsage))), "no requests yet"); }); -test("provider that never reports cache shows an explicit note and no bar", () => { - const { cache } = SECTIONS(perfFixture(1000), 40, "compact", noUsage); - assert.equal(cache.length, 2); assert.equal(cache[1], "no cache reads reported"); assert.doesNotMatch(cache.join(""), /━/); +test("known spend is shown even without cache activity", () => { + const { cache } = SECTIONS(perfFixture(1000), 40, "compact", { ...noUsage, input: 100, cost: 0.84 }); + assert.deepEqual(cache.slice(1), ["no cache activity reported", "spent $0.84"]); }); test("compact SPEED: heading, left-aligned sparkline, labelled detail row; padding is spaces", () => { @@ -99,34 +98,35 @@ test("compact SPEED: heading, left-aligned sparkline, labelled detail row; paddi }); test("a single rate renders one block at the left", () => { - const perf: SidebarPerf = { ...EMPTY_PERF, requests: 1, rates: [30], peak: 30, turn: { output: 300, rate: 30 } }; + const perf: SidebarPerf = { ...EMPTY_PERF, timedReplies: 1, rates: [30], peak: 30, turn: { output: 300, rate: 30 } }; assert.match(SECTIONS(perf).speed[1]!, /^█ +$/); }); test("full SPEED: big digits, two braille rows, then the same detail row", () => { const rows = SECTIONS(perfFixture(1000), 40, "full").speed; assert.equal(rows.length, 7); - assert.match(rows[0]!, /^SPEED\s+last response$/); + assert.match(rows[0]!, /^SPEED\s+last timed reply$/); assert.equal(rows[2], " █ ▀▀█ █▀█ tok/s"); assert.match(rows[4]!, /[⠁-⣿]/); assert.match(rows[5]!, /[⠁-⣿]/); assert.equal(rows[6], "avg 26.7 · peak 45.0 · out 12k"); assert(!rows.join("").includes("Turn avg"), "the 3-column table is gone"); }); -test("avg, peak and headline are known together", () => { - const perf: SidebarPerf = { ...perfFixture(1000), peak: null, rates: [], turn: { output: 10, rate: null } }; - const rows = SECTIONS(perf).speed; - assert.equal(rows.length, 2, "no eligible rates: collapsed waiting state"); - assert.equal(rows[1], "replies too short to time"); +test("untimed replies don't masquerade as missing responses, and incomplete output stays unknown", () => { + const legacy: SidebarPerf = { ...EMPTY_PERF, turn: { output: 10, rate: null } }; + assert.equal(SECTIONS(legacy).speed[1], "no timed replies"); + const base = perfFixture(1000); + const incomplete: SidebarPerf = { ...base, turn: { ...base.turn, output: null } }; + assert.match(SECTIONS(incomplete).speed[2]!, /out —$/); }); test("huge numbers and tiny widths stay inside the width", () => { const base = perfFixture(1000); - const perf: SidebarPerf = { ...base, peak: 1e9, rates: [12_345, 1e9], turn: { output: 9e12, rate: 1e15 }, cache: { ...base.cache, saved: 1.2e6 } }; + const perf: SidebarPerf = { ...base, peak: 1e9, rates: [12_345, 1e9], turn: { output: 9e12, rate: 1e15 } }; assert.equal(SECTIONS(perf, 40, "full").speed[1], "1B tok/s", "unsupported big glyphs fall back to text"); for (const inner of [1, 4, 10, 16, 21, 22, 24, 30, 44, 60]) for (const tier of ["full", "compact"] as const) for (const cost of [1.2e6, 1e308, null]) { - const i = input(perf, inner, tier, 1000, { ...usage, cacheWrite: 1e12, uncached: 1e15, cost }); - for (const r of [...speedRows(i), ...cacheRows(i), combinedRow(i), ...contextRows(i, { percent: 91, tokens: 1e12, window: 1e15, estimated: true })]) { + const i = input(perf, inner, tier, 1000, { ...usage, cacheWrite: 1e12, uncached: 1e15, cost, saved: 1.2e6 }); + for (const r of [...speedRows(i), ...cacheRows(i), ...contextRows(i, { percent: 91, tokens: 1e12, window: 1e15, estimated: true })]) { assert(visibleWidth(r) <= inner, `${inner} ${tier}: ${strip(r)}`); assert.doesNotMatch(strip(r), /NaN|Infinity/); } } @@ -161,7 +161,6 @@ test("CACHE headline and bar use branch totals and distinguish near-perfect from const [heading, bar] = cacheRows({ ...i, paint: (t, x) => t === "success" ? x.replaceAll("━", "█") : x }); assert(heading?.includes(label)); assert.equal(bar, "█".repeat(cells) + "━".repeat(40 - cells)); - assert(combinedRow(i).includes(label)); } const unknown = SECTIONS(perf, 40, "full", { ...usage, input: null, uncached: null }).cache; assert.match(unknown[0]!, /^CACHE\s+◉ 4:41$/, "unknown totals omit the hit rate"); @@ -179,7 +178,7 @@ test("CACHE bars use the context glyph in three tones; money rows handle unknown assert.equal(themed.find(t => t.startsWith("success:━"))!.length - "success:".length + themed.find(t => t.startsWith("warning:━"))!.length - "warning:".length + themed.find(t => t.startsWith("muted:━"))!.length - "muted:".length, 40, "segments sum to the width"); assert.equal(full[2], "read 1.3M · write 108k · new 141k"); assert.equal(full[3], "spent $0.84 · saved ~$1.92"); - const none = SECTIONS({ ...perfFixture(1000), cache: { ...perfFixture(1000).cache, saved: null } }, 40, "full", { ...usage, cost: null }).cache; + const none = SECTIONS(perfFixture(1000), 40, "full", { ...usage, cost: null, saved: null }).cache; assert.equal(none[3], "spent —"); const compact = SECTIONS(perfFixture(1000), 48).cache; assert.equal(compact.length, 3); assert.equal(compact[2], "read 1.3M · write 108k · new 141k · spent $0.84"); @@ -230,7 +229,7 @@ test("render recomputes the countdown each second without extra timers", () => { test("every tier and width keeps rows bounded, during working turns and long sessions", () => { const clock = { now: 1_000_000 }; - const perf: SidebarPerf = { ...perfFixture(clock.now), rates: Array.from({ length: 256 }, (_, i) => 10 + (i % 40)), requests: 5000 }; + const perf: SidebarPerf = { ...perfFixture(clock.now), rates: Array.from({ length: 256 }, (_, i) => 10 + (i % 40)), timedReplies: 5000 }; for (const rows of [10, 19, 20, 29, 30, 43, 44, 70]) for (const width of [0, 1, 5, 12, 20, 28, 44, 60, 90]) { const lines = sidebarWith(rows, perf, clock, { working: true }).render(width); assert.equal(lines.length, rows); @@ -238,11 +237,11 @@ test("every tier and width keeps rows bounded, during working turns and long ses } }); -test("mini tier shows the combined speed/cache row; details explain the numbers", () => { +test("details distinguish branch and last-request cache rates", () => { const clock = { now: 1_000_000 }; const base = perfFixture(clock.now); - const s = sidebarWith(24, { ...base, cache: { ...base.cache, lastHit: 0.9956 } }, clock); - assert.match(s.render(40).map(strip).join("\n"), /14\.6 tok\/s · 84\.03% hit · warm 4:41/); + const s = sidebarWith(30, { ...base, cache: { ...base.cache, lastHit: 0.9956 } }, clock); + assert.match(s.render(40).map(strip).join("\n"), /CACHE\s+84\.03% hit · ◉ 4:41/); assert.match(s.sessionDetails(), /Speed & cache/); assert.match(s.sessionDetails(), /300 ms/); assert.match(s.sessionDetails(), /Cache-hit share: 84\.03%/); diff --git a/pi-slate/tests/perf-stats.test.ts b/pi-slate/tests/perf-stats.test.ts index 11833a6..648f7ba 100644 --- a/pi-slate/tests/perf-stats.test.ts +++ b/pi-slate/tests/perf-stats.test.ts @@ -1,133 +1,92 @@ import assert from "node:assert/strict"; import test from "node:test"; import type { SessionEntry } from "@earendil-works/pi-coding-agent"; -import { branchPerf, cacheWarmth, EMPTY_PERF, PERF_MAX_RATES, type SidebarCachePerf } from "../extensions/pi-slate/perf-stats.ts"; +import { branchPerf, cacheWarmth, EMPTY_PERF, PERF_MAX_RATES } from "../extensions/pi-slate/perf-stats.ts"; let seq = 0; -function entry(fields: Record): SessionEntry { return { id: `e${seq++}`, parentId: null, timestamp: "0", ...fields } as unknown as SessionEntry; } -function user(): SessionEntry { return entry({ type: "message", message: { role: "user" } }); } -function usageOf(over: Record = {}, cost: Record = {}) { - return { input: 10, output: 100, cacheRead: 0, cacheWrite: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, ...cost }, ...over }; +function entry(fields: Record): SessionEntry { + return { id: `e${seq++}`, parentId: null, timestamp: "1970-01-01T00:00:10.000Z", ...fields } as unknown as SessionEntry; } -function asst(over: Record = {}, usage: Record | undefined = usageOf()): SessionEntry { - const message: Record = { role: "assistant", timestamp: 1000, durationMs: 1000, stopReason: "stop", ...over }; - if (usage) message.usage = usage; - return entry({ type: "message", message }); -} -const opts = { retentionLong: false }; - -test("empty branch yields null facts", () => { - const perf = branchPerf([], opts); - assert.deepEqual(perf.rates, []); - assert.equal(perf.requests, 0); assert.equal(perf.peak, null); assert.equal(perf.turn, null); - assert.deepEqual(perf.cache, EMPTY_PERF.cache); -}); - -test("legacy messages without durationMs are not timed", () => { - const perf = branchPerf([user(), asst({ durationMs: undefined })], opts); - assert.equal(perf.requests, 0); assert.equal(perf.turn, null); assert.deepEqual(perf.rates, []); - assert.equal(perf.cache.lastHit, 0); -}); - -test("error, aborted and deferred are excluded from speed and turn", () => { - const perf = branchPerf([user(), asst({ stopReason: "error" }), asst({ stopReason: "aborted" }), asst({ stopReason: "deferred" })], opts); - assert.equal(perf.requests, 3); assert.deepEqual(perf.rates, []); assert.equal(perf.peak, null); assert.equal(perf.turn, null); +const user = () => entry({ type: "message", message: { role: "user" } }); +const asst = (fields: Record = {}, usage: Record = {}) => entry({ + type: "message", message: { role: "assistant", provider: "fixture", model: "a", timestamp: 1000, durationMs: 1000, + stopReason: "stop", usage: { input: 10, output: 100, cacheRead: 0, cacheWrite: 0, ...usage }, ...fields }, }); -test("tiny outputs count in the turn but not in rates or peak", () => { - const perf = branchPerf([user(), asst({}, usageOf({ output: 10 })), asst({ durationMs: 100 }, usageOf({ output: 500 })), asst({}, usageOf({ output: 100 }))], opts); - assert.deepEqual(perf.rates, [100]); assert.equal(perf.peak, 100); - assert.equal(perf.turn?.output, 610); - assert.equal(perf.turn?.rate, 100, "turn average uses the same eligibility as rates and peak"); - const onlyTiny = branchPerf([user(), asst({}, usageOf({ output: 10 }))], opts); - assert.equal(onlyTiny.turn?.output, 10); assert.equal(onlyTiny.turn?.rate, null); assert.equal(onlyTiny.peak, null); +test("empty and unsuccessful branches have no timed replies", () => { + assert.deepEqual(branchPerf([]), EMPTY_PERF); + const failed = ["error", "aborted", "deferred"].map(stopReason => asst({ stopReason }, { cacheRead: 128 })); + assert.deepEqual(branchPerf(failed), EMPTY_PERF); }); -test("turn average is token weighted, not a mean of rates", () => { - const perf = branchPerf([user(), asst({ durationMs: 1000 }, usageOf({ output: 100 })), asst({ durationMs: 9000 }, usageOf({ output: 900 }))], opts); - assert.equal(perf.turn?.rate, 100); // naive mean of (100, 100) agrees; use skewed case below - const skew = branchPerf([user(), asst({ durationMs: 1000 }, usageOf({ output: 1000 })), asst({ durationMs: 9000 }, usageOf({ output: 90 }))], opts); - assert.equal(skew.turn?.rate, 109); // 1090 / 10s, naive mean would be 505 +test("turn output includes tiny and untimed replies, but the weighted rate includes only eligible replies", () => { + const perf = branchPerf([user(), asst({ durationMs: undefined }, { output: 999 }), asst({}, { output: 10 }), + asst({ durationMs: 100 }, { output: 500 }), asst({}, { output: 1000 }), asst({ durationMs: 9000 }, { output: 90 })]); + assert.deepEqual(perf.rates, [1000, 10]); + assert.equal(perf.peak, 1000); + assert.equal(perf.timedReplies, 2); + assert.deepEqual(perf.turn, { output: 2599, rate: 109 }); + assert.deepEqual(branchPerf([asst({ durationMs: undefined })]).turn, { output: 100, rate: null }); }); -test("turn starts after the last user message", () => { - const perf = branchPerf([user(), asst({}, usageOf({ output: 999 })), user(), asst({}, usageOf({ output: 50 }))], opts); - assert.equal(perf.turn?.output, 50); assert.equal(perf.requests, 2); - assert.equal(branchPerf([asst(), user()], opts).turn, null); +test("a missing output makes the turn subtotal unknown without invalidating other timed replies", () => { + const missing = asst({ usage: undefined }); + assert.deepEqual(branchPerf([missing, asst()]).turn, { output: null, rate: 100 }); + assert.deepEqual(branchPerf([missing, user(), asst()]).turn, { output: 100, rate: 100 }); + assert.deepEqual(branchPerf([missing, user()]).turn, EMPTY_PERF.turn); }); -test("keeps newest PERF_MAX_RATES but peak spans all", () => { - const entries: SessionEntry[] = [asst({ durationMs: 400 }, usageOf({ output: 4000 }))]; - for (let i = 0; i < PERF_MAX_RATES + 50; i++) entries.push(asst({ durationMs: 1000 }, usageOf({ output: 100 + i }))); - const perf = branchPerf(entries, opts); +test("retains the newest rates, but peak and reply count cover the entire branch", () => { + const first = asst({ durationMs: 400 }, { output: 4000 }); + const count = PERF_MAX_RATES * 3; + const entries = [first, first, ...Array.from({ length: count }, (_, i) => asst({}, { output: 100 + i }))]; + const perf = branchPerf(entries); + assert.equal(perf.timedReplies, count + 1); assert.equal(perf.rates.length, PERF_MAX_RATES); assert.equal(perf.peak, 10000); - assert.equal(perf.rates.at(-1), 100 + PERF_MAX_RATES + 49); - assert.equal(perf.rates[0], 100 + 50); -}); - -test("5,000 requests process quickly", () => { - const entries: SessionEntry[] = []; - for (let i = 0; i < 5000; i++) entries.push(asst({}, usageOf({ cacheRead: 5, cost: { input: 1, cacheRead: 0.1 } }))); - const start = performance.now(); - const perf = branchPerf(entries, opts); - assert.ok(performance.now() - start < 1000); - assert.equal(perf.requests, 5000); assert.equal(perf.rates.length, PERF_MAX_RATES); -}); - -test("cache hit uses the latest assistant's uncached input, cache read and write", () => { - const tool = entry({ type: "message", message: { role: "toolResult", usage: usageOf({ cacheRead: 99 }) } }); - const perf = branchPerf([ - asst({}, usageOf({ input: 100, cacheRead: 700, cacheWrite: 200 })), - asst({}, usageOf({ input: 50, cacheRead: 150, cacheWrite: 50 })), - tool, entry({ type: "compaction" }), - ], opts); - assert.equal(perf.cache.lastHit, 0.6); + assert.equal(perf.rates.at(-1), 99 + count); + assert.equal(perf.rates[0], 100 + count - PERF_MAX_RATES); }); -test("saved estimates handle mixed models, skip unpriceable requests and zero prices", () => { - const a = asst({}, usageOf({ input: 100, cacheRead: 1000 }, { input: 1, cacheRead: 0.1 })); // 0.01/tok vs 0.0001 - const b = asst({}, usageOf({ input: 10, cacheRead: 200 }, { input: 0.5, cacheRead: 0.02 })); // 0.05 vs 0.0001 - const skip = asst({}, usageOf({ input: 0, cacheRead: 500 }, { input: 0, cacheRead: 1 })); - const perf = branchPerf([a, b, skip], opts); - assert.ok(Math.abs((perf.cache.saved ?? NaN) - (1000 * (0.01 - 0.0001) + 200 * (0.05 - 0.0001))) < 1e-9); - assert.equal(branchPerf([skip], opts).cache.saved, null); - assert.equal(branchPerf([asst({}, usageOf({ input: 10, cacheRead: 100 }))], opts).cache.saved, null); - // cache read priced above fresh input never yields negative savings - const inverted = branchPerf([asst({}, usageOf({ input: 10, cacheRead: 100 }, { input: 1, cacheRead: 100 }))], opts); - assert.equal(inverted.cache.saved, 0); +test("latest completed reply owns hit rate; tool/summary usage and failed replies don't replace it", () => { + const reply = asst({}, { input: 50, cacheRead: 150, cacheWrite: 50 }); + const tool = entry({ type: "message", message: { role: "toolResult", usage: { cacheRead: 99 } } }); + const failed = asst({ stopReason: "error" }); + assert.equal(branchPerf([reply, tool, entry({ type: "compaction" }), failed]).cache.lastHit, 0.6); + assert.equal(branchPerf([reply, asst({}, { cacheRead: Infinity })]).cache.lastHit, null); }); -test("ttl selection by retention, cacheWrite1h and unknown lifetimes", () => { - const pc = { short: 300, long: 3600 }; - const e = [asst({}, usageOf({ cacheWrite: 1 }))]; - assert.equal(branchPerf(e, { promptCache: pc, retentionLong: false }).cache.ttlMs, 300_000); - assert.equal(branchPerf(e, { promptCache: pc, retentionLong: true }).cache.ttlMs, 3_600_000); - assert.equal(branchPerf([asst({}, usageOf({ cacheWrite: 1, cacheWrite1h: 1 }))], { promptCache: pc, retentionLong: false }).cache.ttlMs, 3_600_000); - assert.equal(branchPerf(e, { retentionLong: false }).cache.ttlMs, null); - assert.equal(branchPerf(e, { promptCache: { short: 0 }, retentionLong: false }).cache.ttlMs, null); - assert.equal(branchPerf(e, { promptCache: { long: 3600 }, retentionLong: false }).cache.ttlMs, null); +test("expiry follows the recorded cache producer and timestamp, not an unrelated timed failure or reply", () => { + const lookup = (provider: string, model: string) => provider === "fixture" && model === "physical-a" + ? { short: 300, long: 3600 } : { short: 99, long: 99 }; + const reply = asst({ model: "routed", responseModel: "physical-a" }, { cacheWrite: 40, cacheWrite1h: 40 }); + const failed = asst({ model: "b", timestamp: 3000, stopReason: "error" }, { cacheRead: 900 }); + assert.deepEqual(branchPerf([reply, failed], lookup).cache, { lastHit: 0, lastActivityAt: 2000, ttlMs: 3_600_000 }); + const untimed = asst({ model: "b", durationMs: undefined }, { cacheRead: 30 }); + assert.equal(cacheWarmth(branchPerf([reply, untimed], lookup).cache, 4000).state, "unknown"); + assert.equal(cacheWarmth(branchPerf([reply, asst({ model: "b" })], lookup).cache, 4000).state, "unknown"); }); -test("lastActivityAt is the end of the newest timed request", () => { - const perf = branchPerf([asst({ timestamp: 5000, durationMs: 2000 }), asst({ timestamp: 9000, durationMs: 500 })], opts); - assert.equal(perf.cache.lastActivityAt, 9500); +test("a persisted cache refresh advances activity but not the last reply's hit or speed", () => { + const reply = asst({}, { input: 30, cacheRead: 70, cacheWrite: 0 }); + const warm = entry({ type: "usage", kind: "cache_warm", provider: "fixture", model: "a", usage: { cacheRead: 100 } }); + const perf = branchPerf([reply, warm], () => ({ short: 300, long: 300 })); + assert.deepEqual(perf.cache, { lastHit: 0.7, lastActivityAt: 10_000, ttlMs: 300_000 }); + assert.deepEqual(perf.rates, [100]); + assert.equal(cacheWarmth(perf.cache, 11_000).remainingMs, 299_000); }); -test("cacheWarmth warm, cold, unknown and clock skew", () => { - const base: SidebarCachePerf = { ...EMPTY_PERF.cache, lastActivityAt: 10_000, ttlMs: 300_000 }; - assert.deepEqual(cacheWarmth(base, 70_000), { state: "warm", remainingMs: 240_000, idleMs: 60_000 }); - assert.deepEqual(cacheWarmth(base, 310_000), { state: "cold", remainingMs: 0, idleMs: 300_000 }); - assert.equal(cacheWarmth({ ...base, ttlMs: null }, 20_000).state, "unknown"); - assert.deepEqual(cacheWarmth({ ...base, lastActivityAt: null }, 20_000), { state: "unknown", remainingMs: null, idleMs: null }); - assert.deepEqual(cacheWarmth(base, 5_000), { state: "warm", remainingMs: 300_000, idleMs: 0 }); +test("a cache timer requires evidence of the recorded request's retention tier", () => { + const lookup = () => ({ short: 300, long: 3600 }); + assert.equal(branchPerf([asst({}, { cacheWrite: 10, cacheWrite1h: 10 })], lookup).cache.ttlMs, 3_600_000); + for (const usage of [{ cacheRead: 99 }, { cacheWrite: 10 }, { cacheWrite: 10, cacheWrite1h: 0 }, { cacheWrite: 10, cacheWrite1h: 3 }]) { + assert.equal(branchPerf([asst({}, usage)], lookup).cache.ttlMs, null); + } }); -test("NaN, negative and infinite usage never leak", () => { - const bad = asst({}, usageOf({ input: NaN, output: -5, cacheRead: Infinity, cacheWrite: -1 }, { input: NaN })); - const perf = branchPerf([user(), bad, asst({ durationMs: NaN }), asst({ timestamp: NaN })], opts); - assert.equal(perf.cache.saved, null); - assert.equal(branchPerf([bad], opts).cache.lastHit, null); - assert.deepEqual(perf.rates, []); assert.equal(perf.turn, null); - assert.equal(perf.requests, 1); +test("cache warmth clamps clock skew and expires at TTL", () => { + const cache = { ...EMPTY_PERF.cache, lastActivityAt: 10_000, ttlMs: 300_000 }; + assert.deepEqual(cacheWarmth(cache, 5000), { state: "warm", remainingMs: 300_000, idleMs: 0 }); + assert.equal(cacheWarmth(cache, 310_000).state, "cold"); + assert.equal(cacheWarmth({ ...cache, ttlMs: null }, 70_000).idleMs, 60_000); }); diff --git a/pi-slate/tests/quiet-workbench.test.ts b/pi-slate/tests/quiet-workbench.test.ts index 134e207..7b84590 100644 --- a/pi-slate/tests/quiet-workbench.test.ts +++ b/pi-slate/tests/quiet-workbench.test.ts @@ -16,7 +16,7 @@ const theme = loadThemeFromPath(new URL("../themes/tokyo-night.json", import.met const session: SidebarSession = { id: "example-session", pid: 8421, cwd: "/tmp/project", model: "sample-model", thinking: "medium", tokens: 55000, percent: 11, contextWindow: 500000, estimated: false, rate: 82, startedAt: 1000, lastTurnMs: 14000, working: true, turns: 4, messages: 8, - usage: { input: 128400, output: 6800, total: 135200, cacheRead: 94000, cacheWrite: 22000, uncached: 12400, cacheSeen: true, cost: 1.24 }, perf: perfFixture(1000) }; + usage: { input: 128400, output: 6800, total: 135200, cacheRead: 94000, cacheWrite: 22000, uncached: 12400, cacheSeen: true, cost: 1.24, saved: null }, perf: perfFixture(1000) }; test("bundled default Tokyo Night loads with the native validator and restrained backgrounds", () => { assert.equal(SLATE_THEME, "tokyo-night"); assert.equal(theme.name, SLATE_THEME); @@ -81,7 +81,7 @@ test("growing usage and money keep a stable label lane and value edge with the r test("short terminals keep the CONTEXT heading row grammar with the real theme", () => { const sidebar = new Sidebar(() => 10000); - sidebar.attach({ terminal: { rows: 24, columns: 140 }, requestRender() {} } as unknown as TUI, theme); + sidebar.attach({ terminal: { rows: 30, columns: 140 }, requestRender() {} } as unknown as TUI, theme); for (const width of [28, 40, 80]) { sidebar.setSession(session); const rows = sidebar.render(width); diff --git a/pi-slate/tests/sidebar-data.test.ts b/pi-slate/tests/sidebar-data.test.ts index e691231..8364092 100644 --- a/pi-slate/tests/sidebar-data.test.ts +++ b/pi-slate/tests/sidebar-data.test.ts @@ -16,23 +16,36 @@ function skill(name: string): Skill { return { name, filePath: `/skills/${name}/ test("usage input includes cache categories once; reasoning is already part of output", () => { const a = message("a", "assistant", { usage }); const result = sidebarUsage([a, a]); - assert.deepEqual(result, { input: 450, output: 20, cacheRead: 300, cacheWrite: 50, uncached: 100, cacheSeen: true, total: 470, cost: 0.25 }); + assert.deepEqual(result, { input: 450, output: 20, cacheRead: 300, cacheWrite: 50, uncached: 100, cacheSeen: true, total: 470, cost: 0.25, saved: null }); }); test("tool nested usage, compaction, branch summaries and cache warming each count once", () => { const entries = [message("a", "assistant", { usage }), message("t", "toolResult", { usage, nestedCalls: { calls: [{ usage }], complete: true } }), entry("c", { type: "compaction", usage }), entry("b", { type: "branch_summary", usage }), entry("w", { type: "usage", kind: "cache_warm", usage })]; const result = sidebarUsage(entries); - assert.deepEqual(result, { input: 2250, output: 100, cacheRead: 1500, cacheWrite: 250, uncached: 500, cacheSeen: true, total: 2350, cost: 1.25 }); + assert.deepEqual(result, { input: 2250, output: 100, cacheRead: 1500, cacheWrite: 250, uncached: 500, cacheSeen: true, total: 2350, cost: 1.25, saved: null }); }); test("ordinary tool results without usage are not invented model requests", () => { - assert.deepEqual(sidebarUsage([message("t", "toolResult")]), { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, uncached: 0, cacheSeen: false, total: 0, cost: 0 }); + assert.deepEqual(sidebarUsage([message("t", "toolResult")]), { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, uncached: 0, cacheSeen: false, total: 0, cost: 0, saved: null }); }); test("missing or invalid provider facts show unknown rather than fake zero", () => { - assert.deepEqual(sidebarUsage([message("a", "assistant")]), { input: null, output: null, cacheRead: null, cacheWrite: null, uncached: null, cacheSeen: false, total: null, cost: null }); + assert.deepEqual(sidebarUsage([message("a", "assistant")]), { input: null, output: null, cacheRead: null, cacheWrite: null, uncached: null, cacheSeen: false, total: null, cost: null, saved: null }); const result = sidebarUsage([message("a", "assistant", { usage: { ...usage, cacheRead: NaN, cost: { total: -1 } } })]); - assert.deepEqual(result, { input: null, output: 20, cacheRead: null, cacheWrite: 50, uncached: 100, cacheSeen: true, total: null, cost: null }); + assert.deepEqual(result, { input: null, output: 20, cacheRead: null, cacheWrite: 50, uncached: 100, cacheSeen: true, total: null, cost: null, saved: null }); +}); + +test("estimate savings only when all branch cache reads can be priced", () => { + const priced = { ...usage, input: 100, cacheRead: 100, cost: { input: 1, cacheRead: 0.25, total: 1.25 } }; + const reply = message("a", "assistant", { usage: priced }); + const warm = entry("w", { type: "usage", kind: "cache_warm", usage: priced }); + assert.equal(sidebarUsage([reply, warm]).saved, 1.5); + for (const uncertain of [message("b", "assistant", { usage: { ...priced, input: 0 } }), + message("c", "assistant", { usage }), entry("d", { type: "compaction", usage: priced })]) { + const stats = sidebarUsage([reply, warm, uncertain]); + assert.notEqual(stats.cost, null); + assert.equal(stats.saved, null); + } }); test("legacy summaries without usage make billed totals unknown rather than silently free", () => { diff --git a/pi-slate/tests/sidebar-preview.test.ts b/pi-slate/tests/sidebar-preview.test.ts index 40a2c88..fc9ee0d 100644 --- a/pi-slate/tests/sidebar-preview.test.ts +++ b/pi-slate/tests/sidebar-preview.test.ts @@ -15,8 +15,8 @@ import type { BackgroundTask } from "../extensions/pi-slate/background-tasks.ts" const theme = (code = 32) => ({ fg: (_tone: string, text: string) => `\x1b[${code}m${text}\x1b[0m`, bold: (text: string) => text }) as Theme; const stripAnsi = (text: string) => text.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, ""); const plain = (lines: string[]) => lines.map(line => stripAnsi(line).replace(/^│ ?/, "").replace(/ ?│$/, "").trimEnd()); -const session: SidebarSession = { id: "session-a", pid: 8421, cwd: "/tmp/project", model: "sonnet-4.6", thinking: "medium", tokens: 31600, percent: 16, contextWindow: 200000, estimated: false, rate: 82, startedAt: 1000, lastTurnMs: 5000, working: true, turns: 2, messages: 5, usage: { input: 61400, output: 876, total: 62276, cacheRead: 48000, cacheWrite: 6100, uncached: 7300, cacheSeen: true, cost: 0.12 }, perf: perfFixture(1000) }; -const noUsage: SidebarUsage = { input: null, output: null, total: null, cacheRead: null, cacheWrite: null, uncached: null, cacheSeen: false, cost: null }; +const session: SidebarSession = { id: "session-a", pid: 8421, cwd: "/tmp/project", model: "sonnet-4.6", thinking: "medium", tokens: 31600, percent: 16, contextWindow: 200000, estimated: false, rate: 82, startedAt: 1000, lastTurnMs: 5000, working: true, turns: 2, messages: 5, usage: { input: 61400, output: 876, total: 62276, cacheRead: 48000, cacheWrite: 6100, uncached: 7300, cacheSeen: true, cost: 0.12, saved: null }, perf: perfFixture(1000) }; +const noUsage: SidebarUsage = { input: null, output: null, total: null, cacheRead: null, cacheWrite: null, uncached: null, cacheSeen: false, cost: null, saved: null }; const resources: SidebarResources = { mcp: Array.from({ length: 7 }, (_, i) => ({ name: `server-${i}`, enabled: i !== 2, source: "global" })), skills: Array.from({ length: 6 }, (_, i) => ({ name: `skill-${i}`, path: `/tmp/skills/${i}/SKILL.md`, loaded: i === 0, source: "project" })), @@ -48,7 +48,7 @@ function task(i: number): BackgroundTask { test("quiet session rail merges usage into context and hides empty shelves", () => { const { sidebar } = fixture(); const lines = plain(sidebar.render(80)); - for (const label of ["Working · turn 2", "session-", "sonnet-4.6", "16%", "31.6k/200k", "SPEED", "CACHE", "78.18% hit", "spent $0.12", "MCP · 6 Enabled", "Skills · 1 Loaded", "Prompts · 6"]) + for (const label of ["Working", "session-", "sonnet-4.6", "16%", "31.6k/200k", "SPEED", "CACHE", "78.18% hit", "spent $0.12", "MCP · 6 Enabled", "Skills · 1 Loaded", "Prompts · 6"]) assert(lines.some(line => line.includes(label)), label); for (const label of ["Stats", "Tokens · branch", "Commands ·", "Tasks", "Preview", "no selection", "/run-0", "prompt-0"]) assert(!lines.some(line => line.includes(label)), label); @@ -159,14 +159,14 @@ test("speed and cache replace the usage lane; full accounting stays in details", assert.match(sidebar.sessionDetails(), /Cache read: 48k · Cache write: 6.1k/); assert.match(sidebar.sessionDetails(), /~82 tokens\/sec/); assert.match(sidebar.sessionDetails(), /PID 8421/); - assert.match(sidebar.sessionDetails(), /Speed & cache\n.*end-to-end: output tokens ÷ request duration/); + assert.match(sidebar.sessionDetails(), /Speed & cache\n.*output tokens ÷ Pi's recorded provider-stream duration/); assert.match(sidebar.sessionDetails(), /Cache hit % = cache read ÷ \(uncached \+ cache read \+ cache write\)/); }); test("header height follows the terminal tier and its divider closes the header", () => { const { sidebar, terminal } = fixture(); sidebar.setSession({ ...session, name: "Slate session title" }); - for (const [rows, header] of [[60, 21], [44, 21], [43, 16], [30, 16], [29, 6], [20, 6], [19, 4]] as const) { + for (const [rows, header] of [[60, 21], [44, 21], [43, 16], [30, 16]] as const) { terminal.rows = rows; assert.equal(plain(sidebar.render(40)).findIndex(line => /^├─+┤$/.test(line)), header, `rows ${rows}`); } @@ -181,7 +181,7 @@ test("header height follows the terminal tier and its divider closes the header" }); test("context row keeps the heading grammar and degrades gracefully when narrow", () => { - const { sidebar } = fixture(24); + const { sidebar } = fixture(30); const context = (width: number) => { const line = plain(sidebar.render(width)).find(line => line.startsWith("CONTEXT") || /\d+%|—/.test(line) && !line.includes("tok/s") && !line.includes("Idle") && !line.includes("Working")); assert(line, `context at width ${width}`); return line; @@ -228,14 +228,6 @@ test("context rows keep the branch usage inspect action; nulls render as dashes" assert.deepEqual(inspected, ["Branch usage", "Branch usage"]); }); -test("a 24-row terminal still renders an image body; a very short one prioritizes tasks", () => { - const { sidebar, terminal } = fixture(24); sidebar.setView(image()); sidebar.setTasks([task(0)]); - assert(plain(sidebar.render(40)).some(line => line.includes("IMAGE")), "normal-height thumbnails must not disappear"); - terminal.rows = 14; - const text = plain(sidebar.render(40)).join("\n"); - assert(text.includes("Tasks")); assert(!text.includes("IMAGE")); -}); - test("foldable MCP and Skills sections persist independently and keep counts visible", () => { const { sidebar } = fixture(); const saved: unknown[] = []; sidebar.setActions({ copy() {}, openFile() {}, persistFold: (section, expanded) => { const folds = { ...sidebar.getFolds(), [section]: expanded }; saved.push(folds); return folds; } }); @@ -375,16 +367,17 @@ test("image double-click uses native clickCount or the fallback timer", () => { assert.deepEqual(opened, ["/tmp/a.png"]); }); -test("short terminals collapse the image body, keep tasks visible, and scroll middle overflow", () => { - const { sidebar } = fixture(18); sidebar.setView(image()); sidebar.setTasks([task(0), task(1), task(2)]); +test("the compact rail keeps the image and tasks while the middle scrolls", () => { + const { sidebar } = fixture(30); sidebar.setView(image()); sidebar.setTasks([task(0), task(1), task(2)]); sidebar.setFolds({ mcp: true, skills: true, prompts: false }); const lines = plain(sidebar.render(40)); assert.equal(sidebar.imagePath(), "/tmp/a.png"); - assert(!lines.some(line => line.includes("IMAGE"))); + assert(lines.some(line => line.includes("IMAGE"))); assert(lines.some(line => line.includes("Tasks"))); - sidebar.handleMouse(mouse(6, { type: "wheel", wheelDelta: -40 })); + sidebar.handleMouse(mouse(row(sidebar, "MCP"), { type: "wheel", wheelDelta: -40 })); const scrolled = plain(sidebar.render(40)); - assert(scrolled.some(line => /Skills|Prompts|server-\d|skill-\d|prompt-\d/.test(line))); + assert(scrolled.some(line => /Skills|Prompts|skill-\d|prompt-\d/.test(line))); + assert.notDeepEqual(scrolled, lines); assert.equal(scrolled[0], lines[0]); assert.equal(sidebar.imagePath(), "/tmp/a.png"); }); @@ -499,7 +492,7 @@ test("sidebar closes both rails and joins every horizontal divider at the right test("working status shows the running turn's elapsed time and ticks each second", () => { const { sidebar, advance } = fixture(); sidebar.setSession({ ...session, working: true, turnStartedAt: 4000 - 42_000 }); - assert.match(plain(sidebar.render(44))[1]!, /● Working · turn 2\s+0:42$/); + assert.match(plain(sidebar.render(44))[1]!, /● Working\s+0:42$/); advance(1000); assert.match(plain(sidebar.render(44))[1]!, /0:43$/); sidebar.setSession({ ...session, working: false, turnStartedAt: null }); @@ -511,8 +504,8 @@ test("empty speed and cache sections collapse and give their rows to the resourc sidebar.setSession({ ...session, usage: noUsage, perf: EMPTY_PERF }); const empty = plain(sidebar.render(44)); const mcpEmpty = empty.findIndex(line => line.includes("MCP")); - assert(empty.some(line => line.includes("waiting for first response"))); - assert(empty.some(line => line.includes("no requests yet"))); + assert(empty.some(line => line.includes("no timed replies"))); + assert(empty.some(line => line.includes("no cache activity reported"))); sidebar.setSession(session); const full = plain(sidebar.render(44)); assert.equal(full.findIndex(line => line.includes("MCP")) - mcpEmpty, 7, "5 speed + 2 cache rows are reclaimed"); diff --git a/pi-slate/tests/surfaces-install.test.ts b/pi-slate/tests/surfaces-install.test.ts index 2e58b92..9c0158f 100644 --- a/pi-slate/tests/surfaces-install.test.ts +++ b/pi-slate/tests/surfaces-install.test.ts @@ -130,7 +130,7 @@ async function fixture(t: TestContext, text: string | undefined, mode = "tui", c }; const manager = SessionManager.inMemory(cwd); let stale = false; - const ctx = new Proxy({ cwd, mode, ui, sessionManager: manager, getContextUsage: () => undefined, isIdle: () => true, isProjectTrusted: () => false } as unknown as ExtensionContext, { + const ctx = new Proxy({ cwd, mode, ui, sessionManager: manager, modelRegistry: { find: () => undefined }, getContextUsage: () => undefined, isIdle: () => true, isProjectTrusted: () => false } as unknown as ExtensionContext, { get(target, key, receiver) { if (stale) throw new Error("This extension ctx is stale after session replacement or reload."); return Reflect.get(target, key, receiver); @@ -600,6 +600,56 @@ function railOf(f: Awaited>): Sidebar { return (Reflect.get(Reflect.get(f.tui, "layoutRoot"), "entries") as Array<{ component: Sidebar }>)[1]!.component; } +function sidebarReply(): Extract[0], { role: "assistant" }> { + return { role: "assistant", api: "anthropic-messages", provider: "anthropic", model: "producer", + timestamp: Date.now() - 1000, durationMs: 1000, stopReason: "toolUse", content: [{ type: "text", text: "fixture response" }], + usage: { input: 200, output: 70, cacheRead: 0, cacheWrite: 100, cacheWrite1h: 100, totalTokens: 370, + cost: { input: .01, output: 0, cacheRead: 0, cacheWrite: 0, total: .01 } } }; +} + +test("SPEED follows persistence, not token deltas or an unrelated model selection", async t => { + const f = await fixture(t, JSON.stringify({ surfaces: ["sidebar"] })), reply = sidebarReply(); + const capture = () => unstyled(railOf(f).render(44).join("\n")); + Object.assign(f.ctx, { isIdle: () => false, modelRegistry: { find: (_: string, id: string) => + id === "producer" ? { promptCache: { short: 300, long: 3600 } } : undefined } }); + f.manager.appendMessage(reply); + await f.emit("agent_start"); + assert.match(capture(), /● Working/); assert.doesNotMatch(capture(), /Working · turn/); + Object.assign(f.ctx, { model: { id: "virtual", provider: "fixture", promptCache: { short: 30 } } }); + const scans = t.mock.method(f.manager, "getBranch"); + await f.emit("model_select"); + assert.match(capture(), /◉ (?:1:00:00|59:59)/); + const next = { ...reply, usage: { ...reply.usage, output: 120 } }; + await f.emit("message_start", { message: next }); + const contextReads = t.mock.method(f.ctx, "getContextUsage"); await f.emit("message_update", { message: next }); + assert.equal(scans.mock.callCount() + contextReads.mock.callCount(), 0, "token updates do not rescan context or persisted facts"); + await f.emit("message_end", { message: next }); + assert.match(capture(), /SPEED\s+70\.0 tok\/s/); + f.manager.appendMessage(next); + await f.emit("tool_execution_start", { toolCallId: "call", toolName: "read", args: {} }); + assert.match(capture(), /SPEED\s+120 tok\/s/); +}); + +test("mounted rail preserves the pinned preview and open target under task pressure", async t => { + const f = await fixture(t, JSON.stringify({ surfaces: ["sidebar"], focused: false })); + f.manager.appendMessage(sidebarReply()); await f.emit("agent_settled"); + const sidebar = railOf(f), opened: string[] = []; + const root = Reflect.get(f.tui, "layoutRoot") as Component; + sidebar.setActions({ copy() {}, openFile: path => opened.push(path) }); + sidebar.setView({ id: "image:fixture", filePath: f.imagePath, title: "Fixture", invalidate() {}, render: () => ["pinned-image-body"] }); + sidebar.pinImage(); + sidebar.setTasks([0, 1, 2].map(i => ({ id: `task-${i}`, source: "fixture", label: `task-${i}`, kind: "subagent", state: "running", startedAt: 1 }))); + for (const rows of [29, 30, 32, 44]) { + (f.tui.terminal as NullTerminal).rows = rows; + const frame = root.render(140).join("\n"); + assert.equal(frame.includes("pinned-image-body"), rows >= 30, `${rows} rows`); + if (rows < 30) continue; + const y = sidebar.render(28).findIndex(line => line.includes("[open]")); + assert(y >= 0); + sidebar.handleMouse({ type: "click", button: "left", x: 2, y, width: 28, height: rows, screenX: 114, screenY: y, shift: false, alt: false, ctrl: false }); + } + assert.deepEqual(opened, Array(3).fill(f.imagePath)); +}); test("fold save preserves external sibling state, unknown section keys and unknown nested settings", async t => { const f = await fixture(t, JSON.stringify({ surfaces: ["sidebar"] })); await writeFile(f.path, JSON.stringify({ surfaces: ["sidebar"], sidebarSections: { skills: true, future: "keep" }, modelDisplay: { providerSuffix: true, future: "keep" }, unrelated: { nested: true } })); From 70097d84ccd93c0e799ce7077edcc111a897f4af Mon Sep 17 00:00:00 2001 From: GaganSD Date: Wed, 18 Nov 2026 07:21:52 +0000 Subject: [PATCH 11/15] fix(slate): use the theme accent for cache reads --- pi-slate/extensions/pi-slate/perf-graphics.ts | 2 +- pi-slate/tests/perf-graphics.test.ts | 7 +++---- pi-slate/tests/quiet-workbench.test.ts | 19 +++++++++++++++++++ 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/pi-slate/extensions/pi-slate/perf-graphics.ts b/pi-slate/extensions/pi-slate/perf-graphics.ts index e3cda6a..a17b14f 100644 --- a/pi-slate/extensions/pi-slate/perf-graphics.ts +++ b/pi-slate/extensions/pi-slate/perf-graphics.ts @@ -233,7 +233,7 @@ export function cacheRows(i: PerfInput): string[] { if (!usage.cacheSeen) return [headingRow(i, "CACHE", [[DASH]]), noteRow(i, "no cache activity reported"), ...(usage.cost !== null && (usage.cost > 0 || (usage.input ?? 0) > 0) ? [detailRow(i, [spent])] : [])]; const [r = 0, w = 0, u = 0] = usage.input === null ? [] : stackedBar([usage.cacheRead ?? 0, usage.cacheWrite ?? 0, usage.uncached ?? 0], inner); - const bar = r || w || u ? paint("success", "━".repeat(r)) + paint("warning", "━".repeat(w)) + paint("muted", "━".repeat(u)) : baseline(i); + const bar = r || w || u ? paint("accent", "━".repeat(r)) + paint("warning", "━".repeat(w)) + paint("muted", "━".repeat(u)) : baseline(i); const f = formatCompactTokenCount; const tokens: Array<[string, string]> = [["read", f(usage.cacheRead)], ["write", f(usage.cacheWrite)], ["new", f(usage.uncached)]]; const rows = [headingRow(i, "CACHE", cacheSegs(i)), bar]; diff --git a/pi-slate/tests/perf-graphics.test.ts b/pi-slate/tests/perf-graphics.test.ts index 103206d..c6a6005 100644 --- a/pi-slate/tests/perf-graphics.test.ts +++ b/pi-slate/tests/perf-graphics.test.ts @@ -158,7 +158,7 @@ test("CACHE headline and bar use branch totals and distinguish near-perfect from for (const [read, label, cells] of [[86_000, "86% hit", 34], [95_200, "95.2% hit", 38], [99_560, "99.56% hit", 39], [99_999, "99.99% hit", 39], [100_000, "all cached", 40]] as const) { const totals = { ...usage, input: 100_000, cacheRead: read, cacheWrite: 0, uncached: 100_000 - read }; const i = input(perf, 40, "compact", 1000, totals); - const [heading, bar] = cacheRows({ ...i, paint: (t, x) => t === "success" ? x.replaceAll("━", "█") : x }); + const [heading, bar] = cacheRows({ ...i, paint: (t, x) => t === "accent" ? x.replaceAll("━", "█") : x }); assert(heading?.includes(label)); assert.equal(bar, "█".repeat(cells) + "━".repeat(40 - cells)); } @@ -173,9 +173,8 @@ test("CACHE bars use the context glyph in three tones; money rows handle unknown const full = cacheRows({ ...input(perfFixture(1000), 40, "full"), ...paint }).map(strip); assert.equal(full.length, 4); assert.equal(full[1], "━".repeat(40)); assert(!/[█▓░]/.test(full.join(""))); - const bar = themed.filter(t => /^(success|warning|muted):━/.test(t)).map(t => t.split(":")[0]); - assert.deepEqual(bar, ["success", "warning", "muted"]); - assert.equal(themed.find(t => t.startsWith("success:━"))!.length - "success:".length + themed.find(t => t.startsWith("warning:━"))!.length - "warning:".length + themed.find(t => t.startsWith("muted:━"))!.length - "muted:".length, 40, "segments sum to the width"); + const bar = themed.filter(t => /^(accent|warning|muted):━/.test(t)).map(t => t.split(":")[0]); + assert.deepEqual(bar, ["accent", "warning", "muted"]); assert.equal(full[2], "read 1.3M · write 108k · new 141k"); assert.equal(full[3], "spent $0.84 · saved ~$1.92"); const none = SECTIONS(perfFixture(1000), 40, "full", { ...usage, cost: null, saved: null }).cache; diff --git a/pi-slate/tests/quiet-workbench.test.ts b/pi-slate/tests/quiet-workbench.test.ts index 7b84590..fa0617d 100644 --- a/pi-slate/tests/quiet-workbench.test.ts +++ b/pi-slate/tests/quiet-workbench.test.ts @@ -79,6 +79,25 @@ test("growing usage and money keep a stable label lane and value edge with the r sidebar.dispose(); }); +test("cache reads follow live accent changes within the same theme family", () => { + const lavender = loadThemeFromPath(new URL("../themes/catppuccin-mocha-lavender.json", import.meta.url).pathname, "truecolor"); + const peach = loadThemeFromPath(new URL("../themes/catppuccin-mocha-peach.json", import.meta.url).pathname, "truecolor"); + let active = lavender; + const sidebar = new Sidebar(() => 10000); + sidebar.attach({ terminal: { rows: 40, columns: 140 }, requestRender() {} } as unknown as TUI, lavender); + sidebar.setThemeProvider(() => active); + sidebar.setSession(session); + const cacheBar = () => sidebar.render(44).find(row => stripVTControlCharacters(row).includes("━".repeat(40)))!; + const reads = "━".repeat(29); + assert.equal(lavender.fg("success", reads), peach.fg("success", reads), "status color is fixed across these accents"); + assert(cacheBar().includes(lavender.fg("accent", reads))); + active = peach; + const after = cacheBar(); + assert(after.includes(peach.fg("accent", reads))); + assert(!after.includes(lavender.fg("accent", reads))); + sidebar.dispose(); +}); + test("short terminals keep the CONTEXT heading row grammar with the real theme", () => { const sidebar = new Sidebar(() => 10000); sidebar.attach({ terminal: { rows: 30, columns: 140 }, requestRender() {} } as unknown as TUI, theme); From 59782615c19da0d181e52819622d442659b0c033 Mon Sep 17 00:00:00 2001 From: GaganSD Date: Wed, 18 Nov 2026 07:28:55 +0000 Subject: [PATCH 12/15] fix(slate): keep the context meter in the theme accent --- pi-slate/extensions/pi-slate/perf-graphics.ts | 9 +++--- pi-slate/tests/perf-graphics.test.ts | 12 ++++---- pi-slate/tests/quiet-workbench.test.ts | 7 +++-- pi-slate/tests/sidebar-preview.test.ts | 28 +++++++++---------- 4 files changed, 29 insertions(+), 27 deletions(-) diff --git a/pi-slate/extensions/pi-slate/perf-graphics.ts b/pi-slate/extensions/pi-slate/perf-graphics.ts index a17b14f..9dff99c 100644 --- a/pi-slate/extensions/pi-slate/perf-graphics.ts +++ b/pi-slate/extensions/pi-slate/perf-graphics.ts @@ -148,7 +148,7 @@ const EIGHTHS = ["", "▏", "▎", "▍", "▌", "▋", "▊", "▉"]; * One-row context bar: solid fill on a light-shaded track. The fill edge advances in * eighth-cell steps; any non-zero percent shows at least one eighth so usage never reads as empty. */ -export function contextBar(width: number, percent: number | null, paint: PerfInput["paint"], tone: Tone): string { +export function contextBar(width: number, percent: number | null, paint: PerfInput["paint"]): string { const w = Math.max(0, Math.floor(width)); if (w === 0) return ""; const p = percent === null || !Number.isFinite(percent) ? 0 : Math.max(0, Math.min(100, percent)); @@ -157,18 +157,17 @@ export function contextBar(width: number, percent: number | null, paint: PerfInp const full = Math.floor(eighths / 8), part = eighths % 8; const fill = "█".repeat(full) + EIGHTHS[part]!; const track = "░".repeat(Math.max(0, w - full - (part ? 1 : 0))); - return (fill ? paint(tone, fill) : "") + (track ? paint("dim", track) : ""); + return (fill ? paint("accent", fill) : "") + (track ? paint("dim", track) : ""); } /** CONTEXT: heading + a one-row bar. */ export function contextRows(i: PerfInput, c: { percent: number | null; tokens: number | null; window: number | null; estimated: boolean }): string[] { const percent = c.percent !== null && Number.isFinite(c.percent) ? Math.max(0, Math.min(100, c.percent)) : null; - const tone: Tone = percent !== null && percent >= 80 ? "warning" : "accent"; - const pctSeg: Seg = percent === null ? DASH : [percent >= 80 ? "warning" : "text", `${Math.round(percent)}%`]; + const pctSeg: Seg = percent === null ? DASH : ["text", `${Math.round(percent)}%`]; const figures: Seg = ["dim", `${c.estimated ? "~" : ""}${formatCompactTokenCount(c.tokens)}/${formatCompactTokenCount(c.window)}`]; return [ headingRow(i, "CONTEXT", [[pctSeg, ["dim", " "], figures], [pctSeg]]), - contextBar(i.inner, percent, i.paint, tone), + contextBar(i.inner, percent, i.paint), ]; } diff --git a/pi-slate/tests/perf-graphics.test.ts b/pi-slate/tests/perf-graphics.test.ts index c6a6005..73ddefb 100644 --- a/pi-slate/tests/perf-graphics.test.ts +++ b/pi-slate/tests/perf-graphics.test.ts @@ -263,10 +263,10 @@ test("themed render keeps tones within the theme palette", () => { test("context bar: one row, exact width, eighth-step fill, visible at tiny percents", () => { const paint = (_t: string, x: string) => x; for (const width of [0, 1, 2, 3, 10, 41]) for (const pct of [null, 0, 0.01, 2, 50, 99.9, 100, 140, NaN]) - assert.equal(visibleWidth(contextBar(width, pct as number | null, paint, "accent")), width, `width ${width} pct ${pct}`); - assert.equal(contextBar(10, 0, paint, "accent"), "░".repeat(10)); - assert.equal(contextBar(10, null, paint, "accent"), "░".repeat(10)); - assert.equal(contextBar(10, 0.01, paint, "accent"), "▏" + "░".repeat(9), "any usage is visible"); - assert.equal(contextBar(10, 50, paint, "accent"), "█████" + "░".repeat(5)); - assert.equal(contextBar(10, 100, paint, "accent"), "█".repeat(10)); + assert.equal(visibleWidth(contextBar(width, pct, paint)), width, `width ${width} pct ${pct}`); + assert.equal(contextBar(10, 0, paint), "░".repeat(10)); + assert.equal(contextBar(10, null, paint), "░".repeat(10)); + assert.equal(contextBar(10, 0.01, paint), "▏" + "░".repeat(9), "any usage is visible"); + assert.equal(contextBar(10, 50, paint), "█████" + "░".repeat(5)); + assert.equal(contextBar(10, 100, paint), "█".repeat(10)); }); diff --git a/pi-slate/tests/quiet-workbench.test.ts b/pi-slate/tests/quiet-workbench.test.ts index fa0617d..8dcad73 100644 --- a/pi-slate/tests/quiet-workbench.test.ts +++ b/pi-slate/tests/quiet-workbench.test.ts @@ -79,22 +79,25 @@ test("growing usage and money keep a stable label lane and value edge with the r sidebar.dispose(); }); -test("cache reads follow live accent changes within the same theme family", () => { +test("high context usage and cache reads follow live accent changes within the same theme family", () => { const lavender = loadThemeFromPath(new URL("../themes/catppuccin-mocha-lavender.json", import.meta.url).pathname, "truecolor"); const peach = loadThemeFromPath(new URL("../themes/catppuccin-mocha-peach.json", import.meta.url).pathname, "truecolor"); let active = lavender; const sidebar = new Sidebar(() => 10000); sidebar.attach({ terminal: { rows: 40, columns: 140 }, requestRender() {} } as unknown as TUI, lavender); sidebar.setThemeProvider(() => active); - sidebar.setSession(session); + sidebar.setSession({ ...session, percent: 88 }); + const contextFill = "█".repeat(35) + "▎"; const cacheBar = () => sidebar.render(44).find(row => stripVTControlCharacters(row).includes("━".repeat(40)))!; const reads = "━".repeat(29); assert.equal(lavender.fg("success", reads), peach.fg("success", reads), "status color is fixed across these accents"); assert(cacheBar().includes(lavender.fg("accent", reads))); + assert(sidebar.render(44).some(row => row.includes(lavender.fg("accent", contextFill)))); active = peach; const after = cacheBar(); assert(after.includes(peach.fg("accent", reads))); assert(!after.includes(lavender.fg("accent", reads))); + assert(sidebar.render(44).some(row => row.includes(peach.fg("accent", contextFill)))); sidebar.dispose(); }); diff --git a/pi-slate/tests/sidebar-preview.test.ts b/pi-slate/tests/sidebar-preview.test.ts index fc9ee0d..7395b02 100644 --- a/pi-slate/tests/sidebar-preview.test.ts +++ b/pi-slate/tests/sidebar-preview.test.ts @@ -199,23 +199,23 @@ test("context row keeps the heading grammar and degrades gracefully when narrow" for (const line of sidebar.render(3)) assert(visibleWidth(line) <= 3, "degenerate rail stays bounded"); }); -test("context meter fill follows the theme accent and shifts to the warning tone at 80% and above", () => { +test("context meter keeps the theme accent at every usage level", () => { const codes: Record = { muted: 90, dim: 2, accent: 36, warning: 33, text: 37 }; const toneTheme = { fg: (tone: string, text: string) => `\x1b[${codes[tone] ?? 0}m${text}\x1b[0m`, bold: (text: string) => text } as Theme; - for (const rows of [60]) { - const { sidebar } = fixture(rows); - sidebar.setThemeProvider(() => toneTheme); sidebar.invalidate(); - const meterLine = () => sidebar.render(40).find(line => /^│ ?[█-▏░]{4}/.test(stripAnsi(line)))!; - for (const [percent, code] of [[0, 36], [79, 36], [80, 33], [100, 33]] as const) { - sidebar.setSession({ ...session, percent }); sidebar.invalidate(); - const line = meterLine(); - const fill = stripAnsi(line).match(/[█-▏]+/)?.[0] ?? ""; - if (fill) assert(line.includes(`\x1b[${code}m${fill}\x1b[0m`), `${rows} rows: ${percent}% fills with code ${code}`); - if (percent < 100) assert(line.includes("\x1b[2m"), "track stays dim"); - } - sidebar.setSession({ ...session, percent: null }); sidebar.invalidate(); - assert(!/[█-▏]/.test(stripAnsi(meterLine())), "null percent fills nothing"); + const { sidebar } = fixture(); + sidebar.setThemeProvider(() => toneTheme); + const meterLine = () => sidebar.render(40).find(line => /^│ ?[█-▏░]{4}/.test(stripAnsi(line)))!; + for (const percent of [0, 79, 80, 88, 100]) { + sidebar.setSession({ ...session, percent }); + const line = meterLine(); + const fill = stripAnsi(line).match(/[█-▏]+/)?.[0] ?? ""; + if (percent > 0) assert(fill && line.includes(toneTheme.fg("accent", fill)), `${percent}% uses the theme accent`); + if (percent < 100) assert(line.includes("\x1b[2m"), "track stays dim"); + const heading = sidebar.render(40).find(line => stripAnsi(line).includes("CONTEXT"))!; + assert(heading.includes(toneTheme.fg("text", `${percent}%`)), "percentage keeps the normal value color"); } + sidebar.setSession({ ...session, percent: null }); + assert(!/[█-▏]/.test(stripAnsi(meterLine())), "null percent fills nothing"); }); test("context rows keep the branch usage inspect action; nulls render as dashes", () => { From 1faea9e3f90daeca63741c172d7b75b72e00a47c Mon Sep 17 00:00:00 2001 From: GaganSD Date: Wed, 18 Nov 2026 07:38:03 +0000 Subject: [PATCH 13/15] docs(slate): shorten the sidebar changelog --- pi-slate/CHANGELOG.md | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/pi-slate/CHANGELOG.md b/pi-slate/CHANGELOG.md index 0b11018..971e1e3 100644 --- a/pi-slate/CHANGELOG.md +++ b/pi-slate/CHANGELOG.md @@ -2,16 +2,7 @@ ## Unreleased -### Added - -- Sidebar SPEED section: tok/s of the latest eligible reply (output tokens ÷ Pi's recorded provider-stream duration), a graph of recent responses, turn average, output and peak. Responses under 32 tokens or 300 ms are not timed. Compact terminals use a block sparkline; tall terminals show large digits and a Braille graph. -- Sidebar CACHE section: active-branch hit % matching the read/write/new bar, spend and estimated savings. Session details also show the latest request's hit %. Hit rates use up to two decimal places and show “all cached” instead of 100%. An estimated expiry countdown appears only when the last reported cache activity and its retention tier are known. -- The status row shows Working/Idle, elapsed time while working, and the branch turn count when idle. - -### Changed - -- The sidebar header is reorganised into status, CONTEXT, SPEED and CACHE, which share one layout (heading with the key figure on the right, one bar or graph row, labelled details), and adapts to terminal height (full and compact). CONTEXT is a single bar; use pi-context-view for the category breakdown. -- The SPEED card shows completed replies. The live rate estimate remains in the composer. +redesigned sidebar for performance tracking ## 0.2.1 From f8e89b7d27f2bbebe62878c808868a792478d9ff Mon Sep 17 00:00:00 2001 From: GaganSD Date: Wed, 18 Nov 2026 07:38:47 +0000 Subject: [PATCH 14/15] docs(slate): add performance sidebar screenshots --- docs/images/slate-performance-cool.png | Bin 0 -> 30417 bytes docs/images/slate-performance-warm.png | Bin 0 -> 33218 bytes 2 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 docs/images/slate-performance-cool.png create mode 100644 docs/images/slate-performance-warm.png diff --git a/docs/images/slate-performance-cool.png b/docs/images/slate-performance-cool.png new file mode 100644 index 0000000000000000000000000000000000000000..a4b74c23edca4d880e43867af9a9c16bef654783 GIT binary patch literal 30417 zcmd?RbxsB-PN!|sQAjtw}-NUgqoe%&}6-mCbz%gt;2(@~d& zthdZY1GxT)$gz-i%V#`#=fcxG=GIu@};HdIWw0QL@3tGcS6yi1E1qcFo7G zv%YaD^>e6JH^l@D>o7)rMpwsWDEBZ`gdV{q4$U??6=_7ixW0P~0@sdshzn;TZO2Yd zn-$Otn3`Q%z|zd3i88P#X>mJPZg11!{qV4m{8S1_qfB z3I+>0qk|6dT!{bG3(lJh`JcA(2cf7cKw27fRyB4sHMMoJuydv!VK@N|wE$Gpbk>xY z<1@CiVKOqY`)11IZe#z!0w&4Ag=f4>Rm_Jtj zUz+%rn*X^A(z6hP0P}zLObFrbD%c1NOax3?TvW{+{6r7dn_zyL_;%gvykjZZi+g|z zMm4Iem;z0khV%!f7#=Apya66Kx~D}Rj2tV>Y?Rmemjv}n5cLcC{f}0n$ju;6jVT+xJZhV^L=!d@%LG4@KBT}N@4`= zl8d~#dTJ1BVD}O!i}u^J{hwSaZrAy^1dt>Vv{X4bxMBI?g}Bxaid1sL;9ZFd>==)Z zLJ?3e8k9tUzr%!BPUhv1a;9hk0z{xc2}=*$=Y2Nv^i`-ubp_^sM*d7nLcuK|BE$O8 z&HD*0AtUpYtO*@7Csr{LDcdOjAKyOKFY5ilGMh5|!m01qz4DAnav3FAd%hM~8zy7+B{hdfM4#;cIg z0kQ7)syMZlW)=iTb~h1O)#%Fv zSYri(mEg%PxWUH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z8!a1;Q6SthFpGsL_5Kk@YroFI|`si7HwlG8lh?v_}=7-E1! zuna)F9&tfgNONH(#_Gxki%}dLKY{ck*i_#l^e-F$Ynx^3@v%n-M1CI9j}<`JDc(Ky v3CC~FPX1Uz=;D9E@lKH2OSb=;p?@G%o`vw2=m?*K0Dq*! Date: Wed, 18 Nov 2026 07:38:47 +0000 Subject: [PATCH 15/15] docs(slate): reserve the changelog entry for the release --- pi-slate/CHANGELOG.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/pi-slate/CHANGELOG.md b/pi-slate/CHANGELOG.md index 971e1e3..658bb93 100644 --- a/pi-slate/CHANGELOG.md +++ b/pi-slate/CHANGELOG.md @@ -2,8 +2,6 @@ ## Unreleased -redesigned sidebar for performance tracking - ## 0.2.1 Fallback improvements for newer updates, Remove redundant notification in new sessions, misc. UI improvements around 'model', 'thinking', & 'warning' variables.