diff --git a/pi-slate/CHANGELOG.md b/pi-slate/CHANGELOG.md index 658bb93..f75a02b 100644 --- a/pi-slate/CHANGELOG.md +++ b/pi-slate/CHANGELOG.md @@ -2,6 +2,17 @@ ## Unreleased +### 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. +- 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. + ## 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..c817fdc --- /dev/null +++ b/pi-slate/extensions/pi-slate/perf-graphics.ts @@ -0,0 +1,288 @@ +/** + * 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). + * 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)); + 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).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 < 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[] = []; + 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++) { + if ((r - row) * 4 - d <= heights[cell * 2 + k]!) code |= DOT[d]![k]!; + } + s += code === 0 ? " " : String.fromCharCode(0x2800 + code); + } + lines.push(s); + } + 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. + */ +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 ------------------------------------------------------------------------- +// 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); + +/** 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, "…"); +} + +/** 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", "—"]; + +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 { + 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)); + 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, w - full - (part ? 1 : 0))); + return (fill ? paint(tone, 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 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), + ]; +} + +/** 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 [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 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: 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; + 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)}%`; + +/** 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: 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): 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 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: `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) : [[]]; + 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 new file mode 100644 index 0000000..ab9f6d1 --- /dev/null +++ b/pi-slate/extensions/pi-slate/perf-stats.ts @@ -0,0 +1,219 @@ +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 `~`; 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'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 = { + /** 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). */ + 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. */ + 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 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 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 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; 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; + 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; + 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; + 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: 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 }, + }; +} + +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..6587c98 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: 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 { 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..a749664 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, contextRows, 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 }; +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,41 +257,46 @@ 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 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 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 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 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 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 }) + .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 })); + // 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]; } 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..d08ba56 --- /dev/null +++ b/pi-slate/tests/perf-graphics.test.ts @@ -0,0 +1,287 @@ +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 { 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, 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.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"); + 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, 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)) }; +}; + +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); + 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"); +}); + +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); + 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 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("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("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("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 [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", () => { + const perf = perfFixture(1000); + 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("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 + 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%"); +}); + +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$/); + // 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}~—\/—$/); +}); + +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, /◉ 4:41/); assert.match(b, /◉ 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 tok\/s · 92% hit · warm 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")); +}); + +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)); +}); diff --git a/pi-slate/tests/perf-stats.test.ts b/pi-slate/tests/perf-stats.test.ts new file mode 100644 index 0000000..36e861c --- /dev/null +++ b/pi-slate/tests/perf-stats.test.ts @@ -0,0 +1,146 @@ +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); + 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", () => { + 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..98fea2e 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"); @@ -91,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: 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 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 8fafd20..b789255 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,60 +150,52 @@ 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, 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, 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"); -}); - -test("context meter fills the rail with a thin track and degrades gracefully when narrow", () => { - const { sidebar } = fixture(); - 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; + 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]!) && lines[7] === "", "one-row context bar"); +}); + +test("context row keeps the heading grammar and degrades gracefully when narrow", () => { + const { sidebar } = fixture(24); + 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"); }); @@ -212,28 +203,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 [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"); } - 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 +414,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 +436,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 +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[11], "├" + "─".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, /^[│┌├└]/); @@ -503,3 +496,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, 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 57c7d08..2e58b92 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(), /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 } } }); @@ -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("已恢复的标题");