repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(footer): add acknowledged runtime telemetry

e2a50608027dec0a727390b8e188c2b70a1478e4

Oliver Krylow <o.krylow@isp-insoft.de> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (23)

.system/SYSTEM.md

Modified
8 8 ## Runtime package
10 10 The repository root is the supported Pi installation and distribution unit.
11 -Its manifest exports `extensions/pfui/index.ts` first, then `extensions/*/index.ts`, and no root skills, prompts, or themes.
11 +Its manifest exports `extensions/pfui/index.ts` first, `extensions/footer/index.ts` second, then `extensions/*/index.ts`, and no root skills, prompts, or themes.
12 12 Package filters may select a subset of those exported resources.
13 13 Pi loads the TypeScript extension entrypoints directly through its extension loader.

README.md

Modified
110 110 The root package exports extension entrypoints and extension-owned skills only.
111 111 Personal skills, prompts, and themes live in global Pi config.
112 -PFUI means Pain-Free User Interface and must remain the first explicit root manifest extension entry, before the extension glob.
112 +PFUI means Pain-Free User Interface and must remain the first explicit root manifest extension entry.
113 +The footer follows it explicitly so footer producers discover the shared footer before publishing their initial state.
114 +The extension glob supplies all remaining entrypoints and Pi deduplicates its repeated PFUI and footer matches.
114 116 ```json
116 118 "extensions": [
117 119 "extensions/pfui/index.ts",
120 + "extensions/footer/index.ts",
118 121 "extensions/*/index.ts"

extensions/context-size/index.ts

Modified
5 5 ThemeColor,
6 6 } from "@earendil-works/pi-coding-agent";
8 -const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
9 8 const STATUS_ID = "context-size";
11 -type FooterGlobal = typeof globalThis & {
12 - [FOOTER_KEY]?: { loaded?: boolean; version?: number };
13 -};
15 10 const FOOTER_SEGMENT = {
16 11 id: "context-size",
17 12 icon: "",
46 41 color: ThemeColor;
49 -function hasFooter(): boolean {
50 - const footer = (globalThis as FooterGlobal)[FOOTER_KEY];
51 - return footer?.loaded === true && (footer.version ?? 0) >= 1;
54 44 function clamp(value: number, min: number, max: number): number {
55 45 return Math.min(max, Math.max(min, value));
92 +function offerFooterSegment(pi: ExtensionAPI, segment: object): boolean {
93 + let accepted = false;
94 + pi.events.emit("footer:segment", {
95 + ...segment,
96 + accept: () => {
97 + accepted = true;
98 + },
99 + });
100 + return accepted;
102 103 export default function contextSizeExtension(pi: ExtensionAPI) {
103 104 function clearSegment() {
104 105 pi.events.emit("footer:segment", {
125 126 const view = buildSegment(ctx, usage);
126 - if (hasFooter()) {
127 - ctx.ui.setStatus(STATUS_ID, undefined);
128 - pi.events.emit("footer:segment", {
127 + const accepted =
128 + ctx.mode === "tui" &&
129 + offerFooterSegment(pi, {
129 130 ...FOOTER_SEGMENT,
130 131 text: view.text,
131 132 variants: [
135 136 color: view.color,
137 - return;
138 - }
140 - clearSegment();
141 - ctx.ui.setStatus(STATUS_ID, view.text);
139 + if (!accepted) clearSegment();
140 + ctx.ui.setStatus(STATUS_ID, accepted ? undefined : view.text);
142 141 } catch {
143 142 // Ignore late events during reload/switch/shutdown; Pi marks old ctx/pi stale.

extensions/cost/README.md

Modified
44 44 ## Behavior
46 -Shows last assistant-turn token usage, turn cost, session cost, and
47 -current-month cost.
46 +Shows cumulative session token usage, turn cost, session cost, and current-month cost.
49 -Token label uses input, output, and cache-read counts.
50 -Cache reads use `◐` and `` with cache percentage when mixed with uncached
51 -input.
48 +Token totals include assistant messages, nested tool usage, compactions, and branch summaries across the session.
49 +The token label uses input, output, cache-read, and cache-write counts.
50 +Cache reads use `◐`, cache writes use `W`, and `` shows the latest assistant prompt's cache-hit percentage.
52 51 No token usage shows `↑0`.
54 53 Uses provider-reported `usage.cost.total` when present and greater than zero.

extensions/cost/__tests__/harness.test.ts

Modified
303 - it("formats cached token usage compactly", () => {
303 + it("sums session usage from native usage-bearing entries", () => {
304 304 expect(
305 - __test.tokenLabel({
306 - input: 1100,
307 - output: 978,
308 - cacheRead: 108900,
309 - cacheWrite: 0,
310 - }),
311 - ).toBe("◐ 1.1k ↓978  99%");
305 + __test.sessionUsage([
307 + type: "message",
308 + message: {
309 + role: "assistant",
310 + usage: { input: 100, output: 20, cacheRead: 300 },
311 + },
312 + },
314 + type: "message",
315 + message: { role: "toolResult", usage: { input: 10, output: 5 } },
316 + },
317 + { type: "compaction", usage: { input: 50, cacheWrite: 40 } },
318 + { type: "branch_summary", usage: { output: 7 } },
319 + { type: "message", message: { role: "user", usage: { input: 999 } } },
320 + ]),
321 + ).toEqual({ input: 160, output: 32, cacheRead: 300, cacheWrite: 40 });
322 + });
324 + it("uses the latest assistant prompt for cache hit rate", () => {
325 + expect(
326 + __test.latestAssistantCacheHitRate([
328 + type: "message",
329 + message: { role: "assistant", usage: { input: 90, cacheRead: 10 } },
330 + },
332 + type: "message",
333 + message: {
334 + role: "assistant",
335 + usage: { input: 10, cacheRead: 80, cacheWrite: 10 },
336 + },
337 + },
338 + ]),
339 + ).toBe(80);
340 + });
342 + it("formats cumulative token and cache usage in the existing visual style", () => {
343 + expect(
344 + __test.tokenLabel(
346 + input: 1100,
347 + output: 978,
348 + cacheRead: 108900,
349 + cacheWrite: 2100,
350 + },
351 + 98,
352 + ),
353 + ).toBe("↑1.1k ↓978 ◐ 109k W2.1k  98%");

extensions/cost/index.ts

Modified
3 3 * Cost and token footer segments.
5 5 * Emits into the shared footer "llm" zone:
6 - * - tokens: last assistant turn token usage
6 + * - tokens: cumulative session token and cache usage
7 7 * - cost: turn/session/monthly spend when non-zero
19 19 // ── Constants ─────────────────────────────────────────────────────────────
21 -const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
22 21 const STATUS_ID = "cost";
24 -type FooterGlobal = typeof globalThis & {
25 - [FOOTER_KEY]?: { loaded?: boolean; version?: number };
26 -};
27 22 const CACHE_ICON = "";
28 23 const PRICE_UNIT_TOKENS = 1_000_000;
29 24 const COUNT_DECIMAL_THRESHOLD = 1_000;
44 39 "agent_end",
45 40 "tool_execution_end",
46 41 ] as const;
47 -const RESET_SIGNATURE_EVENTS = ["model_select", "session_compact"] as const;
42 +const RESET_SIGNATURE_EVENTS = [
43 + "model_select",
44 + "session_compact",
45 + "session_tree",
46 +] as const;
49 48 // ── Types ─────────────────────────────────────────────────────────────────
72 71 model?: string;
75 -type Branch = ReturnType<ExtensionContext["sessionManager"]["getBranch"]>;
77 74 type Snapshot = {
78 75 usage: TokenUsage;
76 + cacheHitRate?: number;
79 77 turnCost: number;
80 78 sessionCost: number;
81 79 monthlyCost: number;
88 86 { mtimeMs: number; size: number; cost: number }
91 -// ── Footer capability ─────────────────────────────────────────────────────
93 -function hasFooter(): boolean {
94 - const footer = (globalThis as FooterGlobal)[FOOTER_KEY];
95 - return footer?.loaded === true && (footer.version ?? 0) >= 1;
98 89 // ── Pricing ───────────────────────────────────────────────────────────────
100 91 // Prices per 1M tokens. Used only when providers report $0 cost.
184 175 return total;
187 -function lastAssistantUsage(branch: Branch): TokenUsage {
188 - for (let i = branch.length - 1; i >= 0; i--) {
189 - const entry = branch[i];
190 - if (!isAssistantMessageEntry(entry)) continue;
191 - if (!entry.message.usage) continue;
192 - return normalizeUsage(entry.message.usage);
178 +function usageFromEntry(entry: unknown): UsageWithCost | undefined {
179 + const candidate = entry as
180 + | {
181 + type?: unknown;
182 + message?: { role?: unknown; usage?: UsageWithCost };
183 + usage?: UsageWithCost;
185 + | undefined;
186 + if (candidate?.type === "message") {
187 + if (
188 + candidate.message?.role === "assistant" ||
189 + candidate.message?.role === "toolResult"
191 + return candidate.message.usage;
192 + return undefined;
194 - return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
194 + if (candidate?.type === "compaction" || candidate?.type === "branch_summary")
195 + return candidate.usage;
196 + return undefined;
199 +function sessionUsage(entries: readonly unknown[]): TokenUsage {
200 + const total: TokenUsage = {
201 + input: 0,
202 + output: 0,
203 + cacheRead: 0,
204 + cacheWrite: 0,
205 + };
206 + for (const entry of entries) {
207 + const usage = normalizeUsage(usageFromEntry(entry));
208 + total.input += usage.input;
209 + total.output += usage.output;
210 + total.cacheRead += usage.cacheRead;
211 + total.cacheWrite += usage.cacheWrite;
213 + return total;
216 +function latestAssistantCacheHitRate(
217 + entries: readonly unknown[],
218 +): number | undefined {
219 + for (let i = entries.length - 1; i >= 0; i--) {
220 + const entry = entries[i];
221 + if (!isAssistantMessageEntry(entry) || !entry.message.usage) continue;
222 + const usage = normalizeUsage(entry.message.usage);
223 + const prompt = usage.input + usage.cacheRead + usage.cacheWrite;
224 + return prompt > 0 ? (usage.cacheRead / prompt) * 100 : undefined;
226 + return undefined;
197 229 // ── Session file scan ─────────────────────────────────────────────────────
307 339 return `$${value.toFixed(1)}`;
310 -function tokenLabel(usage: TokenUsage): string {
311 - const totalPrompt = usage.input + usage.cacheRead;
312 - if (totalPrompt === 0 && usage.output === 0) return "↑0";
313 - if (usage.input === 0 && usage.cacheRead > 0)
314 - return `◐ ${formatCount(usage.cacheRead)}`;
315 - if (usage.cacheRead === 0)
316 - return `↑${formatCount(usage.input)} ↓${formatCount(usage.output)}`;
342 +function tokenLabel(usage: TokenUsage, cacheHitRate?: number): string {
343 + if (
344 + usage.input === 0 &&
345 + usage.output === 0 &&
346 + usage.cacheRead === 0 &&
347 + usage.cacheWrite === 0
349 + return "↑0";
318 - const cachePercent = Math.round((usage.cacheRead / totalPrompt) * 100);
319 - return `◐ ${formatCount(usage.input)} ↓${formatCount(usage.output)} ${CACHE_ICON} ${cachePercent}%`;
351 + const parts: string[] = [];
352 + if (usage.input > 0) parts.push(`↑${formatCount(usage.input)}`);
353 + if (usage.output > 0) parts.push(`↓${formatCount(usage.output)}`);
354 + if (usage.cacheRead > 0) parts.push(`◐ ${formatCount(usage.cacheRead)}`);
355 + if (usage.cacheWrite > 0) parts.push(`W${formatCount(usage.cacheWrite)}`);
356 + if (cacheHitRate !== undefined)
357 + parts.push(`${CACHE_ICON} ${Math.round(cacheHitRate)}%`);
358 + return parts.join(" ");
322 361 function costLabel(snapshot: Snapshot): string | undefined {
335 374 pi: ExtensionAPI,
336 375 id: SegmentId,
337 376 text: string | undefined,
338 -) {
339 - if (text === undefined) {
340 - pi.events.emit("footer:segment", { id: FOOTER[id].id, text: undefined });
341 - return;
342 - }
377 +): boolean {
378 + let accepted = false;
344 379 pi.events.emit("footer:segment", {
345 - id: FOOTER[id].id,
346 - text,
347 - color: FOOTER[id].color as ThemeColor,
348 - zone: FOOTER.zone,
349 - order: FOOTER[id].order,
380 + ...(text === undefined
381 + ? { id: FOOTER[id].id, text: undefined }
382 + : {
383 + id: FOOTER[id].id,
384 + text,
385 + color: FOOTER[id].color as ThemeColor,
386 + zone: FOOTER.zone,
387 + order: FOOTER[id].order,
388 + }),
389 + accept: () => {
390 + accepted = true;
391 + },
393 + return accepted;
353 396 function statusLabel(snapshot: Snapshot): string {
354 - return [tokenLabel(snapshot.usage), costLabel(snapshot)]
397 + return [
398 + tokenLabel(snapshot.usage, snapshot.cacheHitRate),
399 + costLabel(snapshot),
355 401 .filter((part): part is string => !!part)
356 402 .join(" · ");
361 407 ctx: ExtensionContext,
362 408 snapshot: Snapshot,
364 - if (hasFooter()) {
365 - ctx.ui.setStatus(STATUS_ID, undefined);
366 - emitSegment(pi, "tokens", tokenLabel(snapshot.usage));
367 - emitSegment(pi, "cost", costLabel(snapshot));
368 - return;
410 + let accepted = false;
411 + if (ctx.mode === "tui") {
412 + const tokensAccepted = emitSegment(
413 + pi,
414 + "tokens",
415 + tokenLabel(snapshot.usage, snapshot.cacheHitRate),
416 + );
417 + const costAccepted = emitSegment(pi, "cost", costLabel(snapshot));
418 + accepted = tokensAccepted && costAccepted;
371 - clearSegments(pi);
372 - ctx.ui.setStatus(STATUS_ID, statusLabel(snapshot));
421 + if (!accepted) clearSegments(pi);
422 + ctx.ui.setStatus(STATUS_ID, accepted ? undefined : statusLabel(snapshot));
375 425 function clearSegments(pi: ExtensionAPI) {
390 440 monthlyCost: number,
391 441 ): Snapshot {
392 442 const branch = ctx.sessionManager.getBranch();
443 + const entries = ctx.sessionManager.getEntries();
393 444 const sessionCost = sumMessageCosts(branch);
395 446 return {
396 - usage: lastAssistantUsage(branch),
447 + usage: sessionUsage(entries),
448 + cacheHitRate: latestAssistantCacheHitRate(entries),
397 449 turnCost: Math.max(0, sessionCost - previousSessionCost),
398 450 sessionCost,
399 451 monthlyCost,
407 459 usage.output,
408 460 usage.cacheRead,
409 461 usage.cacheWrite,
462 + snapshot.cacheHitRate,
410 463 snapshot.sessionCost,
411 464 snapshot.monthlyCost,
412 465 ].join("|");
517 -export const __test = { calculateMonthlyCost, tokenLabel };
570 +export const __test = {
571 + calculateMonthlyCost,
572 + costLabel,
573 + latestAssistantCacheHitRate,
574 + sessionUsage,
575 + tokenLabel,

extensions/footer/README.md

Modified
10 10 ## Commands / tools / settings
12 12 - Commands:
13 - - `/footer`: toggle footer visibility.
13 + - `/footer`: toggle footer visibility in TUI mode.
14 14 - Shortcuts:
15 15 - `ctrl+alt+f`: toggle footer visibility.
16 16 - Tools: none.
18 18 - `session_start`
19 19 - `session_shutdown`
20 20 - Events:
21 - - listens for `footer:segment` and `footer:probe`.
22 - - emits runtime-scoped `footer:ready` capability announcements.
21 + - listens for `footer:segment`.
23 22 - Settings: none.
25 24 ## Behavior
27 -Owns the Pi footer through `ctx.ui.setFooter()`.
26 +Owns the Pi footer through `ctx.ui.setFooter()` only when both `ctx.hasUI` is true and `ctx.mode` is `tui`.
27 +RPC keeps UI capability for protocol interactions but does not mount the terminal footer.
28 +JSON and print modes have no UI and do not mount it.
29 30 Visible footer has two lines normally and adds a third under LLM-segment pressure:
33 34 - line 2: the second `llm` flow row, shown only when content overflows line 1.
35 36 `footer:segment` payloads use `id`, `text`, and `zone` (`workspace` or `llm`).
36 -Optional fields: `variants`, `icon`, `color`, `bar`, `suffix`, `group`, `separator`, and `order`.
37 +Optional fields: `variants`, `icon`, `color`, `bar`, `suffix`, `group`, `separator`, `gap`, `order`, and an `accept` callback.
38 39 Adjacent segments with the same `group` stay together during line flow.
39 -Grouped segments use a space internally unless a segment supplies the separator that precedes it.
40 +Grouped segments use one space internally unless a segment supplies a larger `gap` or the separator that precedes it.
41 42 Send `{ id, text: undefined }` to remove a segment.
43 -Segments sort by `order`; default is `50`.
44 +Segments sort by `order`, then by `id` so equal-priority segments remain deterministic; default order is `50`.
44 45 Current session name is inserted in the `workspace` zone with order `0.5`.
46 47 Render requests are coalesced.
47 -Segments received before footer mount retry until the footer is available.
48 +Segments received before footer mount are retained for the first render without polling.
49 +Malformed updates are ignored without replacing previously valid segments.
50 +A producer rendering failure hides only that segment.
48 51 Branch changes trigger rerender.
50 53 Display text strips ANSI/control characters, collapses whitespace, and stays
54 57 Progress bars render 10 block cells on a dim track.
55 58 Bar values clamp to `0..100`.
57 -Publishes capability state at `Symbol.for("@bugabinga/pi-ext-footer")`:
58 -`{ version: 1, loaded: true }`.
59 -On quit/reload shutdown, `loaded` becomes `false`.
60 +The footer calls `accept` synchronously after validating and retaining an update, including updates received before mount.
61 +TUI producers use that acknowledgement to clear their `ctx.ui.setStatus()` fallback; without acknowledgement they remain independently useful through status text.
62 +Acknowledgement remains local to the runtime event bus, so nested runtimes cannot affect one another.
61 -Hidden mode swaps in a zero-height footer stub.
64 +Hidden mode swaps in a footer component with no rendered content.
65 +Pi fullscreen mode may still reserve layout space for that empty component.
62 66 Shutdown clears segments and footer context.

extensions/footer/__bench__/render.bench.ts

Added
new file mode 100644
1 +import { cpus } from "node:os";
2 +import type {
3 + ExtensionAPI,
4 + ExtensionContext,
5 + Theme,
6 +} from "@earendil-works/pi-coding-agent";
7 +import footerExtension from "../index.ts";
9 +const ROUNDS = 12;
10 +const MINIMUM_ROUND_NS = 200_000_000;
11 +const WIDE_COLUMNS = 160;
12 +const NARROW_COLUMNS = 72;
14 +const handlers = new Map<string, Array<(data: unknown) => void>>();
15 +let footer: { render(width: number): string[]; dispose?(): void } | undefined;
16 +let sink = 0;
18 +const theme = {
19 + fg: (_color: string, text: string) => `\x1b[38;5;245m${text}\x1b[39m`,
20 + getFgAnsi: () => "\x1b[38;5;245m",
21 +} as Theme;
22 +const statuses = new Map([
23 + ["mode", "review"],
24 + ["queue", "2 queued"],
25 +]);
26 +const footerData = {
27 + getExtensionStatuses: () => statuses,
28 + onBranchChange: () => () => {},
29 +};
30 +const tui = {
31 + requestRender: () => {
32 + sink ^= 1;
33 + },
34 +};
35 +const ui = {
36 + setFooter: (factory: unknown) => {
37 + footer?.dispose?.();
38 + footer = (
39 + factory as (
40 + tui: typeof tui,
41 + theme: Theme,
42 + data: typeof footerData,
43 + ) => typeof footer
44 + )(tui, theme, footerData);
45 + },
46 + notify: () => {},
47 +};
48 +const pi = {
49 + events: {
50 + on: (name: string, handler: (data: unknown) => void) => {
51 + handlers.set(name, [...(handlers.get(name) ?? []), handler]);
52 + },
53 + emit: (name: string, data: unknown) => {
54 + for (const handler of handlers.get(name) ?? []) handler(data);
55 + },
56 + },
57 + on: (
58 + name: string,
59 + handler: (event: unknown, ctx: ExtensionContext) => void,
60 + ) => {
61 + handlers.set(name, [
62 + ...(handlers.get(name) ?? []),
63 + (data) => handler(data, context),
64 + ]);
65 + },
66 + registerCommand: () => {},
67 + registerShortcut: () => {},
68 +} as unknown as ExtensionAPI;
69 +const context = {
70 + hasUI: true,
71 + mode: "tui",
72 + ui,
73 + sessionManager: { getSessionName: () => "footer performance" },
74 +} as unknown as ExtensionContext;
76 +function emit(name: string, data: unknown): void {
77 + for (const handler of handlers.get(name) ?? []) handler(data);
80 +function segment(data: Record<string, unknown>): void {
81 + emit("footer:segment", data);
84 +function consume(lines: string[]): void {
85 + sink ^= lines.length;
86 + for (const line of lines) sink ^= line.length;
89 +function render(width: number): void {
90 + if (!footer) throw new Error("footer did not mount");
91 + consume(footer.render(width));
94 +function benchmark(name: string, operation: () => void): void {
95 + for (let index = 0; index < 3; index++) operation();
96 + let iterations = 1;
97 + while (true) {
98 + const started = process.hrtime.bigint();
99 + for (let index = 0; index < iterations; index++) operation();
100 + if (Number(process.hrtime.bigint() - started) >= MINIMUM_ROUND_NS) break;
101 + iterations *= 2;
103 + for (let warmup = 0; warmup < 3; warmup++) {
104 + for (let index = 0; index < iterations; index++) operation();
106 + for (let round = 0; round < ROUNDS; round++) {
107 + (globalThis as { gc?: () => void }).gc?.();
108 + const started = process.hrtime.bigint();
109 + for (let index = 0; index < iterations; index++) operation();
110 + const elapsed = Number(process.hrtime.bigint() - started);
111 + console.log(
112 + `Benchmark${name}-${cpus().length}\t${iterations}\t${(elapsed / iterations).toFixed(0)} ns/op`,
113 + );
117 +footerExtension(pi);
118 +segment({
119 + id: "cwd",
120 + text: "~/Workspace/dotfiles/pi-ext",
121 + zone: "workspace",
122 + order: 0,
123 +});
124 +segment({ id: "vcs", text: "trunk +3 !2", zone: "workspace", order: 1 });
125 +segment({ id: "runtime", text: "node 26.8.2", zone: "workspace", order: 3 });
126 +segment({
127 + id: "provider",
128 + text: "",
129 + icon: "",
130 + zone: "llm",
131 + group: "model-route",
132 + order: -0.5,
133 +});
134 +segment({
135 + id: "subscription",
136 + text: "",
137 + icon: "󱏐",
138 + color: "success",
139 + zone: "llm",
140 + group: "model-route",
141 + gap: 2,
142 + order: -0.25,
143 +});
144 +segment({
145 + id: "model",
146 + text: "sol:medium",
147 + color: "syntaxKeyword",
148 + zone: "llm",
149 + group: "model-route",
150 + gap: 2,
151 + order: 0,
152 +});
153 +segment({
154 + id: "fast",
155 + text: "",
156 + icon: "󱐋",
157 + color: "warning",
158 + zone: "llm",
159 + group: "model-route",
160 + order: 0.5,
161 +});
162 +segment({
163 + id: "angel",
164 + text: "astra:max",
165 + icon: "󰧑",
166 + color: "accent",
167 + zone: "llm",
168 + group: "model-route",
169 + separator: "→",
170 + order: 0.75,
171 +});
172 +segment({
173 + id: "context-size",
174 + text: "112k/200k",
175 + variants: ["56%", "112k"],
176 + bar: 56,
177 + suffix: "56%",
178 + zone: "llm",
179 + order: 1,
180 +});
181 +segment({
182 + id: "tokens",
183 + text: "↑18.2k ↓4.1k ◐ 96k W2.4k  82%",
184 + zone: "llm",
185 + order: 2,
186 +});
187 +segment({
188 + id: "cost",
189 + text: "$0.42 · Σ$9.71 ·  $2624.8",
190 + color: "success",
191 + zone: "llm",
192 + order: 3,
193 +});
194 +segment({
195 + id: "quota:openai-codex",
196 + text: "2h 74% · week 61%",
197 + icon: "●",
198 + zone: "llm",
199 + order: 4,
200 +});
201 +segment({ id: "tps", text: "󰓅 78.4/s", zone: "llm", order: 4 });
202 +emit("session_start", { type: "session_start", reason: "startup" });
204 +console.log(`goos: ${process.platform}`);
205 +console.log(`goarch: ${process.arch}`);
206 +console.log("pkg: pi-ext/footer");
207 +benchmark("RenderWide", () => render(WIDE_COLUMNS));
208 +benchmark("RenderNarrow", () => render(NARROW_COLUMNS));
209 +let update = 0;
210 +benchmark("UpdateAndRender", () => {
211 + segment({
212 + id: "tps",
213 + text: `󰓅 ${(70 + (update++ % 100) / 10).toFixed(1)}/s`,
214 + zone: "llm",
215 + order: 4,
216 + });
217 + render(WIDE_COLUMNS);
218 +});
220 +emit("session_shutdown", { type: "session_shutdown", reason: "quit" });
221 +if (sink === 42) console.error(sink);

extensions/footer/__tests__/harness.test.ts

Modified
1 1 import path from "node:path";
2 2 import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3 3 import { visibleWidth } from "@earendil-works/pi-tui";
4 -import { afterEach, describe, expect, it } from "vitest";
4 +import { afterEach, describe, expect, it, vi } from "vitest";
5 5 import { createTestSession, type TestSession } from "../../../test/harness";
6 6 import footerExtension, { __test } from "../index.ts";
9 9 let t: TestSession | undefined;
11 11 afterEach(() => {
12 + vi.restoreAllMocks();
12 13 t?.dispose();
13 14 t = undefined;
17 + async function mountTui(session: TestSession): Promise<void> {
18 + const runner = session.session.extensionRunner;
19 + runner.setUIContext(runner.getUIContext(), "tui");
20 + await runner.emit({ type: "session_start", reason: "startup" });
21 + }
16 23 it("loads in real Pi extension runtime", async () => {
17 24 const extensionPath = path.resolve(import.meta.dirname, "../index.ts");
18 25 t = await createTestSession({ extensions: [extensionPath] });
21 28 expect(t.session.extensionRunner.extensions[0].path).toBe(extensionPath);
31 + it("acknowledges and retains pre-mount updates without polling", async () => {
32 + let accepted = 0;
33 + let offer: ((id: string) => void) | undefined;
34 + const producer = (pi: ExtensionAPI) => {
35 + offer = (id) =>
36 + pi.events.emit("footer:segment", {
37 + id,
38 + text: "ready",
39 + zone: "llm",
40 + accept: () => accepted++,
41 + });
42 + offer("early");
43 + };
44 + const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout");
45 + t = await createTestSession({
46 + extensionFactories: [footerExtension, producer],
47 + });
49 + expect(accepted).toBe(1);
50 + expect(t.events.uiCallsFor("setFooter")).toHaveLength(0);
52 + const runner = t.session.extensionRunner;
53 + runner.setUIContext(runner.getUIContext(), "rpc");
54 + await runner.emit({ type: "session_start", reason: "startup" });
55 + expect(t.events.uiCallsFor("setFooter")).toHaveLength(0);
56 + offer?.("rpc");
57 + expect(accepted).toBe(1);
59 + await mountTui(t);
60 + expect(accepted).toBe(1);
61 + expect(setTimeoutSpy.mock.calls.some(([, delay]) => delay === 50)).toBe(
62 + false,
63 + );
64 + setTimeoutSpy.mockRestore();
66 + const factory = t.events.uiCallsFor("setFooter").at(-1)?.args[0] as
67 + | ((
68 + tui: { requestRender(): void },
69 + theme: { fg(style: string, text: string): string },
70 + data: {
71 + onBranchChange(callback: () => void): () => void;
72 + getExtensionStatuses(): ReadonlyMap<string, string>;
73 + },
74 + ) => { render(width: number): string[] })
75 + | undefined;
76 + const component = factory?.(
77 + { requestRender() {} },
78 + { fg: (_style, text) => text },
79 + {
80 + onBranchChange: () => () => {},
81 + getExtensionStatuses: () => new Map(),
82 + },
83 + );
84 + expect(component?.render(80).join("\n")).toContain("ready");
85 + });
87 + it("isolates acknowledgements from a nested non-TUI runtime", async () => {
88 + let parentAccepted = 0;
89 + const producer = (pi: ExtensionAPI) => {
90 + pi.events.emit("footer:segment", {
91 + id: "parent",
92 + text: "ready",
93 + zone: "llm",
94 + accept: () => parentAccepted++,
95 + });
96 + };
97 + t = await createTestSession({
98 + extensionFactories: [footerExtension, producer],
99 + });
100 + await mountTui(t);
101 + expect(parentAccepted).toBe(1);
103 + const nested = await createTestSession({
104 + extensionFactories: [footerExtension],
105 + });
106 + try {
107 + const runner = nested.session.extensionRunner;
108 + runner.setUIContext(runner.getUIContext(), "rpc");
109 + await runner.emit({ type: "session_start", reason: "startup" });
110 + await runner.emit({ type: "session_shutdown", reason: "quit" });
111 + expect(parentAccepted).toBe(1);
112 + } finally {
113 + nested.dispose();
115 + });
117 + it("keeps valid segments when a producer emits malformed data", async () => {
118 + let emitSegment: ((segment: unknown) => void) | undefined;
119 + const producer = (pi: ExtensionAPI) => {
120 + emitSegment = (segment) => pi.events.emit("footer:segment", segment);
121 + };
122 + t = await createTestSession({
123 + extensionFactories: [footerExtension, producer],
124 + });
125 + await mountTui(t);
126 + const factory = t.events.uiCallsFor("setFooter").at(-1)?.args[0] as
127 + | ((
128 + tui: { requestRender(): void },
129 + theme: { fg(style: string, text: string): string },
130 + data: {
131 + onBranchChange(callback: () => void): () => void;
132 + getExtensionStatuses(): ReadonlyMap<string, string>;
133 + },
134 + ) => { render(width: number): string[] })
135 + | undefined;
136 + const component = factory?.(
137 + { requestRender() {} },
139 + fg: (style, text) => {
140 + if (style === "not-a-theme-color") throw new Error("bad color");
141 + return text;
142 + },
143 + },
145 + onBranchChange: () => () => {},
146 + getExtensionStatuses: () => new Map(),
147 + },
148 + );
150 + let accepted = 0;
151 + emitSegment?.({
152 + id: "good",
153 + text: "healthy",
154 + zone: "llm",
155 + accept: () => accepted++,
156 + });
157 + emitSegment?.({
158 + id: "good",
159 + text: 42,
160 + zone: "llm",
161 + accept: () => accepted++,
162 + });
163 + expect(accepted).toBe(1);
164 + emitSegment?.({
165 + id: "good",
166 + text: "poison",
167 + zone: "llm",
168 + color: "not-a-theme-color",
169 + accept: () => accepted++,
170 + });
171 + expect(accepted).toBe(1);
172 + expect(component?.render(80).join("\n")).toContain("healthy");
173 + expect(component?.render(80).join("\n")).not.toContain("poison");
174 + });
24 176 it("keeps later LLM components visible as earlier values grow", async () => {
25 177 let emitSegment: ((segment: unknown) => void) | undefined;
26 178 const producer = (pi: ExtensionAPI) => {
29 181 t = await createTestSession({
30 182 extensionFactories: [footerExtension, producer],
184 + await mountTui(t);
33 186 const factory = t.events.uiCallsFor("setFooter").at(-1)?.args[0] as
76 229 const shrunk = component?.render(32) ?? [];
77 230 expect(shrunk).toHaveLength(2);
78 231 expect(shrunk.join("\n")).toContain("50.0/s");
233 + emitSegment?.({
234 + id: "provider",
235 + text: "provider",
236 + zone: "llm",
237 + group: "model-route",
238 + order: -0.5,
239 + });
240 + emitSegment?.({
241 + id: "model",
242 + text: "sol:medium",
243 + zone: "llm",
244 + group: "model-route",
245 + gap: 2,
246 + order: 0,
247 + });
248 + expect(component?.render(80).join("\n")).toContain("provider sol:medium");
79 249 component?.dispose();
252 + it.each([
253 + [true, "tui", true],
254 + [true, "rpc", false],
255 + [false, "json", false],
256 + [false, "print", false],
257 + [false, "tui", false],
258 + ] as const)(
259 + "requires UI and TUI mode when hasUI=%s and mode=%s",
260 + (hasUI, mode, expected) => {
261 + expect(__test.canRenderFooter({ hasUI, mode })).toBe(expected);
262 + },
263 + );
265 + it("keeps equal-priority order stable after removal and reinsertion", () => {
266 + const quota = {
267 + id: "quota:anthropic",
268 + text: "quota",
269 + zone: "llm",
270 + order: 4,
271 + } as const;
272 + const tps = {
273 + id: "tps",
274 + text: "tps",
275 + zone: "llm",
276 + order: 4,
277 + } as const;
278 + const segments = new Map([
279 + [tps.id, tps],
280 + [quota.id, quota],
281 + ]);
282 + segments.delete(tps.id);
283 + segments.set(tps.id, tps);
285 + expect([...segments.values()].sort(__test.compareSegments)).toEqual([
286 + quota,
287 + tps,
288 + ]);
289 + });
291 + it("renders nothing and schedules no retries when hidden", async () => {
292 + let emitSegment: ((segment: unknown) => void) | undefined;
293 + const producer = (pi: ExtensionAPI) => {
294 + emitSegment = (segment) => pi.events.emit("footer:segment", segment);
295 + };
296 + t = await createTestSession({
297 + extensionFactories: [footerExtension, producer],
298 + });
299 + await mountTui(t);
300 + const runner = t.session.extensionRunner;
301 + await runner.extensions[0].commands
302 + .get("footer")
303 + .handler("", runner.createContext());
304 + const factory = t.events.uiCallsFor("setFooter").at(-1)?.args[0] as
305 + | ((tui: { requestRender(force?: boolean): void }) => {
306 + render(width: number): string[];
307 + })
308 + | undefined;
309 + expect(factory?.({ requestRender() {} }).render(80)).toEqual([]);
311 + const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout");
312 + emitSegment?.({ id: "tps", text: "50/s", zone: "llm" });
313 + expect(setTimeoutSpy).not.toHaveBeenCalled();
314 + setTimeoutSpy.mockRestore();
315 + });
82 317 it("right-aligns statuses beside the workspace row", () => {
83 318 expect(__test.alignLeftAndRight("workspace", "busy", 16)).toBe(
84 319 "workspace busy",

extensions/footer/index.ts

Modified
8 8 * line 2 = llm overflow, present only when needed
10 10 * Producers use semantic zones ("workspace" | "llm"). Footer decides row mapping.
11 - * Publishes a process-global capability flag so producers can choose footer
12 - * segments over ctx.ui.setStatus() fallbacks without ping events.
13 - * Uses setFooter() — the single footer owner. Producers are decoupled.
11 + * Valid updates are acknowledged synchronously so producers can choose between
12 + * the shared footer and their ctx.ui.setStatus() fallback without startup races.
13 + * Uses setFooter() as the single footer owner. Producers are decoupled.
15 15 * /footer or ctrl+alt+f toggles visibility by swapping between
16 - * the real footer and a zero-height stub via setFooter().
16 + * the real footer and an empty component via setFooter().
19 19 import type {
23 23 ThemeColor,
24 24 } from "@earendil-works/pi-coding-agent";
25 25 import { Key, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
26 -import { renderBlocksBar } from "./progress";
26 +import { renderBlocksBar } from "./progress.ts";
28 28 // ── Constants ─────────────────────────────────────────────────────
30 -const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
31 30 const SEPARATOR_COLOR = "borderMuted" as ThemeColor;
32 31 const DEFAULT_SEGMENT_COLOR = "muted" as ThemeColor;
33 32 const STATUS_COLOR = "dim" as ThemeColor;
34 33 const BAR_WIDTH = 10;
35 -const RETRY_MOUNT_MS = 50;
34 +const THEME_COLORS: ReadonlySet<string> = new Set<ThemeColor>([
35 + "accent",
36 + "border",
37 + "borderAccent",
38 + "borderMuted",
39 + "success",
40 + "error",
41 + "warning",
42 + "muted",
43 + "dim",
44 + "text",
45 + "thinkingText",
46 + "scrollbarTrack",
47 + "scrollbarThumb",
48 + "searchMatchText",
49 + "userMessageText",
50 + "customMessageText",
51 + "customMessageLabel",
52 + "toolTitle",
53 + "toolOutput",
54 + "mdHeading",
55 + "mdLink",
56 + "mdLinkUrl",
57 + "mdCode",
58 + "mdCodeBlock",
59 + "mdCodeBlockBorder",
60 + "mdQuote",
61 + "mdQuoteBorder",
62 + "mdHr",
63 + "mdListBullet",
64 + "toolDiffAdded",
65 + "toolDiffRemoved",
66 + "toolDiffContext",
67 + "syntaxComment",
68 + "syntaxKeyword",
69 + "syntaxFunction",
70 + "syntaxVariable",
71 + "syntaxString",
72 + "syntaxNumber",
73 + "syntaxType",
74 + "syntaxOperator",
75 + "syntaxPunctuation",
76 + "thinkingOff",
77 + "thinkingMinimal",
78 + "thinkingLow",
79 + "thinkingMedium",
80 + "thinkingHigh",
81 + "thinkingXhigh",
82 + "thinkingMax",
83 + "bashMode",
84 +]);
37 86 // ── Types ─────────────────────────────────────────────────────────
39 -type FooterGlobal = {
40 - version: 1;
41 - loaded: boolean;
42 -};
43 -type FooterGlobalStore = typeof globalThis & {
44 - [FOOTER_KEY]?: FooterGlobal;
45 -};
47 88 type FooterZone = "workspace" | "llm";
49 90 type Segment = {
57 98 zone: FooterZone;
58 99 group?: string;
59 100 separator?: string;
101 + gap?: number;
60 102 order?: number;
65 107 // ── Pure helpers ──────────────────────────────────────────────────
109 +function segmentUpdate(data: unknown): SegmentUpdate | undefined {
110 + if (!data || typeof data !== "object") return undefined;
111 + const value = data as Record<string, unknown>;
112 + if (typeof value.id !== "string" || value.id.length === 0) return undefined;
113 + if (!("text" in value) || value.text === undefined)
114 + return { id: value.id, text: undefined };
115 + if (
116 + typeof value.text !== "string" ||
117 + (value.zone !== "workspace" && value.zone !== "llm") ||
118 + (value.variants !== undefined &&
119 + (!Array.isArray(value.variants) ||
120 + !value.variants.every((variant) => typeof variant === "string"))) ||
121 + !optionalString(value.icon) ||
122 + (value.color !== undefined &&
123 + (typeof value.color !== "string" || !THEME_COLORS.has(value.color))) ||
124 + !optionalNumber(value.bar) ||
125 + !optionalString(value.suffix) ||
126 + !optionalString(value.group) ||
127 + !optionalString(value.separator) ||
128 + !optionalNumber(value.gap) ||
129 + !optionalNumber(value.order)
131 + return undefined;
132 + return value as Segment;
135 +function optionalString(value: unknown): boolean {
136 + return value === undefined || typeof value === "string";
139 +function optionalNumber(value: unknown): boolean {
140 + return (
141 + value === undefined || (typeof value === "number" && Number.isFinite(value))
142 + );
145 +function acknowledgeSegment(data: unknown): void {
146 + if (!data || typeof data !== "object") return;
147 + const accept = (data as { accept?: unknown }).accept;
148 + if (typeof accept !== "function") return;
149 + try {
150 + accept();
151 + } catch {
152 + // A producer callback cannot disrupt other footer segments.
156 +function canRenderFooter(
157 + ctx: Pick<ExtensionContext, "hasUI" | "mode">,
158 +): boolean {
159 + return ctx.hasUI && ctx.mode === "tui";
67 162 /** Pad line with side margins, truncating to fit terminal width. */
68 163 function padLine(line: string, width: number): string {
69 164 if (width <= 1) return truncateToWidth(line, width);
70 165 const contentWidth = width - 2;
71 - return ` ${truncateToWidth(line, contentWidth)} `;
166 + const content =
167 + visibleWidth(line) <= contentWidth
168 + ? line
169 + : truncateToWidth(line, contentWidth);
170 + return ` ${content} `;
74 173 /** Collapse whitespace and strip terminal/control characters for single-line display. */
83 182 .trim();
185 +function compareSegments(a: Segment, b: Segment): number {
186 + const byOrder = (a.order ?? 50) - (b.order ?? 50);
187 + if (byOrder !== 0) return byOrder;
188 + return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
86 191 function groupSegments(segments: Segment[]): Segment[][] {
87 192 const groups: Segment[][] = [];
88 193 for (const segment of segments) {
151 256 // ── Extension ─────────────────────────────────────────────────────
153 258 export default function footerExtension(pi: ExtensionAPI) {
154 - const state: FooterGlobal = { version: 1, loaded: true };
155 - (globalThis as FooterGlobalStore)[FOOTER_KEY] = state;
157 259 const segments = new Map<string, Segment>();
158 260 let requestRender: (() => void) | undefined;
159 261 let renderScheduled = false;
160 262 let hidden = false;
263 + let acceptingSegments = true;
161 264 let currentCtx: ExtensionContext | undefined;
163 266 // ── Segment handling ──────────────────────────────────────────
165 268 function handleSegment(data: unknown) {
166 - const payload = data as SegmentUpdate;
167 - if (!payload?.id) return;
269 + if (!acceptingSegments) return;
270 + const payload = segmentUpdate(data);
271 + if (!payload) return;
169 - if (!("text" in payload) || payload.text === undefined) {
170 - segments.delete(payload.id);
171 - } else {
172 - segments.set(payload.id, payload as Segment);
273 + if (payload.text === undefined) segments.delete(payload.id);
274 + else {
275 + const { accept: _accept, ...segment } = payload as Segment & {
276 + accept?: unknown;
277 + };
278 + segments.set(payload.id, segment);
280 + acknowledgeSegment(data);
174 281 scheduleRender();
177 284 pi.events.on("footer:segment", handleSegment);
178 - pi.events.on("footer:probe", () =>
179 - pi.events.emit("footer:ready", { version: 1 }),
180 - );
181 - pi.events.emit("footer:ready", { version: 1 });
183 286 // ── Coalesced render scheduling ───────────────────────────────
185 288 function scheduleRender() {
186 - if (renderScheduled) return;
187 - if (!requestRender) {
188 - if (segments.size > 0) setTimeout(() => scheduleRender(), RETRY_MOUNT_MS);
189 - return;
190 - }
289 + if (hidden || renderScheduled || !requestRender) return;
191 290 renderScheduled = true;
192 291 queueMicrotask(() => {
193 292 renderScheduled = false;
200 299 function getZoneSegments(zone: FooterZone): Segment[] {
201 300 return Array.from(segments.values())
202 301 .filter((s) => s.zone === zone)
203 - .sort((a, b) => (a.order ?? 50) - (b.order ?? 50));
302 + .sort(compareSegments);
206 305 // ── Segment rendering ─────────────────────────────────────────
239 338 return renderSegmentText(seg, theme, variants.at(-1) ?? "");
242 - function joinSegments(
243 - segs: Segment[],
244 - sep: string,
341 + function safeRenderSegment(
342 + segment: Segment,
245 343 theme: Theme,
246 - width = Number.POSITIVE_INFINITY,
344 + width: number,
345 + ): string | undefined {
346 + try {
347 + return renderSegment(segment, theme, width);
348 + } catch {
349 + return undefined;
353 + function joinSegments(
354 + segments: Segment[],
355 + separator: string,
356 + theme: Theme,
357 + width: number,
247 358 ): string {
248 - return segs.map((s) => renderSegment(s, theme, width)).join(sep);
359 + return segments
360 + .map((segment) => safeRenderSegment(segment, theme, width))
361 + .filter((rendered): rendered is string => rendered !== undefined)
362 + .join(separator);
251 365 function renderSegmentGroup(
253 367 theme: Theme,
254 368 width: number,
255 369 ): string {
256 - return segments
257 - .map((segment, index) => {
258 - const rendered = renderSegment(segment, theme, width);
259 - if (index === 0) return rendered;
260 - const separator = sanitizeDisplayText(segment.separator ?? "");
261 - const joiner = separator
262 - ? ` ${theme.fg(SEPARATOR_COLOR, separator)} `
263 - : " ";
264 - return joiner + rendered;
265 - })
266 - .join("");
370 + let result = "";
371 + for (const segment of segments) {
372 + const rendered = safeRenderSegment(segment, theme, width);
373 + if (rendered === undefined) continue;
374 + if (result.length === 0) {
375 + result = rendered;
376 + continue;
378 + const separator = sanitizeDisplayText(segment.separator ?? "");
379 + const gap = Math.max(1, Math.min(width, Math.floor(segment.gap ?? 1)));
380 + result += separator
381 + ? `${" ".repeat(gap)}${theme.fg(SEPARATOR_COLOR, separator)} ${rendered}`
382 + : `${" ".repeat(gap)}${rendered}`;
384 + return result;
269 387 // ── Zone rendering ────────────────────────────────────────────
294 412 zone: "workspace",
295 413 order: 0.5,
297 - segs.sort((a, b) => (a.order ?? 50) - (b.order ?? 50));
415 + segs.sort(compareSegments);
299 417 if (segs.length === 0) return "";
300 418 const sep = theme.fg(SEPARATOR_COLOR, " | ");
307 425 if (segs.length === 0) return ["", ""];
309 427 const sep = theme.fg(SEPARATOR_COLOR, " | ");
310 - const rendered = groupSegments(segs).map((group) =>
311 - renderSegmentGroup(group, theme, width),
312 - );
428 + const rendered = groupSegments(segs)
429 + .map((group) => renderSegmentGroup(group, theme, width))
430 + .filter(Boolean);
314 432 return flowLines(rendered, sep, width);
384 - setTimeout(() => scheduleRender(), 0);
387 503 // ── Toggle ────────────────────────────────────────────────────
389 505 function toggleVisibility(ctx: ExtensionContext) {
506 + if (!canRenderFooter(ctx)) return;
390 507 hidden = !hidden;
391 508 currentCtx = ctx;
392 509 ctx.ui.notify(hidden ? "Footer hidden" : "Footer visible", "info");
406 523 // ── Lifecycle ─────────────────────────────────────────────────
408 525 pi.on("session_start", async (_event, ctx) => {
409 - if (!ctx.hasUI) return;
526 + acceptingSegments = canRenderFooter(ctx);
527 + if (!acceptingSegments) return;
410 528 currentCtx = ctx;
411 529 mountFooter();
414 - pi.on("session_shutdown", async (event) => {
415 - if (event.reason === "quit" || event.reason === "reload")
416 - state.loaded = false;
532 + pi.on("session_shutdown", async () => {
533 + acceptingSegments = false;
417 534 segments.clear();
418 535 requestRender = undefined;
419 536 currentCtx = undefined;
423 -export const __test = { alignLeftAndRight, flowLines, groupSegments };
540 +export const __test = {
541 + acknowledgeSegment,
542 + alignLeftAndRight,
543 + canRenderFooter,
544 + compareSegments,
545 + segmentUpdate,
546 + flowLines,
547 + groupSegments,

extensions/footer/mise.toml

Modified
1 +[tasks.bench]
2 +description = "Benchmark footer rendering"
3 +depends = ["//:install"]
4 +run = "node --no-warnings --experimental-strip-types --expose-gc __bench__/render.bench.ts"
6 +[tasks.profile]
7 +description = "Profile footer rendering"
8 +depends = ["//:install"]
9 +run = [
10 + '''node -e "require('node:fs').mkdirSync('../../.research/footer', { recursive: true })"''',
11 + "node --no-warnings --experimental-strip-types --expose-gc --cpu-prof --cpu-prof-dir ../../.research/footer --cpu-prof-name footer.cpuprofile __bench__/render.bench.ts",
14 +[tasks.benchstat]
15 +description = "Compare footer benchmark results"
16 +depends = ["//:install"]
17 +usage = '''
18 +arg "<baseline>"
19 +arg "<candidate>"
20 +'''
21 +run = 'benchstat "{{ usage.baseline }}" "{{ usage.candidate }}"'
23 +[tasks.fmt]
24 +description = "Format footer extension"
25 +depends = ["//:install"]
26 +run = [
27 + "biome check --write --config-path ../.. .",
28 + "rumdl fmt --config ../../.rumdl.toml .",
29 + "taplo format --config ../../.taplo.toml mise.toml",
1 32 [tasks.lint]
2 33 description = "Lint footer extension"
3 34 depends = ["//:install"]

extensions/model-info/README.md

Modified
37 37 Events emitted:
39 39 - `footer:segment`:
40 - publishes or clears the grouped `model`, `fast`, and `angel` segments in the `llm` zone.
40 + publishes or clears the grouped `provider`, `subscription`, `model`, `fast`, and `angel` segments in the `llm` zone.
42 42 UI status:
59 59 Thinking level comes from `thinking_level_select`; otherwise from the latest
60 60 `thinking_level_change` session entry; fallback is `off`.
62 -When the shared footer is loaded, the extension publishes one atomic `model-route` group containing the executor, optional fast icon, and optional Angel advisor.
62 +When the shared footer is loaded, the extension publishes one atomic `model-route` group containing the provider, optional subscription marker, executor, optional fast icon, and optional Angel advisor.
63 +Known providers use brand icons; unknown providers retain their text identifier.
64 65 ```text
65 -sol:medium 󱐋 → 󰧑 astra:max
66 + 󱏐 sol:medium 󱐋 → 󰧑 astra:max
68 69 Without the shared footer, it clears the footer segment and writes the

extensions/model-info/__tests__/harness.test.ts

Modified
18 18 expect(t.session.extensionRunner.extensions).toHaveLength(1);
21 + it("uses acknowledged footer segments without transient fallback status", async () => {
22 + let accepted = 0;
23 + const footer = (pi: ExtensionAPI) => {
24 + pi.events.on("footer:segment", (data: unknown) => {
25 + const accept = (data as { accept?: unknown })?.accept;
26 + if (typeof accept !== "function") return;
27 + accept();
28 + accepted++;
29 + });
30 + };
31 + t = await createTestSession({
32 + extensionFactories: [footer, modelInfoExtension],
33 + });
34 + const runner = t.session.extensionRunner;
35 + runner.setUIContext(runner.getUIContext(), "tui");
36 + await runner.emit({ type: "session_start", reason: "startup" });
38 + const statuses = t.events
39 + .uiCallsFor("setStatus")
40 + .filter((call) => call.args[0] === "model-info");
41 + expect(accepted).toBeGreaterThan(0);
42 + expect(statuses.at(-1)?.args[1]).toBeUndefined();
43 + });
45 + it("keeps fallback status when only removals are acknowledged", async () => {
46 + const partialFooter = (pi: ExtensionAPI) => {
47 + pi.events.on("footer:segment", (data: unknown) => {
48 + const segment = data as { text?: unknown; accept?: unknown };
49 + if (segment.text !== undefined || typeof segment.accept !== "function")
50 + return;
51 + segment.accept();
52 + });
53 + };
54 + t = await createTestSession({
55 + extensionFactories: [partialFooter, modelInfoExtension],
56 + });
57 + const runner = t.session.extensionRunner;
58 + runner.setUIContext(runner.getUIContext(), "tui");
59 + await runner.emit({ type: "session_start", reason: "startup" });
61 + const statuses = t.events
62 + .uiCallsFor("setStatus")
63 + .filter((call) => call.args[0] === "model-info");
64 + expect(statuses.at(-1)?.args[1]).toMatch(/:/);
65 + });
21 67 it("replaces producer fallbacks with the combined route", async () => {
22 68 const producer = (pi: ExtensionAPI) => {
23 69 pi.on("session_start", (_event, ctx) => {
53 99 } as any;
55 101 expect(__test.modelInfoLabel(ctx)).toBe("sol:high");
102 + expect(__test.providerLabel(ctx)).toBe("test");
103 + expect(__test.providerIcon(ctx)).toBeUndefined();
58 - it("uses footer segments only in TUI mode", () => {
59 - expect(__test.usesFooter(true, "tui")).toBe(true);
60 - expect(__test.usesFooter(true, "rpc")).toBe(false);
61 - expect(__test.usesFooter(false, "tui")).toBe(false);
106 + it.each([
107 + ["openai-codex", ""],
108 + ["anthropic", ""],
109 + ["klaus", ""],
110 + ["github-copilot", ""],
111 + ["google-gemini-cli", ""],
112 + ])("uses the verified brand icon for %s", (provider, icon) => {
113 + expect(__test.providerIcon({ model: { provider } } as any)).toBe(icon);
114 + });
116 + it("detects declared OAuth subscriptions and Kimi Coding", () => {
117 + const modelRegistry = {
118 + isUsingOAuth: () => true,
119 + getProvider: () => ({ auth: { oauth: { isSubscription: true } } }),
120 + };
121 + expect(
122 + __test.usesSubscription({
123 + model: { provider: "anthropic" },
124 + modelRegistry,
125 + } as any),
126 + ).toBe(true);
127 + expect(
128 + __test.usesSubscription({
129 + model: { provider: "kimi-coding" },
130 + modelRegistry: {},
131 + } as any),
132 + ).toBe(true);
64 135 it("combines executor, transport, and advisor into one route", () => {

extensions/model-info/index.ts

Modified
14 14 const STATUS_ID = "model-info";
15 15 const GROUP_ID = "model-route";
16 +const PROVIDER_SEGMENT_ID = "provider";
17 +const SUBSCRIPTION_SEGMENT_ID = "subscription";
16 18 const MODEL_SEGMENT_ID = "model";
17 19 const FAST_SEGMENT_ID = "fast";
18 20 const ANGEL_SEGMENT_ID = "angel";
19 21 const FAST_ICON = "󱐋";
20 22 const ANGEL_ICON = "󰧑";
23 +const SUBSCRIPTION_ICON = "󱏐";
24 +const PROVIDER_ICONS: Readonly<Record<string, string>> = {
25 + anthropic: "",
26 + klaus: "",
27 + openai: "",
28 + "openai-codex": "",
29 + "github-copilot": "",
30 + google: "",
31 + "google-gemini-cli": "",
32 +};
22 34 type AngelState = { modelId: string; thinkingLevel: string };
24 -function usesFooter(
25 - footerReady: boolean,
26 - mode: ExtensionContext["mode"],
27 -): boolean {
28 - return footerReady && mode === "tui";
31 36 function modelLabel(ctx: Pick<ExtensionContext, "model">): string {
32 37 return shortModelLabel(ctx.model?.id ?? "no-model");
40 +function providerLabel(ctx: Pick<ExtensionContext, "model">): string {
41 + return ctx.model?.provider ?? "no-provider";
44 +function providerIcon(
45 + ctx: Pick<ExtensionContext, "model">,
46 +): string | undefined {
47 + return PROVIDER_ICONS[providerLabel(ctx)];
50 +function usesSubscription(
51 + ctx: Pick<ExtensionContext, "model" | "modelRegistry">,
52 +): boolean {
53 + const model = ctx.model;
54 + if (!model) return false;
55 + if (model.provider === "kimi-coding") return true;
56 + return (
57 + ctx.modelRegistry.isUsingOAuth(model) &&
58 + ctx.modelRegistry.getProvider(model.provider)?.auth.oauth
59 + ?.isSubscription === true
60 + );
35 63 function thinkingLevelFromBranch(
36 64 ctx: Pick<ExtensionContext, "sessionManager">,
37 65 ): string {
59 87 function clearSegments(pi: ExtensionAPI): void {
60 - for (const id of [MODEL_SEGMENT_ID, FAST_SEGMENT_ID, ANGEL_SEGMENT_ID])
88 + for (const id of [
89 + PROVIDER_SEGMENT_ID,
90 + SUBSCRIPTION_SEGMENT_ID,
91 + MODEL_SEGMENT_ID,
92 + FAST_SEGMENT_ID,
93 + ANGEL_SEGMENT_ID,
94 + ])
61 95 pi.events.emit("footer:segment", { id, text: undefined });
98 +function offerFooterSegment(pi: ExtensionAPI, segment: object): boolean {
99 + let accepted = false;
100 + pi.events.emit("footer:segment", {
101 + ...segment,
102 + accept: () => {
103 + accepted = true;
104 + },
105 + });
106 + return accepted;
64 109 function statusLabel(
65 110 model: string,
66 111 fast: boolean,
78 123 export default function modelInfoExtension(pi: ExtensionAPI): void {
79 124 let currentCtx: ExtensionContext | undefined;
80 - let footerReady = false;
81 125 let fast = false;
82 126 let angel: AngelState | undefined;
85 129 const model = modelInfoLabel(ctx, thinking);
86 130 ctx.ui.setStatus(FAST_SEGMENT_ID, undefined);
87 131 ctx.ui.setStatus(ANGEL_SEGMENT_ID, undefined);
88 - if (!usesFooter(footerReady, ctx.mode)) {
132 + if (ctx.mode !== "tui") {
89 133 clearSegments(pi);
90 134 ctx.ui.setStatus(STATUS_ID, statusLabel(model, fast, angel));
91 135 return;
94 - ctx.ui.setStatus(STATUS_ID, undefined);
95 - pi.events.emit("footer:segment", {
138 + let accepted = true;
139 + const offer = (segment: object) => {
140 + accepted = offerFooterSegment(pi, segment) && accepted;
141 + };
142 + const provider = providerIcon(ctx);
143 + offer({
144 + id: PROVIDER_SEGMENT_ID,
145 + text: provider ? "" : providerLabel(ctx),
146 + icon: provider,
147 + color: "dim" as ThemeColor,
148 + zone: "llm",
149 + group: GROUP_ID,
150 + order: -0.5,
151 + });
152 + offer(
153 + usesSubscription(ctx)
154 + ? {
155 + id: SUBSCRIPTION_SEGMENT_ID,
156 + text: "",
157 + icon: SUBSCRIPTION_ICON,
158 + color: "success" as ThemeColor,
159 + zone: "llm",
160 + group: GROUP_ID,
161 + gap: 2,
162 + order: -0.25,
164 + : { id: SUBSCRIPTION_SEGMENT_ID, text: undefined },
165 + );
166 + offer({
96 167 id: MODEL_SEGMENT_ID,
97 168 text: model,
98 169 color: "syntaxKeyword" as ThemeColor,
99 170 zone: "llm",
100 171 group: GROUP_ID,
172 + gap: 2,
101 173 order: 0,
103 - pi.events.emit(
104 - "footer:segment",
175 + offer(
107 178 id: FAST_SEGMENT_ID,
115 186 : { id: FAST_SEGMENT_ID, text: undefined },
117 - pi.events.emit(
118 - "footer:segment",
188 + offer(
121 191 id: ANGEL_SEGMENT_ID,
130 200 : { id: ANGEL_SEGMENT_ID, text: undefined },
203 + if (!accepted) clearSegments(pi);
204 + ctx.ui.setStatus(
205 + STATUS_ID,
206 + accepted ? undefined : statusLabel(model, fast, angel),
207 + );
134 210 function refresh(ctx: ExtensionContext, thinking?: string): void {
137 213 publish(ctx, thinking ?? ctx.thinkingLevel);
140 - pi.events.on("footer:ready", (data: unknown) => {
141 - if ((data as { version?: unknown })?.version !== 1) return;
142 - footerReady = true;
143 - if (currentCtx) refresh(currentCtx);
144 - });
145 216 pi.events.on("model-route:fast", (data: unknown) => {
146 217 if (typeof (data as { active?: unknown })?.active !== "boolean") return;
147 218 fast = (data as { active: boolean }).active;
159 230 if (currentCtx) refresh(currentCtx);
162 - pi.events.emit("footer:probe", undefined);
164 233 pi.on("session_start", (_event, ctx) => refresh(ctx));
165 234 pi.on("model_select", (_event, ctx) => refresh(ctx));
166 235 pi.on("thinking_level_select", (event, ctx) => refresh(ctx, event.level));
169 238 clearSegments(pi);
170 239 if (ctx.hasUI) ctx.ui.setStatus(STATUS_ID, undefined);
171 240 currentCtx = undefined;
172 - footerReady = false;
173 241 fast = false;
174 242 angel = undefined;
178 246 export const __test = {
179 247 modelInfoLabel,
180 248 modelLabel,
249 + providerIcon,
250 + providerLabel,
181 251 statusLabel,
252 + usesSubscription,
182 253 thinkingLevelFromBranch,
183 - usesFooter,

extensions/pfui/README.md

Modified
5 5 ## Install / load
7 7 PFUI is loaded through the root [pi-ext package](../../README.md).
8 -`extensions/pfui/index.ts` must be the first explicit extension entry in the root package manifest, before the extension glob, because PFUI establishes process context and the fallback prompt for later extensions.
8 +`extensions/pfui/index.ts` must be the first explicit extension entry in the root package manifest because PFUI establishes process context and the fallback prompt for later extensions.
9 +The shared footer is the second explicit entry, before the extension glob, so footer producers discover it before publishing their initial state.
10 11 ## Commands / tools / settings

extensions/pfui/__tests__/harness.test.ts

Modified
121 121 ) as { pi?: { extensions?: string[] } };
122 122 expect(manifest.pi?.extensions).toEqual([
123 123 "extensions/pfui/index.ts",
124 + "extensions/footer/index.ts",
124 125 "extensions/*/index.ts",
134 135 { temporary: true },
136 137 const pfuiPath = path.join(extensionRoot, "index.ts");
138 + const footerPath = path.join(repositoryRoot, "extensions/footer/index.ts");
137 139 expect(resolved.extensions[0]?.path).toBe(pfuiPath);
140 + expect(resolved.extensions[1]?.path).toBe(footerPath);
138 141 expect(
139 142 resolved.extensions.filter((extension) => extension.path === pfuiPath),
140 143 ).toHaveLength(1);
144 + expect(
145 + resolved.extensions.filter((extension) => extension.path === footerPath),
146 + ).toHaveLength(1);
143 149 it("composes the fallback with dynamic tools and deduplicated guidelines", async () => {

extensions/quota/index.ts

Modified
13 13 ExtensionContext,
14 14 } from "@earendil-works/pi-coding-agent";
16 -const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
17 16 const STATUS_ID = "quota";
18 17 const REFRESH_MS = 5 * 60_000;
439 438 return used < 50 ? "accent" : used < 80 ? "warning" : "error";
442 -function hasFooter(): boolean {
443 - const footer = (globalThis as any)[FOOTER_KEY];
444 - return footer?.loaded === true && footer.version >= 1;
447 441 // ── Extension ─────────────────────────────────────────────────────────────
449 443 export default function usageExtension(pi: ExtensionAPI) {
605 599 const footerIds = new Set<string>();
601 + function offerFooterSegment(segment: object): boolean {
602 + let accepted = false;
603 + pi.events.emit("footer:segment", {
604 + ...segment,
605 + accept: () => {
606 + accepted = true;
607 + },
608 + });
609 + return accepted;
607 612 function clearFooter() {
608 613 for (const id of footerIds) {
609 614 pi.events.emit("footer:segment", { id, text: undefined });
628 633 function updateFooter(ctx: ExtensionContext) {
629 634 const active = activeProvider(ctx);
631 - if (!hasFooter()) {
636 + if (ctx.mode !== "tui") {
632 637 clearFooter();
633 638 ctx.ui.setStatus(STATUS_ID, quotaStatusLabel(ctx));
634 639 return;
637 - ctx.ui.setStatus(STATUS_ID, undefined);
642 + let offered = false;
643 + let accepted = true;
638 644 const seen = new Set<string>();
640 646 for (const p of providers
648 654 seen.add(id);
649 655 footerIds.add(id);
651 - pi.events.emit("footer:segment", {
652 - id,
653 - icon: isActive ? "●" : "◌",
654 - text: `${label} ${used}%${reset ? ` (${reset})` : ""}`,
655 - variants: [`${label} ${used}%`, `${used}%`],
656 - color: isActive ? color(used) : "muted",
657 - zone: "llm",
658 - order: 4,
659 - });
657 + offered = true;
658 + accepted =
659 + offerFooterSegment({
660 + id,
661 + icon: isActive ? "●" : "◌",
662 + text: `${label} ${used}%${reset ? ` (${reset})` : ""}`,
663 + variants: [`${label} ${used}%`, `${used}%`],
664 + color: isActive ? color(used) : "muted",
665 + zone: "llm",
666 + order: 4,
667 + }) && accepted;
662 670 for (const id of [...footerIds]) {
663 671 if (seen.has(id)) continue;
664 - pi.events.emit("footer:segment", { id, text: undefined });
672 + offered = true;
673 + accepted = offerFooterSegment({ id, text: undefined }) && accepted;
665 674 footerIds.delete(id);
677 + accepted = offered && accepted;
678 + if (!accepted) clearFooter();
679 + ctx.ui.setStatus(STATUS_ID, accepted ? undefined : quotaStatusLabel(ctx));
669 682 // ── Widget ─────────────────────────────────────────────────────────────

extensions/runtime/index.ts

Modified
17 17 const execFileAsync = promisify(execFile);
19 -const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
20 19 const VERSION_TIMEOUT_MS = 2500;
21 20 const SEGMENT_ID = "runtime";
22 21 const STATUS_ID = "runtime";
60 59 suffixes?: readonly string[];
61 60 version: () => Promise<string | undefined>;
63 -type FooterGlobal = typeof globalThis & {
64 - [FOOTER_KEY]?: { loaded?: boolean; version?: number };
65 -};
67 -function hasFooter(): boolean {
68 - const footer = (globalThis as FooterGlobal)[FOOTER_KEY];
69 - return footer?.loaded === true && (footer.version ?? 0) >= 1;
72 62 async function commandOutput(
73 63 cmd: string,
74 64 args: readonly string[] = [],
293 + function offerFooterSegment(segment: object): boolean {
294 + let accepted = false;
295 + ignoreStaleContext(() =>
296 + pi.events.emit("footer:segment", {
297 + ...segment,
298 + accept: () => {
299 + accepted = true;
300 + },
301 + }),
302 + );
303 + return accepted;
303 306 async function refresh(ctx: ExtensionContext) {
304 307 const ticket = generation;
305 308 let cwd: string;
323 326 const text = rt.version ?? rt.name;
324 - if (hasFooter()) {
325 - ignoreStaleContext(() => ctx.ui.setStatus(STATUS_ID, undefined));
326 - ignoreStaleContext(() =>
327 - pi.events.emit("footer:segment", {
328 - id: SEGMENT_ID,
329 - icon: rt.icon,
330 - text,
331 - color: RUNTIME_COLORS[rt.name],
332 - zone: SEGMENT_ZONE,
333 - order: SEGMENT_ORDER,
334 - }),
335 - );
336 - return;
337 - }
327 + const accepted =
328 + ctx.mode === "tui" &&
329 + offerFooterSegment({
330 + id: SEGMENT_ID,
331 + icon: rt.icon,
332 + text,
333 + color: RUNTIME_COLORS[rt.name],
334 + zone: SEGMENT_ZONE,
335 + order: SEGMENT_ORDER,
336 + });
339 - clearSegment();
340 - ignoreStaleContext(() => ctx.ui.setStatus(STATUS_ID, `${rt.icon} ${text}`));
338 + if (!accepted) clearSegment();
339 + ignoreStaleContext(() =>
340 + ctx.ui.setStatus(STATUS_ID, accepted ? undefined : `${rt.icon} ${text}`),
341 + );
343 344 pi.on("session_start", async (_e, ctx) => {

extensions/tps/index.ts

Modified
4 4 import type {
5 5 ExtensionAPI,
6 6 ExtensionContext,
7 7 ThemeColor,
8 8 } from "@earendil-works/pi-coding-agent";
10 -const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
11 10 const STATUS_ID = "tps";
12 11 const SEGMENT_ID = "tps";
13 12 const ICON = "󰓅"; // nf-md-speedometer U+F04C5
24 23 type Clock = () => number;
25 -type FooterGlobal = typeof globalThis & {
26 - [FOOTER_KEY]?: { loaded?: boolean; version?: number };
27 -};
29 -function hasFooter(): boolean {
30 - const footer = (globalThis as FooterGlobal)[FOOTER_KEY];
31 - return footer?.loaded === true && (footer.version ?? 0) >= 1;
34 25 function isAssistantMessage(message: unknown): message is AssistantLike {
35 26 return (
171 162 pi.events.emit("footer:segment", { id: SEGMENT_ID, text: undefined });
174 -function publish(
165 +function publishPresentation(
175 166 pi: ExtensionAPI,
176 167 ctx: ExtensionContext,
177 168 text: string | undefined,
178 - color: ThemeColor = "accent",
169 + color: ThemeColor,
179 170 ): void {
180 171 if (!ctx.hasUI) return;
183 - if (hasFooter()) {
184 - ctx.ui.setStatus(STATUS_ID, undefined);
185 - pi.events.emit(
186 - "footer:segment",
187 - text === undefined
174 + let accepted = false;
175 + if (ctx.mode === "tui") {
176 + pi.events.emit("footer:segment", {
177 + ...(text === undefined
188 178 ? { id: SEGMENT_ID, text: undefined }
190 180 id: SEGMENT_ID,
194 184 color,
195 185 zone: "llm",
196 186 order: 4,
197 - },
198 - );
199 - return;
187 + }),
188 + accept: () => {
189 + accepted = true;
190 + },
191 + });
202 - clearSegment(pi);
194 + if (!accepted) clearSegment(pi);
203 195 ctx.ui.setStatus(
204 196 STATUS_ID,
205 - text === undefined ? undefined : `${ICON} ${text}`,
197 + accepted || text === undefined ? undefined : `${ICON} ${text}`,
207 199 } catch {
208 200 // Ignore stale ctx during reload/switch/shutdown.
212 204 export default function tpsExtension(pi: ExtensionAPI) {
213 205 let run: TpsRun | null = null;
207 + function publish(
208 + ctx: ExtensionContext,
209 + text: string | undefined,
210 + color: ThemeColor = "accent",
211 + ): void {
212 + publishPresentation(pi, ctx, text, color);
215 215 pi.on("session_start", async (_event, ctx) => {
216 - publish(pi, ctx, IDLE_TEXT, "dim");
216 + publish(ctx, IDLE_TEXT, "dim");
219 219 pi.on("agent_start", async (_event, ctx) => {
220 220 run = new TpsRun();
221 221 run.startAgent();
222 - publish(pi, ctx, "0.0/s", "dim");
222 + publish(ctx, "0.0/s", "dim");
225 225 pi.on("message_start", async (event, _ctx) => {
232 232 run.startAssistant();
233 233 run.addDelta(deltaLength(event));
234 234 if (!run.shouldPublishLive()) return;
235 - publish(pi, ctx, run.liveText(), "accent");
235 + publish(ctx, run.liveText(), "accent");
238 238 pi.on("message_end", async (event, _ctx) => {
244 244 if (!run) return;
245 245 const text = run.finish(event.messages);
246 246 run = null;
247 - publish(pi, ctx, text, text === IDLE_TEXT ? "dim" : "success");
247 + publish(ctx, text, text === IDLE_TEXT ? "dim" : "success");
250 250 pi.on("session_shutdown", async (_event, ctx) => {
251 251 run = null;
252 - publish(pi, ctx, undefined);
252 + publish(ctx, undefined);

extensions/vcs-status/index.ts

Modified
15 15 } from "@earendil-works/pi-coding-agent";
17 17 const execFileAsync = promisify(execFile);
18 -const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");
19 18 const CWD_STATUS_ID = "cwd";
20 19 const VCS_STATUS_ID = "vcs";
21 20 const COMMAND_TIMEOUT_MS = 2500;
91 90 deleted: 0,
94 -function hasFooter(): boolean {
95 - const footer = (globalThis as any)[FOOTER_KEY];
96 - return footer?.loaded === true && footer.version >= 1;
99 93 async function pathType(path: string): Promise<"file" | "dir" | undefined> {
100 94 try {
101 95 const s = await stat(path);
376 +function offerFooterSegment(pi: ExtensionAPI, segment: object): boolean {
377 + let accepted = false;
378 + ignoreStaleContext(() =>
379 + pi.events.emit("footer:segment", {
380 + ...segment,
381 + accept: () => {
382 + accepted = true;
383 + },
384 + }),
385 + );
386 + return accepted;
382 389 function cwdLabel(cwd: string): string {
383 390 const home = process.env.HOME;
384 391 return home && cwd.startsWith(home) ? `~${cwd.slice(home.length)}` : cwd;
391 398 vcs: VcsSegment | undefined,
393 400 const path = cwdLabel(cwd);
401 + let accepted = false;
395 - if (hasFooter()) {
396 - ignoreStaleContext(() => ctx.ui.setStatus(CWD_STATUS_ID, undefined));
397 - ignoreStaleContext(() => ctx.ui.setStatus(VCS_STATUS_ID, undefined));
398 - ignoreStaleContext(() =>
399 - pi.events.emit("footer:segment", {
400 - id: "cwd",
401 - text: path,
402 - icon: "󰝰",
403 - color: "syntaxOperator",
404 - zone: "workspace",
405 - order: 0,
406 - }),
403 + if (ctx.mode === "tui") {
404 + const cwdAccepted = offerFooterSegment(pi, {
405 + id: "cwd",
406 + text: path,
407 + icon: "󰝰",
408 + color: "syntaxOperator",
409 + zone: "workspace",
410 + order: 0,
411 + });
412 + const vcsAccepted = offerFooterSegment(
413 + pi,
414 + vcs?.text
415 + ? {
416 + id: "vcs",
417 + text: vcs.text,
418 + icon: vcs.icon,
419 + color: "syntaxKeyword",
420 + zone: "workspace",
421 + order: 1,
423 + : { id: "vcs", text: undefined },
408 - if (vcs?.text) {
409 - ignoreStaleContext(() =>
410 - pi.events.emit("footer:segment", {
411 - id: "vcs",
412 - text: vcs.text,
413 - icon: vcs.icon,
414 - color: "syntaxKeyword",
415 - zone: "workspace",
416 - order: 1,
417 - }),
418 - );
419 - } else {
420 - ignoreStaleContext(() =>
421 - pi.events.emit("footer:segment", { id: "vcs", text: undefined }),
422 - );
423 - }
424 - return;
425 + accepted = cwdAccepted && vcsAccepted;
427 - clearSegments(pi);
428 - ignoreStaleContext(() => ctx.ui.setStatus(CWD_STATUS_ID, path));
428 + if (!accepted) clearSegments(pi);
429 + ignoreStaleContext(() =>
430 + ctx.ui.setStatus(CWD_STATUS_ID, accepted ? undefined : path),
431 + );
429 432 ignoreStaleContext(() =>
430 433 ctx.ui.setStatus(
431 434 VCS_STATUS_ID,
432 - vcs?.text ? `${vcs.icon} ${vcs.text}` : undefined,
435 + accepted || !vcs?.text ? undefined : `${vcs.icon} ${vcs.text}`,

package.json

Modified
30 30 "pi": {
31 31 "extensions": [
32 32 "extensions/pfui/index.ts",
33 + "extensions/footer/index.ts",
33 34 "extensions/*/index.ts"

scripts/extensions.mjs

Modified
824 824 errors.push("root: workspaces must be ['extensions/*']");
826 826 JSON.stringify(pkg.pi?.extensions) !==
827 - JSON.stringify(["extensions/pfui/index.ts", "extensions/*/index.ts"])
827 + JSON.stringify([
828 + "extensions/pfui/index.ts",
829 + "extensions/footer/index.ts",
830 + "extensions/*/index.ts",
831 + ])
829 833 errors.push(
830 - "root: pi.extensions must load pfui explicitly before the extension glob",
834 + "root: pi.extensions must load pfui and footer explicitly before the extension glob",
832 836 if ("skills" in (pkg.pi ?? {})) errors.push("root: pi.skills must be absent");
833 837 if ("prompts" in (pkg.pi ?? {}))

scripts/test_extensions_static_check.mjs

Modified
185 185 assert(!tuneIndex.includes('exec("bash"'));
187 187 assert.deepEqual(rootPkg().pi, {
188 - extensions: ["extensions/pfui/index.ts", "extensions/*/index.ts"],
188 + extensions: [
189 + "extensions/pfui/index.ts",
190 + "extensions/footer/index.ts",
191 + "extensions/*/index.ts",
192 + ],
191 195 const cliFailure = spawnSync(