import type { ExtensionContext, Theme } from "@earendil-works/pi-coding-agent"; import { type Component, Key, matchesKey, ScrollView, stripTerminalSequences, Text, type TUI, } from "@earendil-works/pi-tui"; import type { NativeHistoryEntry } from "./voice-history.ts"; const PAGE_SIZE = 40; /** Read-only voice history, with bounded rendering even for long persisted conversations. */ export async function showNativeVoiceHistory( ctx: ExtensionContext, entries: readonly NativeHistoryEntry[], ): Promise { await ctx.ui.custom( (tui, theme, _keybindings, done) => createNativeVoiceHistoryView(tui, theme, entries, () => done()), { blocked: { kind: "question", message: "Review voice history" } }, ); } export function createNativeVoiceHistoryView( tui: TUI, theme: Pick, entries: readonly NativeHistoryEntry[], close: () => void, ): Component { const pages = Math.max(1, Math.ceil(entries.length / PAGE_SIZE)); let page = pages - 1; const content = () => historyText( entries.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE), theme, page, pages, entries.length, ); const text = new Text(content(), 1, 0); const scroll = new ScrollView(text, { follow: "end", primary: true, scrollbar: "auto", }); // Preserve ScrollView's layout node so Pi can assign a real viewport. return Object.assign(scroll, { handleInput(data: string) { if (data === "q" || matchesKey(data, Key.escape)) { close(); return; } if (data === "[" || data === "]") { page = Math.max(0, Math.min(pages - 1, page + (data === "[" ? -1 : 1))); text.setText(content()); scroll.scrollToEnd(); } else if (data === "j" || matchesKey(data, Key.down)) scroll.scrollBy(1); else if (data === "k" || matchesKey(data, Key.up)) scroll.scrollBy(-1); else if (data === "g") scroll.scrollToStart(); else if (data === "G") scroll.scrollToEnd(); tui.requestRender(); }, }); } function historyText( entries: readonly NativeHistoryEntry[], theme: Pick, page: number, pages: number, count: number, ): string { const header = theme.fg( "accent", theme.bold(`VOICE HISTORY · page ${page + 1}/${pages} · ${count} entries`), ); return [ header, theme.fg( "muted", "[ older page · ] newer page · j/k scroll · g/G start/end · q/Esc close", ), "", ...(entries.length ? entries.map(formatEntry) : ["Voice history is empty."]), ].join("\n\n"); } function clean(value: string): string { return stripTerminalSequences(value).replace( /[\u0000-\u001f\u007f-\u009f]/gu, " ", ); } function formatEntry(entry: NativeHistoryEntry): string { const role = entry.role === "assistant" ? entry.kind === "status" ? "VOICE · STATUS" : "VOICE" : "YOU"; const playback = entry.role === "assistant" ? ` [${entry.interrupted ? "interrupted" : entry.playback}]` : ""; const generated = clean(entry.text) || "(empty)"; if (entry.role !== "assistant" || entry.playback === "played") return `${role}${playback}\n${generated}`; return `${role}${playback}\n${generated}\nPlayed: ${entry.playedText ? clean(entry.playedText) : "none"}`; }