repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi(ext/footer): semantic zones, flow layout, 4-line stable height, /footer toggle

933bcb65cabda4f3aef47c360b8e85fc575ca9b1

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (2)

pi/agent/extensions/footer/index.ts

Added
new file mode 100644
1 +/**
2 + * Footer renderer extension.
3 + *
4 + * Listens for "footer:segment" events from producer extensions and renders
5 + * a 4-line footer with stable height:
6 + * line 0 = workspace zone (cwd, branch, PR, runtime)
7 + * line 1-2 = llm zone (model, thinking, context, tokens, cost, timing) — flow layout
8 + * line 3 = extension statuses via ctx.ui.setStatus()
9 + *
10 + * Producers use semantic zones ("workspace" | "llm"). Footer decides row mapping.
11 + * Uses setFooter() — the single footer owner. Producers are decoupled.
12 + */
14 +import type { ExtensionAPI, ExtensionContext, Theme, ThemeColor } from "@mariozechner/pi-coding-agent";
15 +import { Key } from "@mariozechner/pi-coding-agent";
16 +import { truncateToWidth, visibleWidth } from "@mariozechner/pi-tui";
17 +import { renderContinuousBar, renderBlocksBar, type BarStyle } from "./progress";
19 +// ── Footer segment types ──────────────────────────────────────────
21 +type FooterZone = "workspace" | "llm";
23 +type Segment = {
24 + id: string;
25 + text: string;
26 + icon?: string;
27 + color?: string;
28 + bar?: number;
29 + suffix?: string;
30 + zone: FooterZone;
31 + order?: number;
32 +};
34 +type SegmentUpdate = Segment | { id: string; text: undefined };
36 +type FooterConfig = {
37 + separatorColor: string;
38 + barStyle: BarStyle;
39 + barWidth: number;
40 +};
42 +const DEFAULT_CONFIG: FooterConfig = {
43 + separatorColor: "borderMuted",
44 + barStyle: "blocks",
45 + barWidth: 10,
46 +};
48 +export default function footerExtension(pi: ExtensionAPI) {
49 + const segments = new Map<string, Segment>();
50 + let config: FooterConfig = { ...DEFAULT_CONFIG };
51 + let requestRender: (() => void) | undefined;
52 + let renderScheduled = false;
53 + let hidden = false;
55 + // ── Event listener ────────────────────────────────────────────────
57 + function handleSegment(data: unknown) {
58 + const payload = data as SegmentUpdate;
59 + if (!payload?.id) return;
61 + if (!("text" in payload) || payload.text === undefined) {
62 + segments.delete(payload.id);
63 + } else {
64 + segments.set(payload.id, payload as Segment);
65 + }
66 + scheduleRender();
67 + }
69 + // Subscribe at load time so producers can emit during their session_start
70 + // before footer's session_start runs (load order may vary).
71 + pi.events.on("footer:segment", handleSegment);
73 + // ── Coalesced update ──────────────────────────────────────────────
75 + function scheduleRender() {
76 + if (renderScheduled) return;
77 + if (!requestRender) {
78 + // Footer not mounted yet — retry after a tick
79 + if (segments.size > 0) setTimeout(() => scheduleRender(), 50);
80 + return;
81 + }
82 + renderScheduled = true;
83 + queueMicrotask(() => {
84 + renderScheduled = false;
85 + requestRender?.();
86 + });
87 + }
89 + // ── Render ────────────────────────────────────────────────────────
91 + function getZoneSegments(zone: FooterZone, ctx?: ExtensionContext): Segment[] {
92 + const segs = Array.from(segments.values()).filter((s) => s.zone === zone);
93 + if (zone === "workspace" && ctx) {
94 + // Session name is Pi-owned state, not an extension-owned producer segment.
95 + // `pi.setSessionName()` emits core `session_info_changed` to interactive mode,
96 + // which already requests a render; that event is not part of the extension
97 + // lifecycle/event-bus surface. Read it live here so /name, session-rename,
98 + // resume, and any future core setter all update without a footer:segment emit.
99 + const name = getSessionName(ctx);
100 + if (name) {
101 + segs.push({ id: "session-name", text: name, icon: "✎", color: "accent", zone: "workspace", order: 0.5 });
104 + return segs.sort((a, b) => (a.order ?? 50) - (b.order ?? 50));
107 + function separator(theme: Theme): string {
108 + return theme.fg(config.separatorColor as ThemeColor, " | ");
111 + function renderSegment(seg: Segment, theme: Theme): string {
112 + const color = (seg.color ?? "muted") as ThemeColor;
113 + const parts: string[] = [];
115 + if (seg.icon) parts.push(theme.fg(color, seg.icon));
116 + if (seg.text) parts.push(theme.fg(color, seg.text));
118 + if (seg.bar !== undefined) {
119 + const bar = config.barStyle === "blocks"
120 + ? renderBlocksBar(seg.bar, config.barWidth, theme, color)
121 + : renderContinuousBar(seg.bar, config.barWidth, theme, color);
122 + // Attach suffix directly to bar (no gap)
123 + const suffix = seg.suffix ? theme.fg(color, seg.suffix) : "";
124 + parts.push(bar + suffix);
125 + } else if (seg.suffix) {
126 + parts.push(theme.fg(color, seg.suffix));
129 + return parts.join(" ");
132 + function getSessionName(ctx: ExtensionContext): string | undefined {
133 + try { return ctx.sessionManager.getSessionName(); } catch { return undefined; }
136 + function renderWorkspaceLine(theme: Theme, width: number, ctx: ExtensionContext): string {
137 + const segs = getZoneSegments("workspace", ctx);
138 + if (segs.length === 0) return "";
139 + const sep = separator(theme);
140 + return truncateToWidth(segs.map((s) => renderSegment(s, theme)).join(sep), width);
143 + /** Flow layout: fill line 1, overflow to line 2, truncate line 2 if needed. */
144 + function renderLlmLines(theme: Theme, width: number): [string, string] {
145 + const segs = getZoneSegments("llm");
146 + if (segs.length === 0) return ["", ""];
148 + const sep = separator(theme);
149 + const rendered = segs.map((s) => renderSegment(s, theme));
151 + let line1 = "";
152 + let line1Width = 0;
153 + let overflowIndex = -1;
155 + for (let i = 0; i < rendered.length; i++) {
156 + const segWidth = visibleWidth(rendered[i]!);
157 + const prefixWidth = line1Width > 0 ? visibleWidth(sep) : 0;
159 + if (line1Width + prefixWidth + segWidth <= width) {
160 + line1 += (line1Width > 0 ? sep : "") + rendered[i];
161 + line1Width += prefixWidth + segWidth;
162 + } else {
163 + overflowIndex = i;
164 + break;
168 + if (overflowIndex === -1) return [line1, ""];
170 + const line2 = truncateToWidth(rendered.slice(overflowIndex).join(sep), width);
171 + return [line1, line2];
174 + // ── Toggle ────────────────────────────────────────────────────────
176 + function toggleVisibility(ctx: ExtensionContext) {
177 + hidden = !hidden;
178 + ctx.ui.notify(hidden ? "Footer hidden" : "Footer visible", "info");
179 + scheduleRender();
182 + pi.registerCommand("footer", {
183 + description: "Toggle footer visibility",
184 + handler: async (_args, ctx) => toggleVisibility(ctx),
185 + });
187 + pi.registerShortcut(Key.ctrlAlt("f"), {
188 + description: "Toggle footer visibility",
189 + handler: async (ctx) => toggleVisibility(ctx),
190 + });
192 + // ── Lifecycle ─────────────────────────────────────────────────────
194 + pi.on("session_start", async (_event, ctx) => {
195 + if (!ctx.hasUI) return;
197 + ctx.ui.setFooter((tui, theme, footerData) => {
198 + requestRender = () => tui.requestRender();
199 + const unsubBranch = footerData.onBranchChange(() => scheduleRender());
201 + return {
202 + dispose: () => {
203 + unsubBranch();
204 + requestRender = undefined;
205 + },
206 + invalidate() {},
207 + render(width: number): string[] {
208 + if (hidden) return [];
210 + const contentWidth = Math.max(0, width - 2);
211 + const padLine = (line: string) => {
212 + if (width <= 1) return truncateToWidth(line, width);
213 + return ` ${truncateToWidth(line, contentWidth)} `;
214 + };
216 + const workspaceLine = renderWorkspaceLine(theme, contentWidth, ctx);
217 + const [llmLine1, llmLine2] = renderLlmLines(theme, contentWidth);
219 + // Extension statuses (3rd party, via setStatus)
220 + const extStatuses = footerData.getExtensionStatuses();
221 + let statusLine = "";
222 + if (extStatuses.size > 0) {
223 + const parts = Array.from(extStatuses.entries())
224 + .sort(([a], [b]) => a.localeCompare(b))
225 + .map(([, t]) => t.replace(/[\r\n\t]/g, " ").replace(/ +/g, " ").trim())
226 + .join(" · ");
227 + statusLine = theme.fg("dim" as ThemeColor, parts);
230 + // Always return exactly 4 lines for stable height
231 + return [
232 + padLine(workspaceLine),
233 + padLine(llmLine1),
234 + padLine(llmLine2),
235 + padLine(statusLine),
236 + ];
237 + },
238 + };
239 + });
241 + // Force initial render of any segments that were emitted during
242 + // other extensions' session_start (before our setFooter ran)
243 + setTimeout(() => scheduleRender(), 0);
244 + });
246 + pi.on("session_shutdown", async () => {
247 + segments.clear();
248 + requestRender = undefined;
249 + });

pi/agent/extensions/footer/progress.ts

Added
new file mode 100644
1 +/**
2 + * Progress bar rendering with sub-character precision.
3 + *
4 + * Two styles:
5 + * - continuous: █ + partial-width glyphs ▏▎▍▌▋▊▉
6 + * - blocks: discrete partial-height glyphs ▁▂▃▄▅▆▇█ on dim background
7 + */
9 +import type { Theme, ThemeColor } from "@mariozechner/pi-coding-agent";
11 +export type BarStyle = "continuous" | "blocks";
13 +/** Render a continuous progress bar with sub-character precision. */
14 +export function renderContinuousBar(pct: number, width: number, theme: Theme, color: string): string {
15 + const clamped = Math.max(0, Math.min(100, pct));
16 + const filledFloat = (clamped / 100) * width;
17 + const filledFull = Math.floor(filledFloat);
18 + const remainder = filledFloat - filledFull;
20 + const levels = ["▏", "▎", "▍", "▌", "▋", "▊", "▉"];
21 + const filledStr = theme.fg(color as ThemeColor, "█".repeat(filledFull));
23 + let partial = "";
24 + let emptyCount = width - filledFull;
26 + if (remainder >= 0.0625 && filledFull < width) {
27 + const levelIndex = Math.max(0, Math.min(levels.length - 1, Math.round(remainder * 8) - 1));
28 + partial = theme.fg(color as ThemeColor, levels[levelIndex]!);
29 + emptyCount = Math.max(0, emptyCount - 1);
30 + }
32 + return filledStr + partial + " ".repeat(emptyCount);
35 +/** Render discrete block characters with dim background track. */
36 +export function renderBlocksBar(pct: number, segments: number, theme: Theme, color: string): string {
37 + const glyphs = [" ", "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"];
38 + const dimBg = fgToBgAnsi(theme.getFgAnsi("dim"));
39 + const fgColor = theme.getFgAnsi(color as ThemeColor);
40 + const reset = "\x1b[39m\x1b[49m";
41 + const clamped = Math.max(0, Math.min(100, pct));
42 + const filledFloat = (clamped / 100) * segments;
44 + const result: string[] = [];
45 + for (let i = 0; i < segments; i++) {
46 + const blockFill = Math.max(0, Math.min(1, filledFloat - i));
47 + const level = Math.round(blockFill * 8);
48 + const glyph = glyphs[level];
49 + result.push(level > 0 ? `${dimBg}${fgColor}${glyph}${reset}` : `${dimBg}${glyph}${reset}`);
50 + }
52 + return result.join("");
55 +function fgToBgAnsi(fgAnsi: string): string {
56 + return fgAnsi.replace("\x1b[38;", "\x1b[48;");