import type { ExtensionCommandContext, Theme, } from "@earendil-works/pi-coding-agent"; import { type Component, CURSOR_MARKER, decodeKittyPrintable, type Focusable, isKeyRelease, type KeybindingsManager, matchesKey, parseKey, renderFakeCursor, type SelectItem, SelectList, sliceByColumn, stripTerminalSequences, type TUI, type TuiMouseEvent, truncateToWidth, visibleWidth, } from "@earendil-works/pi-tui"; import type { ActivityManager } from "./runtime.js"; import type { ActivitySnapshot, TimerView } from "./types.js"; import type { TerminalView } from "./view.js"; type ManagerApi = Pick< ActivityManager, | "list" | "read" | "attention" | "acknowledge" | "write" | "resize" | "subscribe" | "terminalView" | "timerView" | "stop" >; type TerminalInput = | { detach: true } | { text: string; paste?: true } | undefined; const OUTPUT_LIMIT = 16_384; const OUTPUT_LINES = 48; const EVENT_LINES = 8; const REFRESH_MS = 100; const MIN_COLS = 20; const MAX_COLS = 200; const MIN_ROWS = 5; const MAX_ROWS = 60; export async function openActivities( manager: ManagerApi, ctx: ExtensionCommandContext, id?: string, ): Promise { if (ctx.mode !== "tui") { if (ctx.hasUI) ctx.ui.notify("Activities require Pi's terminal UI.", "warning"); return; } const api: ManagerApi = manager; let selectedId = id; let previousId: string | undefined; try { while (true) { if (!selectedId) { if (api.list().length === 0) { ctx.ui.notify("No activities.", "info"); return; } selectedId = await ctx.ui.custom( (tui, theme, _keybindings, done) => activityPicker(api, tui, theme, done, previousId), { overlay: true, blocked: { kind: "question", message: "Choose an activity" }, overlayOptions: { anchor: "center", width: 68, maxHeight: "90%" }, }, ); } if (!selectedId) return; const inspectedId = selectedId; const activity = api.read(inspectedId); await ctx.ui.custom( (tui, theme, keybindings, done) => new ActivityInspector( tui, theme, keybindings, done, api, inspectedId, !id, ), { overlay: true, blocked: { kind: "question", message: "Inspect activity" }, overlayOptions: { anchor: "center", width: activity.kind === "terminal" ? "90%" : 68, maxHeight: "90%", }, }, ); if (id) return; previousId = inspectedId; selectedId = undefined; } } catch (error) { ctx.ui.notify(`Activities unavailable: ${errorMessage(error)}`, "error"); } } const KINDS = { process: { icon: "⚙", label: "Process", running: "Running" }, terminal: { icon: "▣", label: "Terminal", running: "Open" }, watch: { icon: "◎", label: "Watch", running: "Watching" }, timer: { icon: "◷", label: "Timer", running: "Waiting" }, } as const; const STATES = { running: { icon: "●", label: "Running" }, stopping: { icon: "◌", label: "Stopping…" }, completed: { icon: "✓", label: "Done" }, failed: { icon: "✕", label: "Failed" }, stopped: { icon: "■", label: "Stopped" }, } as const; const RESET = "\x1b[0m"; const WIDGET_ICON = "\u{F0996}"; // nf-md-progress_clock function isActive(activity: ActivitySnapshot): boolean { return activity.status === "running" || activity.status === "stopping"; } function statusLabel(activity: ActivitySnapshot): string { return activity.status === "running" ? KINDS[activity.kind].running : STATES[activity.status].label; } /** Compact, non-focusable status using the same labels as the inspector. */ export function activityWidget( activities: ActivitySnapshot[], theme: Theme, ): Component { const active = activities.filter(isActive).length; const failed = activities.filter( (activity) => activity.status === "failed", ).length; const priority = { stopping: 0, running: 1, failed: 2, completed: 3, stopped: 4, }; const sorted = [...activities].sort( (a, b) => priority[a.status] - priority[b.status] || b.createdAt - a.createdAt, ); const shown = active ? sorted.filter(isActive).slice(0, 3) : sorted.slice(0, 1); const failure = active ? sorted.find((activity) => activity.status === "failed") : undefined; if (failure) shown.push(failure); const more = activities.length - shown.length; return { render(width) { if (width < 1 || !activities.length) return []; const parts: string[] = []; if (active) parts.push(`${active} active`); if (failed) parts.push(`${failed} failed`); if (more) parts.push(`${more} hidden`); const icon = theme.fg( failed ? "error" : active ? "accent" : "muted", ` ${WIDGET_ICON} `, ); const headingWidth = Math.max(0, width - visibleWidth(icon)); const full = ["Activities", ...parts].join(" · "); const heading = visibleWidth(full) <= headingWidth || !parts.length ? full : parts.join(" "); const header = icon + theme.fg("accent", heading); return [ header, ...shown.map((activity) => { const state = theme.fg( statusColor(activity), `${STATES[activity.status].icon} ${statusLabel(activity)}`, ); const title = singleLine(sanitizeActivityText(activity.title)); const exit = activity.status === "failed" && activity.exitCode != null ? ` · exit ${activity.exitCode}` : ""; const prefix = ` ${state} · `; const suffix = theme.fg( "text", ` · ${KINDS[activity.kind].label}${exit}`, ); const available = Math.max( 0, width - visibleWidth(prefix) - visibleWidth(suffix), ); const titleWidth = visibleWidth(title); const tail = Math.floor((available - 1) / 3); const compact = titleWidth > available && tail > 0 ? `${sliceByColumn(title, 0, available - tail - 1, true)}…${sliceByColumn(title, titleWidth - tail, tail, true)}` : truncateToWidth(title, available, "…"); return prefix + compact + suffix; }), ].map((line) => truncateToWidth(line, width)); }, invalidate() {}, }; } export function formatActivityOption( activity: ActivitySnapshot, hidden = false, ): SelectItem { return { value: activity.id, label: `${STATES[activity.status].icon} ${KINDS[activity.kind].icon} ${singleLine(sanitizeActivityText(activity.title))}`, description: `${statusLabel(activity)}${hidden ? " · hidden" : ""}`, }; } export function activityPicker( manager: Pick< ManagerApi, "list" | "attention" | "subscribe" | "stop" | "acknowledge" >, tui: TUI, theme: Theme, done: (id: string | undefined) => void, selectedId?: string, ): Component & { dispose(): void } { const items = manager .list() .slice() .sort( (a, b) => Number(isActive(b)) - Number(isActive(a)) || b.createdAt - a.createdAt, ) .map(formatActivityOption); let list: SelectList; let visibleRows = 0; let listHeight = 0; let stopFailed = false; const updateSize = () => { const rows = Math.max( 1, Math.min(8, Math.floor(tui.terminal.rows * 0.9) - 6), ); if (rows === visibleRows) return; const selected = list?.getSelectedItem()?.value ?? selectedId; list = new SelectList(items, rows, { selectedPrefix: (text) => theme.fg("accent", text), selectedText: (text) => theme.fg("accent", theme.bold(text)), description: (text) => theme.fg("muted", text), scrollInfo: (text) => theme.fg("dim", text), noMatch: (text) => theme.fg("muted", text), }); list.setSelectedIndex( Math.max( 0, items.findIndex((item) => item.value === selected), ), ); list.onSelect = (item) => { if (manager.list().some((activity) => activity.id === item.value)) done(item.value); }; list.onCancel = () => done(undefined); visibleRows = rows; }; updateSize(); const unsubscribe = manager.subscribe(() => tui.requestRender()); return { render(width) { // Keep row identities/order stable during mouse gestures; refresh presentation only. const current = new Map( manager.list().map((activity) => [activity.id, activity]), ); const pinned = new Set(manager.attention().map(({ id }) => id)); for (const item of items) { const activity = current.get(item.value); if (activity) Object.assign( item, formatActivityOption( activity, activity.status === "failed" && !pinned.has(activity.id), ), ); else { item.label = "○ No longer available"; item.description = ""; } } updateSize(); const lines = list.render(Math.max(1, width - 4)); listHeight = lines.length; return renderPanel( "Activities", [ "", ...lines.map((line) => ` ${line}`), "", ` ${theme.fg(stopFailed ? "error" : "text", stopFailed ? "Stop failed; inspect activity for details." : "↑↓ · Enter inspect · x stop · d hide · D hide all · Esc close")}`, ], width, theme, ); }, dispose: unsubscribe, invalidate() { list.invalidate(); }, handleInput(data) { if (data === "x") { const id = list.getSelectedItem()?.value; const activity = manager.list().find((item) => item.id === id); if (activity && isActive(activity)) { stopFailed = false; void manager.stop(activity.id).catch(() => { stopFailed = true; tui.requestRender(); }); } } else if (data === "d") { const id = list.getSelectedItem()?.value; if (id) manager.acknowledge(id); } else if (data === "D") { for (const activity of manager.list()) if (!isActive(activity)) manager.acknowledge(activity.id); } else list.handleInput(data); tui.requestRender(); }, handleMouse(event: TuiMouseEvent) { if ( event.x < 2 || event.x >= event.width - 2 || event.y < 2 || event.y >= listHeight + 2 ) return undefined; return list.handleMouse({ ...event, x: event.x - 2, y: event.y - 2, width: Math.max(1, event.width - 4), height: listHeight, }); }, }; } /** Remove terminal controls before rendering activity-owned text in Pi's TUI. */ export function sanitizeActivityText(text: string): string { return stripTerminalSequences(text) .replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, "�") .slice(-OUTPUT_LIMIT); } /** Translate Pi's normalized keyboard input to conservative terminal application bytes. */ export function terminalInput(data: string): TerminalInput { if (isKeyRelease(data)) return undefined; if (data.startsWith("\x1b[200~") && data.endsWith("\x1b[201~")) return { text: data.slice(6, -6), paste: true }; if (matchesKey(data, "ctrl+g")) return { detach: true }; // Preserve legacy control/Meta bytes instead of Pi editor aliases (e.g. Alt+B → Alt+Left). if ( /^[\x00-\x1f\x7f]$/.test(data) || /^\x1b[^\x00-\x1f\x7f-\x9f]$/u.test(data) ) return { text: data }; const key = parseKey(data); if (key) { const mapped = TERMINAL_KEYS[key]; if (mapped !== undefined) return { text: mapped }; const modifiers = key.split("+"); const base = modifiers.pop() ?? ""; const modifier = 1 + (modifiers.includes("shift") ? 1 : 0) + (modifiers.includes("alt") ? 2 : 0) + (modifiers.includes("ctrl") ? 4 : 0); const sequence = TERMINAL_KEYS[base]; if (modifier > 1 && sequence?.startsWith("\x1b[")) { const navigation = /^\x1b\[([ABCDHF])$/.exec(sequence); if (navigation) return { text: `\x1b[1;${modifier}${navigation[1]}` }; const editing = /^\x1b\[(\d+)~$/.exec(sequence); if (editing) return { text: `\x1b[${editing[1]};${modifier}~` }; } if (modifier > 1 && sequence?.startsWith("\x1bO")) return { text: `\x1b[1;${modifier}${sequence.at(-1)}` }; const control = modifiers.includes("ctrl") ? (CONTROL_KEYS[base] ?? (/^[a-z]$/i.test(base) ? String.fromCharCode(base.toLowerCase().charCodeAt(0) - 96) : undefined)) : undefined; const text = control ?? sequence ?? decodeKittyPrintable(data) ?? (base.length === 1 ? base : undefined); if (text !== undefined) return { text: (modifiers.includes("alt") ? "\x1b" : "") + text }; } // Pi's keybinding parser need not name every standard modified function key. if (/^\x1b\[(?:1;[2-8][PQRS]|(?:15|17|18|19|20|21|23|24);[2-8]~)$/.test(data)) return { text: data }; const printable = decodeKittyPrintable(data); if (printable !== undefined) return { text: printable }; return /^[^\u0000-\u001f\u007f\u001b]+$/u.test(data) ? { text: data } : undefined; } const CONTROL_KEYS: Record = { space: "\x00", "@": "\x00", "[": "\x1b", "\\": "\x1c", "]": "\x1d", "^": "\x1e", _: "\x1f", "?": "\x7f", }; const TERMINAL_KEYS: Record = { escape: "\u001b", enter: "\r", return: "\r", backspace: "\u007f", delete: "\u001b[3~", insert: "\u001b[2~", f1: "\x1bOP", f2: "\x1bOQ", f3: "\x1bOR", f4: "\x1bOS", f5: "\x1b[15~", f6: "\x1b[17~", f7: "\x1b[18~", f8: "\x1b[19~", f9: "\x1b[20~", f10: "\x1b[21~", f11: "\x1b[23~", f12: "\x1b[24~", up: "\u001b[A", down: "\u001b[B", right: "\u001b[C", left: "\u001b[D", home: "\u001b[H", end: "\u001b[F", pageUp: "\u001b[5~", pageDown: "\u001b[6~", tab: "\t", "shift+tab": "\u001b[Z", "ctrl+c": "\u0003", }; function clipPanelText(text: string, width: number): string { if (width < 1) return ""; return visibleWidth(text) > width ? `${sliceByColumn(text, 0, width - 1, true)}…` : text; } function renderPanel( title: string, rows: string[], width: number, theme?: Theme, markClipping = true, ): string[] { const safeWidth = Math.max(1, width); if (safeWidth < 3) return [truncateToWidth(title, safeWidth, "")]; const inner = safeWidth - 2; const background = theme?.getBgAnsi("customMessageBg") ?? ""; const foreground = theme?.getFgAnsi("text") ?? ""; const edgeStyle = theme?.getFgAnsi("border") ?? ""; const edge = (text: string) => RESET + background + edgeStyle + text + RESET; const caption = clipPanelText(` ${title} `, inner); const heading = theme ? theme.fg("accent", theme.bold(caption)) : caption; return [ edge("╭") + background + heading + edge("─".repeat(Math.max(0, inner - visibleWidth(caption))) + "╮"), ...rows.map((text) => { const body = markClipping ? clipPanelText(singleLine(text), inner) : truncateToWidth(singleLine(text), inner, ""); return ( edge("│") + background + foreground + body + RESET + background + " ".repeat(Math.max(0, inner - visibleWidth(body))) + edge("│") ); }), edge(`╰${"─".repeat(inner)}╯`), ]; } function duration(milliseconds: number): string { const seconds = Math.max(0, Math.ceil(milliseconds / 1000)); if (seconds < 60) return `${seconds}s`; if (seconds < 3600) return `${Math.floor(seconds / 60)}m${seconds % 60 ? ` ${seconds % 60}s` : ""}`; return `${Math.floor(seconds / 3600)}h${Math.floor((seconds % 3600) / 60) ? ` ${Math.floor((seconds % 3600) / 60)}m` : ""}`; } function timerLines( activity: ActivitySnapshot, timer: TimerView | undefined, theme?: Theme, ): string[] { if (!timer) return [isActive(activity) ? "Waiting for timer…" : "Timer finished"]; if (activity.status !== "running") return [ `${duration(timer.delayMs)} ${timer.repeat ? "between ticks" : "timer"}`, ]; const remaining = Math.max(0, timer.nextAt - Date.now()); const filled = Math.round( 20 * Math.max(0, Math.min(1, 1 - remaining / timer.delayMs)), ); const progress = "━".repeat(filled); const rest = "─".repeat(20 - filled); return [ `${duration(remaining)} ${timer.repeat ? "until next tick" : "remaining"}`, theme ? theme.fg("accent", progress) + theme.fg("dim", rest) : progress + rest, ...(timer.repeat ? [`Repeats every ${duration(timer.delayMs)}`] : []), ]; } export function renderActivityFrame( activity: ActivitySnapshot, width: number, maxRows = 64, { view, theme, timer, backToPicker = false, stopFailed = false, }: { view?: TerminalView; theme?: Theme; timer?: TimerView; backToPicker?: boolean; stopFailed?: boolean; } = {}, ): string[] { const kind = KINDS[activity.kind]; const title = `${kind.icon} ${singleLine(sanitizeActivityText(activity.title))}`; const endedAt = isActive(activity) ? Date.now() : activity.events?.findLast( (event) => event.type === "exit" || event.type === "error", )?.time; const elapsed = (activity.kind === "process" || activity.kind === "terminal") && endedAt !== undefined ? ` · ${duration(Math.floor(Math.max(0, endedAt - activity.createdAt) / 1000) * 1000)} elapsed` : ""; const meta = `${STATES[activity.status].icon} ${kind.label} · ${statusLabel(activity)}${activity.status === "failed" && activity.exitCode != null ? ` · exit ${activity.exitCode}` : ""}${elapsed}`; const error = stopFailed ? "✕ Stop failed; retry x." : activity.error ? `✕ ${sanitizeActivityText(activity.error)}` : view?.truncated ? "View clipped; resize terminal" : ""; const content = activity.kind === "terminal" ? (view?.lines ?? terminalLines(activity, Math.max(1, width - 2))) : activity.kind === "timer" ? timerLines(activity, timer, theme) : outputLines(activity); const hints = activity.kind === "terminal" && isActive(activity) ? activity.status === "running" ? ["Ctrl+G back · keys → app", "Stop: Ctrl+G → /activities → x"] : ["Ctrl+G back"] : [ `${isActive(activity) ? "x stop · " : ""}${backToPicker ? "Esc back" : "Esc close"}`, ]; const availableRows = Math.max(1, maxRows - 4 - hints.length); const rowBudget = activity.kind === "terminal" ? availableRows : Math.min(OUTPUT_LINES, availableRows); const omitted = activity.kind === "process" && (activity.outputTruncated || content.length > rowBudget); const limit = Math.max(1, rowBudget - (omitted && error ? 1 : 0)); const visible = activity.kind === "terminal" ? content.slice(0, limit) : content.slice(-limit).map((line) => ` ${line}`); const notice = omitted ? `Showing ${visible.length} lines · earlier omitted` : ""; const details = error && notice ? [error, notice] : [error || notice]; return renderPanel( title, [ clipPanelText( ` ${theme ? theme.fg(statusColor(activity), meta) : meta}`, width - 2, ), ...details.map((detail, index) => clipPanelText( ` ${theme && detail ? theme.fg(index === 0 && error ? (activity.error || stopFailed ? "error" : "warning") : "text", detail) : detail}`, width - 2, ), ), ...visible, ...hints.map((hint) => clipPanelText(` ${theme ? theme.fg("text", hint) : hint}`, width - 2), ), ], width, theme, activity.kind !== "terminal", ); } function singleLine(text: string): string { return text.replace(/[\r\n\t\u0080-\u009f]+/g, " "); } function outputLines(activity: ActivitySnapshot): string[] { if (activity.kind === "watch") { const changes = (activity.events ?? []) .filter((event) => event.type === "change") .slice(-EVENT_LINES); return changes.length ? changes.map( (event) => `↻ ${sanitizeActivityText(event.text ?? "Change detected")}`, ) : [isActive(activity) ? "Watching for changes…" : "No changes recorded"]; } const output = sanitizeActivityText(activity.output ?? ""); return output ? output.split("\n") : [isActive(activity) ? "Waiting for output…" : "No output"]; } function terminalLines(activity: ActivitySnapshot, width: number): string[] { const screen = activity.screen; if (!screen) return ["(terminal screen unavailable)"]; const lines = sanitizeActivityText(screen.text).split("\n"); return lines .slice(-Math.min(MAX_ROWS, Math.max(MIN_ROWS, screen.rows))) .map((line) => sliceByColumn(line, 0, width, true)); } export class ActivityInspector implements Component, Focusable { focused = false; private unsubscribe: (() => void) | undefined; private refreshTimer: ReturnType | undefined; private resizeTimer: ReturnType | undefined; private clockTimer: ReturnType | undefined; private disposed = false; private renderedWidth = 0; private stopFailed = false; constructor( private readonly tui: TUI, private readonly theme: Theme, private readonly keybindings: KeybindingsManager, private readonly done: () => void, private readonly manager: ManagerApi, private readonly id: string, private readonly backToPicker = false, ) { this.unsubscribe = manager.subscribe(() => this.scheduleRefresh()); const activity = this.current(); if (activity && isActive(activity) && activity.kind !== "watch") { this.clockTimer = setInterval(() => { const current = this.current(); if (!current || !isActive(current)) { clearInterval(this.clockTimer); this.clockTimer = undefined; } this.scheduleRefresh(); }, 1000); this.clockTimer.unref?.(); } } handleInput(data: string): void { const activity = this.current(); if (!activity) { this.done(); return; } if (activity.kind !== "terminal" || !isActive(activity)) { if (data === "x" && isActive(activity)) { this.stopFailed = false; void this.manager.stop(this.id).catch(() => { this.stopFailed = true; this.scheduleRefresh(); }); this.scheduleRefresh(); return; } if ( this.keybindings.matches(data, "tui.select.cancel") || matchesKey(data, "escape") || matchesKey(data, "ctrl+c") || matchesKey(data, "ctrl+g") ) this.done(); return; } const input = terminalInput(data); if (input?.detach) { this.done(); return; } if (input?.text && activity.status === "running") { try { this.manager.write(this.id, input.text, input.paste, true); } catch { this.done(); } } } render(width: number): string[] { this.renderedWidth = Math.max(1, width); this.scheduleResize(); const activity = this.current(); if (!activity) return [ this.theme.fg( "warning", truncateToWidth("Activity no longer exists", width, ""), ), ]; const height = Math.max(1, Math.floor(this.tui.terminal.rows * 0.9)); if (width < 22 || height < 11) return [ this.theme.fg( "muted", truncateToWidth("Activities: enlarge terminal", width, ""), ), ]; const view = activity.kind === "terminal" ? this.manager.terminalView(this.id) : undefined; const lines = renderActivityFrame(activity, width, height, { view, theme: this.theme, backToPicker: this.backToPicker, stopFailed: this.stopFailed, timer: activity.kind === "timer" ? this.manager.timerView(this.id) : undefined, }); const screen = activity.screen; if ( this.focused && activity.status === "running" && screen && !screen.truncated && (!view || view.cursor) ) { const row = (view?.cursor?.y ?? screen.cursorY) + 3; const column = (view?.cursor?.x ?? screen.cursorX) + 1; if (row < lines.length - 2 && column < width - 1) { const line = lines[row]; const cursor = view?.cursor; const cell = cursor?.text ?? (sliceByColumn(line, column, 1) || " "); const cellWidth = cursor?.width ?? visibleWidth(cell); const style = cursor?.style ?? ""; const painted = this.tui.getShowHardwareCursor() ? cell : cursor?.inverse ? `\x1b[27m${cell}` : renderFakeCursor(cell); lines[row] = sliceByColumn(line, 0, column, true) + style + CURSOR_MARKER + painted + style + sliceByColumn( line, column + cellWidth, width - column - cellWidth, true, ) + RESET; } } return lines; } invalidate(): void {} dispose(): void { if (this.disposed) return; this.disposed = true; // Closing an inspected finished activity acknowledges its failure. const activity = this.current(); if (activity && !isActive(activity)) try { this.manager.acknowledge(this.id); } catch {} this.unsubscribe?.(); if (this.refreshTimer) clearTimeout(this.refreshTimer); if (this.resizeTimer) clearTimeout(this.resizeTimer); if (this.clockTimer) clearInterval(this.clockTimer); } private current(): ActivitySnapshot | undefined { try { return this.manager.read(this.id); } catch { return undefined; } } private scheduleRefresh(): void { if (this.disposed || this.refreshTimer) return; this.refreshTimer = setTimeout(() => { this.refreshTimer = undefined; if (!this.disposed) this.tui.requestRender(); }, REFRESH_MS); } private scheduleResize(): void { if (this.disposed || this.resizeTimer) return; this.resizeTimer = setTimeout(() => { this.resizeTimer = undefined; const activity = this.current(); if ( this.disposed || activity?.kind !== "terminal" || activity.status !== "running" || this.renderedWidth < 22 || this.tui.terminal.rows < 13 ) return; const cols = clamp(this.renderedWidth - 2, MIN_COLS, MAX_COLS); const rows = clamp( Math.floor(this.tui.terminal.rows * 0.9) - 6, MIN_ROWS, MAX_ROWS, ); if (activity.screen?.cols === cols && activity.screen.rows === rows) return; try { this.manager.resize(this.id, cols, rows); } catch { this.done(); } }, 0); } } function statusColor(activity: ActivitySnapshot) { if (activity.status === "completed") return "success" as const; if (activity.status === "failed") return "error" as const; if (activity.status === "running") return "accent" as const; return "warning" as const; } function clamp(value: number, min: number, max: number): number { return Math.min(max, Math.max(min, value)); } function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); }