diff --git a/docs/images/slate-performance-cool.png b/docs/images/slate-performance-cool.png new file mode 100644 index 0000000..a4b74c2 Binary files /dev/null and b/docs/images/slate-performance-cool.png differ diff --git a/docs/images/slate-performance-warm.png b/docs/images/slate-performance-warm.png new file mode 100644 index 0000000..6e8e4c3 Binary files /dev/null and b/docs/images/slate-performance-warm.png differ diff --git a/pi-slate/extensions/pi-slate/index.ts b/pi-slate/extensions/pi-slate/index.ts index 49b856b..d084585 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,7 @@ 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 inspectingSidebar = false; let sidebarYielded = false; let sessionEpoch = 0; @@ -267,9 +268,8 @@ export default function piSlate(pi: ExtensionAPI): void { const tokenRate = new TokenRateTracker(); const thinkingFold = new ThinkingFoldTracker({ onChange: () => syncThinkingStatus() }); const branch = new GitBranchPoller(pi, (next) => { gitBranch = next; requestRender(); }); - let contextEdge = { - tokens: formatFocusedContextTokens(null, null, null), - resources: formatFocusedContextResources(null, false, 0), + let contextEdge: { percent: number | null; window: number | null; resources: string } = { + percent: null, window: null, resources: formatFocusedContextResources(null, false, 0), }; let requestRender = (_force = false) => {}; @@ -326,26 +326,26 @@ export default function piSlate(pi: ExtensionAPI): void { percent = resolved.percent; contextWindow = usage?.contextWindow ?? ctx.model?.contextWindow ?? null; } catch { /* Context can be temporarily unavailable; keep identity and other facts fresh. */ } - const leaf = ctx.sessionManager.getLeafId?.(); - if (!branchFacts || leaf === undefined || leaf !== branchFacts.leaf) { - const entries = ctx.sessionManager.getBranch(); - branchFacts = { leaf, counts: sidebarMessageCounts(entries), usage: sidebarUsage(entries) }; - } - const mcpCount = resources.mcp.filter(server => server.enabled === true).length; if (owns("sidebar") && !sidebarYielded) { + const leaf = ctx.sessionManager.getLeafId?.(); + if (!branchFacts || leaf === undefined || leaf !== branchFacts.leaf) { + const entries = ctx.sessionManager.getBranch(); + branchFacts = { leaf, counts: sidebarMessageCounts(entries), usage: sidebarUsage(entries), + perf: branchPerf(entries, (provider, model) => ctx.modelRegistry.find(provider, model)?.promptCache) }; + } + const rate = tokenRate.rate(); sidebar.setSession({ id: ctx.sessionManager.getSessionId?.() ?? "", name: ctx.sessionManager.getSessionName?.(), 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: rate > 0 ? rate : null, startedAt: sessionStartedAt, lastTurnMs, turnStartedAt: turnStartedAt ?? null, working: typeof ctx.isIdle === "function" && !ctx.isIdle(), ...branchFacts.counts, usage: branchFacts.usage, + perf: branchFacts.perf, }); } - contextEdge = { - tokens: formatFocusedContextTokens(percent, tokenRate.rate(), contextWindow), - resources: formatFocusedContextResources(percent, estimated, mcpCount), - }; + contextEdge = { percent, window: contextWindow, + resources: formatFocusedContextResources(percent, estimated, resources.mcp.filter(server => server.enabled === true).length) }; }; const refreshResources = (ctx: ExtensionContext): void => { if (ctx.mode !== "tui" || !ctx.sessionManager || (!owns("sidebar") && !owns("editor")) || (sidebarYielded && !editorActive())) return; @@ -434,11 +434,7 @@ export default function piSlate(pi: ExtensionAPI): void { skills.reset([]); skills.restore(ctx.sessionManager.getBranch(), ctx.cwd); refreshResources(ctx); - tokenRate.setOnChange(() => { - const ctx = liveContext(); - if (ctx) syncSidebar(ctx); - if (thinkingFold.elapsedMs() !== null) syncThinkingStatus(); - }); + tokenRate.setOnChange(() => { if (thinkingFold.elapsedMs() !== null) syncThinkingStatus(); }); syncSidebar(ctx); } @@ -533,8 +529,9 @@ export default function piSlate(pi: ExtensionAPI): void { const ctx = liveContext(); if (!ctx || ctx.mode !== "tui" || !sidebar.splitActive) return; diagnostics.attempt("dashboard", "Last dashboard snapshot retained; a background refresh failed.", () => { - sidebar.tick(); if (++ticks % 5 === 0) { refreshResources(ctx); syncSidebar(ctx); } + else if (ctx.sessionManager.getLeafId() !== branchFacts?.leaf) syncSidebar(ctx); + sidebar.tick(); }, () => {}); }, 1000); dashboardClock.unref?.(); @@ -579,7 +576,9 @@ export default function piSlate(pi: ExtensionAPI): void { working: typeof current.isIdle === "function" && !current.isIdle(), workspaceHeader: owns("header"), dashboardVisible: sidebar.isVisible(tui.terminal.columns, tui.terminal.rows), - ...(!sidebar.isVisible(tui.terminal.columns, tui.terminal.rows) ? { context: contextEdge } : {}), + ...(!sidebar.isVisible(tui.terminal.columns, tui.terminal.rows) ? { context: { + tokens: formatFocusedContextTokens(contextEdge.percent, tokenRate.rate(), contextEdge.window), resources: contextEdge.resources, + } } : {}), }); let cachedMetadata = metadata(ctx); activeEditor = new ComposerEditor( @@ -710,7 +709,10 @@ export default function piSlate(pi: ExtensionAPI): void { currentContext = ctx; if (event.message.role === "assistant") { thinkingFold.stop(); - if (ctx.mode === "tui" && (owns("editor") || owns("sidebar"))) tokenRate.startMessage(); + if (ctx.mode === "tui" && (owns("editor") || owns("sidebar"))) { + tokenRate.startMessage(); + syncSidebar(ctx); // Pi has persisted the input that started this request. + } } }); pi.on("message_update", (event, ctx) => { @@ -732,7 +734,6 @@ export default function piSlate(pi: ExtensionAPI): void { skills.observeNested(event.message.nestedCalls?.calls ?? [], ctx.cwd); } refreshResources(ctx); - syncSidebar(ctx); syncVisibleMessages(); }); pi.on("session_info_changed", (_event, ctx) => { currentContext = ctx; syncSidebar(ctx); }); @@ -748,6 +749,7 @@ export default function piSlate(pi: ExtensionAPI): void { skills.readStart(event.toolCallId, event.toolName, event.args, ctx.cwd); background.shellStart(event.toolCallId, event.toolName, event.args, Date.now()); sidebar.setTasks(background.snapshot()); + syncSidebar(ctx); // message_end precedes persistence; the tool starts after it. }); pi.on("tool_execution_end", (event, ctx) => { if (ctx.mode !== "tui") return; 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..9dff99c --- /dev/null +++ b/pi-slate/extensions/pi-slate/perf-graphics.ts @@ -0,0 +1,244 @@ +/** + * 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 { sidebarCacheHit, type SidebarUsage } from "./sidebar-data.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: one decimal below 100, otherwise use the session's compact token notation. */ +export function formatRate(n: number | null | undefined): string { + if (!nonneg(n)) return "—"; + const tenth = Math.round(n * 10) / 10; + return tenth < 100 ? tenth.toFixed(1) : formatCompactTokenCount(n); +} + +/** 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(" ")); +} +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; +} + +/** Round proportional boundaries; keep positive segments visible when they fit. */ +export function stackedBar(parts: readonly number[], width: number): number[] { + const w = Math.max(0, Math.floor(width)); + const values = parts.map(v => nonneg(v) ? v : 0); + const max = Math.max(0, ...values); + if (!w || !max) return values.map(() => 0); + const total = values.reduce((sum, v) => sum + v / max, 0); + let remaining = values.filter(v => v > 0).length; + const min = w >= remaining ? 1 : 0; + let cumulative = 0; let boundary = 0; + return values.map(v => { + if (!v) return 0; + remaining--; + const rounded = Math.round((cumulative += v / max) / total * w); + const next = Math.max(boundary + min, Math.min(w - remaining * min, rounded)); + const cells = next - boundary; + boundary = next; + return cells; + }); +} + +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; usage: SidebarUsage; now: number; inner: number; tier: SidebarTier } & PerfPaint; +type Seg = readonly [Tone, string]; + +const fit = (lines: string[], width: number): string[] => lines.map(l => truncateToWidth(l, width, "…")); +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"]): 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("accent", fill) : "") + (track ? paint("dim", track) : ""); +} + +/** CONTEXT: heading + a one-row bar. */ +export function contextRows(i: PerfInput, c: { percent: number | null; tokens: number | null; window: number | null; estimated: boolean }): string[] { + const percent = c.percent !== null && Number.isFinite(c.percent) ? Math.max(0, Math.min(100, c.percent)) : null; + const pctSeg: Seg = percent === null ? DASH : ["text", `${Math.round(percent)}%`]; + const figures: Seg = ["dim", `${c.estimated ? "~" : ""}${formatCompactTokenCount(c.tokens)}/${formatCompactTokenCount(c.window)}`]; + return [ + headingRow(i, "CONTEXT", [[pctSeg, ["dim", " "], figures], [pctSeg]]), + contextBar(i.inner, percent, i.paint), + ]; +} + +function speedSparkline(rates: readonly number[], width: number): string { + if (width <= 0) return ""; + const shown = rates.slice(-width); + const peak = Math.max(...shown); + return shown.map(rate => "▁▂▃▄▅▆▇█"[Math.round(rate / peak * 7)]).join("").padEnd(width); +} + +/** Headline is always the exact last eligible response. */ +export function speedRows(i: PerfInput): string[] { + const { perf, inner, paint } = i; + const rate = perf.rates.at(-1); + if (rate === undefined) { + return [headingRow(i, "SPEED", [[DASH]]), noteRow(i, "no timed replies")]; + } + const digits = formatRate(rate); + const value: Seg = ["text", digits]; + const unit: Seg = ["dim", " tok/s"]; + const detail = detailRow(i, [["avg", formatRate(perf.turn.rate)], ["peak", formatRate(perf.peak)], ["out", formatCompactTokenCount(perf.turn.output)]]); + if (i.tier !== "full") { + const visual = paint("accent", speedSparkline(perf.rates, inner)); + return [headingRow(i, "SPEED", [[value, unit], [value]]), visual, detail]; + } + const rows = [headingRow(i, "SPEED", [[["dim", "last timed reply"]]])]; + const [a, b, c] = bigDigits(digits) as [string, string, string]; + const digitWidth = visibleWidth(a); + if (digitWidth <= inner && [...digits].every(ch => ch in FONT)) { + const withUnit = digitWidth + 1 + "tok/s".length <= inner; + rows.push(paint("text", a), paint("text", b) + (withUnit ? " " + paint("dim", "tok/s") : ""), paint("text", c)); + } else rows.push(paintSegs(i, [value, unit])); + if (inner >= 22) rows.push(...brailleBars(perf.rates, inner, 2).map(g => paint("accent", g))); + rows.push(detail); + return fit(rows, inner); +} + +export function formatCacheHit(rate: number | null): string { + if (rate === null) return "—"; + if (rate === 1) return "all cached"; + return `${Math.min(99.99, Math.round(rate * 10_000) / 100)}%`; +} + +/** Headline uses the same branch totals as the bar; warmth is based on the latest request. */ +function cacheSegs(i: PerfInput): Seg[][] { + const { cache: c } = i.perf; + const rate = sidebarCacheHit(i.usage); + const hit = rate === null ? null : formatCacheHit(rate); + const w = cacheWarmth(c, i.now); + const warm: Seg | null = w.state === "warm" ? ["success", `◉ ${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 && rate !== 1 ? [["text", hit], ["dim", " hit"]] : [["text", hit]]; + const join = (a: Seg[], b: Seg | null): Seg[] => b ? (a.length ? [...a, sep, b] : [b]) : a; + return [join(hitSegs(true), warm), join(hitSegs(false), warm), hitSegs(true), hitSegs(false)]; +} + +export function cacheRows(i: PerfInput): string[] { + const { usage, inner, paint } = i; + const spent: [string, string] = ["spent", sidebarCost(usage.cost)]; + if (!usage.cacheSeen) return [headingRow(i, "CACHE", [[DASH]]), noteRow(i, "no cache activity reported"), + ...(usage.cost !== null && (usage.cost > 0 || (usage.input ?? 0) > 0) ? [detailRow(i, [spent])] : [])]; + const [r = 0, w = 0, u = 0] = usage.input === null ? [] : stackedBar([usage.cacheRead ?? 0, usage.cacheWrite ?? 0, usage.uncached ?? 0], inner); + const bar = r || w || u ? paint("accent", "━".repeat(r)) + paint("warning", "━".repeat(w)) + paint("muted", "━".repeat(u)) : baseline(i); + const f = formatCompactTokenCount; + const tokens: Array<[string, string]> = [["read", f(usage.cacheRead)], ["write", f(usage.cacheWrite)], ["new", f(usage.uncached)]]; + const rows = [headingRow(i, "CACHE", cacheSegs(i)), bar]; + if (i.tier === "full") { + const saved = usage.saved; + rows.push(detailRow(i, tokens), detailRow(i, nonneg(saved) ? [spent, ["saved", `~${sidebarCost(saved)}`]] : [spent])); + } else rows.push(detailRow(i, [...tokens, spent])); + return fit(rows, inner); +} 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..abd909e --- /dev/null +++ b/pi-slate/extensions/pi-slate/perf-stats.ts @@ -0,0 +1,112 @@ +import type { SessionEntry } from "@earendil-works/pi-coding-agent"; +import { nonnegative, record } from "./sidebar-data.ts"; + +export const PERF_MIN_OUTPUT_TOKENS = 32; +export const PERF_MIN_DURATION_MS = 300; +export const PERF_MAX_RATES = 256; + +export type SidebarCachePerf = { + lastHit: number | null; + lastActivityAt: number | null; + ttlMs: number | null; +}; + +export type SidebarPerf = { + timedReplies: number; + /** Eligible output rates, oldest first. Peak includes replies outside this window. */ + rates: number[]; + peak: number | null; + turn: { output: number | null; rate: number | null }; + cache: SidebarCachePerf; +}; + +export const EMPTY_PERF: SidebarPerf = { + timedReplies: 0, rates: [], peak: null, turn: { output: 0, rate: null }, + cache: { lastHit: null, lastActivityAt: null, ttlMs: null }, +}; + +type CacheProducer = { provider: string; model: string }; +type CacheActivity = CacheProducer & { at: number | null; writes: number | null; hourWrites: number | null }; +type PromptCacheLookup = (provider: string, model: string) => { short?: number; long?: number } | undefined; + +function cacheActivity(producer: CacheProducer & { responseModel?: string }, usage: Record | undefined, at: number | null): CacheActivity | undefined { + const writes = nonnegative(usage?.cacheWrite); + if (!(writes || (nonnegative(usage?.cacheRead) ?? 0) > 0)) return; + return { provider: producer.provider, model: producer.responseModel ?? producer.model, at, writes, hourWrites: nonnegative(usage?.cacheWrite1h) }; +} + +function cacheLifetime(activity: CacheActivity, lookup: PromptCacheLookup): number | null { + const { short, long } = lookup(activity.provider, activity.model) ?? {}; + // Neither the current selection nor a zero 1h split proves what a past request used: + // the Anthropic adapter also reports zero when the split is absent. + const { writes, hourWrites } = activity; + const seconds = short === long ? short : writes && hourWrites === writes ? long : undefined; + const ms = nonnegative((seconds ?? 0) * 1000); + return ms || null; +} + +function reportedHit(usage: Record | undefined): number | null { + const read = nonnegative(usage?.cacheRead); + const write = nonnegative(usage?.cacheWrite); + const input = nonnegative(usage?.input); + if (read === null || write === null || input === null) return null; + const total = read + write + input; + return total > 0 && Number.isFinite(total) ? read / total : null; +} + +/** Completed output does not require timing. Rates use Pi's recorded provider-stream duration. */ +export function branchPerf(entries: readonly SessionEntry[], promptCacheFor: PromptCacheLookup = () => undefined): SidebarPerf { + let timedReplies = 0; + let rates: number[] = []; + let peak: number | null = null; + let turnOutput: number | null = 0; + let turnRateOut = 0; let turnRateMs = 0; + let lastHit: number | null = null; + let latestCache: CacheActivity | undefined; + const ids = new Set(); + + for (const entry of entries) { + if (ids.has(entry.id)) continue; + ids.add(entry.id); + if (entry.type === "usage" && entry.kind === "cache_warm") { + latestCache = cacheActivity(entry, record(entry.usage), nonnegative(Date.parse(entry.timestamp))) ?? latestCache; + } + if (entry.type !== "message") continue; + const { message } = entry; + if (message.role === "user") { turnOutput = 0; turnRateOut = 0; turnRateMs = 0; continue; } + if (message.role !== "assistant" || message.stopReason === "error" || message.stopReason === "aborted" || message.stopReason === "deferred") continue; + + const usage = record(message.usage); + const duration = nonnegative(message.durationMs); + const timestamp = nonnegative(message.timestamp); + const endedAt = timestamp === null || duration === null ? null : nonnegative(timestamp + duration); + latestCache = cacheActivity(message, usage, endedAt); + lastHit = reportedHit(usage); + const output = nonnegative(usage?.output); + turnOutput = output === null || turnOutput === null ? null : nonnegative(turnOutput + output); + if (output === null || output < PERF_MIN_OUTPUT_TOKENS || duration === null || duration < PERF_MIN_DURATION_MS) continue; + + const rate = output / (duration / 1000); + if (!Number.isFinite(rate)) continue; + timedReplies += 1; + turnRateOut += output; turnRateMs += duration; + rates.push(rate); + if (rates.length >= PERF_MAX_RATES * 2) rates = rates.slice(-PERF_MAX_RATES); + if (peak === null || rate > peak) peak = rate; + } + + return { + timedReplies, rates: rates.slice(-PERF_MAX_RATES), peak, + turn: { output: turnOutput, rate: turnRateMs > 0 ? nonnegative(turnRateOut / (turnRateMs / 1000)) : null }, + cache: { lastHit, lastActivityAt: latestCache?.at ?? null, ttlMs: latestCache ? cacheLifetime(latestCache, promptCacheFor) : null }, + }; +} + +export type CacheWarmth = { state: "warm" | "cold" | "unknown"; remainingMs: number | null; idleMs: number | null }; + +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..f29f492 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"; @@ -9,7 +10,10 @@ export { parseMcpFile, sidebarMcp, SidebarMcpFiles, type SidebarMcp, type Sideba export type SidebarUsage = { input: number | null; output: number | null; cacheRead: number | null; - cacheWrite: number | null; total: number | null; cost: number | null; + cacheWrite: number | null; uncached: number | null; total: number | null; cost: number | null; + cacheSeen: boolean; + /** Branch-wide read savings estimate; unknown unless every cached read is priceable. */ + saved: number | null; }; export type SidebarSkill = { name: string; path: string; source: string; loaded: boolean }; export type SidebarCommand = { name: string; source: string; description?: string }; @@ -19,7 +23,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 }; @@ -28,15 +35,24 @@ export function parseSidebarFolds(value: unknown): SidebarFolds { const raw = record(value); return { mcp: raw?.mcp === true, skills: raw?.skills === true, prompts: raw?.prompts === true }; } -function nonnegative(value: unknown): number | null { +export function nonnegative(value: unknown): number | null { return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null; } +function cacheReadSavings(raw: Record, cost: Record | undefined, read: number): number | null { + const input = nonnegative(raw.input); + const inputCost = nonnegative(cost?.input); + const readCost = nonnegative(cost?.cacheRead); + return input && inputCost && readCost !== null ? nonnegative(Math.max(0, read * (inputCost / input) - readCost)) : null; +} + /** Active-branch usage, including nested tools and summaries, once per owning entry. */ export function sidebarUsage(entries: readonly SessionEntry[]): SidebarUsage { const sums = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 }; const missing = new Set(); const seen = new Set(); + let cacheSeen = false; + let saved: number | null = 0; for (const entry of entries) { if (seen.has(entry.id)) continue; seen.add(entry.id); @@ -54,10 +70,22 @@ export function sidebarUsage(entries: readonly SessionEntry[]): SidebarUsage { if (expected) for (const key of Object.keys(sums) as Array) missing.add(key); continue; } + const cost = record(raw.cost); + const read = nonnegative(raw.cacheRead); + if (read && saved !== null) { + // Summary and tool ledgers may blend distinct requests and prices. + const singleRequest = entry.type === "usage" && entry.kind === "cache_warm" || entry.type === "message" && entry.message.role === "assistant"; + const estimate = singleRequest ? cacheReadSavings(raw, cost, read) : null; + saved = estimate === null ? null : nonnegative(saved + estimate); + } for (const key of Object.keys(sums) as Array) { - const value = nonnegative(key === "cost" ? record(raw.cost)?.total : raw[key]); + const value = nonnegative(key === "cost" ? cost?.total : raw[key]); if (value === null) missing.add(key); - else { sums[key] += value; if (!Number.isFinite(sums[key])) missing.add(key); } + else { + sums[key] += value; + if (!Number.isFinite(sums[key])) missing.add(key); + if ((key === "cacheRead" || key === "cacheWrite") && value > 0) cacheSeen = true; + } } } // Pi's input is uncached input; cacheRead/cacheWrite are separate categories. @@ -65,14 +93,20 @@ export function sidebarUsage(entries: readonly SessionEntry[]): SidebarUsage { ? null : nonnegative(sums.input + sums.cacheRead + sums.cacheWrite); const output = missing.has("output") ? null : sums.output; return { - input: inbound, output, + input: inbound, output, cacheSeen, + uncached: missing.has("input") ? null : sums.input, cacheRead: missing.has("cacheRead") ? null : sums.cacheRead, cacheWrite: missing.has("cacheWrite") ? null : sums.cacheWrite, total: inbound === null || output === null ? null : nonnegative(inbound + output), cost: missing.has("cost") ? null : sums.cost, + saved: missing.has("cacheRead") || !sums.cacheRead ? null : saved, }; } +export function sidebarCacheHit({ input, cacheRead }: SidebarUsage): number | null { + return input !== null && input > 0 && cacheRead !== null ? cacheRead / input : null; +} + export function sidebarMessageCounts(entries: readonly SessionEntry[]): { turns: number; messages: number } { let turns = 0; let messages = 0; for (const entry of entries) { diff --git a/pi-slate/extensions/pi-slate/sidebar-layout.ts b/pi-slate/extensions/pi-slate/sidebar-layout.ts index 13d322b..a2418a9 100644 --- a/pi-slate/extensions/pi-slate/sidebar-layout.ts +++ b/pi-slate/extensions/pi-slate/sidebar-layout.ts @@ -1,18 +1,22 @@ -export type SidebarSlots = { header: number; middle: number; tasks: number; image: number; footer: number }; +export type SidebarSlots = { frame: number; header: number; middle: number; tasks: number; image: number; footer: number }; +export type SidebarTier = "full" | "compact"; -/** Allocate once for both painting and hit testing. Never depend on composer height. */ -export function sessionSidebarSlots(height: number, taskCount: number, hasImage: boolean): SidebarSlots { +/** Budget borders, content and hit regions together. Shed header gaps before squeezing a preview. */ +export function sessionSidebarSlots(height: number, headerRows: number, taskCount: number, hasImage: boolean, gaps = 0): SidebarSlots { const rows = Math.max(0, Math.floor(height)); - const footer = rows >= 12 ? 1 : 0; - const header = Math.min(rows >= 30 ? 11 : 4, rows - footer); - let remaining = rows - header - footer; - const middleMin = Math.min(6, remaining); - const taskWant = taskCount ? (rows < 30 ? 1 : 2) + Math.min(rows < 30 ? 2 : 3, taskCount) * 2 : 0; - const tasks = Math.min(taskWant, Math.max(0, remaining - middleMin)); - remaining -= tasks; - const imageWant = hasImage ? rows < 20 ? 2 : Math.min(10, Math.max(4, Math.floor(rows / 5))) : 0; - const image = Math.min(imageWant, Math.max(0, remaining - middleMin)); - return { header, middle: remaining - image, tasks, image, footer }; + const frame = rows >= 12 ? 2 : 0; + const footer = frame ? 1 : 0; + const available = rows - frame - footer; + const taskWant = taskCount ? 2 + Math.min(3, taskCount) * 2 : 0; + const previewMin = hasImage ? 4 : 0; + const headerWant = hasImage ? Math.max(headerRows - gaps, Math.min(headerRows, available - 6 - taskWant - previewMin)) : headerRows; + const header = Math.min(available, headerWant); + const body = available - header; + const spare = Math.max(0, body - 6); + const tasks = Math.min(taskWant, spare - Math.min(previewMin, spare)); + const imageWant = hasImage ? Math.min(10, Math.max(previewMin, Math.floor(rows / 5))) : 0; + const image = Math.min(imageWant, spare - tasks); + return { frame, header, middle: body - tasks - image, tasks, image, footer }; } export function sidebarListOffset(offset: number, count: number, visible: number): number { @@ -29,17 +33,6 @@ export function sidebarCost(cost: number | null): string { return `$${(cost / unit).toFixed(1)}${suffix}`; } -/** Input is inbound (uncached + cache read + cache write). */ -export function sidebarUncached(usage: { input: number | null; cacheRead: number | null; cacheWrite: number | null }): number | null { - if (usage.input === null || usage.cacheRead === null || usage.cacheWrite === null) return null; - return Math.max(0, usage.input - usage.cacheRead - usage.cacheWrite); -} - -export function sidebarRate(rate: number | null): string { - if (rate === null || !Number.isFinite(rate) || rate < 0) return "—"; - return `~${Math.round(rate)} t/s`; -} - export function sidebarDuration(ms: number | null): string { if (ms === null || !Number.isFinite(ms)) return "—"; const seconds = Math.max(0, Math.floor(ms / 1000)); diff --git a/pi-slate/extensions/pi-slate/sidebar.ts b/pi-slate/extensions/pi-slate/sidebar.ts index 74d69fd..591ebec 100644 --- a/pi-slate/extensions/pi-slate/sidebar.ts +++ b/pi-slate/extensions/pi-slate/sidebar.ts @@ -5,14 +5,17 @@ import { installSidebarSplit, type SidebarSplitLease } from "./sidebar-split.ts" import { mcpDetails } from "./sidebar-mcp.ts"; import type { WorkspaceView } from "./workspace.ts"; import { chromePaint } from "./composer.ts"; -import { DEFAULT_SIDEBAR_FOLDS, sidebarText, type SidebarFolds, type SidebarResources, type SidebarSession } from "./sidebar-data.ts"; +import { DEFAULT_SIDEBAR_FOLDS, sidebarCacheHit, sidebarText, type SidebarFolds, type SidebarResources, type SidebarSession } from "./sidebar-data.ts"; import type { BackgroundTask } from "./background-tasks.ts"; -import { sessionSidebarSlots, sidebarCost, sidebarDuration, sidebarListOffset, sidebarRate, sidebarUncached } from "./sidebar-layout.ts"; +import { sessionSidebarSlots, sidebarDuration, sidebarListOffset, type SidebarTier } from "./sidebar-layout.ts"; +import { cacheRows, contextRows, formatCacheHit, formatCountdown, formatRate, speedRows, type PerfInput } from "./perf-graphics.ts"; +import { cacheWarmth, EMPTY_PERF } from "./perf-stats.ts"; export const DOUBLE_CLICK_MS = 400; type ListName = "mcp" | "skills" | "prompts" | "tasks"; -type Row = { divider?: boolean; text: string; action?: () => void; list?: ListName; item?: number }; +type Row = { divider?: boolean; text: string; action?: () => void; list?: ListName; item?: number; extra?: Array<{ x0: number; x1: number; action: () => void }> }; type Hit = { y: number; x0: number; x1: number; action: () => void }; +const HEADER_GAP: Row = { text: "" }; export type SidebarActions = { copy(text: string): void; openFile(filePath: string): void; @@ -25,7 +28,8 @@ const EMPTY_SESSION: SidebarSession = { id: "", name: "", pid: process.pid, cwd: "", model: "—", thinking: "—", tokens: null, percent: null, contextWindow: null, estimated: false, rate: null, startedAt: 0, lastTurnMs: null, working: false, turns: 0, messages: 0, - usage: { input: null, output: null, total: null, cacheRead: null, cacheWrite: null, cost: null }, + usage: { input: null, output: null, total: null, cacheRead: null, cacheWrite: null, uncached: null, cacheSeen: false, cost: null, saved: null }, + perf: EMPTY_PERF, }; const EMPTY_RESOURCES: SidebarResources = { skills: [], commands: [], prompts: [], mcp: [] }; @@ -150,8 +154,7 @@ export class Sidebar implements Component { isImagePinned(): boolean { return this.pinned; } sessionDetails(): string { const s = this.session; - const uncached = sidebarUncached(s.usage); - const hit = s.usage.input !== null && s.usage.cacheRead !== null && s.usage.input > 0 ? `${Math.round(s.usage.cacheRead / s.usage.input * 100)}%` : "—"; + const hit = formatCacheHit(sidebarCacheHit(s.usage)); return [`Session ${sidebarText(s.id) || "—"} · PID ${s.pid}`, `Title: ${s.name || "—"}`, `Model: ${s.model} · ${s.thinking}`, `Context: ${formatCompactTokenCount(s.tokens)} / ${formatCompactTokenCount(s.contextWindow)}${s.estimated ? " (estimated)" : ""}`, `Wall time (this runtime): ${sidebarDuration(s.startedAt > 0 ? this.now() - s.startedAt : null)}`, @@ -159,8 +162,21 @@ export class Sidebar implements Component { `Active-branch usage:`, `Input (uncached + cache read + cache write): ${formatCompactTokenCount(s.usage.input)}`, `Output: ${formatCompactTokenCount(s.usage.output)} · Total: ${formatCompactTokenCount(s.usage.total)}`, `Cache read: ${formatCompactTokenCount(s.usage.cacheRead)} · Cache write: ${formatCompactTokenCount(s.usage.cacheWrite)}`, - `Uncached input: ${formatCompactTokenCount(uncached)} · Cache-hit share: ${hit}`, - `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"); + `Uncached input: ${formatCompactTokenCount(s.usage.uncached)} · Cache-hit share: ${hit}`, + `Cost: ${s.usage.cost === null ? "—" : `$${s.usage.cost.toFixed(2)}`}`, `Estimated rate: ${s.rate === null ? "—" : `~${Math.round(s.rate)} tokens/sec`}`, s.cwd, ...this.speedCacheDetails()].join("\n"); + } + private speedCacheDetails(): string[] { + const perf = this.session.perf; + const c = perf.cache; + const warmth = cacheWarmth(c, this.now()); + return ["", "Speed & cache", + `Speed is output tokens ÷ Pi's recorded provider-stream duration, not total turn time.`, + `Replies with less than 32 output tokens, less than 300 ms, or missing timing are excluded from speed.`, + `The composer's live rate is an estimate (visible text ÷ 4) and is marked ~.`, + `Timed replies: ${perf.timedReplies} · last timed reply: ${formatRate(perf.rates.at(-1))} tok/s · peak: ${formatRate(perf.peak)} tok/s · this turn: ${formatRate(perf.turn.rate)} tok/s`, + `Cache hit % = cache read ÷ (uncached + cache read + cache write); latest request ${formatCacheHit(c.lastHit)}.`, + `Saved is estimated from recorded prices only when all branch cache reads are priceable.`, + `Cache expiry is estimated from the last reported cache activity when its retention tier is known${warmth.state === "unknown" ? " (not established here)" : ""}.`]; } tick(): void { if (!this.hidden && this.splitActive) this.tui?.requestRender(); } invalidate(): void { @@ -210,19 +226,20 @@ export class Sidebar implements Component { const key = `${width}:${height}:${this.revision}:${Math.floor(this.now() / 1000)}`; if (this.cached?.key === key) return this.cached.lines; this.hits = []; this.listRows = []; - const chrome = height >= 12 ? 1 : 0; - const slots = sessionSidebarSlots(height, this.tasks.length, Boolean(this.imageView())); - if (chrome) slots.middle = Math.max(0, slots.middle - 2); const inner = Math.max(0, width - 4); + const header = this.headerRows(inner, height >= 44 ? "full" : "compact"); + const slots = sessionSidebarSlots(height, header.length, this.tasks.length, Boolean(this.imageView()), header.filter(row => row === HEADER_GAP).length); + let dropGaps = header.length - slots.header; const lines: string[] = []; const add = (row: Row): void => { const y = lines.length; 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); + if (slots.frame) lines.push(this.dividerLine(width, "┌")); + for (const row of header.filter(row => row !== HEADER_GAP || dropGaps-- <= 0).slice(0, slots.header)) add(row); const middle = this.middle(); this.middleRows = middle.length; this.middleHeight = slots.middle; this.middleStart = lines.length; this.middleOffset = sidebarListOffset(this.middleOffset, middle.length, slots.middle); @@ -231,47 +248,46 @@ export class Sidebar implements Component { this.imageStart = lines.length; this.imageHeight = slots.image; lines.push(...this.imageLines(width, slots.image, lines.length)); if (slots.footer) add({ text: this.paint("dim", "/slate session · details"), action: () => this.actions?.inspect?.("Session", this.sessionDetails()) }); - while (lines.length < height - chrome) lines.push(this.decorateLine("", width)); - if (chrome) lines.push(this.dividerLine(width, "└")); + if (slots.frame) lines.push(this.dividerLine(width, "└")); this.cached = { key, lines: lines.slice(0, height) }; return this.cached.lines; } - private headerRows(width: number): Row[] { + private headerRows(width: number, tier: SidebarTier): Row[] { const s = this.session; 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("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: s.perf, usage: s.usage, now: this.now(), inner: width, tier, paint: (t, x) => this.paint(t, x), heading: x => this.heading(x) }; + const context: Row[] = contextRows(input, { percent, tokens: s.tokens, window: s.contextWindow, estimated: s.estimated }) + .map(text => ({ text, action: branchUsage })); + const rows = (lines: string[]): Row[] => lines.map(text => ({ text })); + return [status, identity, model, HEADER_GAP, ...context, HEADER_GAP, + ...rows(speedRows(input)), HEADER_GAP, + ...rows(cacheRows(input)), HEADER_GAP, divider]; } private middle(): Row[] { const enabled = this.resources.mcp.filter(x => x.enabled === true).length; diff --git a/pi-slate/tests/perf-fixture.ts b/pi-slate/tests/perf-fixture.ts new file mode 100644 index 0000000..cfcad2d --- /dev/null +++ b/pi-slate/tests/perf-fixture.ts @@ -0,0 +1,12 @@ +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 { + timedReplies: 28, + rates: [18, 22, 26, 31, 24, 28, 35, 30, 22, 19, 27, 33, 38, 29, 24, 31, 36, 41, 45, 37, 30, 26, 33, 28, 21, 25, 30, 14.6], + peak: 45, + turn: { output: 12_000, rate: 26.7 }, + cache: { lastHit: 0.92, lastActivityAt: now - 19_000, ttlMs: 300_000 }, + }; +} diff --git a/pi-slate/tests/perf-graphics.test.ts b/pi-slate/tests/perf-graphics.test.ts new file mode 100644 index 0000000..73ddefb --- /dev/null +++ b/pi-slate/tests/perf-graphics.test.ts @@ -0,0 +1,272 @@ +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, contextRows, formatCountdown, formatRate, speedRows, stackedBar, type PerfInput } from "../extensions/pi-slate/perf-graphics.ts"; +import { EMPTY_PERF, type SidebarPerf } from "../extensions/pi-slate/perf-stats.ts"; +import { Sidebar } from "../extensions/pi-slate/sidebar.ts"; +import type { SidebarSession, SidebarUsage } from "../extensions/pi-slate/sidebar-data.ts"; +import { perfFixture } from "./perf-fixture.ts"; + +const strip = (t: string) => t.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, ""); +const plainPaint = { paint: (_t: string, x: string) => x, heading: (x: string) => x }; +const usage: SidebarUsage = { input: 1_559_000, output: 12_000, total: 1_571_000, cacheRead: 1_310_000, cacheWrite: 108_000, uncached: 141_000, cacheSeen: true, cost: 0.84, saved: 1.92 }; +const noUsage: SidebarUsage = { input: null, output: null, total: null, cacheRead: null, cacheWrite: null, uncached: null, cacheSeen: false, cost: null, saved: null }; +const input = (perf: SidebarPerf, inner = 40, tier: PerfInput["tier"] = "full", now = 1000, totals = usage): PerfInput => ({ perf, usage: totals, now, inner, tier, ...plainPaint }); + +test("formatRate uses one decimal below 100, integers below 1000, then compact units", () => { + const cases: Array<[number | null, string]> = [[14.64, "14.6"], [0, "0.0"], [99.96, "100"], [100, "100"], [999.4, "999"], [999.6, "1k"], [1234, "1.2k"], + [12_345, "12.3k"], [123_456, "123k"], [2_500_000, "2.5M"], [null, "—"], [Number.NaN, "—"], [Infinity, "—"], [-3, "—"]]; + for (const [n, out] of cases) assert.equal(formatRate(n), out, String(n)); +}); + +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 + 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], [1e308, 1e308, 1e308]]) { + const out = stackedBar(parts, width); + assert.equal(out.reduce((a, b) => a + b, 0), width, `${width} ${parts}`); + assert(out.every(n => Number.isInteger(n) && n >= 0)); + 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)); +}); + +const SECTIONS = (perf: SidebarPerf, inner = 40, tier: PerfInput["tier"] = "compact", totals = usage) => { + const i = input(perf, inner, tier, 1000, totals); + return { speed: speedRows(i).map(strip), cache: cacheRows(i).map(strip) }; +}; + +test("empty perf: sections keep the grammar, collapse to two rows, and never print NaN or 0%", () => { + for (const tier of ["full", "compact"] as const) { + const { speed, cache } = SECTIONS(EMPTY_PERF, 40, tier, noUsage); + assert.equal(speed.length, 2); assert.equal(cache.length, 2); + assert.match(speed[0]!, /^SPEED\s+—$/); assert.equal(speed[1], "no timed replies"); + assert.match(cache[0]!, /^CACHE\s+—$/); assert.equal(cache[1], "no cache activity reported"); + assert.doesNotMatch([...speed, ...cache].join("\n"), /NaN|Infinity|-\d|0%|[█▀]/); + } +}); + +test("known spend is shown even without cache activity", () => { + const { cache } = SECTIONS(perfFixture(1000), 40, "compact", { ...noUsage, input: 100, cost: 0.84 }); + assert.deepEqual(cache.slice(1), ["no cache activity reported", "spent $0.84"]); +}); + +test("compact SPEED: heading, left-aligned sparkline, labelled detail row; padding is spaces", () => { + const perf: SidebarPerf = { ...perfFixture(1000), rates: [10, 20, 15, 18, 23.5], peak: 23.5, turn: { output: 214, rate: 13.9 } }; + const { speed } = SECTIONS(perf); + assert.equal(speed.length, 3); + assert.match(speed[0]!, /^SPEED\s+23\.5 tok\/s$/); + assert.equal(speed[1], "▄▇▅▆█".padEnd(40)); + assert.equal(SECTIONS(perf, 3).speed[1], "▅▆█", "show the newest sample per column"); + assert.equal(speed[2], "avg 13.9 · peak 23.5 · out 214"); +}); + +test("a single rate renders one block at the left", () => { + const perf: SidebarPerf = { ...EMPTY_PERF, timedReplies: 1, rates: [30], peak: 30, turn: { output: 300, rate: 30 } }; + assert.match(SECTIONS(perf).speed[1]!, /^█ +$/); +}); + +test("full SPEED: big digits, two braille rows, then the same detail row", () => { + const rows = SECTIONS(perfFixture(1000), 40, "full").speed; + assert.equal(rows.length, 7); + assert.match(rows[0]!, /^SPEED\s+last timed reply$/); + assert.equal(rows[2], " █ ▀▀█ █▀█ tok/s"); + assert.match(rows[4]!, /[⠁-⣿]/); assert.match(rows[5]!, /[⠁-⣿]/); + assert.equal(rows[6], "avg 26.7 · peak 45.0 · out 12k"); + assert(!rows.join("").includes("Turn avg"), "the 3-column table is gone"); +}); + +test("untimed replies don't masquerade as missing responses, and incomplete output stays unknown", () => { + const legacy: SidebarPerf = { ...EMPTY_PERF, turn: { output: 10, rate: null } }; + assert.equal(SECTIONS(legacy).speed[1], "no timed replies"); + const base = perfFixture(1000); + const incomplete: SidebarPerf = { ...base, turn: { ...base.turn, output: null } }; + assert.match(SECTIONS(incomplete).speed[2]!, /out —$/); +}); + +test("huge numbers and tiny widths stay inside the width", () => { + const base = perfFixture(1000); + const perf: SidebarPerf = { ...base, peak: 1e9, rates: [12_345, 1e9], turn: { output: 9e12, rate: 1e15 } }; + assert.equal(SECTIONS(perf, 40, "full").speed[1], "1B tok/s", "unsupported big glyphs fall back to text"); + for (const inner of [1, 4, 10, 16, 21, 22, 24, 30, 44, 60]) for (const tier of ["full", "compact"] as const) for (const cost of [1.2e6, 1e308, null]) { + const i = input(perf, inner, tier, 1000, { ...usage, cacheWrite: 1e12, uncached: 1e15, cost, saved: 1.2e6 }); + for (const r of [...speedRows(i), ...cacheRows(i), ...contextRows(i, { percent: 91, tokens: 1e12, window: 1e15, estimated: true })]) { + assert(visibleWidth(r) <= inner, `${inner} ${tier}: ${strip(r)}`); assert.doesNotMatch(strip(r), /NaN|Infinity/); + } + } +}); + +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+84\.03% hit · ◉ 4:41$/); + assert.match(head({}, 1_000_000 + 1000), /◉ 4:40$/, "countdown moves with the clock alone"); + assert.match(head({}, 1_000_000 + 400_000), /84\.03% hit · cold$/); + assert.match(head({ ttlMs: null }, 1_000_000 + 30_000), /^CACHE\s+84\.03% hit$/, "no lifetime and recent: nothing extra"); + assert.match(head({ ttlMs: null, lastActivityAt: 1_000_000 - 62_000 }, 1_000_000, "compact"), /^CACHE\s+84\.03% hit · idle 1m$/); +}); + +test("CACHE headline and bar use branch totals and distinguish near-perfect from exact hits", () => { + const base = perfFixture(1000); + const perf = { ...base, cache: { ...base.cache, lastHit: 0.9956 } }; + for (const [read, label, cells] of [[86_000, "86% hit", 34], [95_200, "95.2% hit", 38], [99_560, "99.56% hit", 39], [99_999, "99.99% hit", 39], [100_000, "all cached", 40]] as const) { + const totals = { ...usage, input: 100_000, cacheRead: read, cacheWrite: 0, uncached: 100_000 - read }; + const i = input(perf, 40, "compact", 1000, totals); + const [heading, bar] = cacheRows({ ...i, paint: (t, x) => t === "accent" ? x.replaceAll("━", "█") : x }); + assert(heading?.includes(label)); + assert.equal(bar, "█".repeat(cells) + "━".repeat(40 - cells)); + } + const unknown = SECTIONS(perf, 40, "full", { ...usage, input: null, uncached: null }).cache; + assert.match(unknown[0]!, /^CACHE\s+◉ 4:41$/, "unknown totals omit the hit rate"); + assert.equal(unknown[1], "─".repeat(40), "missing input is not treated as all cached"); +}); + +test("CACHE bars use the context glyph in three tones; money rows handle unknowns", () => { + 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 => /^(accent|warning|muted):━/.test(t)).map(t => t.split(":")[0]); + assert.deepEqual(bar, ["accent", "warning", "muted"]); + assert.equal(full[2], "read 1.3M · write 108k · new 141k"); + assert.equal(full[3], "spent $0.84 · saved ~$1.92"); + const none = SECTIONS(perfFixture(1000), 40, "full", { ...usage, cost: null, saved: null }).cache; + 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), 40, "compact", { ...usage, input: 0, cacheRead: 0, cacheWrite: 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, 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: noUsage }); + 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, during working turns and long sessions", () => { + const clock = { now: 1_000_000 }; + const perf: SidebarPerf = { ...perfFixture(clock.now), rates: Array.from({ length: 256 }, (_, i) => 10 + (i % 40)), timedReplies: 5000 }; + for (const rows of [10, 19, 20, 29, 30, 43, 44, 70]) for (const width of [0, 1, 5, 12, 20, 28, 44, 60, 90]) { + const lines = sidebarWith(rows, perf, clock, { working: true }).render(width); + assert.equal(lines.length, rows); + assert(lines.every(l => visibleWidth(l) <= width), `${width}x${rows}`); + } +}); + +test("details distinguish branch and last-request cache rates", () => { + const clock = { now: 1_000_000 }; + const base = perfFixture(clock.now); + const s = sidebarWith(30, { ...base, cache: { ...base.cache, lastHit: 0.9956 } }, clock); + assert.match(s.render(40).map(strip).join("\n"), /CACHE\s+84\.03% hit · ◉ 4:41/); + assert.match(s.sessionDetails(), /Speed & cache/); + assert.match(s.sessionDetails(), /300 ms/); + assert.match(s.sessionDetails(), /Cache-hit share: 84\.03%/); + assert.match(s.sessionDetails(), /latest request 99\.56%\./); +}); + +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, 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, paint)), width, `width ${width} pct ${pct}`); + assert.equal(contextBar(10, 0, paint), "░".repeat(10)); + assert.equal(contextBar(10, null, paint), "░".repeat(10)); + assert.equal(contextBar(10, 0.01, paint), "▏" + "░".repeat(9), "any usage is visible"); + assert.equal(contextBar(10, 50, paint), "█████" + "░".repeat(5)); + assert.equal(contextBar(10, 100, paint), "█".repeat(10)); +}); diff --git a/pi-slate/tests/perf-stats.test.ts b/pi-slate/tests/perf-stats.test.ts new file mode 100644 index 0000000..648f7ba --- /dev/null +++ b/pi-slate/tests/perf-stats.test.ts @@ -0,0 +1,92 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import type { SessionEntry } from "@earendil-works/pi-coding-agent"; +import { branchPerf, cacheWarmth, EMPTY_PERF, PERF_MAX_RATES } from "../extensions/pi-slate/perf-stats.ts"; + +let seq = 0; +function entry(fields: Record): SessionEntry { + return { id: `e${seq++}`, parentId: null, timestamp: "1970-01-01T00:00:10.000Z", ...fields } as unknown as SessionEntry; +} +const user = () => entry({ type: "message", message: { role: "user" } }); +const asst = (fields: Record = {}, usage: Record = {}) => entry({ + type: "message", message: { role: "assistant", provider: "fixture", model: "a", timestamp: 1000, durationMs: 1000, + stopReason: "stop", usage: { input: 10, output: 100, cacheRead: 0, cacheWrite: 0, ...usage }, ...fields }, +}); + +test("empty and unsuccessful branches have no timed replies", () => { + assert.deepEqual(branchPerf([]), EMPTY_PERF); + const failed = ["error", "aborted", "deferred"].map(stopReason => asst({ stopReason }, { cacheRead: 128 })); + assert.deepEqual(branchPerf(failed), EMPTY_PERF); +}); + +test("turn output includes tiny and untimed replies, but the weighted rate includes only eligible replies", () => { + const perf = branchPerf([user(), asst({ durationMs: undefined }, { output: 999 }), asst({}, { output: 10 }), + asst({ durationMs: 100 }, { output: 500 }), asst({}, { output: 1000 }), asst({ durationMs: 9000 }, { output: 90 })]); + assert.deepEqual(perf.rates, [1000, 10]); + assert.equal(perf.peak, 1000); + assert.equal(perf.timedReplies, 2); + assert.deepEqual(perf.turn, { output: 2599, rate: 109 }); + assert.deepEqual(branchPerf([asst({ durationMs: undefined })]).turn, { output: 100, rate: null }); +}); + +test("a missing output makes the turn subtotal unknown without invalidating other timed replies", () => { + const missing = asst({ usage: undefined }); + assert.deepEqual(branchPerf([missing, asst()]).turn, { output: null, rate: 100 }); + assert.deepEqual(branchPerf([missing, user(), asst()]).turn, { output: 100, rate: 100 }); + assert.deepEqual(branchPerf([missing, user()]).turn, EMPTY_PERF.turn); +}); + +test("retains the newest rates, but peak and reply count cover the entire branch", () => { + const first = asst({ durationMs: 400 }, { output: 4000 }); + const count = PERF_MAX_RATES * 3; + const entries = [first, first, ...Array.from({ length: count }, (_, i) => asst({}, { output: 100 + i }))]; + const perf = branchPerf(entries); + assert.equal(perf.timedReplies, count + 1); + assert.equal(perf.rates.length, PERF_MAX_RATES); + assert.equal(perf.peak, 10000); + assert.equal(perf.rates.at(-1), 99 + count); + assert.equal(perf.rates[0], 100 + count - PERF_MAX_RATES); +}); + +test("latest completed reply owns hit rate; tool/summary usage and failed replies don't replace it", () => { + const reply = asst({}, { input: 50, cacheRead: 150, cacheWrite: 50 }); + const tool = entry({ type: "message", message: { role: "toolResult", usage: { cacheRead: 99 } } }); + const failed = asst({ stopReason: "error" }); + assert.equal(branchPerf([reply, tool, entry({ type: "compaction" }), failed]).cache.lastHit, 0.6); + assert.equal(branchPerf([reply, asst({}, { cacheRead: Infinity })]).cache.lastHit, null); +}); + +test("expiry follows the recorded cache producer and timestamp, not an unrelated timed failure or reply", () => { + const lookup = (provider: string, model: string) => provider === "fixture" && model === "physical-a" + ? { short: 300, long: 3600 } : { short: 99, long: 99 }; + const reply = asst({ model: "routed", responseModel: "physical-a" }, { cacheWrite: 40, cacheWrite1h: 40 }); + const failed = asst({ model: "b", timestamp: 3000, stopReason: "error" }, { cacheRead: 900 }); + assert.deepEqual(branchPerf([reply, failed], lookup).cache, { lastHit: 0, lastActivityAt: 2000, ttlMs: 3_600_000 }); + const untimed = asst({ model: "b", durationMs: undefined }, { cacheRead: 30 }); + assert.equal(cacheWarmth(branchPerf([reply, untimed], lookup).cache, 4000).state, "unknown"); + assert.equal(cacheWarmth(branchPerf([reply, asst({ model: "b" })], lookup).cache, 4000).state, "unknown"); +}); + +test("a persisted cache refresh advances activity but not the last reply's hit or speed", () => { + const reply = asst({}, { input: 30, cacheRead: 70, cacheWrite: 0 }); + const warm = entry({ type: "usage", kind: "cache_warm", provider: "fixture", model: "a", usage: { cacheRead: 100 } }); + const perf = branchPerf([reply, warm], () => ({ short: 300, long: 300 })); + assert.deepEqual(perf.cache, { lastHit: 0.7, lastActivityAt: 10_000, ttlMs: 300_000 }); + assert.deepEqual(perf.rates, [100]); + assert.equal(cacheWarmth(perf.cache, 11_000).remainingMs, 299_000); +}); + +test("a cache timer requires evidence of the recorded request's retention tier", () => { + const lookup = () => ({ short: 300, long: 3600 }); + assert.equal(branchPerf([asst({}, { cacheWrite: 10, cacheWrite1h: 10 })], lookup).cache.ttlMs, 3_600_000); + for (const usage of [{ cacheRead: 99 }, { cacheWrite: 10 }, { cacheWrite: 10, cacheWrite1h: 0 }, { cacheWrite: 10, cacheWrite1h: 3 }]) { + assert.equal(branchPerf([asst({}, usage)], lookup).cache.ttlMs, null); + } +}); + +test("cache warmth clamps clock skew and expires at TTL", () => { + const cache = { ...EMPTY_PERF.cache, lastActivityAt: 10_000, ttlMs: 300_000 }; + assert.deepEqual(cacheWarmth(cache, 5000), { state: "warm", remainingMs: 300_000, idleMs: 0 }); + assert.equal(cacheWarmth(cache, 310_000).state, "cold"); + assert.equal(cacheWarmth({ ...cache, ttlMs: null }, 70_000).idleMs, 60_000); +}); diff --git a/pi-slate/tests/quiet-workbench.test.ts b/pi-slate/tests/quiet-workbench.test.ts index 49e6c58..8dcad73 100644 --- a/pi-slate/tests/quiet-workbench.test.ts +++ b/pi-slate/tests/quiet-workbench.test.ts @@ -7,15 +7,16 @@ import { loadThemeFromPath, SYSTEM_THEME_NAME } from "../node_modules/@earendil- import { ComposerEditor, type ComposerSource } from "../extensions/pi-slate/composer.ts"; import { dashboardColumnWidth, formatCompactTokenCount, parseSlateArgs } from "../extensions/pi-slate/layout.ts"; import { SLATE_NATIVE_THEME, SLATE_THEME } from "../extensions/pi-slate/install-defaults.ts"; -import { sessionSidebarSlots, sidebarCost, sidebarRate } from "../extensions/pi-slate/sidebar-layout.ts"; +import { sessionSidebarSlots, sidebarCost } from "../extensions/pi-slate/sidebar-layout.ts"; import { Sidebar } from "../extensions/pi-slate/sidebar.ts"; +import { perfFixture } from "./perf-fixture.ts"; import type { SidebarSession } from "../extensions/pi-slate/sidebar-data.ts"; 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, uncached: 12400, cacheSeen: true, cost: 1.24, saved: null }, perf: perfFixture(1000) }; test("bundled default Tokyo Night loads with the native validator and restrained backgrounds", () => { assert.equal(SLATE_THEME, "tokyo-night"); assert.equal(theme.name, SLATE_THEME); @@ -48,10 +49,10 @@ test("compact viewport hides the rail without changing stored width or focus", ( test("empty shelves allocate zero rows and all allocations remain bounded", () => { for (let height = 0; height < 80; height++) { - const empty = sessionSidebarSlots(height, 0, false); + const empty = sessionSidebarSlots(height, 11, 0, false); assert.equal(empty.tasks, 0); assert.equal(empty.image, 0); for (const tasks of [0, 1, 10]) for (const image of [false, true]) { - const values = Object.values(sessionSidebarSlots(height, tasks, image)); + const values = Object.values(sessionSidebarSlots(height, 11, tasks, image)); assert.equal(values.reduce((a, b) => a + b, 0), height); assert(values.every(n => n >= 0)); } @@ -65,56 +66,53 @@ 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"); assert.equal(sidebarCost(null), "—"); assert.equal(sidebarCost(Number.NaN), "—"); assert.equal(sidebarCost(-1), "—"); assert.equal(sidebarCost(1.24), "$1.24"); assert.equal(sidebarCost(1e308), "$1.0e+308"); - assert.equal(sidebarRate(33.4), "~33 t/s"); assert.equal(sidebarRate(300), "~300 t/s"); - assert.equal(sidebarRate(null), "—"); assert.equal(sidebarRate(Number.NaN), "—"); - assert.equal(sidebarRate(-1), "—"); assert.equal(sidebarRate(Infinity), "—"); sidebar.dispose(); }); -test("context meter keeps a thin track and dim separator with the real theme", () => { +test("high context usage and cache reads follow live accent changes within the same theme family", () => { + const lavender = loadThemeFromPath(new URL("../themes/catppuccin-mocha-lavender.json", import.meta.url).pathname, "truecolor"); + const peach = loadThemeFromPath(new URL("../themes/catppuccin-mocha-peach.json", import.meta.url).pathname, "truecolor"); + let active = lavender; const sidebar = new Sidebar(() => 10000); - sidebar.attach({ terminal: { rows: 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: 40, columns: 140 }, requestRender() {} } as unknown as TUI, lavender); + sidebar.setThemeProvider(() => active); + sidebar.setSession({ ...session, percent: 88 }); + const contextFill = "█".repeat(35) + "▎"; + const cacheBar = () => sidebar.render(44).find(row => stripVTControlCharacters(row).includes("━".repeat(40)))!; + const reads = "━".repeat(29); + assert.equal(lavender.fg("success", reads), peach.fg("success", reads), "status color is fixed across these accents"); + assert(cacheBar().includes(lavender.fg("accent", reads))); + assert(sidebar.render(44).some(row => row.includes(lavender.fg("accent", contextFill)))); + active = peach; + const after = cacheBar(); + assert(after.includes(peach.fg("accent", reads))); + assert(!after.includes(lavender.fg("accent", reads))); + assert(sidebar.render(44).some(row => row.includes(peach.fg("accent", contextFill)))); + sidebar.dispose(); +}); + +test("short terminals keep the CONTEXT heading row grammar with the real theme", () => { + const sidebar = new Sidebar(() => 10000); + sidebar.attach({ terminal: { rows: 30, columns: 140 }, requestRender() {} } as unknown as TUI, theme); 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-data.test.ts b/pi-slate/tests/sidebar-data.test.ts index f02636a..8364092 100644 --- a/pi-slate/tests/sidebar-data.test.ts +++ b/pi-slate/tests/sidebar-data.test.ts @@ -16,36 +16,50 @@ function skill(name: string): Skill { return { name, filePath: `/skills/${name}/ test("usage input includes cache categories once; reasoning is already part of output", () => { const a = message("a", "assistant", { usage }); const result = sidebarUsage([a, a]); - assert.deepEqual(result, { input: 450, output: 20, cacheRead: 300, cacheWrite: 50, total: 470, cost: 0.25 }); + assert.deepEqual(result, { input: 450, output: 20, cacheRead: 300, cacheWrite: 50, uncached: 100, cacheSeen: true, total: 470, cost: 0.25, saved: null }); }); test("tool nested usage, compaction, branch summaries and cache warming each count once", () => { const entries = [message("a", "assistant", { usage }), message("t", "toolResult", { usage, nestedCalls: { calls: [{ usage }], complete: true } }), entry("c", { type: "compaction", usage }), entry("b", { type: "branch_summary", usage }), entry("w", { type: "usage", kind: "cache_warm", usage })]; const result = sidebarUsage(entries); - assert.equal(result.input, 2250); assert.equal(result.output, 100); assert.equal(result.cost, 1.25); + assert.deepEqual(result, { input: 2250, output: 100, cacheRead: 1500, cacheWrite: 250, uncached: 500, cacheSeen: true, total: 2350, cost: 1.25, saved: null }); }); test("ordinary tool results without usage are not invented model requests", () => { - assert.deepEqual(sidebarUsage([message("t", "toolResult")]), { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, cost: 0 }); + assert.deepEqual(sidebarUsage([message("t", "toolResult")]), { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, uncached: 0, cacheSeen: false, total: 0, cost: 0, saved: null }); }); test("missing or invalid provider facts show unknown rather than fake zero", () => { - assert.deepEqual(sidebarUsage([message("a", "assistant")]), { input: null, output: null, cacheRead: null, cacheWrite: null, total: null, cost: null }); + assert.deepEqual(sidebarUsage([message("a", "assistant")]), { input: null, output: null, cacheRead: null, cacheWrite: null, uncached: null, cacheSeen: false, total: null, cost: null, saved: null }); const result = sidebarUsage([message("a", "assistant", { usage: { ...usage, cacheRead: NaN, cost: { total: -1 } } })]); - assert.equal(result.input, null); assert.equal(result.output, 20); assert.equal(result.cacheWrite, 50); assert.equal(result.total, null); assert.equal(result.cost, null); + assert.deepEqual(result, { input: null, output: 20, cacheRead: null, cacheWrite: 50, uncached: 100, cacheSeen: true, total: null, cost: null, saved: null }); +}); + +test("estimate savings only when all branch cache reads can be priced", () => { + const priced = { ...usage, input: 100, cacheRead: 100, cost: { input: 1, cacheRead: 0.25, total: 1.25 } }; + const reply = message("a", "assistant", { usage: priced }); + const warm = entry("w", { type: "usage", kind: "cache_warm", usage: priced }); + assert.equal(sidebarUsage([reply, warm]).saved, 1.5); + for (const uncertain of [message("b", "assistant", { usage: { ...priced, input: 0 } }), + message("c", "assistant", { usage }), entry("d", { type: "compaction", usage: priced })]) { + const stats = sidebarUsage([reply, warm, uncertain]); + assert.notEqual(stats.cost, null); + assert.equal(stats.saved, null); + } }); test("legacy summaries without usage make billed totals unknown rather than silently free", () => { for (const type of ["compaction", "branch_summary"]) { const result = sidebarUsage([message("a", "assistant", { usage }), entry("summary", { type })]); - assert.equal(result.input, null); assert.equal(result.cost, null); + assert.equal(result.input, null); assert.equal(result.uncached, null); assert.equal(result.cost, null); + assert.equal(result.cacheSeen, true); } }); test("overflow in otherwise finite usage never manufactures Infinity metrics", () => { const huge = { ...usage, input: 1e308, output: 1e308, cacheRead: 1e308, cacheWrite: 1e308, cost: { total: 1e308 } }; const result = sidebarUsage([message("a", "assistant", { usage: huge }), message("b", "assistant", { usage: huge })]); - assert(Object.values(result).every(value => value === null || Number.isFinite(value))); + assert(Object.values(result).every(value => typeof value !== "number" || Number.isFinite(value))); assert.equal(result.input, null); assert.equal(result.cost, null); }); diff --git a/pi-slate/tests/sidebar-preview.test.ts b/pi-slate/tests/sidebar-preview.test.ts index 8fafd20..7395b02 100644 --- a/pi-slate/tests/sidebar-preview.test.ts +++ b/pi-slate/tests/sidebar-preview.test.ts @@ -6,15 +6,17 @@ 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 { SidebarMcpFiles, type SidebarResources, type SidebarSession } from "../extensions/pi-slate/sidebar-data.ts"; -import { sessionSidebarSlots } from "../extensions/pi-slate/sidebar-layout.ts"; +import { perfFixture } from "./perf-fixture.ts"; +import { EMPTY_PERF } from "../extensions/pi-slate/perf-stats.ts"; +import { SidebarMcpFiles, type SidebarResources, type SidebarSession, type SidebarUsage } from "../extensions/pi-slate/sidebar-data.ts"; import { DiffWorkspaceView, type WorkspaceView } from "../extensions/pi-slate/workspace.ts"; import type { BackgroundTask } from "../extensions/pi-slate/background-tasks.ts"; const theme = (code = 32) => ({ fg: (_tone: string, text: string) => `\x1b[${code}m${text}\x1b[0m`, bold: (text: string) => text }) as Theme; const stripAnsi = (text: string) => text.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, ""); const plain = (lines: string[]) => lines.map(line => stripAnsi(line).replace(/^│ ?/, "").replace(/ ?│$/, "").trimEnd()); -const session: SidebarSession = { id: "session-a", pid: 8421, cwd: "/tmp/project", model: "sonnet-4.6", thinking: "medium", tokens: 31600, percent: 16, contextWindow: 200000, estimated: false, rate: 82, startedAt: 1000, lastTurnMs: 5000, working: true, turns: 2, messages: 5, usage: { input: 61400, output: 876, total: 62276, cacheRead: 48000, cacheWrite: 6100, cost: 0.12 } }; +const session: SidebarSession = { id: "session-a", pid: 8421, cwd: "/tmp/project", model: "sonnet-4.6", thinking: "medium", tokens: 31600, percent: 16, contextWindow: 200000, estimated: false, rate: 82, startedAt: 1000, lastTurnMs: 5000, working: true, turns: 2, messages: 5, usage: { input: 61400, output: 876, total: 62276, cacheRead: 48000, cacheWrite: 6100, uncached: 7300, cacheSeen: true, cost: 0.12, saved: null }, perf: perfFixture(1000) }; +const noUsage: SidebarUsage = { input: null, output: null, total: null, cacheRead: null, cacheWrite: null, uncached: null, cacheSeen: false, cost: null, saved: null }; const resources: SidebarResources = { mcp: Array.from({ length: 7 }, (_, i) => ({ name: `server-${i}`, enabled: i !== 2, source: "global" })), skills: Array.from({ length: 6 }, (_, i) => ({ name: `skill-${i}`, path: `/tmp/skills/${i}/SKILL.md`, loaded: i === 0, source: "project" })), @@ -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", "session-", "sonnet-4.6", "16%", "31.6k/200k", "SPEED", "CACHE", "78.18% hit", "spent $0.12", "MCP · 6 Enabled", "Skills · 1 Loaded", "Prompts · 6"]) assert(lines.some(line => line.includes(label)), label); for (const label of ["Stats", "Tokens · branch", "Commands ·", "Tasks", "Preview", "no selection", "/run-0", "prompt-0"]) assert(!lines.some(line => line.includes(label)), label); @@ -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"); }); @@ -144,104 +143,89 @@ test("all sizes allocate exact bounded rows, including zero, Unicode, and tiny t assert.equal(lines.length, height); assert(lines.every(line => visibleWidth(line) <= width), `${width}×${height}`); assert(lines.every(line => !line.includes("\x1b[2J") && !line.includes("\n"))); - const slots = sessionSidebarSlots(height, 4, true); - assert.equal(Object.values(slots).reduce((a, b) => a + b, 0), height); - assert(Object.values(slots).every(x => x >= 0)); } } }); -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")); + assert.doesNotMatch(text, /● streaming/); + if (width >= 28) for (const value of ["6.1k", "$0.12", "78.18%"]) assert(text.includes(value), value); + assert(!/\bCached\b|Uncached|\bPID\b/.test(text), "old usage rows are gone"); } 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.*output tokens ÷ Pi's recorded provider-stream 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", () => { - const { sidebar } = fixture(); +test("header height follows the terminal tier and its divider closes the header", () => { + const { sidebar, terminal } = 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]] as const) { + terminal.rows = rows; + assert.equal(plain(sidebar.render(40)).findIndex(line => /^├─+┤$/.test(line)), header, `rows ${rows}`); + } + terminal.rows = 60; const lines = plain(sidebar.render(40)); assert.match(lines[0]!, /^┌─+┐$/, "top bar"); assert.match(lines.at(-1)!, /^└─+┘$/, "bottom bar"); - const hairline = lines.findIndex((line, i) => i > 0 && i < lines.length - 1 && /^├─+┤$/.test(line)); - assert.equal(hairline, 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.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(30); + const context = (width: number) => { + const line = plain(sidebar.render(width)).find(line => line.startsWith("CONTEXT") || /\d+%|—/.test(line) && !line.includes("tok/s") && !line.includes("Idle") && !line.includes("Working")); + assert(line, `context at width ${width}`); return line; }; - 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"); }); -test("context meter fill follows the theme accent and shifts to the warning tone at 80% and above", () => { +test("context meter keeps the theme accent at every usage level", () => { const codes: Record = { muted: 90, dim: 2, accent: 36, warning: 33, text: 37 }; const toneTheme = { fg: (tone: string, text: string) => `\x1b[${codes[tone] ?? 0}m${text}\x1b[0m`, bold: (text: string) => text } as Theme; 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(); + sidebar.setThemeProvider(() => toneTheme); + const meterLine = () => sidebar.render(40).find(line => /^│ ?[█-▏░]{4}/.test(stripAnsi(line)))!; + for (const percent of [0, 79, 80, 88, 100]) { + sidebar.setSession({ ...session, percent }); const line = meterLine(); - const fill = 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"); + const fill = stripAnsi(line).match(/[█-▏]+/)?.[0] ?? ""; + if (percent > 0) assert(fill && line.includes(toneTheme.fg("accent", fill)), `${percent}% uses the theme accent`); + if (percent < 100) assert(line.includes("\x1b[2m"), "track stays dim"); + const heading = sidebar.render(40).find(line => stripAnsi(line).includes("CONTEXT"))!; + assert(heading.includes(toneTheme.fg("text", `${percent}%`)), "percentage keeps the normal value color"); } - sidebar.setSession({ ...session, percent: null }); sidebar.invalidate(); - assert(!/━/.test(stripAnsi(meterLine())), "null percent fills nothing"); + sidebar.setSession({ ...session, percent: null }); + 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"]); -}); - -test("a 24-row terminal still renders an image body; a very short one prioritizes tasks", () => { - const { sidebar, terminal } = fixture(24); sidebar.setView(image()); sidebar.setTasks([task(0)]); - assert(plain(sidebar.render(40)).some(line => line.includes("IMAGE")), "normal-height thumbnails must not disappear"); - terminal.rows = 14; - const text = plain(sidebar.render(40)).join("\n"); - assert(text.includes("Tasks")); assert(!text.includes("IMAGE")); + sidebar.setSession({ ...session, estimated: true, usage: noUsage }); + const heading = row(sidebar, "~31.6k/200k"); + sidebar.handleMouse(mouse(heading)); + sidebar.handleMouse(mouse(heading + 1)); + assert.deepEqual(inspected, ["Branch usage", "Branch usage"]); }); test("foldable MCP and Skills sections persist independently and keep counts visible", () => { @@ -383,16 +367,17 @@ test("image double-click uses native clickCount or the fallback timer", () => { assert.deepEqual(opened, ["/tmp/a.png"]); }); -test("short terminals collapse the image body, keep tasks visible, and scroll middle overflow", () => { - const { sidebar } = fixture(18); sidebar.setView(image()); sidebar.setTasks([task(0), task(1), task(2)]); +test("the compact rail keeps the image and tasks while the middle scrolls", () => { + const { sidebar } = fixture(30); sidebar.setView(image()); sidebar.setTasks([task(0), task(1), task(2)]); sidebar.setFolds({ mcp: true, skills: true, prompts: false }); const lines = plain(sidebar.render(40)); assert.equal(sidebar.imagePath(), "/tmp/a.png"); - assert(!lines.some(line => line.includes("IMAGE"))); + assert(lines.some(line => line.includes("IMAGE"))); assert(lines.some(line => line.includes("Tasks"))); - sidebar.handleMouse(mouse(6, { type: "wheel", wheelDelta: -40 })); + sidebar.handleMouse(mouse(row(sidebar, "MCP"), { type: "wheel", wheelDelta: -40 })); const scrolled = plain(sidebar.render(40)); - assert(scrolled.some(line => /Skills|Prompts|server-\d|skill-\d|prompt-\d/.test(line))); + assert(scrolled.some(line => /Skills|Prompts|skill-\d|prompt-\d/.test(line))); + assert.notDeepEqual(scrolled, lines); assert.equal(scrolled[0], lines[0]); assert.equal(sidebar.imagePath(), "/tmp/a.png"); }); @@ -418,10 +403,10 @@ test("clock and theme changes invalidate cached output; pure repeated render is test("unknown values and invalid MCP config remain explicit even when folded", () => { const { sidebar } = fixture(); - sidebar.setSession({ ...session, percent: null, tokens: null, contextWindow: null, usage: { input: null, output: null, total: null, cacheRead: null, cacheWrite: null, cost: null } }); + sidebar.setSession({ ...session, percent: null, tokens: null, contextWindow: null, usage: noUsage }); sidebar.setResources({ ...resources, mcpError: "MCP config unreadable" }); const lines = plain(sidebar.render(80)); - assert(lines.some(line => 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 +428,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 +478,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 +488,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\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, usage: noUsage, perf: EMPTY_PERF }); + const empty = plain(sidebar.render(44)); + const mcpEmpty = empty.findIndex(line => line.includes("MCP")); + assert(empty.some(line => line.includes("no timed replies"))); + assert(empty.some(line => line.includes("no cache activity reported"))); + sidebar.setSession(session); + const full = plain(sidebar.render(44)); + assert.equal(full.findIndex(line => line.includes("MCP")) - mcpEmpty, 7, "5 speed + 2 cache rows are reclaimed"); + 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..9c0158f 100644 --- a/pi-slate/tests/surfaces-install.test.ts +++ b/pi-slate/tests/surfaces-install.test.ts @@ -130,7 +130,7 @@ async function fixture(t: TestContext, text: string | undefined, mode = "tui", c }; const manager = SessionManager.inMemory(cwd); let stale = false; - const ctx = new Proxy({ cwd, mode, ui, sessionManager: manager, getContextUsage: () => undefined, isIdle: () => true, isProjectTrusted: () => false } as unknown as ExtensionContext, { + const ctx = new Proxy({ cwd, mode, ui, sessionManager: manager, modelRegistry: { find: () => undefined }, getContextUsage: () => undefined, isIdle: () => true, isProjectTrusted: () => false } as unknown as ExtensionContext, { get(target, key, receiver) { if (stale) throw new Error("This extension ctx is stale after session replacement or reload."); return Reflect.get(target, key, receiver); @@ -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("已恢复的标题"); @@ -600,6 +600,56 @@ function railOf(f: Awaited>): Sidebar { return (Reflect.get(Reflect.get(f.tui, "layoutRoot"), "entries") as Array<{ component: Sidebar }>)[1]!.component; } +function sidebarReply(): Extract[0], { role: "assistant" }> { + return { role: "assistant", api: "anthropic-messages", provider: "anthropic", model: "producer", + timestamp: Date.now() - 1000, durationMs: 1000, stopReason: "toolUse", content: [{ type: "text", text: "fixture response" }], + usage: { input: 200, output: 70, cacheRead: 0, cacheWrite: 100, cacheWrite1h: 100, totalTokens: 370, + cost: { input: .01, output: 0, cacheRead: 0, cacheWrite: 0, total: .01 } } }; +} + +test("SPEED follows persistence, not token deltas or an unrelated model selection", async t => { + const f = await fixture(t, JSON.stringify({ surfaces: ["sidebar"] })), reply = sidebarReply(); + const capture = () => unstyled(railOf(f).render(44).join("\n")); + Object.assign(f.ctx, { isIdle: () => false, modelRegistry: { find: (_: string, id: string) => + id === "producer" ? { promptCache: { short: 300, long: 3600 } } : undefined } }); + f.manager.appendMessage(reply); + await f.emit("agent_start"); + assert.match(capture(), /● Working/); assert.doesNotMatch(capture(), /Working · turn/); + Object.assign(f.ctx, { model: { id: "virtual", provider: "fixture", promptCache: { short: 30 } } }); + const scans = t.mock.method(f.manager, "getBranch"); + await f.emit("model_select"); + assert.match(capture(), /◉ (?:1:00:00|59:59)/); + const next = { ...reply, usage: { ...reply.usage, output: 120 } }; + await f.emit("message_start", { message: next }); + const contextReads = t.mock.method(f.ctx, "getContextUsage"); await f.emit("message_update", { message: next }); + assert.equal(scans.mock.callCount() + contextReads.mock.callCount(), 0, "token updates do not rescan context or persisted facts"); + await f.emit("message_end", { message: next }); + assert.match(capture(), /SPEED\s+70\.0 tok\/s/); + f.manager.appendMessage(next); + await f.emit("tool_execution_start", { toolCallId: "call", toolName: "read", args: {} }); + assert.match(capture(), /SPEED\s+120 tok\/s/); +}); + +test("mounted rail preserves the pinned preview and open target under task pressure", async t => { + const f = await fixture(t, JSON.stringify({ surfaces: ["sidebar"], focused: false })); + f.manager.appendMessage(sidebarReply()); await f.emit("agent_settled"); + const sidebar = railOf(f), opened: string[] = []; + const root = Reflect.get(f.tui, "layoutRoot") as Component; + sidebar.setActions({ copy() {}, openFile: path => opened.push(path) }); + sidebar.setView({ id: "image:fixture", filePath: f.imagePath, title: "Fixture", invalidate() {}, render: () => ["pinned-image-body"] }); + sidebar.pinImage(); + sidebar.setTasks([0, 1, 2].map(i => ({ id: `task-${i}`, source: "fixture", label: `task-${i}`, kind: "subagent", state: "running", startedAt: 1 }))); + for (const rows of [29, 30, 32, 44]) { + (f.tui.terminal as NullTerminal).rows = rows; + const frame = root.render(140).join("\n"); + assert.equal(frame.includes("pinned-image-body"), rows >= 30, `${rows} rows`); + if (rows < 30) continue; + const y = sidebar.render(28).findIndex(line => line.includes("[open]")); + assert(y >= 0); + sidebar.handleMouse({ type: "click", button: "left", x: 2, y, width: 28, height: rows, screenX: 114, screenY: y, shift: false, alt: false, ctrl: false }); + } + assert.deepEqual(opened, Array(3).fill(f.imagePath)); +}); test("fold save preserves external sibling state, unknown section keys and unknown nested settings", async t => { const f = await fixture(t, JSON.stringify({ surfaces: ["sidebar"] })); await writeFile(f.path, JSON.stringify({ surfaces: ["sidebar"], sidebarSections: { skills: true, future: "keep" }, modelDisplay: { providerSuffix: true, future: "keep" }, unrelated: { nested: true } }));