import { stripVTControlCharacters } from "node:util"; import type { Theme } from "@earendil-works/pi-coding-agent"; import { type Component, type TUI, truncateToWidth, } from "@earendil-works/pi-tui"; import type { LoopSnapshot } from "./controller.ts"; import { gateLabel } from "./gates.ts"; const FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]; const clean = (text: string) => stripVTControlCharacters(text).replace(/[\u0000-\u001f\u007f-\u009f]/gu, " "); const lastLine = (text = "") => stripVTControlCharacters(text) .split(/[\r\n]/u) .map(clean) .findLast((line) => line.trim()); /** Bounded, editor-adjacent feedback; elapsed time reports waiting, not completion. */ export function createProgress( tui: Pick, theme: Theme, state: () => { run: LoopSnapshot | null; baseline: boolean; agentRunning: boolean; }, ): Component & { dispose(): void } { let timer: ReturnType | undefined; let disposed = false; const stop = () => { clearInterval(timer); timer = undefined; }; return { render(width) { if (disposed) return []; const { run, baseline, agentRunning } = state(); if (run?.pending) { timer ??= setInterval(() => tui.requestRender(), 250); timer.unref(); } else stop(); if (!run || width < 1) return []; const line = (text: string) => truncateToWidth(text, width); if (run.status !== "active") { const color = run.status === "succeeded" ? "success" : "warning"; return [ line( theme.fg( color, `Loop ${run.status === "succeeded" ? "passed" : run.status}${run.pending ? " · cancelling gate" : ""}`, ), ), ]; } if (!run.pending) { const failed = run.lastPass?.failedIndex; const gate = failed == null ? undefined : run.gates[failed]; return [ line( theme.fg( "accent", `${agentRunning ? "Agent working" : "Waiting for agent"}${gate ? ` · gate ${clean(gateLabel(gate))} failed` : ""}`, ), ), ]; } const now = Date.now(); const seconds = Math.max( 0, Math.floor((now - (run.runningSince ?? now)) / 1000), ); const elapsed = `${String(Math.floor(seconds / 60)).padStart(2, "0")}:${String(seconds % 60).padStart(2, "0")}`; const index = run.runningGate; const gate = index === null ? undefined : run.gates[index]; const label = gate ? `${clean(gateLabel(gate))} [${(index ?? 0) + 1}/${run.gates.length}]` : "starting gates"; const frame = FRAMES[Math.floor(now / 250) % FRAMES.length]; const output = run.liveOutput; const tail = lastLine(output?.stderr) || lastLine(output?.stdout); return [ line( theme.fg( "accent", `${frame} ${baseline ? "Baseline" : "Checking gates"} · ${label} · ${elapsed} elapsed`, ), ), line( theme.fg( "muted", tail ? `Output: ${clean(tail)}` : "Waiting for gate result · no output yet", ), ), line( theme.fg( "dim", baseline ? "Esc / /loop pause → cancel" : "/loop pause → cancel", ), ), ]; }, invalidate() {}, dispose() { disposed = true; stop(); }, }; }