import type { Theme } from "@earendil-works/pi-coding-agent"; import { matchesKey, type TUI, truncateToWidth, visibleWidth, wrapTextWithAnsi, } from "@earendil-works/pi-tui"; import { DIMENSIONS, type ModelAggregate, type SessionScoreRecord, } from "./core.js"; export type DashboardTab = "leaderboard" | "sessions" | "method"; export type DashboardAction = "scan" | undefined; export interface DashboardData { judge: string; stateDirectory: string; leaderboard: ModelAggregate[]; records: SessionScoreRecord[]; pending: number; unranked: number; storageErrors: number; } export interface ScanDisplayState { phase: "prepare" | "judge"; model: string; currentName: string; session: number; sessions: number; chunk: number; chunks: number; evidence: number; cost: number; failures: number; startedAt: number; } const TABS: DashboardTab[] = ["leaderboard", "sessions", "method"]; const SPINNER = ["◐", "◓", "◑", "◒"] as const; function padRight(text: string, width: number): string { const truncated = truncateToWidth(text, Math.max(0, width)); return truncated + " ".repeat(Math.max(0, width - visibleWidth(truncated))); } function padLeft(text: string, width: number): string { const truncated = truncateToWidth(text, Math.max(0, width)); return " ".repeat(Math.max(0, width - visibleWidth(truncated))) + truncated; } function joinEnds(left: string, right: string, width: number): string { if (visibleWidth(left) + visibleWidth(right) + 1 > width) return truncateToWidth(left, width); return `${left}${" ".repeat(width - visibleWidth(left) - visibleWidth(right))}${right}`; } function dateLabel(timestamp: string): string { const date = new Date(timestamp); if (Number.isNaN(date.valueOf())) return "?"; return date.toLocaleDateString("en-US", { month: "short", day: "numeric" }); } function scoreColor(theme: Theme, score: number, text: string): string { if (score >= 115) return theme.fg("success", text); if (score >= 100) return theme.fg("accent", text); if (score >= 85) return theme.fg("warning", text); return theme.fg("error", text); } function scoreLabel(score: number | null): string { return score === null ? "?" : score.toFixed(1); } function windowed( items: readonly T[], selected: number, maximum: number, ): T[] { if (items.length <= maximum) return [...items]; const half = Math.floor(maximum / 2); const start = Math.min( Math.max(0, selected - half), Math.max(0, items.length - maximum), ); return items.slice(start, start + maximum); } export class IqDashboardComponent { private tab: DashboardTab = "leaderboard"; private selectedModel = 0; private selectedSession = 0; private expanded = true; constructor( private readonly theme: Theme, private readonly data: DashboardData, private readonly requestRender: () => void, private readonly done: (action: DashboardAction) => void, ) {} handleInput(input: string): void { if (matchesKey(input, "escape") || matchesKey(input, "q")) { this.done(undefined); return; } if (matchesKey(input, "s")) { this.done("scan"); return; } if (matchesKey(input, "tab") || matchesKey(input, "right")) { const index = TABS.indexOf(this.tab); this.tab = TABS[(index + 1) % TABS.length] ?? this.tab; this.requestRender(); return; } if (matchesKey(input, "shift+tab") || matchesKey(input, "left")) { const index = TABS.indexOf(this.tab); this.tab = TABS[(index - 1 + TABS.length) % TABS.length] ?? this.tab; this.requestRender(); return; } const maximum = this.tab === "leaderboard" ? this.data.leaderboard.length : this.tab === "sessions" ? this.data.records.length : 0; if (matchesKey(input, "up") && maximum > 0) { if (this.tab === "leaderboard") this.selectedModel = Math.max(0, this.selectedModel - 1); else this.selectedSession = Math.max(0, this.selectedSession - 1); this.requestRender(); return; } if (matchesKey(input, "down") && maximum > 0) { if (this.tab === "leaderboard") this.selectedModel = Math.min(maximum - 1, this.selectedModel + 1); else this.selectedSession = Math.min(maximum - 1, this.selectedSession + 1); this.requestRender(); return; } if (matchesKey(input, "enter") || matchesKey(input, "space")) { this.expanded = !this.expanded; this.requestRender(); } } render(width: number): string[] { const safeWidth = Math.max(1, width); const lines = [ ...this.renderHeader(safeWidth), ...this.renderTabs(safeWidth), ...(this.tab === "leaderboard" ? this.renderLeaderboard(safeWidth) : this.tab === "sessions" ? this.renderSessions(safeWidth) : this.renderMethod(safeWidth)), "", this.theme.fg( "dim", safeWidth >= 58 ? "Tab/←→ view · ↑↓ select · Enter detail · s scan · q close" : "Tab · ↑↓ · Enter · s scan · q close", ), ]; return lines.map((line) => truncateToWidth(line, safeWidth)); } private renderHeader(width: number): string[] { const title = `${this.theme.fg("accent", this.theme.bold("IQ"))} ${this.theme.fg("dim", "personal work ability")}`; const statusParts = this.data.pending ? [`${this.data.pending} unscored`] : ["all scoreable sessions scored"]; if (this.data.unranked) statusParts.push(`${this.data.unranked} unranked`); const statusText = statusParts.join(" · "); const status = this.data.pending ? this.theme.fg("warning", statusText) : this.theme.fg("dim", statusText); const sharedLine = visibleWidth(title) + visibleWidth(status) + 1 <= width; const lines = [sharedLine ? joinEnds(title, status, width) : title]; if (!sharedLine) lines.push(status); if (this.data.storageErrors) lines.push( this.theme.fg( "error", `${this.data.storageErrors} unreadable persisted record${this.data.storageErrors === 1 ? "" : "s"}`, ), ); return [...lines, ""]; } private renderTabs(width: number): string[] { const tabs = TABS.map((tab) => { const label = tab.toUpperCase(); return tab === this.tab ? this.theme.fg("accent", `[${label}]`) : this.theme.fg("dim", ` ${label} `); }).join(width >= 44 ? " " : " "); return [tabs, ""]; } private renderLeaderboard(width: number): string[] { if (this.data.leaderboard.length === 0) return [this.theme.fg("dim", "No scored sessions. Press s to scan.")]; return width >= 72 ? this.renderWideLeaderboard(width) : this.renderNarrowLeaderboard(width); } private renderWideLeaderboard(width: number): string[] { const modelWidth = Math.max(20, width - 35); const lines = [ this.theme.fg( "muted", `${padRight("MODEL", modelWidth)}${padLeft("IQ", 8)}${padLeft("N", 5)}${padLeft("SPAN", 10)}${padLeft("LAST", 12)}`, ), this.theme.fg("border", "─".repeat(Math.min(width, modelWidth + 35))), ]; const visible = windowed(this.data.leaderboard, this.selectedModel, 10); const first = this.data.leaderboard.indexOf(visible[0] as ModelAggregate); for (let offset = 0; offset < visible.length; offset++) { const model = visible[offset]; if (!model) continue; const selected = first + offset === this.selectedModel; const marker = selected ? "▸ " : " "; const name = `${marker}${model.model}`; const row = `${padRight(name, modelWidth)}${padLeft(model.score.toFixed(1), 8)}${padLeft(String(model.sessions), 5)}${padLeft(`${model.minimum.toFixed(0)}–${model.maximum.toFixed(0)}`, 10)}${padLeft(dateLabel(model.lastScoredAt), 12)}`; lines.push( selected ? this.theme.fg("accent", row) : truncateToWidth(row, width), ); } if (this.expanded) lines.push("", ...this.renderModelDetail(width)); return lines; } private renderNarrowLeaderboard(width: number): string[] { const lines: string[] = [ this.theme.fg("border", "─".repeat(Math.max(1, width - 2))), ]; const visible = windowed(this.data.leaderboard, this.selectedModel, 6); const first = this.data.leaderboard.indexOf(visible[0] as ModelAggregate); for (let offset = 0; offset < visible.length; offset++) { const model = visible[offset]; if (!model) continue; const selected = first + offset === this.selectedModel; lines.push( (selected ? this.theme.fg("accent", "▸ ") : " ") + (selected ? this.theme.fg("accent", truncateToWidth(model.model, width - 2)) : truncateToWidth(model.model, width - 2)), ); lines.push( ` ${scoreColor(this.theme, model.score, model.score.toFixed(1))} · ${model.sessions} session${model.sessions === 1 ? "" : "s"} · ${model.minimum.toFixed(0)}–${model.maximum.toFixed(0)}`, "", ); } if (this.expanded) lines.push(...this.renderModelDetail(width)); return lines; } private renderModelDetail(width: number): string[] { const selected = this.data.leaderboard[this.selectedModel]; if (!selected) return []; const title = `${this.theme.bold(selected.model)} · ${scoreColor(this.theme, selected.score, selected.score.toFixed(1))}`; const parts = DIMENSIONS.map((dimension) => { const score = selected.dimensions[dimension.name]; return `${dimension.label} ${scoreLabel(score)}`; }); const lines = [title]; if (width >= 76) { lines.push(this.theme.fg("dim", parts.slice(0, 3).join(" · "))); lines.push(this.theme.fg("dim", parts.slice(3).join(" · "))); } else { lines.push( ...wrapTextWithAnsi( this.theme.fg("dim", parts.join(" · ")), Math.max(1, width), ), ); } lines.push( this.theme.fg( "dim", `${selected.evidence} cited observations · equal session weighting`, ), ); return lines; } private renderSessions(width: number): string[] { if (this.data.records.length === 0) return [this.theme.fg("dim", "No scored sessions.")]; const visible = windowed(this.data.records, this.selectedSession, 10); const first = this.data.records.indexOf(visible[0] as SessionScoreRecord); const lines: string[] = []; if (width >= 72) { const nameWidth = Math.max(16, width - 36); lines.push( this.theme.fg( "muted", `${padRight("SESSION", nameWidth)}${padLeft("IQ", 8)}${padLeft("EVENTS", 9)}${padLeft("MODEL", 19)}`, ), this.theme.fg("border", "─".repeat(width)), ); for (let offset = 0; offset < visible.length; offset++) { const record = visible[offset]; if (!record) continue; const selected = first + offset === this.selectedSession; const name = record.source.name || record.source.sessionId || "unnamed"; const model = record.source.model?.split("/").at(-1) ?? "?"; const row = `${padRight(`${selected ? "▸" : " "} ${name}`, nameWidth)}${padLeft(scoreLabel(record.score.overall), 8)}${padLeft(String(record.observations.length), 9)}${padLeft(model, 19)}`; lines.push(selected ? this.theme.fg("accent", row) : row); } } else { for (let offset = 0; offset < visible.length; offset++) { const record = visible[offset]; if (!record) continue; const selected = first + offset === this.selectedSession; const name = record.source.name || record.source.sessionId || "unnamed"; lines.push( `${selected ? this.theme.fg("accent", "▸") : " "} ${truncateToWidth(name, width - 2)}`, ` ${scoreLabel(record.score.overall)} · ${record.observations.length} observations · ${dateLabel(record.scoredAt)}`, "", ); } } if (this.expanded) { const selected = this.data.records[this.selectedSession]; if (selected) lines.push( "", this.theme.bold(selected.source.name || selected.source.sessionId), ...wrapTextWithAnsi( this.theme.fg( "dim", `${selected.source.model ?? "unknown model"} · ${selected.source.userMessages} user turns · ${selected.source.toolResults} tool results · judge ${selected.judge}`, ), Math.max(1, width), ), ); } return lines; } private renderMethod(width: number): string[] { const paragraphs = [ "The judge emits cited observations, never the final score.", "Ratings: 1 severe · 2 weak · 3 competent · 4 strong · 5 exceptional.", "Dimension score = 100 + 15 × (weighted mean rating − 3).", "Overall weights: judgment 25% · adaptation 25% · context 20% · reliability 20% · steerability 10%.", "Sessions contribute equally to a model score. Mixed-model and trivial sessions remain unranked.", `Judge: ${this.data.judge}`, `State: ${this.data.stateDirectory}`, ]; const lines: string[] = []; for (const paragraph of paragraphs) { lines.push(...wrapTextWithAnsi(paragraph, Math.max(1, width)), ""); } return lines; } invalidate(): void {} dispose(): void {} } export class IqScanComponent { private readonly abortController = new AbortController(); private readonly timer: ReturnType; constructor( private readonly tui: TUI, private readonly theme: Theme, readonly state: ScanDisplayState, ) { this.timer = setInterval(() => this.tui.requestRender(), 100); this.timer.unref?.(); } get signal(): AbortSignal { return this.abortController.signal; } handleInput(input: string): void { if (matchesKey(input, "escape")) this.abortController.abort(); } render(width: number): string[] { const safeWidth = Math.max(1, width); const elapsed = Math.max(0, Date.now() - this.state.startedAt); const spinner = SPINNER[Math.floor(elapsed / 100) % SPINNER.length] ?? "◐"; const phase = this.state.phase === "prepare" ? "PREPARE" : "JUDGE"; const progress = `${this.state.session}/${this.state.sessions}`; const lines = [ `${this.theme.fg("accent", spinner)} ${this.theme.bold(`IQ ${phase}`)} · ${progress} · ${(elapsed / 1_000).toFixed(1)}s`, truncateToWidth( this.state.currentName || "Discovering sessions…", safeWidth, ), ]; if (this.state.phase === "judge") { lines.push( `chunks ${this.state.chunk}/${this.state.chunks} · evidence ${this.state.evidence}`, `judge ${this.state.model}`, `cost $${this.state.cost.toFixed(3)} · failures ${this.state.failures}`, ); } else { lines.push( "Reading session metadata and estimating calls.", `judge ${this.state.model}`, ); } lines.push("", this.theme.fg("dim", "Esc cancel")); return lines.map((line) => truncateToWidth(line, safeWidth)); } invalidate(): void { this.tui.requestRender(true); } dispose(): void { clearInterval(this.timer); } }