import { matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component, type TuiMouseEvent, type TuiMouseEventResult, } from "@earendil-works/pi-tui"; import { CONTEXT_CATEGORIES, type ContextBreakdownNode, type ContextBreakdownSnapshot, type KeybindingsManager, type Theme, } from "@selesai/code"; export const CONTEXT_GRID_CELLS = 100; const CATEGORY_MARKS = ["I", "D", "C", "T", "S", "O"] as const; const CATEGORY_COLORS = ["accent", "syntaxType", "success", "warning", "syntaxString", "muted"] as const; const count = (value: number | null | undefined): string => value == null ? "unknown" : String(value); const percentage = (value: number | null, capacity: number | null): string => value === null || capacity === null ? "unknown" : `${(value / capacity * 100).toFixed(1)}%`; type GridAllocation = { categories: number[]; remainder: number; scaled: boolean }; /** Display rounding only: roots are inclusive core subtotals, never parent-plus-child accounting. */ export function allocateContextGrid(snapshot: ContextBreakdownSnapshot): GridAllocation | null { const capacity = snapshot.capacityTokens; if (capacity === null || snapshot.estimatedAllocationTokens === null || snapshot.status === "unavailable") return null; const weights = CONTEXT_CATEGORIES.map((category) => snapshot.categories.find((node) => node.category === category)?.estimatedTokens ?? 0); const total = weights.reduce((sum, value) => sum + value, 0); const scaled = total > capacity; weights.push(Math.max(0, capacity - total)); const denominator = Math.max(capacity, total); const quotas = weights.map((value) => value / denominator * CONTEXT_GRID_CELLS); const cells = quotas.map(Math.floor); const ranking = quotas.map((quota, index) => ({ index, fraction: quota - cells[index] })) .sort((a, b) => b.fraction - a.fraction || a.index - b.index); const remaining = CONTEXT_GRID_CELLS - cells.reduce((sum, value) => sum + value, 0); for (const { index } of ranking.slice(0, remaining)) cells[index]++; return { categories: cells.slice(0, 6), remainder: cells[6], scaled }; } interface InspectorOptions { readSnapshot: () => ContextBreakdownSnapshot; theme: Theme; keybindings: Pick; getHeight: () => number; requestRender: () => void; onClose: () => void; } interface TreeRow { node: ContextBreakdownNode; depth: number; parent?: ContextBreakdownNode } interface DocumentLine { text: string; nodeId?: string } export class ContextInspectorComponent implements Component { private snapshot: ContextBreakdownSnapshot; private expanded = new Set(); private selectedId: string | undefined; private scroll = 0; private documentHeight = 0; private viewportHeight = 1; private renderedWidth = 0; private renderedHeight = 0; private hitRows = new Map(); private revealSelection = false; private closed = false; constructor(private readonly options: InspectorOptions) { this.snapshot = options.readSnapshot(); this.selectedId = this.snapshot.categories[0]?.id; } invalidate(): void { // Mouse targets always describe the last rendered viewport, never a pending layout. this.hitRows.clear(); } private treeRows(): TreeRow[] { const rows: TreeRow[] = []; const visit = (node: ContextBreakdownNode, depth: number, parent?: ContextBreakdownNode) => { rows.push({ node, depth, parent }); if (this.expanded.has(node.id)) for (const child of node.children) visit(child, depth + 1, node); }; for (const root of this.snapshot.categories) visit(root, 0); return rows; } private change(): void { this.invalidate(); this.options.requestRender(); } private close(): void { this.closed = true; this.hitRows.clear(); this.options.onClose(); } private refresh(): void { this.snapshot = this.options.readSnapshot(); this.expanded.clear(); this.selectedId = this.snapshot.categories[0]?.id; this.scroll = 0; this.revealSelection = false; this.change(); } private toggle(id: string): void { this.selectedId = id; if (this.expanded.has(id)) this.expanded.delete(id); else this.expanded.add(id); this.revealSelection = true; this.change(); } handleInput(data: string): void { if (this.closed) return; const kb = this.options.keybindings; if (matchesKey(data, "escape") || kb.matches(data, "tui.select.cancel")) { this.close(); return; } if (data === "r") { this.refresh(); return; } if (kb.matches(data, "tui.select.pageUp") || kb.matches(data, "tui.select.pageDown")) { const delta = kb.matches(data, "tui.select.pageUp") ? -this.viewportHeight : this.viewportHeight; this.scrollBy(delta); return; } const rows = this.treeRows(); if (!rows.length) return; let index = Math.max(0, rows.findIndex(({ node }) => node.id === this.selectedId)); const row = rows[index]; if (kb.matches(data, "tui.select.confirm") || matchesKey(data, "space")) { this.toggle(row.node.id); return; } if (kb.matches(data, "tui.select.up")) index = Math.max(0, index - 1); else if (kb.matches(data, "tui.select.down")) index = Math.min(rows.length - 1, index + 1); else if (matchesKey(data, "home")) index = 0; else if (matchesKey(data, "end")) index = rows.length - 1; else if (matchesKey(data, "left")) { if (this.expanded.has(row.node.id)) this.expanded.delete(row.node.id); else if (row.parent) index = rows.findIndex(({ node }) => node.id === row.parent!.id); } else if (matchesKey(data, "right")) { if (!this.expanded.has(row.node.id)) this.expanded.add(row.node.id); else if (row.node.children.length) index++; } else if (/^[1-6]$/.test(data)) { const root = this.snapshot.categories[Number(data) - 1]; if (!root) return; index = rows.findIndex(({ node }) => node.id === root.id); this.expanded.add(root.id); } else return; this.selectedId = rows[index].node.id; this.revealSelection = true; this.change(); } private scrollBy(delta: number): void { this.scroll = Math.max(0, Math.min(Math.max(0, this.documentHeight - this.viewportHeight), this.scroll + delta)); this.revealSelection = false; this.change(); } handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined { if (this.closed || event.shift || event.alt || event.ctrl || event.width !== this.renderedWidth || event.height !== this.renderedHeight || event.x < 0 || event.x >= event.width || event.y < 0 || event.y >= event.height) return undefined; if (event.type === "wheel" && event.wheelDelta && Number.isFinite(event.wheelDelta)) { this.scrollBy(Math.trunc(event.wheelDelta)); return { handled: true, render: true }; } if (event.type !== "click" || event.button !== "left" || (event.clickCount ?? 1) !== 1) return undefined; const id = this.hitRows.get(event.y); if (!id) return undefined; this.toggle(id); return { handled: true, render: true }; } render(width: number): string[] { this.hitRows.clear(); if (this.closed || width < 1) return []; const height = Math.max(1, Math.floor(this.options.getHeight())); const framed = width >= 4 && height >= 4; const bodyWidth = framed ? width - 2 : width; this.viewportHeight = Math.max(1, height - (framed ? 3 : height > 1 ? 1 : 0)); const lines: DocumentLine[] = []; const add = (text: string, nodeId?: string) => { for (const line of wrapTextWithAnsi(text, bodyWidth)) lines.push({ text: truncateToWidth(line, bodyWidth, ""), nodeId }); }; const s = this.snapshot; add("Main context · logical allocation estimate"); add(`${s.basis} · ${s.freshness} · ${s.status} · coverage: ${s.coverage}`); add(`Model: ${s.selectedModel ? `${s.selectedModel.provider}/${s.selectedModel.id}` : "unknown"}`); if (s.effectiveModel) add(`Effective: ${s.effectiveModel.provider}/${s.effectiveModel.id}`); add(`Revision ${s.revision} · captured ${new Date(s.capturedAt).toISOString()}`); add(`Capacity: ${count(s.capacityTokens)} tokens`); const usagePercent = s.authoritativeUsage?.percent; add(`Authoritative usage: ${count(s.authoritativeUsage?.tokens)} tokens (${usagePercent == null ? "unknown" : `${usagePercent}%`})`); add(`Estimated allocation: ${count(s.estimatedAllocationTokens)} tokens (${percentage(s.estimatedAllocationTokens, s.capacityTokens)})`); add(`Discrepancy (usage - estimate): ${count(s.discrepancyTokens)} tokens`); add(`Method: ${s.estimateMethod}. Not provider-exact; no reserved-output/free-space claim.`); add(`Reasons: ${s.reasons.length ? s.reasons.join(", ") : "none"}`); const grid = allocateContextGrid(s); add("Grid basis: estimated allocation / capacity; ? = unknown/unaccounted remainder, NOT measured free space."); if (grid) { if (grid.scaled) add(`OVER CAPACITY by ${count(s.estimatedAllocationTokens! - s.capacityTokens!)} tokens. Cells scaled to fit; numeric percentages are uncapped.`); const cells: string[] = []; for (let i = 0; i < 6; i++) { for (let n = 0; n < grid.categories[i]; n++) { const cell = bodyWidth > 1 ? `\x1b[7m${CATEGORY_MARKS[i]} \x1b[27m` : CATEGORY_MARKS[i]; cells.push(this.options.theme.fg(CATEGORY_COLORS[i], cell)); } } for (let n = 0; n < grid.remainder; n++) cells.push(this.options.theme.fg("dim", bodyWidth > 1 ? "? " : "?")); const columns = Math.max(1, Math.min(20, Math.floor(bodyWidth / 2))); for (let start = 0; start < cells.length; start += columns) { lines.push({ text: cells.slice(start, start + columns).join("") }); } add(`${CONTEXT_GRID_CELLS} fixed-budget square cells; letters identify categories without color.`); } else add("Capacity grid unavailable; unknown is not zero."); for (let i = 0; i < 6; i++) { const root = s.categories.find((node) => node.category === CONTEXT_CATEGORIES[i]); add(`${CATEGORY_MARKS[i]} = ${CONTEXT_CATEGORIES[i]}: ${count(root?.estimatedTokens)} tokens (${percentage(root?.estimatedTokens ?? null, s.capacityTokens)})`); } add("Contributors · select and expand for verified metadata (no raw bodies)"); const rows = this.treeRows(); if (!rows.length) add("No context contributors available."); for (const { node, depth } of rows) { const expanded = this.expanded.has(node.id); const selected = node.id === this.selectedId; const categoryIndex = CONTEXT_CATEGORIES.indexOf(node.category); const text = `${selected ? ">" : " "}${" ".repeat(depth)}${expanded ? "[-]" : "[+]"} ${depth === 0 ? `${CATEGORY_MARKS[categoryIndex]} ` : ""}${node.label}: ${count(node.estimatedTokens)} tokens (${percentage(node.estimatedTokens, s.capacityTokens)})`; add(this.options.theme.fg(selected ? "accent" : "text", text), node.id); if (expanded) { add(` Attribution: ${node.attribution}; source: ${node.sourceKind}; included children: ${node.children.length}; omitted: ${node.omittedChildren}.`); if (!node.children.length && !node.omittedChildren) add(" No deeper contributors available."); if (node.omittedChildren) add(" Inclusive subtotal includes omitted contributors."); } } if (s.omittedNodes) add(`Omitted contributors: ${s.omittedNodes}; totals include omitted items.`); const hint = (id: Parameters[0]) => this.options.keybindings.getKeys(id).join("/") || "unbound"; add(`${hint("tui.select.up")}/${hint("tui.select.down")} select; ${hint("tui.select.confirm")}/Space/click expand; Left/Right collapse/expand; 1–6 category; Home/End first/last`); add(`${hint("tui.select.pageUp")}/${hint("tui.select.pageDown")}/wheel scroll all content; r refresh; Esc close`); this.documentHeight = lines.length; if (this.revealSelection) { const selected = lines.findIndex((line) => line.nodeId === this.selectedId); // Input/mouse selection always names a rendered tree row; refresh clears revealSelection. if (selected < this.scroll) this.scroll = selected; else if (selected >= this.scroll + this.viewportHeight) this.scroll = selected; this.revealSelection = false; } this.scroll = Math.max(0, Math.min(Math.max(0, lines.length - this.viewportHeight), this.scroll)); const output: string[] = []; const th = this.options.theme; if (framed) output.push(th.fg("border", `╭${"─".repeat(bodyWidth)}╮`)); const visible = lines.slice(this.scroll, this.scroll + this.viewportHeight); for (const line of visible) { if (line.nodeId) this.hitRows.set(output.length, line.nodeId); output.push(framed ? `${th.fg("border", "│")}${line.text}${" ".repeat(Math.max(0, bodyWidth - visibleWidth(line.text)))}${th.fg("border", "│")}` : line.text); } if (height > 1) { const status = `Esc close · r refresh · ${hint("tui.select.pageUp")}/${hint("tui.select.pageDown")} scroll · ${this.scroll + 1}-${Math.min(lines.length, this.scroll + this.viewportHeight)}/${lines.length}`; output.push(truncateToWidth(status, width, "")); } if (framed) output.push(th.fg("border", `╰${"─".repeat(bodyWidth)}╯`)); this.renderedWidth = width; this.renderedHeight = output.length; return output; } }