pi-footer-stats 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,48 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.1.3] - 2026-12-04
9
+
10
+ ### Added
11
+
12
+ - `working m:ss` run timer: elapsed time of the current agent run, ticking
13
+ once per second while pi is generating and frozen at the final duration
14
+ after the run settles (`agent_settled`, not `agent_end`, so pi retries and
15
+ continuations don't reset it). Resets on new sessions; the render interval
16
+ is stopped on settle and on `dispose`, so an idle footer never wakes the
17
+ process.
18
+
19
+ ## [0.1.4] - 2026-12-04
20
+
21
+ ### Added
22
+
23
+ - `footerStats` settings: one boolean per item (`input`, `output`,
24
+ `cacheRead`, `cacheWrite`, `cacheHit`, `rate`, `timer`, `cost`,
25
+ `context`) in user or project `settings.json`. Project overrides user;
26
+ missing or malformed values fall back to showing everything. Lets a local
27
+ model hide just what it never produces, e.g. `"cacheWrite": false`.
28
+ - `/footer` command: `status`, `hide`/`show <item>`, `timer <session|response>`,
29
+ `theme <default|mono>`, and `reset`. Changes persist atomically to
30
+ `footer-stats-state.json` in the agent dir and survive restarts; keys set in
31
+ `settings.json` override the command.
32
+ - `timerMode` preference: `session` (cumulative working time, the default) or
33
+ `response` (the current run while active, the last run once idle). `theme`
34
+ preference: `default` palette or `mono`, which renders every stat in muted
35
+ color with no bold accents.
36
+
37
+ ### Changed
38
+
39
+ - The stats line groups related segments one space apart (tokens; cache
40
+ reads, writes, and hit rate; throughput plus work time); only group
41
+ boundaries spread across the width, so the row packs tighter and truncates
42
+ later on narrow terminals.
43
+ - The run timer now renders as a braille dots spinner (`⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏`, the
44
+ same frames pi-tui's own Loader ships, ~10 steps per second) instead of the
45
+ word `working`. The segment counts cumulative session working time: while idle
46
+ it freezes at the session total with a static `·`, so the number never
47
+ moves while pi is at rest. All frames measure one column in
48
+ `visibleWidth`, so layout math is unchanged. 106 assertions.
49
+
8
50
  ## [0.1.2] - 2026-12-04
9
51
 
10
52
  ### Fixed
package/README.md CHANGED
@@ -1,6 +1,8 @@
1
1
  <p align="center">
2
2
  <b>pi footer-stats</b><br>
3
- Colored session stats, a tokens/second average, and a context-window progress bar for <a href="https://github.com/earendil-works/pi">pi</a>.
3
+ Colored session stats, tokens/second, a work timer, and a context-window
4
+ progress bar for <a href="https://github.com/earendil-works/pi">pi</a>, all
5
+ customizable with <code>/footer</code>.
4
6
  </p>
5
7
 
6
8
  <p align="center">
@@ -13,6 +15,8 @@
13
15
  <p align="center">
14
16
  <a href="#install">Install</a> ·
15
17
  <a href="#what-you-get">What you get</a> ·
18
+ <a href="#settings">Settings</a> ·
19
+ <a href="#commands">Commands</a> ·
16
20
  <a href="#behavior--privacy">Behavior &amp; privacy</a> ·
17
21
  <a href="SECURITY.md">Security</a> ·
18
22
  <a href="CONTRIBUTING.md">Contributing</a>
@@ -24,7 +28,7 @@
24
28
 
25
29
  ```
26
30
  ~/workspace/apps/toolbox (main)
27
- ↑10k ↓5.4k ↺ R650k ✎ W0 ◎ CH98.5% ⚡77.1 tok/s $0.000 ▄▁▁▁▁▁▁▁▁▁ 2.5%/1.0M (auto) (omlx) Qwen4-35B-A3B-oQ4e-mtp • medium
31
+ ↑10k ↓5.4k ↺ R650k ✎ W0 ◎ CH98.5% ⚡77.1 tok/s ⠋ 0:42 $0.000 ▄▁▁▁▁▁▁▁▁▁ 2.5%/1.0M (auto) (omlx) Qwen4-35B-A3B-oQ4e-mtp • medium
28
32
  ```
29
33
 
30
34
  ## Install
@@ -57,17 +61,82 @@ Then `/reload` (or restart pi) and the footer replaces the built-in one.
57
61
  session** — not a model benchmark: it reflects the model, hardware, and
58
62
  load of this session. Measured with pi's per-message monotonic timing
59
63
  (`durationMs`); reasoning tokens never double-counted
64
+ - **Work timer** — `⠋ 0:42`: time the agent has spent working this session.
65
+ While a run is active the braille dots spinner pi's own loaders use cycles
66
+ (~10 steps/second) and the number includes the current run; when idle it
67
+ freezes at the session total (`· 1:03`) and never ticks while at rest
60
68
  - **Context bar** — `▄▁▁▁▁▁▁▁▁▁`, one cell per 1%, dim → yellow >70% →
61
69
  **bold red >90%** as auto-compact nears, with `(auto)` when enabled
62
- - **Stable layout** — every indicator always shown (`0`/`—` placeholders),
63
- stats spread across the width, model + provider + thinking right-aligned,
64
- graceful truncation on narrow terminals
70
+ - **Stable layout** — every enabled indicator always shown (`0`/`—`
71
+ placeholders), related stats grouped (tokens; cache reads, writes, hit rate;
72
+ throughput + work time) one space apart with only group boundaries spreading
73
+ across the width, model + provider + thinking right-aligned, graceful
74
+ truncation on narrow terminals
75
+
76
+ ## Settings
77
+
78
+ Optional. Put a `footerStats` object in `settings.json` (user at
79
+ `~/.pi/agent/settings.json`, or project at `.pi/settings.json`; project wins)
80
+ with one boolean per item. Missing, malformed, or unreadable values fall back
81
+ to showing everything:
82
+
83
+ ```json
84
+ {
85
+ "footerStats": {
86
+ "input": true,
87
+ "output": true,
88
+ "cacheRead": true,
89
+ "cacheWrite": true,
90
+ "cacheHit": true,
91
+ "rate": true,
92
+ "timer": true,
93
+ "cost": true,
94
+ "context": true,
95
+ "timerMode": "session",
96
+ "theme": "default"
97
+ }
98
+ }
99
+ ```
100
+
101
+ Set an item to `false` to hide just that segment: a local model that never
102
+ writes cache can use `"cacheWrite": false` and keep `cacheRead`. `timerMode`
103
+ picks what the timer counts: `session` (cumulative working time) or `response`
104
+ (the current run while active, the last run once idle). `theme` picks `default`
105
+ (the color palette) or `mono` (every stat in muted color, no bold accents).
106
+ Hiding items never changes the math of the ones that remain. Changes apply on
107
+ the next session start: run `/reload` or restart pi.
108
+
109
+ ## Commands
110
+
111
+ `/footer` with no arguments opens an interactive checkbox menu. Arrow keys move
112
+ between rows, space toggles the row under the cursor (`[x]`/`[ ]` per item,
113
+ cycling the value for timer mode and theme) and applies it immediately, so the
114
+ footer behind the menu updates live while it stays open. Enter or Escape closes;
115
+ nothing is discarded on close because every toggle persisted on the spot. All
116
+ changes are stored in `~/.pi/agent/footer-stats-state.json` and survive
117
+ restarts. The same actions work as arguments, for scripting or muscle memory:
118
+
119
+ ```
120
+ /footer open the interactive menu
121
+ /footer status list what is on, plus timer mode and theme
122
+ /footer hide cost hide the $ segment
123
+ /footer hide cacheWrite hide just the cache-write segment
124
+ /footer show cost bring it back
125
+ /footer timer response timer counts the last run instead of the session total
126
+ /footer theme mono render every stat in muted color
127
+ /footer reset back to defaults
128
+ ```
129
+
130
+ Keys set in `settings.json` override `/footer`; delete them there to hand
131
+ control back to the command.
65
132
 
66
133
  ## Behavior & privacy
67
134
 
68
135
  - One file, no dependencies beyond pi itself, no build step
69
- - **Read-only**: session state and two settings files (user + project, for
70
- the `(auto)` flag). No network, no writes, no tools, no credentials
136
+ - **Read-only footprint**: reads session state and three config files (user
137
+ settings, project settings, and its own state file); the only write is its
138
+ own `footer-stats-state.json` in the agent dir, written atomically when you
139
+ change preferences. No network, no tools, no credentials
71
140
  - **Degrades gracefully**: a render error (e.g. pi API drift on an untested
72
141
  version) collapses to one dim line instead of breaking the TUI
73
142
  - Tested with **pi 1.8.0**; uses only public extension APIs
package/SECURITY.md CHANGED
@@ -4,14 +4,18 @@
4
4
 
5
5
  `pi-footer-stats` is a **read-only** pi footer extension. By design it:
6
6
 
7
- - reads session state (token usage, context size) and two settings files —
8
- user (`~/.pi/agent/settings.json`) and project (`.pi/settings.json`) —
9
- purely to render the footer
10
- - performs **no network access**, **no writes**, **no tool calls**, and
11
- stores **no credentials**; nothing is persisted outside the pi process
12
-
13
- Any change that would introduce network access, file writes, or credential
14
- handling is considered a security regression and should be reported as one.
7
+ - reads session state (token usage, context size) and three config files —
8
+ user (`~/.pi/agent/settings.json`), project (`.pi/settings.json`), and its
9
+ own state file (`~/.pi/agent/footer-stats-state.json`) — purely to render
10
+ the footer and to remember `/footer` command changes
11
+ - performs **no network access**, **no tool calls**, and stores **no
12
+ credentials**; the only file it writes is its own state file, written
13
+ atomically inside the pi agent directory. Nothing else is persisted outside
14
+ the pi process
15
+
16
+ Any change that would introduce network access, writes outside its own state
17
+ file, or credential handling is considered a security regression and should
18
+ be reported as one.
15
19
 
16
20
  ## Reporting a vulnerability
17
21
 
package/demo.svg CHANGED
@@ -1,27 +1,29 @@
1
- <svg xmlns="http://www.w3.org/2000/svg" width="1400" height="230" viewBox="0 0 1400 230" role="img" aria-label="pi footer-stats example footer with color legend">
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="1400" height="260" viewBox="0 0 1400 260" role="img" aria-label="pi footer-stats example footer with color legend">
2
2
  <!-- Generated by scripts/make-demo.mjs from the real footer component output. Do not edit by hand. -->
3
- <rect width="1400" height="230" rx="8" fill="#23232e"/>
3
+ <rect width="1400" height="260" rx="8" fill="#23232e"/>
4
4
  <g font-family="Menlo, Monaco, Consolas, 'DejaVu Sans Mono', monospace" font-size="14">
5
5
  <text x="18" y="34" xml:space="preserve"><tspan fill="#8a8fa3">~/workspace/apps/toolbox (main)</tspan></text>
6
- <text x="18" y="66" xml:space="preserve"><tspan fill="#a78bfa">↑10k</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#56d364">↓5.4k</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#768390">↺ R650k</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#e3b341">✎ W0</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#56d364">◎ CH98.5%</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#63d9a8">⚡77.1 tok/s</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#58a6ff">$0.000</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#8a8fa3">▄▁▁▁▁▁▁▁▁▁ 2.5%/1.0M (auto)</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#8a8fa3">(omlx) Qwen4-35B-A3B-oQ4e-mtp • medium</tspan></text>
6
+ <text x="18" y="66" xml:space="preserve"><tspan fill="#a78bfa">↑10k</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#56d364">↓5.4k</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#768390">↺ R650k</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#e3b341">✎ W0</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#56d364">◎ CH98.5%</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#63d9a8">⚡77.1 tok/s</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#a78bfa">⠋ 0:42</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#58a6ff">$0.000</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#8a8fa3">▄▁▁▁▁▁▁▁▁▁ 2.5%/1.0M (auto)</tspan><tspan fill="#8a8fa3"> </tspan><tspan fill="#8a8fa3">(omlx) Qwen4-35B-A3B-oQ4e-mtp • medium</tspan></text>
7
7
  </g>
8
8
  <line x1="18" y1="96" x2="1382" y2="96" stroke="#3a3a48" stroke-width="1"/>
9
9
  <g font-family="Menlo, Monaco, Consolas, 'DejaVu Sans Mono', monospace" font-size="15">
10
- <circle cx="26" cy="130" r="6" fill="#a78bfa"/>
11
- <text x="42" y="135" fill="#e6e6f0">↑ input tokens</text>
12
- <circle cx="330" cy="130" r="6" fill="#56d364"/>
13
- <text x="346" y="135" fill="#e6e6f0">↓ output tokens</text>
14
- <circle cx="640" cy="130" r="6" fill="#768390"/>
15
- <text x="656" y="135" fill="#e6e6f0">↺ cache reads</text>
16
- <circle cx="950" cy="130" r="6" fill="#e3b341"/>
17
- <text x="966" y="135" fill="#e6e6f0">✎ cache writes</text>
18
- <circle cx="26" cy="180" r="6" fill="#56d364"/>
19
- <text x="42" y="185" fill="#e6e6f0">◎ cache-hit rate</text>
20
- <circle cx="330" cy="180" r="6" fill="#63d9a8"/>
21
- <text x="346" y="185" fill="#e6e6f0">⚡ session tok/s</text>
22
- <circle cx="640" cy="180" r="6" fill="#58a6ff"/>
23
- <text x="656" y="185" fill="#e6e6f0">$ session cost</text>
24
- <circle cx="950" cy="180" r="6" fill="#8a8fa3"/>
25
- <text x="966" y="185" fill="#e6e6f0">▄▁ context bar · 1%/cell</text>
10
+ <circle cx="26" cy="120" r="6" fill="#a78bfa"/>
11
+ <text x="42" y="125" fill="#e6e6f0">↑ input tokens</text>
12
+ <circle cx="480" cy="120" r="6" fill="#56d364"/>
13
+ <text x="496" y="125" fill="#e6e6f0">↓ output tokens</text>
14
+ <circle cx="950" cy="120" r="6" fill="#768390"/>
15
+ <text x="966" y="125" fill="#e6e6f0">↺ cache reads</text>
16
+ <circle cx="26" cy="170" r="6" fill="#e3b341"/>
17
+ <text x="42" y="175" fill="#e6e6f0">✎ cache writes</text>
18
+ <circle cx="480" cy="170" r="6" fill="#56d364"/>
19
+ <text x="496" y="175" fill="#e6e6f0">◎ cache-hit rate</text>
20
+ <circle cx="950" cy="170" r="6" fill="#63d9a8"/>
21
+ <text x="966" y="175" fill="#e6e6f0">⚡ session tok/s</text>
22
+ <circle cx="26" cy="220" r="6" fill="#58a6ff"/>
23
+ <text x="42" y="225" fill="#e6e6f0">$ session cost</text>
24
+ <circle cx="480" cy="220" r="6" fill="#a78bfa"/>
25
+ <text x="496" y="225" fill="#e6e6f0">⠋ run timer</text>
26
+ <circle cx="950" cy="220" r="6" fill="#8a8fa3"/>
27
+ <text x="966" y="225" fill="#e6e6f0">▄▁ context bar · 1%/cell</text>
26
28
  </g>
27
29
  </svg>
@@ -28,7 +28,7 @@
28
28
  * present, otherwise entry timestamps — approximate, includes queue/TTFT gaps).
29
29
  */
30
30
 
31
- import { readFileSync } from "node:fs";
31
+ import { readFileSync, renameSync, writeFileSync } from "node:fs";
32
32
  import { isAbsolute, join, relative, resolve, sep } from "node:path";
33
33
 
34
34
  import { CONFIG_DIR_NAME, getAgentDir } from "@earendil-works/pi-coding-agent";
@@ -42,6 +42,34 @@ let totalMs = 0;
42
42
  let turnStartMs: number | null = null;
43
43
  let tuiRef: { requestRender(): void } | null = null;
44
44
 
45
+ // --- working-run timer -----------------------------------------------------
46
+ // One segment, two modes: while a run is active it shows the session's
47
+ // cumulative working time plus the current run's elapsed time with the
48
+ // spinner glyph; while idle it freezes at the session total with a static
49
+ // glyph. agent_start opens a run, agent_settled is the final-idle signal
50
+ // (agent_end is not final, pi may retry or continue).
51
+ let runStartMs: number | null = null;
52
+ let activeMs = 0;
53
+ let lastRunMs = 0;
54
+ let runTimer: ReturnType<typeof setInterval> | null = null;
55
+
56
+ const stopRunTimer = (): void => {
57
+ if (runTimer !== null) {
58
+ clearInterval(runTimer);
59
+ runTimer = null;
60
+ }
61
+ };
62
+
63
+ // Spinner frames for the working timer: the same braille "dots" frames pi-tui's
64
+ // own Loader component ships (DEFAULT_FRAMES in pi-tui/components/loader.js).
65
+ // Host-blessed: pi renders these everywhere it shows a spinner. All frames
66
+ // measure 1 column in pi-tui's visibleWidth. The bar steps every
67
+ // SPINNER_STEP_MS while a run is active; the duration text still changes
68
+ // once per second.
69
+ const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
70
+ const SPINNER_IDLE = "·";
71
+ const SPINNER_STEP_MS = 100;
72
+
45
73
  // Generated tokens = usage.output only. usage.reasoning is a subset of output
46
74
  // (pi-ai Usage docs: "output already includes these tokens"), so summing both
47
75
  // would double-count thinking tokens.
@@ -64,6 +92,15 @@ const fmtTokens = (count: number): string => {
64
92
  return `${Math.round(count / 1000000)}M`;
65
93
  };
66
94
 
95
+ const formatDuration = (ms: number): string => {
96
+ const total = Math.max(0, Math.floor(ms / 1000));
97
+ const sec = total % 60;
98
+ const min = Math.floor(total / 60) % 60;
99
+ const hr = Math.floor(total / 3600);
100
+ const pad = (n: number): string => n.toString().padStart(2, "0");
101
+ return hr > 0 ? `${hr}:${pad(min)}:${pad(sec)}` : `${min}:${pad(sec)}`;
102
+ };
103
+
67
104
  const fmtCwd = (cwd: string, home: string | undefined): string => {
68
105
  if (!home) return cwd;
69
106
  const resolvedCwd = resolve(cwd);
@@ -97,6 +134,115 @@ const autoCompactEnabled = (cwd: string): boolean =>
97
134
  readCompactionEnabled(join(getAgentDir(), "settings.json")) ??
98
135
  true;
99
136
 
137
+ // Footer preferences: which groups show, which timer mode, which theme.
138
+ // Precedence: defaults, then the /footer state file, then user settings.json,
139
+ // then project settings.json (pi merges those the same way). Anything missing,
140
+ // malformed, or unreadable falls back to the default of showing everything.
141
+ type TimerMode = "session" | "response";
142
+ type FooterTheme = "default" | "mono";
143
+ interface FooterSettings {
144
+ input: boolean;
145
+ output: boolean;
146
+ cacheRead: boolean;
147
+ cacheWrite: boolean;
148
+ cacheHit: boolean;
149
+ rate: boolean;
150
+ timer: boolean;
151
+ cost: boolean;
152
+ context: boolean;
153
+ timerMode: TimerMode;
154
+ theme: FooterTheme;
155
+ }
156
+
157
+ type ItemKey =
158
+ | "input"
159
+ | "output"
160
+ | "cacheRead"
161
+ | "cacheWrite"
162
+ | "cacheHit"
163
+ | "rate"
164
+ | "timer"
165
+ | "cost"
166
+ | "context";
167
+
168
+ const ITEM_KEYS: ItemKey[] = [
169
+ "input",
170
+ "output",
171
+ "cacheRead",
172
+ "cacheWrite",
173
+ "cacheHit",
174
+ "rate",
175
+ "timer",
176
+ "cost",
177
+ "context",
178
+ ];
179
+ const ITEM_LABELS: Record<ItemKey, string> = {
180
+ input: "↑ input",
181
+ output: "↓ output",
182
+ cacheRead: "↺ cache read",
183
+ cacheWrite: "✎ cache write",
184
+ cacheHit: "◎ cache hit",
185
+ rate: "⚡ tok/s",
186
+ timer: "timer",
187
+ cost: "$ cost",
188
+ context: "context bar",
189
+ };
190
+ const TIMER_MODES: TimerMode[] = ["session", "response"];
191
+ const FOOTER_THEMES: FooterTheme[] = ["default", "mono"];
192
+
193
+ const DEFAULT_SETTINGS: FooterSettings = {
194
+ input: true,
195
+ output: true,
196
+ cacheRead: true,
197
+ cacheWrite: true,
198
+ cacheHit: true,
199
+ rate: true,
200
+ timer: true,
201
+ cost: true,
202
+ context: true,
203
+ timerMode: "session",
204
+ theme: "default",
205
+ };
206
+
207
+ // The /footer command persists here, atomically, inside the agent dir. This
208
+ // is the only file the extension ever writes (see SECURITY.md).
209
+ const STATE_FILE_NAME = "footer-stats-state.json";
210
+
211
+ const readFooterSettings = (path: string): Partial<FooterSettings> | undefined => {
212
+ try {
213
+ const settings = JSON.parse(readFileSync(path, "utf8"));
214
+ const value = settings?.footerStats;
215
+ if (typeof value !== "object" || value === null) return undefined;
216
+ const out: Partial<FooterSettings> = {};
217
+ for (const key of ITEM_KEYS) {
218
+ const v = (value as Record<string, unknown>)[key];
219
+ if (typeof v === "boolean") out[key] = v;
220
+ }
221
+ if (TIMER_MODES.includes(value.timerMode as TimerMode)) out.timerMode = value.timerMode;
222
+ if (FOOTER_THEMES.includes(value.theme as FooterTheme)) out.theme = value.theme;
223
+ return out;
224
+ } catch {
225
+ return undefined;
226
+ }
227
+ };
228
+
229
+ const loadSettings = (cwd: string): FooterSettings => ({
230
+ ...DEFAULT_SETTINGS,
231
+ ...readFooterSettings(join(getAgentDir(), STATE_FILE_NAME)),
232
+ ...readFooterSettings(join(getAgentDir(), "settings.json")),
233
+ ...readFooterSettings(join(cwd, CONFIG_DIR_NAME, "settings.json")),
234
+ });
235
+
236
+ const writeStateFile = (settings: FooterSettings): void => {
237
+ try {
238
+ const path = join(getAgentDir(), STATE_FILE_NAME);
239
+ writeFileSync(`${path}.tmp`, `${JSON.stringify({ footerStats: settings }, null, 2)}\n`);
240
+ renameSync(`${path}.tmp`, path);
241
+ } catch {
242
+ // Persistence is best-effort: a failed write never breaks the footer.
243
+ }
244
+ };
245
+
100
246
  interface UsageLike {
101
247
  input?: number;
102
248
  output?: number;
@@ -160,16 +306,22 @@ const scanSession = (entries: readonly unknown[]): ScanResult => {
160
306
  export default function (pi: ExtensionAPI) {
161
307
  let ctxRef: ExtensionContext | null = null;
162
308
  let autoCompact = true;
309
+ let settings: FooterSettings = DEFAULT_SETTINGS;
163
310
 
164
311
  pi.on("session_start", async (_event, ctx) => {
165
312
  ctxRef = ctx;
166
313
  autoCompact = autoCompactEnabled(ctx.cwd);
314
+ settings = loadSettings(ctx.cwd);
167
315
 
168
316
  // Reset before seeding so rates never mix across sessions and seeding
169
317
  // stays idempotent if session_start fires more than once for one session.
170
318
  totalTokens = 0;
171
319
  totalMs = 0;
172
320
  turnStartMs = null;
321
+ stopRunTimer();
322
+ runStartMs = null;
323
+ activeMs = 0;
324
+ lastRunMs = 0;
173
325
 
174
326
  // Seed the rate accumulator from session history. Entries written by
175
327
  // recent pi versions carry message.durationMs (exact); older entries fall
@@ -231,22 +383,69 @@ export default function (pi: ExtensionAPI) {
231
383
  scanCache = { key: cacheKey, stats: scanSession(entries), usage: context.getContextUsage() };
232
384
  }
233
385
  const stats = scanCache.stats;
234
- const segs: string[] = [];
235
- // All indicators always shown; unknown values render as —
236
- segs.push(theme.fg("accent", `↑${fmtTokens(stats.input)}`));
237
- segs.push(theme.fg("success", `↓${fmtTokens(stats.output)}`));
238
- segs.push(theme.fg("muted", `↺ R${fmtTokens(stats.cacheRead)}`));
239
- segs.push(theme.fg("warning", `✎ W${fmtTokens(stats.cacheWrite)}`));
240
- if (stats.cacheHitRate !== undefined) {
241
- const color =
242
- stats.cacheHitRate >= 90 ? "success" : stats.cacheHitRate >= 50 ? "warning" : "muted";
243
- segs.push(theme.fg(color, `◎ CH${stats.cacheHitRate.toFixed(1)}%`));
244
- } else {
245
- segs.push(theme.fg("muted", "◎ CH—"));
386
+ // Segments are grouped: related pairs stay one space apart and
387
+ // only group boundaries spread across the available width.
388
+ // mono theme renders every stat in muted color with no bold
389
+ // accents, keeping the line quiet; default keeps the palette.
390
+ const mono = settings.theme === "mono";
391
+ const paint = {
392
+ fg: (color: string, text: string): string =>
393
+ theme.fg(mono ? "muted" : color, text),
394
+ };
395
+ const groups: string[][] = [];
396
+ const group = (...items: string[]): void => {
397
+ groups.push(items);
398
+ };
399
+ // Groups show unless disabled through footerStats settings;
400
+ // unknown values within a shown group render as —
401
+ if (settings.input || settings.output) {
402
+ const pair: string[] = [];
403
+ if (settings.input) pair.push(paint.fg("accent", `↑${fmtTokens(stats.input)}`));
404
+ if (settings.output) pair.push(paint.fg("success", `↓${fmtTokens(stats.output)}`));
405
+ group(...pair);
406
+ }
407
+ if (settings.cacheRead || settings.cacheWrite || settings.cacheHit) {
408
+ const cacheSegs: string[] = [];
409
+ if (settings.cacheRead) cacheSegs.push(paint.fg("muted", `↺ R${fmtTokens(stats.cacheRead)}`));
410
+ if (settings.cacheWrite) cacheSegs.push(paint.fg("warning", `✎ W${fmtTokens(stats.cacheWrite)}`));
411
+ if (settings.cacheHit) {
412
+ cacheSegs.push(
413
+ stats.cacheHitRate !== undefined
414
+ ? paint.fg(
415
+ stats.cacheHitRate >= 90
416
+ ? "success"
417
+ : stats.cacheHitRate >= 50
418
+ ? "warning"
419
+ : "muted",
420
+ `◎ CH${stats.cacheHitRate.toFixed(1)}%`,
421
+ )
422
+ : paint.fg("muted", "◎ CH—"),
423
+ );
424
+ }
425
+ group(...cacheSegs);
246
426
  }
247
427
  const rate = rateText();
248
- segs.push(theme.fg("bashMode", rate ? `⚡${rate} tok/s` : "⚡ — tok/s"));
249
- segs.push(theme.fg("mdLink", `$${stats.cost.toFixed(3)}`));
428
+ // Timer: session mode shows cumulative working time (plus the
429
+ // current run while active); response mode shows the current
430
+ // run's elapsed time, then the last run's duration once idle.
431
+ const running = runStartMs !== null;
432
+ const elapsed =
433
+ settings.timerMode === "response"
434
+ ? running
435
+ ? Date.now() - runStartMs
436
+ : lastRunMs
437
+ : running
438
+ ? activeMs + (Date.now() - runStartMs)
439
+ : activeMs;
440
+ const glyph = running
441
+ ? SPINNER_FRAMES[Math.floor(elapsed / SPINNER_STEP_MS) % SPINNER_FRAMES.length]
442
+ : SPINNER_IDLE;
443
+ // Throughput and work time read as one performance pair.
444
+ const perf: string[] = [];
445
+ if (settings.rate) perf.push(paint.fg("bashMode", rate ? `⚡${rate} tok/s` : "⚡ — tok/s"));
446
+ if (settings.timer) perf.push(paint.fg("accent", `${glyph} ${formatDuration(elapsed)}`));
447
+ if (perf.length > 0) group(...perf);
448
+ if (settings.cost) group(paint.fg("mdLink", `$${stats.cost.toFixed(3)}`));
250
449
 
251
450
  // Context segment with auto-compact proximity coloring + mini bar
252
451
  const usage = scanCache.usage;
@@ -267,11 +466,12 @@ export default function (pi: ExtensionAPI) {
267
466
  if (percent === null || percent === undefined) filled = 0;
268
467
  filled = Math.min(10, Math.max(0, filled));
269
468
  const bar = "▄".repeat(filled) + "▁".repeat(10 - filled);
270
- if (percentValue > 90) segs.push(theme.bold(theme.fg("error", `${bar} ${pctStr}`)));
271
- else if (percentValue > 70) segs.push(theme.fg("warning", `${bar} ${pctStr}`));
272
- else segs.push(theme.fg("dim", `${bar} ${pctStr}`));
273
-
274
- // Right side: provider + model + thinking level
469
+ if (settings.context) {
470
+ if (!mono && percentValue > 90) group(theme.bold(paint.fg("error", `${bar} ${pctStr}`)));
471
+ else if (!mono && percentValue > 70) group(paint.fg("warning", `${bar} ${pctStr}`));
472
+ else group(paint.fg("dim", `${bar} ${pctStr}`));
473
+ }
474
+ // Right side: provider + model + thinking level
275
475
  let rightSide = context.model?.id || "no-model";
276
476
  if (context.model?.reasoning) {
277
477
  const level = context.thinkingLevel || "off";
@@ -284,7 +484,7 @@ export default function (pi: ExtensionAPI) {
284
484
  rightSide = theme.fg("dim", rightSide);
285
485
 
286
486
  // Spread segments across available width (capped spacing), right-align model
287
- let statsLeft = segs.join(" ");
487
+ let statsLeft = groups.flat().join(" ");
288
488
  if (visibleWidth(statsLeft) > width) {
289
489
  statsLeft = truncateToWidth(statsLeft, width, "...");
290
490
  }
@@ -294,10 +494,10 @@ export default function (pi: ExtensionAPI) {
294
494
  if (statsWidth + 2 + rightWidth <= width) {
295
495
  const avail = width - rightWidth - 2;
296
496
  const extra = avail - statsWidth;
297
- const gaps = segs.length - 1;
497
+ const gaps = groups.length - 1;
298
498
  if (gaps > 0 && extra >= gaps) {
299
499
  const per = Math.min(6, Math.floor(extra / gaps));
300
- if (per > 0) statsLeft = segs.join(" ".repeat(per + 1));
500
+ if (per > 0) statsLeft = groups.map((g) => g.join(" ")).join(" ".repeat(per + 1));
301
501
  }
302
502
  const pad = " ".repeat(Math.max(0, width - visibleWidth(statsLeft) - rightWidth));
303
503
  statsLine = statsLeft + pad + rightSide;
@@ -333,7 +533,10 @@ export default function (pi: ExtensionAPI) {
333
533
  return lines;
334
534
  };
335
535
  return {
336
- dispose: unsub,
536
+ dispose() {
537
+ unsub();
538
+ stopRunTimer();
539
+ },
337
540
  invalidate() {},
338
541
  render(width: number): string[] {
339
542
  try {
@@ -355,6 +558,10 @@ export default function (pi: ExtensionAPI) {
355
558
  totalTokens = 0;
356
559
  totalMs = 0;
357
560
  turnStartMs = null;
561
+ stopRunTimer();
562
+ runStartMs = null;
563
+ activeMs = 0;
564
+ lastRunMs = 0;
358
565
  tuiRef = null;
359
566
  ctxRef = null;
360
567
  });
@@ -387,4 +594,156 @@ export default function (pi: ExtensionAPI) {
387
594
  tuiRef?.requestRender();
388
595
  }
389
596
  });
390
- }
597
+
598
+ // Timer: agent_start opens a run (fast ticker); agent_settled is the
599
+ // final-idle signal (agent_end is not final; pi may retry or continue) and
600
+ // folds the run's elapsed time into the session total. The ticker is torn
601
+ // down on settle/shutdown/dispose.
602
+ pi.on("agent_start", async () => {
603
+ if (runStartMs === null) runStartMs = Date.now();
604
+ stopRunTimer();
605
+ runTimer = setInterval(() => tuiRef?.requestRender(), SPINNER_STEP_MS);
606
+ tuiRef?.requestRender();
607
+ });
608
+
609
+ pi.on("agent_settled", async () => {
610
+ if (runStartMs !== null) {
611
+ const delta = Date.now() - runStartMs;
612
+ activeMs += delta;
613
+ lastRunMs = delta;
614
+ }
615
+ runStartMs = null;
616
+ stopRunTimer();
617
+ tuiRef?.requestRender();
618
+ });
619
+
620
+ // /footer command: show or change groups, timer mode, and theme. Changes
621
+ // persist to the agent-dir state file, so they survive restarts.
622
+ pi.registerCommand("footer", {
623
+ description: "Show or change the pi-footer-stats footer: groups, timer mode, theme",
624
+ handler: async (args, ctx) => {
625
+ const notify = (message: string, kind: "info" | "error"): void => {
626
+ ctx.ui.notify(message, kind);
627
+ };
628
+ const parts = String(args ?? "").trim().split(/\s+/).filter(Boolean);
629
+ const [sub, ...rest] = parts;
630
+ const apply = (next: FooterSettings, message: string): void => {
631
+ settings = next;
632
+ writeStateFile(next);
633
+ tuiRef?.requestRender();
634
+ notify(message, "info");
635
+ };
636
+ if (sub === undefined) {
637
+ // No arguments: open the checkbox menu. Space toggles the row under
638
+ // the cursor and applies it immediately, so the footer behind the
639
+ // menu updates live; up/down move; Enter or Escape closes. Nothing
640
+ // is discarded on close because every toggle persisted on the spot.
641
+ await ctx.ui.custom<null>((tui, menuTheme, keybindings, done) => {
642
+ const rows: Array<{ kind: "item"; key: ItemKey } | { kind: "timer" } | { kind: "theme" }> = [
643
+ ...ITEM_KEYS.map((key) => ({ kind: "item", key })),
644
+ { kind: "timer" },
645
+ { kind: "theme" },
646
+ ];
647
+ let cursor = 0;
648
+ const rowLabel = (row: (typeof rows)[number]): string => {
649
+ if (row.kind === "item") return `${settings[row.key] ? "[x]" : "[ ]"} ${ITEM_LABELS[row.key]}`;
650
+ if (row.kind === "timer") return `timer mode: ${settings.timerMode}`;
651
+ return `theme: ${settings.theme}`;
652
+ };
653
+ return {
654
+ render(width: number): string[] {
655
+ return [
656
+ menuTheme.fg("accent", "footer settings"),
657
+ ...rows.map((row, i) =>
658
+ truncateToWidth(`${cursor === i ? "> " : " "}${rowLabel(row)}`, width),
659
+ ),
660
+ truncateToWidth(
661
+ menuTheme.fg("dim", "space toggles, up/down moves, enter or esc closes"),
662
+ width,
663
+ ),
664
+ ];
665
+ },
666
+ handleInput(data: string): void {
667
+ if (data === " ") {
668
+ const row = rows[cursor];
669
+ if (row.kind === "item") {
670
+ apply(
671
+ { ...settings, [row.key]: !settings[row.key] },
672
+ `footer: ${ITEM_LABELS[row.key]} ${settings[row.key] ? "hidden" : "shown"}`,
673
+ );
674
+ } else if (row.kind === "timer") {
675
+ const mode: TimerMode = settings.timerMode === "session" ? "response" : "session";
676
+ apply({ ...settings, timerMode: mode }, `footer: timer mode ${mode}`);
677
+ } else {
678
+ const name: FooterTheme = settings.theme === "default" ? "mono" : "default";
679
+ apply({ ...settings, theme: name }, `footer: theme ${name}`);
680
+ }
681
+ } else if (keybindings.matches(data, "tui.select.up") || data === "\x1b[A") {
682
+ cursor = (cursor + rows.length - 1) % rows.length;
683
+ } else if (keybindings.matches(data, "tui.select.down") || data === "\x1b[B") {
684
+ cursor = (cursor + 1) % rows.length;
685
+ } else if (
686
+ keybindings.matches(data, "tui.select.confirm") ||
687
+ data === "\r" ||
688
+ data === "\n"
689
+ ) {
690
+ done(null);
691
+ } else if (
692
+ keybindings.matches(data, "tui.select.cancel") ||
693
+ data === "\x1b" ||
694
+ data === "\x1b\x1b"
695
+ ) {
696
+ done(null);
697
+ }
698
+ },
699
+ invalidate() {},
700
+ };
701
+ });
702
+ return;
703
+ }
704
+ if (sub === "status") {
705
+ const on = ITEM_KEYS.filter((key) => settings[key]).map((key) => ITEM_LABELS[key]).join(", ");
706
+ notify(
707
+ `footer on: ${on || "none"} | timer: ${settings.timerMode} | theme: ${settings.theme}`,
708
+ "info",
709
+ );
710
+ return;
711
+ }
712
+ if (sub === "hide" || sub === "show") {
713
+ const key = rest[0] as ItemKey | undefined;
714
+ if (key === undefined || !ITEM_KEYS.includes(key)) {
715
+ notify(`usage: /footer ${sub} <${ITEM_KEYS.join("|")}>`, "error");
716
+ return;
717
+ }
718
+ apply(
719
+ { ...settings, [key]: sub === "show" },
720
+ `footer: ${ITEM_LABELS[key]} ${sub === "show" ? "shown" : "hidden"}`,
721
+ );
722
+ return;
723
+ }
724
+ if (sub === "timer") {
725
+ const mode = rest[0] as TimerMode | undefined;
726
+ if (mode === undefined || !TIMER_MODES.includes(mode)) {
727
+ notify(`usage: /footer timer <${TIMER_MODES.join("|")}>`, "error");
728
+ return;
729
+ }
730
+ apply({ ...settings, timerMode: mode }, `footer: timer mode ${mode}`);
731
+ return;
732
+ }
733
+ if (sub === "theme") {
734
+ const name = rest[0] as FooterTheme | undefined;
735
+ if (name === undefined || !FOOTER_THEMES.includes(name)) {
736
+ notify(`usage: /footer theme <${FOOTER_THEMES.join("|")}>`, "error");
737
+ return;
738
+ }
739
+ apply({ ...settings, theme: name }, `footer: theme ${name}`);
740
+ return;
741
+ }
742
+ if (sub === "reset") {
743
+ apply({ ...DEFAULT_SETTINGS }, "footer: reset to defaults");
744
+ return;
745
+ }
746
+ notify("usage: /footer [status|hide|show|timer|theme|reset]", "error");
747
+ },
748
+ });
749
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-footer-stats",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "Custom pi footer: colored session stats, a tokens/second average, and a context-window progress bar",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -119,7 +119,26 @@ const mod = await jiti.import(join(import.meta.dirname, "..", "extensions", "foo
119
119
 
120
120
  // --- test scaffolding ------------------------------------------------------
121
121
 
122
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
122
+ // Controllable clock: tests advance a fake offset instead of sleeping, so the
123
+ // suite runs in ~1s instead of burning real seconds on wall-clock windows.
124
+ const realDateNow = Date.now.bind(Date);
125
+ let clockOffsetMs = 0;
126
+ Date.now = () => realDateNow() + clockOffsetMs;
127
+ const advance = (ms) => {
128
+ clockOffsetMs += ms;
129
+ };
130
+
131
+ // Fail fast: a hung interval or timer must end the suite, not stall CI.
132
+ const WATCHDOG_MS = 20_000;
133
+ const watchdog = setTimeout(() => {
134
+ console.error(`\nFAIL: suite exceeded the ${WATCHDOG_MS / 1000}s watchdog`);
135
+ process.exit(1);
136
+ }, WATCHDOG_MS);
137
+
138
+ // Hermetic agent dir: the suite must never read the developer's real
139
+ // settings or /footer state file.
140
+ const SUITE_AGENT_DIR = mkdtempSync(join(tmpdir(), "pi-footer-suite-"));
141
+ process.env.PI_CODING_AGENT_DIR = SUITE_AGENT_DIR;
123
142
  let failures = 0;
124
143
  const check = (name, cond, detail) => {
125
144
  console.log(`${cond ? "PASS" : "FAIL"}: ${name}${detail ? ` (${detail})` : ""}`);
@@ -138,7 +157,11 @@ const plainTheme = { fg: (_c, t) => t, bold: (t) => t };
138
157
 
139
158
  function makeInstance() {
140
159
  const handlers = {};
141
- mod.default({ on(name, fn) { (handlers[name] ??= []).push(fn); } });
160
+ handlers.commands = {};
161
+ mod.default({
162
+ on(name, fn) { (handlers[name] ??= []).push(fn); },
163
+ registerCommand(name, def) { handlers.commands[name] = def; },
164
+ });
142
165
  return handlers;
143
166
  }
144
167
 
@@ -189,7 +212,7 @@ const rateFrom = (line) => {
189
212
  check("fresh session shows — rate", rateFrom(render()) === "—");
190
213
 
191
214
  h.message_start[0]({ message: { role: "assistant" } });
192
- await sleep(200);
215
+ advance(200);
193
216
  // output=100 INCLUDES reasoning=40; double-counting would yield ~700 tok/s
194
217
  h.message_end[0]({ message: { role: "assistant", usage: { output: 100, reasoning: 40 } } });
195
218
  const rate = parseFloat(rateFrom(render()));
@@ -235,7 +258,7 @@ const rateFrom = (line) => {
235
258
  ]);
236
259
  await h.session_start[0]({}, a.ctx);
237
260
  h.message_start[0]({ message: { role: "assistant" } });
238
- await sleep(50);
261
+ advance(50);
239
262
  h.message_end[0]({ message: { role: "assistant", usage: { output: 500 } } });
240
263
 
241
264
  const b = makeCtx([], { percent: null, tokens: null });
@@ -253,7 +276,7 @@ const rateFrom = (line) => {
253
276
  h.message_end[0]({ message: { role: "assistant", usage: { output: 0 } } }); // zero tokens skipped
254
277
  h.message_start[0]({ message: { role: "assistant" } });
255
278
  h.message_start[0]({ message: { role: "assistant" } }); // aborted start overwritten, no corruption
256
- await sleep(100);
279
+ advance(100);
257
280
  h.message_end[0]({ message: { role: "assistant", usage: { output: 50 } } });
258
281
  const rate = parseFloat(rateFrom(render()));
259
282
  check("zero-token and aborted-start cases safe", Math.abs(rate - 500) / 500 < 0.3, `got ${rate}, expected ~500`);
@@ -265,7 +288,7 @@ const rateFrom = (line) => {
265
288
  const { ctx, render } = makeCtx([]);
266
289
  await h.session_start[0]({}, ctx);
267
290
  h.message_start[0]({ message: { role: "assistant" } });
268
- await sleep(200);
291
+ advance(200);
269
292
  // Wall window ≈200ms would give ~500 tok/s; durationMs=1000 must win → ~100.
270
293
  h.message_end[0]({ message: { role: "assistant", usage: { output: 100 }, durationMs: 1000 } });
271
294
  const rate = parseFloat(rateFrom(render()));
@@ -273,7 +296,7 @@ const rateFrom = (line) => {
273
296
 
274
297
  // Invalid durationMs falls back to the wall window (started ~now → small).
275
298
  h.message_start[0]({ message: { role: "assistant" } });
276
- await sleep(100);
299
+ advance(100);
277
300
  h.message_end[0]({ message: { role: "assistant", usage: { output: 50 }, durationMs: 0 } });
278
301
  const rate2 = parseFloat(rateFrom(render()));
279
302
  check("non-positive durationMs falls back to wall clock", Number.isFinite(rate2) && rate2 > 0, `got ${rate2}`);
@@ -303,7 +326,7 @@ const rateFrom = (line) => {
303
326
  const bad = [Number.NaN, Number.POSITIVE_INFINITY, -1000, "1000", null, undefined];
304
327
  for (const value of bad) {
305
328
  h.message_start[0]({ message: { role: "assistant" } });
306
- await sleep(50);
329
+ advance(50);
307
330
  h.message_end[0]({ message: { role: "assistant", usage: { output: 100 }, durationMs: value } });
308
331
  const rate = parseFloat(rateFrom(render()));
309
332
  check(
@@ -636,5 +659,217 @@ const rateFrom = (line) => {
636
659
  );
637
660
  }
638
661
 
662
+ // --- 20. timer: cumulative working time, frozen while idle ---
663
+ {
664
+ const parseWorking = (line) => {
665
+ const m = line.match(/([⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏·]) (\d+):(\d{2})/);
666
+ return m ? { glyph: m[1], secs: parseInt(m[2], 10) * 60 + parseInt(m[3], 10) } : null;
667
+ };
668
+ const h = makeInstance();
669
+ const { ctx, render } = makeCtx([]);
670
+ await h.session_start[0]({}, ctx);
671
+ const fresh = parseWorking(render());
672
+ check("fresh session timer shows idle glyph at 0:00", fresh?.glyph === "·" && fresh?.secs === 0, JSON.stringify(fresh));
673
+
674
+ h.agent_start[0]({});
675
+ advance(1500);
676
+ const running = parseWorking(render());
677
+ check("run time advances while running", running && running.secs >= 1, JSON.stringify(running));
678
+ check("running glyph is a spinner frame", running && ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"].includes(running.glyph), running?.glyph);
679
+
680
+ h.agent_settled[0]({});
681
+ const settled1 = parseWorking(render());
682
+ check("idle glyph after settle", settled1?.glyph === "·", settled1?.glyph);
683
+ advance(2000);
684
+ const stillIdle = parseWorking(render());
685
+ check("timer frozen while idle", stillIdle && settled1 && stillIdle.secs === settled1.secs, `${settled1?.secs}s vs ${stillIdle?.secs}s`);
686
+
687
+ h.agent_start[0]({});
688
+ advance(1000);
689
+ h.agent_settled[0]({});
690
+ const cumulative = parseWorking(render());
691
+ check("working time accumulates across runs", cumulative && settled1 && cumulative.secs === settled1.secs + 1, `${settled1?.secs}s -> ${cumulative?.secs}s`);
692
+
693
+ // a fresh session resets the timer
694
+ await h.session_shutdown[0]({}, {});
695
+ const h2 = makeInstance();
696
+ const { ctx: ctx2, render: render2 } = makeCtx([]);
697
+ await h2.session_start[0]({}, ctx2);
698
+ const reset = parseWorking(render2());
699
+ check("timer resets on a new session", reset?.glyph === "·" && reset?.secs === 0, JSON.stringify(reset));
700
+ }
701
+
702
+ // --- 21. footerStats settings hide groups ---
703
+ {
704
+ const tmp = mkdtempSync(join(tmpdir(), "pi-agent-test-"));
705
+ const savedEnv = process.env.PI_CODING_AGENT_DIR;
706
+ try {
707
+ const lineWith = async (settingsJson) => {
708
+ writeFileSync(join(tmp, "settings.json"), settingsJson);
709
+ process.env.PI_CODING_AGENT_DIR = tmp;
710
+ const inst = makeInstance();
711
+ const { ctx, render } = makeCtx([]);
712
+ await inst.session_start[0]({}, ctx);
713
+ return render();
714
+ };
715
+ const all = await lineWith(JSON.stringify({}));
716
+ check(
717
+ "default shows every group",
718
+ all.includes("↑0") && all.includes("↺ R0") && all.includes("tok/s") && all.includes("$0.000") && /· 0:00/.test(all) && all.includes("(auto)"),
719
+ );
720
+ const noTokens = await lineWith(JSON.stringify({ footerStats: { input: false, output: false } }));
721
+ check("input+output=false hides the token pair", !noTokens.includes("↑") && !noTokens.includes("↓") && noTokens.includes("↺ R0"));
722
+ const noCache = await lineWith(JSON.stringify({ footerStats: { cacheRead: false, cacheWrite: false, cacheHit: false } }));
723
+ check("all cache items false hides the cache group", !noCache.includes("↺") && !noCache.includes("◎ CH") && noCache.includes("↑0"));
724
+ const noPerf = await lineWith(JSON.stringify({ footerStats: { rate: false, timer: false } }));
725
+ check("rate+timer=false hides the performance pair", !noPerf.includes("tok/s") && !/· 0:00/.test(noPerf) && noPerf.includes("$0.000"));
726
+ const onlyCost = await lineWith(JSON.stringify({ footerStats: { input: false, output: false, cacheRead: false, cacheWrite: false, cacheHit: false, rate: false, timer: false, context: false } }));
727
+ check("only cost visible when everything else is off", onlyCost.includes("$0.000") && !onlyCost.includes("↑") && !onlyCost.includes("▄") && !onlyCost.includes("(auto)"));
728
+ const bad = await lineWith("not json");
729
+ check("unreadable settings -> every group default", bad.includes("↑0") && bad.includes("↺ R0"));
730
+ } finally {
731
+ if (savedEnv === undefined) delete process.env.PI_CODING_AGENT_DIR;
732
+ else process.env.PI_CODING_AGENT_DIR = savedEnv;
733
+ rmSync(tmp, { recursive: true });
734
+ }
735
+ // project settings override user settings
736
+ {
737
+ const proj = mkdtempSync(join(tmpdir(), "pi-proj-test-"));
738
+ const agent = mkdtempSync(join(tmpdir(), "pi-agent-test2-"));
739
+ const savedEnv2 = process.env.PI_CODING_AGENT_DIR;
740
+ try {
741
+ mkdirSync(join(proj, ".pi"), { recursive: true });
742
+ writeFileSync(join(proj, ".pi", "settings.json"), JSON.stringify({ footerStats: { input: false } }));
743
+ writeFileSync(join(agent, "settings.json"), JSON.stringify({ footerStats: { input: true } }));
744
+ process.env.PI_CODING_AGENT_DIR = agent;
745
+ const inst = makeInstance();
746
+ const { ctx, render } = makeCtx([], { cwd: proj });
747
+ await inst.session_start[0]({}, ctx);
748
+ check("project footerStats overrides user", !render().includes("↑"));
749
+ } finally {
750
+ if (savedEnv2 === undefined) delete process.env.PI_CODING_AGENT_DIR;
751
+ else process.env.PI_CODING_AGENT_DIR = savedEnv2;
752
+ rmSync(proj, { recursive: true });
753
+ rmSync(agent, { recursive: true });
754
+ }
755
+ }
756
+ }
757
+ // --- 22. /footer command: toggles, timer mode, theme, persisted state ---
758
+ {
759
+ const tmp = mkdtempSync(join(tmpdir(), "pi-agent-test-"));
760
+ const savedEnv = process.env.PI_CODING_AGENT_DIR;
761
+ process.env.PI_CODING_AGENT_DIR = tmp;
762
+ const notes = [];
763
+ try {
764
+ const inst = makeInstance();
765
+ const { ctx, render, renderLines } = makeCtx([]);
766
+ await inst.session_start[0]({}, ctx);
767
+ const cmdCtx = {
768
+ ui: { notify: (msg, kind) => notes.push({ msg, kind }), custom: async () => null },
769
+ };
770
+ const cmd = inst.commands.footer;
771
+ check("footer command registered", typeof cmd?.handler === "function");
772
+
773
+ await cmd.handler("status", cmdCtx);
774
+ check(
775
+ "status lists groups, timer, theme",
776
+ notes.at(-1).msg.includes("timer: session") && notes.at(-1).msg.includes("theme: default"),
777
+ notes.at(-1).msg,
778
+ );
779
+ const notesBefore = notes.length;
780
+ await cmd.handler(undefined, cmdCtx);
781
+ check("bare /footer with cancel shows nothing", notes.length === notesBefore);
782
+
783
+ await cmd.handler("hide cost", cmdCtx);
784
+ check("hide cost drops the $ segment", !render().includes("$0.000"), render());
785
+ const state = JSON.parse(readFileSync(join(tmp, "footer-stats-state.json"), "utf8"));
786
+ check("state file persists the change", state.footerStats.cost === false, JSON.stringify(state.footerStats));
787
+
788
+ await cmd.handler("show cost", cmdCtx);
789
+ check("show cost brings it back", render().includes("$0.000"));
790
+
791
+ await cmd.handler("hide cacheWrite", cmdCtx);
792
+ check("hide cacheWrite drops only the write segment", !render().includes("✎") && render().includes("↺ R0"));
793
+
794
+ await cmd.handler("bogus", cmdCtx);
795
+ check(
796
+ "unknown subcommand errors",
797
+ notes.at(-1).kind === "error" && notes.at(-1).msg.includes("usage"),
798
+ notes.at(-1).msg,
799
+ );
800
+
801
+ // timer modes: two runs of ~1s each
802
+ inst.agent_start[0]({});
803
+ advance(1000);
804
+ inst.agent_settled[0]({});
805
+ inst.agent_start[0]({});
806
+ advance(1000);
807
+ inst.agent_settled[0]({});
808
+ check("session mode accumulates", render().includes("· 0:02"), render().match(/· [\d:]+/)?.[0]);
809
+ await cmd.handler("timer response", cmdCtx);
810
+ check("response mode shows last run only", render().includes("· 0:01"), render().match(/· [\d:]+/)?.[0]);
811
+
812
+ // theme mono collapses the palette
813
+ await cmd.handler("theme mono", cmdCtx);
814
+ const monoLine = renderLines(130, theme)[1];
815
+ check("mono theme uses no accent color", !monoLine.includes("\x1b[35m"), monoLine.slice(0, 40));
816
+
817
+ // a fresh instance reads the persisted state
818
+ const inst2 = makeInstance();
819
+ const { ctx: ctx2, render: render2 } = makeCtx([]);
820
+ await inst2.session_start[0]({}, ctx2);
821
+ check("state survives a restart", !render2().includes("✎") && render2().includes("↺ R0") && render2().includes("$0.000"));
822
+
823
+ await cmd.handler("reset", cmdCtx);
824
+ check("reset restores defaults", render().includes("↑0") && notes.at(-1).kind === "info");
825
+
826
+ // checkbox menu via ctx.ui.custom
827
+ let menuComp = null;
828
+ let menuClosed = null;
829
+ const keyStub = {
830
+ matches: (data, id) =>
831
+ (data === "\r" && id === "tui.select.confirm") ||
832
+ (data === "\x1b" && id === "tui.select.cancel") ||
833
+ (data === "\x1b[A" && id === "tui.select.up") ||
834
+ (data === "\x1b[B" && id === "tui.select.down"),
835
+ };
836
+ cmdCtx.ui.custom = (factory) => {
837
+ menuClosed = new Promise((resolve) => {
838
+ menuComp = factory({ requestRender() {} }, theme, keyStub, (v) => resolve(v));
839
+ });
840
+ return menuClosed;
841
+ };
842
+ const menuPromise = cmd.handler("", cmdCtx);
843
+ const menuLines = menuComp.render(80).join("\n");
844
+ check(
845
+ "menu renders checkbox rows",
846
+ menuLines.includes("[x] ↑ input") && menuLines.includes("[ ] ✎ cache write") === false && menuLines.includes("timer mode: session"),
847
+ menuLines.slice(0, 80),
848
+ );
849
+ menuComp.handleInput(" ");
850
+ check("space toggles input immediately", !render().includes("↑"));
851
+ check("checkbox reflects the new state", menuComp.render(80).join("\n").includes("[ ] ↑ input"));
852
+ menuComp.handleInput("\x1b[B");
853
+ menuComp.handleInput(" ");
854
+ check("second row toggles output", !render().includes("↓"));
855
+ for (let i = 0; i < 8; i++) menuComp.handleInput("\x1b[B");
856
+ menuComp.handleInput(" ");
857
+ const midState = JSON.parse(readFileSync(join(tmp, "footer-stats-state.json"), "utf8"));
858
+ check("timer row cycles the mode", midState.footerStats.timerMode === "response", midState.footerStats.timerMode);
859
+ menuComp.handleInput("\r");
860
+ check("enter closes the menu", (await menuClosed) === null);
861
+ await menuPromise;
862
+ await cmd.handler("reset", cmdCtx);
863
+ check("reset after menu restores defaults", render().includes("↑0") && render().includes("↺ R0"));
864
+
865
+ } finally {
866
+ if (savedEnv === undefined) delete process.env.PI_CODING_AGENT_DIR;
867
+ else process.env.PI_CODING_AGENT_DIR = savedEnv;
868
+ rmSync(tmp, { recursive: true });
869
+ }
870
+ }
871
+
872
+ clearTimeout(watchdog);
873
+ rmSync(SUITE_AGENT_DIR, { recursive: true, force: true });
639
874
  console.log(failures === 0 ? "\nALL TESTS PASSED" : `\n${failures} FAILURE(S)`);
640
875
  process.exit(failures === 0 ? 0 : 1);