@aeondave/pi-theme-1337 0.5.1 → 0.6.0

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/src/index.ts CHANGED
@@ -1,1195 +1,1264 @@
1
- /**
2
- * pi-theme-1337 — a redesign for Pi's terminal UI.
3
- *
4
- * Two parts, the way the Pi docs split it:
5
- * - bundled THEMES (`themes/*.json`): palettes on one 51-token contract, the
6
- * default being a yellow-green phosphor with amber accents;
7
- * - an EXTENSION (this file): it re-houses Pi's editor in a centered rounded
8
- * panel (see `editor.ts`) that carries the only chrome worth keeping — the
9
- * model identity in its top border, a prompt sigil, the working spinner,
10
- * the workspace, usage, cost estimate and the subscription quota a provider
11
- * reports (plus the active persona) inside
12
- * — restyles the built-in tool rows, folds settled exploration, and marks
13
- * where each run ended. The default footer and spinner row are hidden. A
14
- * keyboard shortcut copies the input buffer as clean text (the logical
15
- * buffer, free of frame glyphs and wraps).
16
- *
17
- * All on documented primitives: `setTheme`, `setEditorComponent` (with
18
- * `getEditorComponent`, so another extension's editor is never erased), `setFooter`,
19
- * `setWorkingVisible`, `setHiddenThinkingLabel`, `registerShortcut`, `setTitle`,
20
- * and `appendEntry` + `registerEntryRenderer` for the end-of-run summary row.
21
- * Everything is restored on `/theme-1337` off or shutdown. TUI-only; a no-op elsewhere.
22
- */
23
-
24
- import { readFileSync, statSync } from "node:fs";
25
- import { basename, dirname, isAbsolute, resolve as resolvePath } from "node:path";
26
- import { copyToClipboard, getLanguageFromPath, highlightCode, keyHint, type ExtensionAPI, type ExtensionContext, type ReadonlyFooterDataProvider } from "@earendil-works/pi-coding-agent";
27
- import {
28
- Box,
29
- Container,
30
- Text,
31
- getCapabilities,
32
- getCellDimensions,
33
- getImageDimensions,
34
- Image,
35
- type ImageDimensions,
36
- type ImageProtocol,
37
- truncateToWidth as piTruncateToWidth,
38
- type TUI,
39
- visibleWidth as piVisibleWidth,
40
- } from "@earendil-works/pi-tui";
41
- import type { KeyId } from "@earendil-works/pi-tui";
42
- import { avatarImageColumns, layoutAvatarRows, type AvatarFrames, type AvatarState, parseAvatar, selectAvatar } from "./avatar.ts";
43
- import { OSC11_RESET, osc11Set, resolveBackground, resolveBackgroundHex } from "./background.ts";
44
- import { activityEnabled, autoThemeEnabled, backgroundEnv, chooseStartupTheme, copyShortcut, groupsEnabled, hiddenThinkingLabel, isDisabled, maxBoxWidth, polishEnabled, quotaEnabled, resetConfigCache, summaryEnabled, titleEnabled } from "./config.ts";
45
- import { makeFramedEditorFactory, type EditorFactory } from "./editor.ts";
46
- import { costTotal, formatCost, formatRunDelta, parseBackgroundStatus, parsePersonaCost, type ContextUsageLike } from "./format.ts";
47
- import { CODEX_RATE_LIMITS_EVENT, CODEX_STREAM_API, EMPTY_QUOTA, nextQuota, nextQuotaEvent, nextQuotaMessage, quotaView, type QuotaState, type QuotaView } from "./quota.ts";
48
- import { forceFullRedraw, installOutOfBandRedrawGuard, type RedrawWritable } from "./redraw-guard.ts";
49
- import { createRunCollector, createRunSummaryRow, RUN_SUMMARY_TYPE } from "./run-summary.ts";
50
- import { DEFAULT_SPINNER, parseSpinner, spinnerFrame, type SpinnerProfile } from "./spinner.ts";
51
- import { defaultTitle, terminalTitle, type TitlePhase } from "./terminal-title.ts";
52
- import { useTerminalMetrics } from "./width.ts";
53
- import { createActivityTracker, createRunClock, currentActivity } from "./tool-activity.ts";
54
- import { createFlatToolView, createSwitchableToolView } from "./tool-adapter.ts";
55
- import { createToolRunRegistry, type ToolRunRegistry } from "./tool-groups.ts";
56
- import { isPolishedTool } from "./tool-lexicon.ts";
57
- import { createToolView } from "./tool-view.ts";
58
-
59
- // Measure with the renderer's own ruler, never a copy of it. A row measured one
60
- // column short pads past the terminal edge, wraps, and desynchronizes pi's
61
- // differential renderer — which is how stale border rows survive a repaint (pi
62
- // throws outright on an over-wide line). The mirror in width.ts stays only as
63
- // the dependency-free fallback the pure unit tests run on.
64
- // `stripAnsi` is deliberately absent: pi-tui no longer exports a sequence stripper, and the
65
- // built-in one is a pure string transform with no terminal state to get wrong.
66
- useTerminalMetrics({
67
- visibleWidth: piVisibleWidth,
68
- truncateToWidth: (text, max, ellipsis = "…") => piTruncateToWidth(text, max, ellipsis),
69
- });
70
-
71
- const AVATAR_WIDGET_KEY = "pi1337-avatar";
72
- const AVATAR_COLS = 18; // max width of the avatar image, in terminal columns
73
- const AVATAR_ROWS = 10; // max height of the avatar image, in terminal rows
74
- const MAX_AVATAR_IMAGE_BYTES = 8 * 1024 * 1024;
75
- const MIME_BY_EXT: Record<string, string> = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp" };
76
-
77
- /** The bits of pi-1337 config a theme file may carry (read via its `sourcePath`). */
78
- interface ThemeConfig {
79
- pageBg?: string; // export.pageBg — the palette's `void`
80
- background?: string; // pi1337.background — "on"/"auto"/a hex
81
- avatar?: AvatarFrames; // pi1337.avatar — parsed frames (PNG or ASCII)
82
- avatarAlign?: "left" | "center"; // pi1337.avatar.align — horizontal placement of the avatar widget
83
- avatarPlacement?: "aboveEditor" | "belowEditor"; // pi1337.avatar.placement — which side of the editor
84
- spinner?: SpinnerProfile;
85
- }
86
-
87
- interface LoadedAvatarImage {
88
- component: Image;
89
- dimensions: ImageDimensions;
90
- }
91
-
92
- interface RenderedAvatarAscii {
93
- lines: string[];
94
- }
95
-
96
- const PERSONA_STATUS_KEY = "persona"; // published by pi-persona
97
- const COST_STATUS_KEY = "persona-cost"; // pending background-leg cost estimate published by pi-persona
98
- const BACKGROUND_STATUS_KEY = "persona-background"; // "agents=3 timers=1": work pi-persona still runs in the background
99
- const MIN_MARGIN = 2;
100
-
101
- /** Any extension's editor factory, as the host hands it back (its root export omits the named type). */
102
- type HostEditorFactory = NonNullable<ReturnType<ExtensionContext["ui"]["getEditorComponent"]>>;
103
-
104
- export default function pi1337(pi: ExtensionAPI) {
105
- // A fresh factory (startup or `/reload`) re-reads config.json, so an edit to
106
- // the file takes effect without restarting Pi. The loader bumps its cache
107
- // generation on reload, so this module is re-evaluated anyway; resetting
108
- // explicitly keeps that guarantee from depending on loader internals.
109
- resetConfigCache();
110
- if (isDisabled()) return;
111
-
112
- let enabled = true;
113
- let working = false;
114
- let runActive = false;
115
- let waitingForUser = false;
116
- let compacting = false;
117
- let spin = 0;
118
- let timer: ReturnType<typeof setInterval> | undefined;
119
- let activeTui: TUI | undefined;
120
- let disposeOutOfBandRedrawGuard: (() => void) | undefined;
121
- let activeEditor: { getText(): string } | undefined;
122
- let footerData: ReadonlyFooterDataProvider | undefined;
123
- let branchUnsub: (() => void) | undefined; // git-branch change subscription (re-render the status row)
124
- let themeApplied = false;
125
- let previousTheme: string | undefined;
126
- let appliedTheme: string | undefined; // the palette we actually switched to (undefined = no switch to undo)
127
- let chromeActive = false; // true only while the framed editor + footer are installed (tui mode)
128
- let bgPainted = false; // true only while we hold an OSC 11 tint that clear() must reset
129
- let themeConfig: ThemeConfig = {}; // pi-1337 config read from the active theme file at apply()
130
- let themeDir: string | undefined; // dir of the active theme file, to resolve relative avatar images
131
- let themeConfigSource: string | undefined; // sourcePath the config was read from (detects a live /settings switch)
132
- let themeRefreshQueued = false;
133
- let themeRefreshGeneration = 0;
134
- let themeRefreshContext: ExtensionContext | undefined;
135
- let avatarShown = false; // whether the avatar widget is currently installed
136
- let avatarState: AvatarState = "idle"; // task-lifecycle state the avatar reflects
137
- let turnErrored = false; // a tool/compaction errored → show the error frame when the run settles
138
- const avatarImageCache = new Map<string, LoadedAvatarImage | null>(); // resolved path → decoded component (null = unrenderable)
139
- let cachedSessionName: string | undefined;
140
- let cachedContextUsage: ContextUsageLike | undefined;
141
- // The session-entry sum is walked only on agent/turn/session events; the
142
- // persona-cost status is compared on each footer pass and added on top.
143
- let cachedEntriesCost = 0;
144
- let cachedPersonaCost: string | undefined; // raw persona-cost status the totals were built from
145
- let cachedTotal = 0;
146
- let cachedCost = "";
147
- let runBaseline: number | undefined; // the total when the run began; undefined = no run to measure
148
- let cachedRunDelta = "";
149
- let costRenderQueued = false;
150
- let cachedThinkingLevel: string | undefined; // host's level, cached off the 90 ms render path
151
- // An assistant message has ended since the last refresh: Pi persists it right
152
- // after its message_end listeners return, so the next tool call can show it.
153
- let statsStale = false;
154
- // The editor slot is shared: only a factory of ours is ours to remove, and
155
- // what stood there before us comes back on toggle-off.
156
- let ourEditorFactory: EditorFactory | undefined; // the factory apply() installed
157
- let previousEditorFactory: HostEditorFactory | undefined; // never one of ours
158
- const ownEditorFactories = new WeakSet<object>(); // every factory this instance made
159
- // Read once, like the other settings: /reload applies a change.
160
- const maxWidth = maxBoxWidth();
161
- // Both presentation toggles are read once, like polish: /reload applies a change.
162
- const activityTracker = activityEnabled() ? createActivityTracker() : undefined; // names a long-running tool in the status row
163
- // The same slot's run clock ("Working… 45s"), under the same toggle. Like the
164
- // cost baseline it is the run's, not the chrome's: it survives a toggle, and a
165
- // run that began while the redesign was off never gets one.
166
- const runClock = activityTracker ? createRunClock() : undefined;
167
- let toolRuns: ToolRunRegistry | undefined; // folds settled exploration rows (polished lane only)
168
- const adapterTools = new Set<string>(); // tool names whose rows our adapter renders
169
- // Read once, like the other toggles: /reload applies a change.
170
- const summaryOn = summaryEnabled();
171
- const titleOn = titleEnabled(); // off: setTitle is never called at all
172
- // Fed from live events whatever the toggle, so a run toggled on halfway is
173
- // still summarized whole; the title only needs its outcome.
174
- const runCollector = summaryOn || titleOn ? createRunCollector() : undefined;
175
- let finished: "done" | "failed" | undefined; // the title's after-run state, until the next run or user input
176
- let titleSession: string | undefined; // survives clear(): the default title is written after it
177
- let titleCwdBase = "";
178
- let lastTitle: string | undefined; // the title the terminal holds as far as we know (dedupe)
179
- let titleLabel: string | undefined; // the activity label the title was last decided with
180
- let titleBackground: string | undefined; // the raw persona-background status the title was last decided with
181
- let titleRefreshQueued = false;
182
- let titleRefreshGeneration = 0;
183
- // Read once, like the other toggles: /reload applies a change. Off registers
184
- // no response or stream handler at all.
185
- const quotaOn = quotaEnabled();
186
- // What providers have said about the subscription, per provider. It is session
187
- // state like the run baseline: recorded while the redesign is toggled off, so
188
- // apply() finds it current, and kept across a model switch away and back.
189
- let quotaState: QuotaState = EMPTY_QUOTA;
190
- /** The model the turn in flight was started with: whose response the next headers are. */
191
- let quotaRequestModel: { provider?: string; api?: string } | undefined;
192
- let cachedQuota: QuotaView | undefined; // the current model's view; the render path reads only this
193
- let cachedQuotaKey = "";
194
- // Another extension installed its editor over ours: the footer and Pi's working
195
- // row went back to the host until the next apply() (see the footer's render).
196
- let displaced = false;
197
- let displacementQueued = false;
198
- let displacementGeneration = 0;
199
-
200
- // Registered at load, not in apply(): on a session switch Pi paints the
201
- // history before session_start, and a row whose renderer returns nothing
202
- // then is never added. Gated on the toggle for the same reason; apply() and
203
- // clear() invalidate the transcript, which rebuilds every entry row.
204
- const expandHint = () => keyHint("app.tools.expand", "to expand"); // the host's own wording
205
- if (summaryOn) {
206
- pi.registerEntryRenderer(RUN_SUMMARY_TYPE, (entry, options, theme) => {
207
- if (!enabled) return undefined;
208
- // Pi 1.5.2 passes no outputPad to entry renderers; use one if a host ever does.
209
- const pad = (options as { outputPad?: unknown }).outputPad;
210
- return createRunSummaryRow(entry.data, options.expanded, theme, typeof pad === "number" ? pad : 1, expandHint);
211
- });
212
- }
213
-
214
- // Pi keeps a row's renderer descriptor for its entire lifetime. Install a
215
- // stable adapter once, including for history drawn before session_start;
216
- // changing only the resolver on toggle would leave existing rows unchanged.
217
- if (polishEnabled()) {
218
- const toolStateKeys = new Map<string, symbol>();
219
- // Folding rides the polished lane: one registry decides which rows fold,
220
- // fed by the same tool and message events the host builds its rows from.
221
- if (groupsEnabled()) toolRuns = createToolRunRegistry();
222
- const groups = toolRuns;
223
- pi.registerToolRenderer((name, next) => {
224
- const baseline = next();
225
- const foreign = !isPolishedTool(name) && (baseline?.renderCall || baseline?.renderResult) ? baseline : undefined;
226
- // Purpose-built extension renderers (persona, MCP, etc.) keep their content.
227
- // One that frames itself, or leaves a slot to the host's private fallback
228
- // formatter (which no adapter lane can recompose byte for byte), is not ours.
229
- if (foreign && (foreign.renderShell === "self" || !foreign.renderCall || !foreign.renderResult)) return foreign;
230
- let stateKey = toolStateKeys.get(name);
231
- if (!stateKey) {
232
- stateKey = Symbol(`pi1337-tool-row:${name}`);
233
- toolStateKeys.set(name, stateKey);
234
- }
235
- // The rest are drawn in our flat shell while the redesign is active and in the
236
- // host's box otherwise. They stay out of adapterTools: such a row never folds,
237
- // and its tool_execution_start closes the exploration run above it.
238
- if (foreign) {
239
- return createFlatToolView(foreign, () => chromeActive, { Box, Container, Text, toolName: name, expandHint,
240
- imagesSupported: () => getCapabilities().images !== null }, stateKey);
241
- }
242
- adapterTools.add(name);
243
- return createSwitchableToolView(createToolView(name, expandHint, {
244
- highlightCode: (code, path) => {
245
- const language = getLanguageFromPath(path);
246
- return language ? highlightCode(code, language) : code.split("\n");
247
- },
248
- }), baseline,
249
- () => chromeActive, { Box, Container, Text, toolName: name, expandHint,
250
- imagesSupported: () => getCapabilities().images !== null, groups }, stateKey);
251
- });
252
- }
253
-
254
- // Read the theme's page background and optional adjacent .pi1337 sidecar.
255
- // Keep reading a legacy root pi1337 block when no sidecar exists, so custom
256
- // themes created before the strict Pi 1.0 schema migration still work.
257
- const readThemeConfig = (ctx: ExtensionContext): ThemeConfig => {
258
- const path = ctx.ui.theme.sourcePath;
259
- if (!path) return {};
260
- try {
261
- const json = JSON.parse(readFileSync(path, "utf8")) as {
262
- export?: { pageBg?: unknown };
263
- pi1337?: { background?: unknown; avatar?: unknown; spinner?: unknown };
264
- };
265
- let extras = json.pi1337;
266
- try {
267
- const sidecarPath = /\.json$/i.test(path) ? path.replace(/\.json$/i, ".pi1337") : `${path}.pi1337`;
268
- extras = JSON.parse(readFileSync(sidecarPath, "utf8")) as typeof extras;
269
- } catch (error) {
270
- // A missing sidecar permits older custom themes; a malformed one does
271
- // not silently activate stale metadata from the theme JSON.
272
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") extras = undefined;
273
- }
274
- const avatar = extras?.avatar;
275
- const avatarObj = avatar && typeof avatar === "object" && !Array.isArray(avatar) ? (avatar as { align?: unknown; placement?: unknown }) : undefined;
276
- return {
277
- spinner: parseSpinner(extras?.spinner),
278
- pageBg: typeof json.export?.pageBg === "string" ? json.export.pageBg : undefined,
279
- background: typeof extras?.background === "string" ? extras.background : undefined,
280
- avatar: parseAvatar(avatar),
281
- avatarAlign: avatarObj?.align === "center" ? "center" : "left",
282
- // Default below the editor: a kitty-image widget placed *above* the editor
283
- // disturbs the box's redraw beneath it (reserved image rows + cursor math),
284
- // leaving the input frame corrupted until a resize forces a full repaint.
285
- avatarPlacement: avatarObj?.placement === "aboveEditor" ? "aboveEditor" : "belowEditor",
286
- };
287
- } catch {
288
- return {}; // unreadable/foreign theme file → no tint, no avatar
289
- }
290
- };
291
-
292
- // Opt-in tint of the terminal window background so the empty margins around the
293
- // frame match the palette instead of the terminal's own color. Enabled by env
294
- // `PI_1337_BG` OR the theme's `pi1337.background` (env wins). Written once per
295
- // install; always reversed in clear() (unpaintBackground/OSC 111).
296
- const paintBackground = (): void => {
297
- if (bgPainted || !enabled || !chromeActive || !activeTui) return;
298
- const bg = resolveBackground(backgroundEnv(), themeConfig.background);
299
- if (!bg.enabled) return;
300
- const hex = resolveBackgroundHex(bg.hex, themeConfig.pageBg);
301
- if (!hex) return;
302
- try {
303
- activeTui.terminal.write(osc11Set(hex));
304
- bgPainted = true;
305
- } catch {
306
- /* cosmetic — a terminal that rejects OSC 11 just keeps its background */
307
- }
308
- };
309
-
310
- const unpaintBackground = (): void => {
311
- if (!bgPainted) return;
312
- bgPainted = false;
313
- try {
314
- activeTui?.terminal.write(OSC11_RESET); // reset to the terminal's configured default
315
- } catch {
316
- /* cosmetic */
317
- }
318
- };
319
-
320
- // Re-tint after a theme change: drop the old color, then paint the new palette's.
321
- const repaintBackground = (): void => {
322
- unpaintBackground();
323
- paintBackground();
324
- };
325
-
326
- // Theme-driven ASCII avatar (e.g. a Fallout vault-boy). Shown in a widget next to
327
- // the editor (below by default) and swapped on the agent's working state; only present when the
328
- // active theme ships `pi1337.avatar`. Colored with the palette accent here (the
329
- // pure avatar module stays color-free). Removed in clear() — fully reversible.
330
- // A PNG frame is delegated to pi-tui's Image component, which owns the protocol-
331
- // specific cursor/row accounting and re-renders when main/fullscreen capability
332
- // changes. Bytes are loaded once per path; terminals without image support use
333
- // the configured ASCII fallback. Custom images are capped before reading.
334
- const loadAvatarImage = (imagePath: string): LoadedAvatarImage | undefined => {
335
- const abs = isAbsolute(imagePath) ? imagePath : themeDir ? resolvePath(themeDir, imagePath) : imagePath;
336
- const cached = avatarImageCache.get(abs);
337
- if (cached !== undefined) return cached ?? undefined;
338
- let result: LoadedAvatarImage | null = null;
339
- try {
340
- const stat = statSync(abs);
341
- if (!stat.isFile() || stat.size <= 0 || stat.size > MAX_AVATAR_IMAGE_BYTES) throw new Error("avatar image outside size limit");
342
- const b64 = readFileSync(abs).toString("base64");
343
- const ext = abs.split(".").pop()?.toLowerCase() ?? "";
344
- const mime = MIME_BY_EXT[ext] ?? "image/png";
345
- const dims = getImageDimensions(b64, mime);
346
- if (dims) {
347
- result = {
348
- component: new Image(b64, mime, { fallbackColor: (text) => text }, { maxWidthCells: AVATAR_COLS, maxHeightCells: AVATAR_ROWS, filename: abs }, dims),
349
- dimensions: dims,
350
- };
351
- }
352
- } catch {
353
- result = null; // unreadable/invalid/oversized file → ASCII fallback
354
- }
355
- avatarImageCache.set(abs, result);
356
- return result ?? undefined;
357
- };
358
-
359
- // Pi's Image can return either a protocol payload or a textual fallback.
360
- // Center actual images by their reserved cell width, but measure/clip fallback
361
- // text just like ASCII; never truncate an image escape sequence in half.
362
- const avatarWidget = (image: LoadedAvatarImage | undefined, ascii: RenderedAvatarAscii | undefined) => () => {
363
- let imageProtocol: ImageProtocol | undefined;
364
- return {
365
- invalidate() {
366
- imageProtocol = undefined;
367
- image?.component.invalidate();
368
- },
369
- render(width: number): string[] {
370
- const liveProtocol = getCapabilities().images;
371
- if (liveProtocol !== imageProtocol) {
372
- imageProtocol = liveProtocol;
373
- image?.component.invalidate();
374
- }
375
- const imageUsable = image !== undefined && imageProtocol !== null && getCapabilities().images === imageProtocol;
376
- const lines = imageUsable ? image.component.render(width) : ascii?.lines;
377
- if (!lines) return [];
378
- const maxImageCols = Math.min(AVATAR_COLS, Math.max(1, width - 2));
379
- const imageColumns = imageUsable
380
- ? avatarImageColumns(image.dimensions, getCellDimensions(), maxImageCols, AVATAR_ROWS, imageProtocol)
381
- : undefined;
382
- return layoutAvatarRows(lines, width, { align: themeConfig.avatarAlign, imageColumns });
383
- },
384
- };
385
- };
386
-
387
- const updateAvatar = (ctx: ExtensionContext): void => {
388
- if (!ctx.hasUI || ctx.mode !== "tui") return;
389
- const source = enabled && chromeActive ? selectAvatar(themeConfig.avatar, avatarState) : undefined;
390
- let image: LoadedAvatarImage | undefined;
391
- let ascii: RenderedAvatarAscii | undefined;
392
- if (source) {
393
- image = source.image ? loadAvatarImage(source.image) : undefined; // Pi Image handles Kitty/iTerm cursor accounting
394
- if (source.lines) {
395
- ascii = {
396
- lines: source.lines.map((l) => ctx.ui.theme.fg("accent", l)),
397
- };
398
- }
399
- }
400
- if (!image && !ascii) {
401
- if (avatarShown) {
402
- ctx.ui.setWidget(AVATAR_WIDGET_KEY, undefined);
403
- avatarShown = false;
404
- }
405
- return;
406
- }
407
- ctx.ui.setWidget(AVATAR_WIDGET_KEY, avatarWidget(image, ascii), {
408
- placement: themeConfig.avatarPlacement ?? "belowEditor",
409
- });
410
- avatarShown = true;
411
- };
412
-
413
- // Pi exposes no theme-change event, so a live `/settings` switch would otherwise
414
- // keep the old palette's tint + avatar. Detect it by the theme's sourcePath and
415
- // re-read: cheap string compare per call, real work only when it actually changed.
416
- const refreshThemeConfig = (ctx: ExtensionContext, force = false): void => {
417
- if (!ctx.hasUI || ctx.mode !== "tui") return;
418
- const src = ctx.ui.theme.sourcePath;
419
- if (!force && src === themeConfigSource) return;
420
- themeConfigSource = src;
421
- avatarImageCache.clear(); // a live palette switch must not retain every custom image ever seen
422
- const previousSpinner = themeConfig.spinner ?? DEFAULT_SPINNER;
423
- themeConfig = readThemeConfig(ctx);
424
- const nextSpinner = themeConfig.spinner ?? DEFAULT_SPINNER;
425
- if (previousSpinner !== nextSpinner) {
426
- spin = 0;
427
- if (working && chromeActive && !waitingForUser && !displaced) startSpinner();
428
- else stopSpinner();
429
- }
430
- themeDir = src ? dirname(src) : undefined;
431
- if (!force) {
432
- repaintBackground(); // the palette's void (tint) may have changed
433
- updateAvatar(ctx); // swap to the new theme's avatar (or remove it)
434
- }
435
- };
436
-
437
- const stopSpinner = () => {
438
- if (timer) {
439
- clearInterval(timer);
440
- timer = undefined;
441
- }
442
- };
443
-
444
- const requestRender = () => {
445
- activeTui?.requestRender();
446
- };
447
-
448
- const requestFullRender = (): void => {
449
- forceFullRedraw(activeTui);
450
- };
451
-
452
- const cancelThemeConfigRefresh = (): void => {
453
- themeRefreshQueued = false;
454
- themeRefreshContext = undefined;
455
- themeRefreshGeneration++;
456
- };
457
-
458
- // A theme switch has no Pi event. The empty footer may detect `sourcePath`
459
- // during render, but filesystem reads, OSC writes and widget mutation must run
460
- // only after that render has unwound. A generation token makes clear()/reload
461
- // invalidate an already queued microtask without retaining a stale context.
462
- const scheduleThemeConfigRefresh = (ctx: ExtensionContext): void => {
463
- themeRefreshContext = ctx;
464
- if (themeRefreshQueued) return;
465
- themeRefreshQueued = true;
466
- const generation = ++themeRefreshGeneration;
467
- queueMicrotask(() => {
468
- if (!themeRefreshQueued || generation !== themeRefreshGeneration) return;
469
- themeRefreshQueued = false;
470
- const next = themeRefreshContext;
471
- themeRefreshContext = undefined;
472
- if (!next || !enabled || !chromeActive) return;
473
- refreshThemeConfig(next);
474
- requestFullRender();
475
- });
476
- };
477
-
478
- // The terminal title follows the run: decided on the events that change it,
479
- // written only when the text changes, and Pi's own title whenever idle or off.
480
- // The events that define a phase (run start/end, prompt start/end) write it
481
- // even unchanged: Pi's own refresh (on win32, after its update check) may
482
- // have overwritten it unseen, and the dedupe would otherwise keep it lost.
483
- const titlePhase = (): TitlePhase => {
484
- if (!enabled || !chromeActive) return "idle";
485
- if (waitingForUser) return "waiting";
486
- if (runActive || compacting) return "running";
487
- return finished ?? "idle";
488
- };
489
-
490
- // Cheap enough for the render path: a phase check and one map lookup.
491
- const desiredTitleLabel = (): string | undefined =>
492
- titlePhase() === "running" ? activityTracker?.current(Date.now())?.label : undefined;
493
-
494
- // After a clean run the title depends on what pi-persona still has running:
495
- // its raw status, read only in that phase. One map lookup, so the footer can
496
- // compare it on every pass; only the parsed counts ever reach the title.
497
- const desiredTitleBackground = (): string | undefined =>
498
- titlePhase() === "done" ? footerData?.getExtensionStatuses().get(BACKGROUND_STATUS_KEY) || undefined : undefined;
499
-
500
- const updateTitle = (ctx: ExtensionContext, phaseChange = false): void => {
501
- if (!titleOn || !ctx.hasUI || ctx.mode !== "tui") return;
502
- titleLabel = desiredTitleLabel();
503
- titleBackground = desiredTitleBackground();
504
- const next = terminalTitle({
505
- phase: titlePhase(), label: titleLabel, background: parseBackgroundStatus(titleBackground),
506
- session: titleSession, cwdBase: titleCwdBase,
507
- });
508
- // A burst of calls must not rewrite the tab; toggled off, nothing re-asserts.
509
- if (next === lastTitle && !(phaseChange && enabled && chromeActive)) return;
510
- lastTitle = next;
511
- try {
512
- ctx.ui.setTitle(next);
513
- } catch {
514
- /* cosmetic */
515
- }
516
- };
517
-
518
- const cancelTitleRefresh = (): void => {
519
- titleRefreshQueued = false;
520
- titleRefreshGeneration++;
521
- };
522
-
523
- // The activity label appears only after its grace period, with no event to
524
- // announce it, and pi-persona's background status changes with none either.
525
- // The footer notices the change during render; the terminal write waits
526
- // until that render has unwound, like a theme switch.
527
- const scheduleTitleRefresh = (ctx: ExtensionContext): void => {
528
- if (titleRefreshQueued) return;
529
- titleRefreshQueued = true;
530
- const generation = ++titleRefreshGeneration;
531
- queueMicrotask(() => {
532
- if (!titleRefreshQueued || generation !== titleRefreshGeneration) return;
533
- titleRefreshQueued = false;
534
- if (enabled && chromeActive) updateTitle(ctx);
535
- });
536
- };
537
-
538
- // Labels from the cached sums only: never a session walk, so it is safe on any path.
539
- const recomputeCost = (): void => {
540
- cachedTotal = costTotal([], cachedEntriesCost) + parsePersonaCost(cachedPersonaCost);
541
- cachedCost = formatCost(cachedTotal);
542
- cachedRunDelta = runBaseline === undefined ? "" : formatRunDelta(cachedTotal - runBaseline);
543
- };
544
-
545
- // pi-persona republishes persona-cost when a background leg settles, possibly
546
- // while the parent is idle and no agent/turn event will follow. The footer
547
- // renders after the editor in a pass, so a change repaints once more after it.
548
- const syncPersonaCost = (data: ReadonlyFooterDataProvider): void => {
549
- const status = data.getExtensionStatuses().get(COST_STATUS_KEY);
550
- if (status === cachedPersonaCost) return;
551
- cachedPersonaCost = status;
552
- recomputeCost();
553
- if (costRenderQueued) return;
554
- costRenderQueued = true;
555
- queueMicrotask(() => {
556
- costRenderQueued = false;
557
- if (enabled && chromeActive) requestRender();
558
- });
559
- };
560
-
561
- const refreshSessionStats = (ctx: ExtensionContext): void => {
562
- cachedSessionName = ctx.sessionManager.getSessionName();
563
- cachedContextUsage = ctx.getContextUsage();
564
- cachedEntriesCost = costTotal(ctx.sessionManager.getEntries());
565
- cachedPersonaCost = footerData?.getExtensionStatuses().get(COST_STATUS_KEY);
566
- recomputeCost();
567
- // A model switch clamps the level before model_select fires, so every
568
- // refresh point re-reads it; thinking_level_select covers changes in between.
569
- cachedThinkingLevel = ctx.thinkingLevel;
570
- };
571
-
572
- // The quota view belongs to the current model's provider and is rebuilt only
573
- // on events: a response, a message's end, a model or session change, a run or
574
- // turn boundary. A window's expiry is therefore noticed at the next of those,
575
- // never by a timer, and the 90 ms render path reads the cached view alone.
576
- // Like every quota handler it does nothing outside the TUI and cannot throw.
577
- const refreshQuota = (ctx: ExtensionContext): void => {
578
- if (!quotaOn) return;
579
- try {
580
- if (!ctx.hasUI || ctx.mode !== "tui") return;
581
- const model = ctx.model as { provider?: string; api?: string } | undefined;
582
- const next = quotaView(quotaState, { provider: model?.provider, api: model?.api }, Date.now());
583
- // Everything the row paints from: the three forms, and which figures have aged.
584
- const key = next ? `${next.limit}|${next.two}|${next.one}|${next.windows.map((window) => (window.aged ? "a" : "f")).join("")}` : "";
585
- if (key === cachedQuotaKey) return;
586
- cachedQuotaKey = key;
587
- cachedQuota = next;
588
- if (enabled && chromeActive) requestRender();
589
- } catch {
590
- /* cosmetic: the row keeps the last view */
591
- }
592
- };
593
-
594
- // Third-party diagnostics occasionally bypass Pi's UI and write directly to
595
- // stderr. Those bytes must remain untouched, but they move the real terminal
596
- // cursor behind pi-tui's differential renderer. While our frame is active,
597
- // observe that one out-of-band channel and force a clean repaint after the
598
- // current write burst. Never wrap stdout: pi-tui itself renders there.
599
- const startOutOfBandRedrawGuard = (): void => {
600
- disposeOutOfBandRedrawGuard ??= installOutOfBandRedrawGuard(
601
- process.stderr as unknown as RedrawWritable,
602
- requestFullRender,
603
- );
604
- };
605
-
606
- const stopOutOfBandRedrawGuard = (): void => {
607
- disposeOutOfBandRedrawGuard?.();
608
- disposeOutOfBandRedrawGuard = undefined;
609
- };
610
-
611
- // Single source of motion: always restart from a clean timer so we never stack intervals.
612
- const startSpinner = () => {
613
- stopSpinner();
614
- const profile = themeConfig.spinner ?? DEFAULT_SPINNER;
615
- timer = setInterval(() => {
616
- spin = (spin + 1) % profile.frames.length;
617
- requestRender();
618
- }, profile.intervalMs);
619
- };
620
-
621
- // Pi may retry, compact, or continue after agent_end. Only agent_settled ends
622
- // the run. Prompts pause animation without losing the underlying activity;
623
- // manual compaction can also be active while there is no agent run at all.
624
- const syncActivity = (ctx: ExtensionContext, phaseChange = false): void => {
625
- updateTitle(ctx, phaseChange); // off or toggled off, this settles on Pi's own title
626
- if (!enabled || !chromeActive) return;
627
- working = (runActive || compacting) && !waitingForUser;
628
- // Displaced, nothing of ours shows the spinner: Pi's working row does.
629
- if (working && !displaced) {
630
- if (!timer) startSpinner();
631
- } else stopSpinner();
632
- avatarState = compacting ? "confused" : waitingForUser ? "idle" : working ? "working" : turnErrored ? "error" : "idle";
633
- updateAvatar(ctx);
634
- requestRender();
635
- };
636
-
637
- function applyTheme(ctx: ExtensionContext): void {
638
- if (!autoThemeEnabled() || themeApplied) return;
639
- const current = ctx.ui.theme.name;
640
- // Env pin > Pi's current bundled choice > config-file fallback > light theme
641
- // kept > green. A palette selected via /settings must survive reload even when
642
- // config.json contains an older startup preference; setTheme persists any target to Pi.
643
- const target = chooseStartupTheme(current, ctx.ui.theme.appearance);
644
- if (current === target) {
645
- themeApplied = true;
646
- appliedTheme = undefined; // nothing switched, nothing to undo
647
- return;
648
- }
649
- const result = ctx.ui.setTheme(target);
650
- themeApplied = result.success;
651
- if (result.success) {
652
- previousTheme = current; // only remember the prior theme once the switch actually took
653
- appliedTheme = target;
654
- } else {
655
- try {
656
- ctx.ui.notify(`pi-theme-1337: could not load theme "${target}" (${result.error ?? "unknown"})`, "warning");
657
- } catch {
658
- /* cosmetic */
659
- }
660
- }
661
- }
662
-
663
- function restoreTheme(ctx: ExtensionContext): void {
664
- if (!themeApplied) return;
665
- themeApplied = false;
666
- // Only revert if the live theme is still the one we switched to. If the user
667
- // (or another extension) changed themes while pi-1337 was active — including
668
- // picking another bundled palette — leave their newer choice untouched.
669
- if (previousTheme && appliedTheme && previousTheme !== appliedTheme && ctx.ui.theme.name === appliedTheme) {
670
- ctx.ui.setTheme(previousTheme);
671
- }
672
- previousTheme = undefined;
673
- appliedTheme = undefined;
674
- }
675
-
676
- // A host (or a test double) without getEditorComponent cannot say who holds
677
- // the editor slot: `known: false` keeps the behaviour from before it existed.
678
- const currentEditorFactory = (ctx: ExtensionContext): { known: boolean; factory?: HostEditorFactory } => {
679
- const ui = ctx.ui as { getEditorComponent?: () => HostEditorFactory | undefined };
680
- if (typeof ui.getEditorComponent !== "function") return { known: false };
681
- try {
682
- return { known: true, factory: ui.getEditorComponent() };
683
- } catch {
684
- return { known: false };
685
- }
686
- };
687
-
688
- // The framed editor is the only place the redesign shows the workspace, usage,
689
- // cost and spinner. When another extension installs its editor after ours,
690
- // that frame is no longer mounted, yet apply() has emptied the footer and
691
- // hidden Pi's working row: the user would be left with none of it. The
692
- // footer's render notices (one identity compare per UI pass) and this runs
693
- // once that render has unwound: the footer and the working row go back to the
694
- // host and our spinner stops. Tool rows, the theme, the title and the summary
695
- // stay ours, and the frame is taken again only by the next apply() — a toggle
696
- // or a session_start — never by itself.
697
- const editorDisplaced = (ctx: ExtensionContext): boolean => {
698
- if (displaced || !ourEditorFactory) return false;
699
- const installed = currentEditorFactory(ctx);
700
- return installed.known && installed.factory !== ourEditorFactory;
701
- };
702
-
703
- const cancelDisplacementCheck = (): void => {
704
- displacementQueued = false;
705
- displacementGeneration++;
706
- };
707
-
708
- const scheduleDisplacementCheck = (ctx: ExtensionContext): void => {
709
- if (displacementQueued) return;
710
- displacementQueued = true;
711
- const generation = ++displacementGeneration;
712
- queueMicrotask(() => {
713
- if (!displacementQueued || generation !== displacementGeneration) return;
714
- displacementQueued = false;
715
- // Checked again: the slot may have come back to us since the render that saw it.
716
- if (!enabled || !chromeActive || !editorDisplaced(ctx)) return;
717
- displaced = true;
718
- stopSpinner();
719
- try {
720
- ctx.ui.setFooter(undefined);
721
- ctx.ui.setWorkingVisible(true);
722
- } catch {
723
- /* cosmetic */
724
- }
725
- requestRender();
726
- });
727
- };
728
-
729
- function apply(ctx: ExtensionContext): void {
730
- if (!ctx.hasUI || ctx.mode !== "tui") return;
731
- spin = 0;
732
- displaced = false; // apply() takes the frame, the footer and the working row again
733
- cancelDisplacementCheck();
734
- applyTheme(ctx);
735
-
736
- // Read the palette's pi-1337 config now that the (possibly switched) theme is live.
737
- refreshThemeConfig(ctx, true);
738
- refreshSessionStats(ctx);
739
- refreshQuota(ctx); // recorded while toggled off too: the row opens on current figures
740
- ctx.ui.setWorkingVisible(false); // working moves into the frame's spinner
741
- ctx.ui.setHiddenThinkingLabel(hiddenThinkingLabel());
742
-
743
- // Empty footer — the editor frame carries the status. The factory also
744
- // captures `footerData` so the editor can read the persona status from it.
745
- ctx.ui.setFooter((tui, _theme, data) => {
746
- footerData = data;
747
- activeTui = tui;
748
- paintBackground(); // tui is now bound; tint the window if enabled by env or theme
749
- // The footer re-renders on every UI pass — including a live /settings theme
750
- // switch, which fires no event — detect it here, then apply it after render.
751
- const renderFooter = () => {
752
- if (ctx.ui.theme.sourcePath !== themeConfigSource) scheduleThemeConfigRefresh(ctx);
753
- if (titleOn && (desiredTitleLabel() !== titleLabel || desiredTitleBackground() !== titleBackground)) scheduleTitleRefresh(ctx);
754
- // Another extension's editor over ours has no event either; acted on after this render.
755
- if (editorDisplaced(ctx)) scheduleDisplacementCheck(ctx);
756
- syncPersonaCost(data);
757
- return [] as string[];
758
- };
759
- // Branch switches happen outside any agent activity; without this the
760
- // status row would show the old branch until the next unrelated render.
761
- branchUnsub ??= data.onBranchChange(() => requestRender());
762
- return { invalidate() {}, render: renderFooter };
763
- });
764
-
765
- // Whatever holds the slot now comes back on toggle-off, unless it is ours
766
- // (a second apply() without a clear() between: session_start in one session).
767
- const installedEditor = currentEditorFactory(ctx);
768
- if (!installedEditor.known || !installedEditor.factory) previousEditorFactory = undefined;
769
- else if (!ownEditorFactories.has(installedEditor.factory)) previousEditorFactory = installedEditor.factory;
770
- ourEditorFactory =
771
- makeFramedEditorFactory({
772
- ctx,
773
- getPersona: () => footerData?.getExtensionStatuses().get(PERSONA_STATUS_KEY) || undefined,
774
- getGitBranch: () => footerData?.getGitBranch(),
775
- getSessionName: () => cachedSessionName,
776
- getContextUsage: () => cachedContextUsage,
777
- getCost: () => cachedCost,
778
- getRunDelta: () => cachedRunDelta,
779
- getQuota: () => cachedQuota,
780
- getThinkingLevel: () => cachedThinkingLevel,
781
- isWorking: () => working,
782
- isWaitingForUser: () => waitingForUser,
783
- // Revealed by the spinner's own repaint once a call outlasts its grace
784
- // period, or the run its own; the editor only consults it while working
785
- // (so never during a blocking prompt). Compaction is Pi's indicator's to
786
- // announce: the run clock stays out of it.
787
- getActivity: activityTracker && (() => currentActivity(activityTracker, compacting ? undefined : runClock, Date.now())),
788
- spinnerFrame: () => spinnerFrame(themeConfig.spinner ?? DEFAULT_SPINNER, spin),
789
- spinnerRows: () => (themeConfig.spinner ?? DEFAULT_SPINNER).frameRows(spin),
790
- spinnerColor: () => (themeConfig.spinner ?? DEFAULT_SPINNER).color,
791
- spinnerHeight: () => (themeConfig.spinner ?? DEFAULT_SPINNER).height,
792
- spinnerColumns: () => (themeConfig.spinner ?? DEFAULT_SPINNER).columns,
793
- bindTui: (tui) => {
794
- activeTui = tui;
795
- paintBackground(); // editor may bind the tui before the footer factory runs
796
- },
797
- bindEditor: (editor) => {
798
- activeEditor = editor;
799
- },
800
- maxWidth,
801
- minMargin: MIN_MARGIN,
802
- });
803
- ownEditorFactories.add(ourEditorFactory);
804
- ctx.ui.setEditorComponent(ourEditorFactory);
805
-
806
- chromeActive = true;
807
- startOutOfBandRedrawGuard();
808
- paintBackground(); // covers a re-enable where the footer factory already ran (activeTui bound)
809
- syncActivity(ctx); // restore the current run/prompt/compaction state on toggle-on
810
- // Invalidate existing transcript rows: a full redraw alone does not rebuild
811
- // component caches, including history created before session_start.
812
- activeTui?.invalidate();
813
- // Also repairs any raw startup diagnostic emitted before the guard was bound.
814
- requestFullRender();
815
- }
816
-
817
- function clear(ctx: ExtensionContext, shutdown = false): void {
818
- stopOutOfBandRedrawGuard();
819
- cancelThemeConfigRefresh();
820
- cancelDisplacementCheck();
821
- displaced = false;
822
- working = false; // reset spinner state so a re-enable never shows a frozen frame
823
- spin = 0;
824
- chromeActive = false;
825
- avatarState = "idle";
826
- turnErrored = false;
827
- finished = undefined;
828
- cancelTitleRefresh();
829
- stopSpinner();
830
- if (ctx.hasUI && ctx.mode === "tui") {
831
- unpaintBackground(); // reset the OSC 11 tint before we drop the tui handle
832
- // Pi never resets the title itself: leave its own behind, once, if ours is showing.
833
- updateTitle(ctx);
834
- updateAvatar(ctx); // chromeActive=false → removes the avatar widget
835
- // The editor is ours to give back only while our factory still holds the
836
- // slot: one another extension installed after us stays where it is.
837
- const installedEditor = currentEditorFactory(ctx);
838
- if (installedEditor.known ? ourEditorFactory !== undefined && installedEditor.factory === ourEditorFactory : true) {
839
- // Toggle-off hands the slot back to the editor that held it before us.
840
- // Shutdown never builds another extension's editor: the slot is emptied.
841
- let restored = false;
842
- if (!shutdown && previousEditorFactory) {
843
- try {
844
- ctx.ui.setEditorComponent(previousEditorFactory);
845
- restored = true;
846
- } catch {
847
- /* its factory failed: Pi's own editor instead */
848
- }
849
- }
850
- if (!restored) ctx.ui.setEditorComponent(undefined);
851
- }
852
- ctx.ui.setFooter(undefined);
853
- ctx.ui.setWorkingVisible(true);
854
- ctx.ui.setHiddenThinkingLabel();
855
- // Restore original tool callbacks/shells before dropping the TUI handle.
856
- activeTui?.invalidate();
857
- requestFullRender();
858
- }
859
- themeConfig = {};
860
- themeDir = undefined;
861
- themeConfigSource = undefined;
862
- avatarImageCache.clear();
863
- cachedSessionName = undefined;
864
- cachedContextUsage = undefined;
865
- cachedEntriesCost = 0;
866
- cachedPersonaCost = undefined;
867
- cachedTotal = 0;
868
- cachedCost = "";
869
- cachedRunDelta = ""; // the baseline is session state and survives a toggle
870
- cachedThinkingLevel = undefined;
871
- activityTracker?.clear();
872
- toolRuns?.reset();
873
- branchUnsub?.();
874
- branchUnsub = undefined;
875
- footerData = undefined;
876
- activeTui = undefined;
877
- activeEditor = undefined;
878
- ourEditorFactory = undefined;
879
- previousEditorFactory = undefined;
880
- if (ctx.hasUI) restoreTheme(ctx);
881
- }
882
-
883
- pi.on("session_start", (_event, ctx) => {
884
- runActive = !ctx.isIdle();
885
- waitingForUser = false;
886
- compacting = false;
887
- activityTracker?.clear();
888
- toolRuns?.reset(); // rows rebuilt from history stay unfolded: no events replay for them
889
- runBaseline = undefined; // a new, resumed or forked session has no run to measure yet
890
- runClock?.stop(); // nor a start to count from, even when Pi is mid-run
891
- runCollector?.reset();
892
- finished = undefined;
893
- titleSession = ctx.sessionManager.getSessionName();
894
- titleCwdBase = basename(ctx.cwd);
895
- // Pi writes exactly this right after binding extensions: nothing to write now.
896
- lastTitle = defaultTitle(titleSession, titleCwdBase);
897
- refreshQuota(ctx); // the session's model may be another provider's; apply() re-reads it when on
898
- if (enabled) apply(ctx);
899
- });
900
-
901
- // Subscription quota, from what the provider already sends with each response.
902
- // Both handlers are synchronous and constant-time, never throw (pi-ai awaits
903
- // the first before it reads the stream) and do nothing outside the TUI. They
904
- // keep recording while the redesign is toggled off, like prompt and compaction
905
- // state, so apply() finds current figures. No request is ever made for this.
906
- if (quotaOn) {
907
- pi.on("after_provider_response", (event, ctx) => {
908
- try {
909
- if (!ctx.hasUI || ctx.mode !== "tui") return;
910
- // The event names no provider. Inside a turn the response answers the
911
- // model that turn started with — the user may have switched since;
912
- // outside one (cache warming) it is the current model's.
913
- const model = quotaRequestModel ?? (ctx.model as { provider?: string; api?: string } | undefined);
914
- quotaState = nextQuota(quotaState, { status: event.status, headers: event.headers, api: model?.api, provider: model?.provider }, Date.now());
915
- refreshQuota(ctx);
916
- } catch {
917
- /* cosmetic: a response must never fail over the status row */
918
- }
919
- });
920
- // Fires for every raw stream chunk of every provider: two comparisons, then out.
921
- pi.on("provider_stream_event", (event, ctx) => {
922
- if (event.api !== CODEX_STREAM_API) return;
923
- try {
924
- if ((event.data as { type?: unknown } | null | undefined)?.type !== CODEX_RATE_LIMITS_EVENT) return;
925
- if (!ctx.hasUI || ctx.mode !== "tui") return;
926
- quotaState = nextQuotaEvent(quotaState, event, Date.now());
927
- refreshQuota(ctx);
928
- } catch {
929
- /* cosmetic */
930
- }
931
- });
932
- }
933
-
934
- pi.on("agent_start", (_event, ctx) => {
935
- // Pi re-enters its loop inside one run (an auto-retry, a mid-run compaction,
936
- // drained steering or follow-ups), emitting agent_start each time; only the
937
- // first after a settle begins the run, and the rest keep accumulating.
938
- const opening = !runActive;
939
- runActive = true;
940
- turnErrored = false; // fresh turn: clear any lingering error frame
941
- activityTracker?.clear(); // a call that never reported its end must not name the next run
942
- refreshQuota(ctx); // a window whose reset has passed leaves here, not on a timer
943
- if (opening) {
944
- finished = undefined;
945
- runCollector?.start(Date.now());
946
- }
947
- if (enabled && chromeActive) refreshSessionStats(ctx);
948
- if (opening) {
949
- // The delta measures this run: it starts at zero and replaces the last one.
950
- // Started while off, the run has no baseline, never the previous run's.
951
- runBaseline = enabled && chromeActive ? cachedTotal : undefined;
952
- if (enabled && chromeActive) recomputeCost();
953
- // The clock follows the same rule: started while off, the run has none.
954
- if (enabled && chromeActive) runClock?.start(Date.now());
955
- else runClock?.stop();
956
- }
957
- syncActivity(ctx, opening);
958
- });
959
-
960
- pi.on("agent_end", (_event, ctx) => {
961
- refreshQuota(ctx);
962
- if (!enabled || !chromeActive) return;
963
- refreshSessionStats(ctx);
964
- syncActivity(ctx);
965
- });
966
-
967
- pi.on("agent_settled", (event, ctx) => {
968
- runActive = false;
969
- compacting = false;
970
- activityTracker?.clear();
971
- runClock?.stop();
972
- toolRuns?.closeAll(); // nothing more can join the last run
973
- refreshQuota(ctx);
974
- if (enabled && chromeActive) refreshSessionStats(ctx);
975
- // An interrupted run goes straight back to Pi's own title.
976
- const outcome = runCollector?.outcome(event.aborted);
977
- finished = outcome === "done" || outcome === "failed" ? outcome : undefined;
978
- // What pi-persona still runs in the background, as of now: the row must not
979
- // say "Done" over it. Read-only, and absent without pi-persona.
980
- const stillRunning = parseBackgroundStatus(footerData?.getExtensionStatuses().get(BACKGROUND_STATUS_KEY));
981
- // The status row's own run delta, taken after the refresh above.
982
- const summary = runCollector?.finish(Date.now(), event.aborted, runBaseline === undefined ? 0 : cachedTotal - runBaseline, stillRunning);
983
- // The one deliberate session-file write: a custom entry, which never
984
- // becomes model input. Synchronous in this handler, never from a timer, and
985
- // it touches no message queue, so pi-persona's follow-ups are undisturbed.
986
- if (summary && summaryOn && enabled && chromeActive && ctx.hasUI && ctx.mode === "tui") {
987
- try {
988
- pi.appendEntry(RUN_SUMMARY_TYPE, summary);
989
- } catch {
990
- /* cosmetic: a failed write must not stall settlement */
991
- }
992
- }
993
- syncActivity(ctx, true);
994
- });
995
-
996
- // Submitting input ends the after-run title, as a new run would.
997
- if (titleOn) {
998
- pi.on("input", (_event, ctx) => {
999
- if (!finished) return;
1000
- finished = undefined;
1001
- updateTitle(ctx);
1002
- });
1003
- }
1004
-
1005
- pi.on("ui_prompt_start", (_event, ctx) => {
1006
- waitingForUser = true;
1007
- syncActivity(ctx, true);
1008
- });
1009
-
1010
- pi.on("ui_prompt_end", (_event, ctx) => {
1011
- waitingForUser = false;
1012
- syncActivity(ctx, true);
1013
- });
1014
-
1015
- // Context compaction reads as the model "thinking hard" — show the confused frame
1016
- // for its duration, then return to the working frame the turn resumes in.
1017
- pi.on("session_before_compact", (_event, ctx) => {
1018
- toolRuns?.closeAll(); // Pi paints a compaction row (or its failure) below the rows so far
1019
- compacting = true;
1020
- syncActivity(ctx);
1021
- });
1022
-
1023
- pi.on("session_compact", (_event, ctx) => {
1024
- toolRuns?.reset(); // the chat is rebuilt from the retained entries, unfolded
1025
- compacting = false;
1026
- if (enabled && chromeActive) refreshSessionStats(ctx);
1027
- syncActivity(ctx);
1028
- });
1029
-
1030
- pi.on("session_compact_failed", (event, ctx) => {
1031
- compacting = false;
1032
- if (!event.aborted) turnErrored = true;
1033
- syncActivity(ctx);
1034
- });
1035
-
1036
- // The summary's model time: each turn runs from here to its assistant message's end.
1037
- pi.on("turn_start", (_event, ctx) => {
1038
- runCollector?.turnStart(Date.now());
1039
- const model = ctx.model as { provider?: string; api?: string } | undefined;
1040
- quotaRequestModel = model ? { provider: model.provider, api: model.api } : undefined;
1041
- refreshQuota(ctx);
1042
- });
1043
-
1044
- pi.on("turn_end", (event, ctx) => {
1045
- runCollector?.turnEnd(event.message);
1046
- quotaRequestModel = undefined;
1047
- refreshQuota(ctx);
1048
- if (!enabled || !chromeActive) return;
1049
- refreshSessionStats(ctx);
1050
- requestRender();
1051
- });
1052
-
1053
- pi.on("session_tree", (_event, ctx) => {
1054
- // The host is about to rebuild the chat from the new branch: a fold's tally
1055
- // row may not be on it, so rebuilt rows start unfolded.
1056
- toolRuns?.reset();
1057
- refreshQuota(ctx); // the branch may have been written by another provider's model
1058
- if (!enabled || !chromeActive) return;
1059
- refreshSessionStats(ctx);
1060
- requestRender();
1061
- });
1062
-
1063
- pi.on("session_info_changed", (event, ctx) => {
1064
- titleSession = event.name;
1065
- // Pi rewrote its own title just before this handler: re-apply ours over it.
1066
- lastTitle = defaultTitle(titleSession, titleCwdBase);
1067
- updateTitle(ctx);
1068
- if (!enabled || !chromeActive) return;
1069
- cachedSessionName = event.name;
1070
- requestRender();
1071
- });
1072
-
1073
- pi.on("model_select", (_event, ctx) => {
1074
- // The state is per provider: switching away hides its figures, switching back finds them.
1075
- refreshQuota(ctx);
1076
- if (!enabled || !chromeActive) return;
1077
- refreshSessionStats(ctx);
1078
- requestRender();
1079
- });
1080
-
1081
- pi.on("thinking_level_select", (event) => {
1082
- if (!enabled || !chromeActive) return;
1083
- cachedThinkingLevel = event.level;
1084
- requestRender();
1085
- });
1086
-
1087
- pi.on("tool_execution_start", (event, ctx) => {
1088
- // The end event carries no arguments: the summary keeps what it needs from here.
1089
- runCollector?.toolStart(event.toolCallId, event.toolName, event.args, ctx.cwd);
1090
- if (!enabled) return;
1091
- // Nested codemode calls are shown inside their parent's row, never as rows
1092
- // of their own: they feed neither the label nor the runs.
1093
- if (!event.parentToolCallId) {
1094
- // The response that launched this call is in the session by now: show its
1095
- // tokens and spend while the call runs, not the figures from before it.
1096
- // Once per assistant message; the spinner's repaint carries it.
1097
- if (statsStale && chromeActive) {
1098
- statsStale = false;
1099
- refreshSessionStats(ctx);
1100
- }
1101
- activityTracker?.onStart(event.toolCallId, event.toolName, event.args, Date.now());
1102
- toolRuns?.onToolStart(event.toolCallId, event.toolName,
1103
- { args: event.args, cwd: ctx.cwd, rendersHere: adapterTools.has(event.toolName) });
1104
- }
1105
- });
1106
-
1107
- pi.on("tool_execution_end", (event) => {
1108
- // Nested calls count too, and only live: their results are not persisted.
1109
- runCollector?.toolEnd(event.toolCallId, event.toolName, event.result, event.isError, !!event.parentToolCallId);
1110
- if (!enabled) return;
1111
- if (event.isError) turnErrored = true; // remembered until agent_settled shows the error frame
1112
- // The fold registry is settled by the row itself, once it shows the result.
1113
- if (!event.parentToolCallId) activityTracker?.onEnd(event.toolCallId);
1114
- });
1115
-
1116
- // Whatever paints a transcript row ends the run above it. A streaming assistant
1117
- // message is empty at its start, so the update is what catches the first thinking
1118
- // or text the moment it appears; start covers user and custom messages, end the
1119
- // providers that do not stream. The registry returns at once while no run is open.
1120
- const closeRunOnPaintedMessage = (event: { message: unknown }): void => {
1121
- if (enabled) toolRuns?.onMessage(event.message);
1122
- };
1123
- pi.on("message_start", closeRunOnPaintedMessage);
1124
- pi.on("message_update", (event) => {
1125
- // The summary's thinking time: only the stream's thinking_start/end are read.
1126
- runCollector?.streamEvent(event.assistantMessageEvent, Date.now());
1127
- closeRunOnPaintedMessage(event);
1128
- });
1129
- pi.on("message_end", (event, ctx) => {
1130
- // An assistant message's end closes its turn's model interval and carries its usage.
1131
- runCollector?.messageEnd(event.message, Date.now());
1132
- // Not refreshed here: Pi appends the message to the session after this returns.
1133
- if ((event.message as { role?: unknown } | undefined)?.role === "assistant") {
1134
- statsStale = true;
1135
- // A usage-limit error is the only quota signal some routes give; any other
1136
- // ending of that provider's assistant message clears it.
1137
- if (quotaOn) {
1138
- try {
1139
- if (ctx.hasUI && ctx.mode === "tui") {
1140
- quotaState = nextQuotaMessage(quotaState, event.message, (ctx.model as { provider?: string } | undefined)?.provider, Date.now());
1141
- refreshQuota(ctx);
1142
- }
1143
- } catch {
1144
- /* cosmetic */
1145
- }
1146
- }
1147
- }
1148
- closeRunOnPaintedMessage(event);
1149
- });
1150
-
1151
- pi.on("session_shutdown", (_event, ctx) => {
1152
- runActive = false;
1153
- waitingForUser = false;
1154
- compacting = false;
1155
- runClock?.stop();
1156
- clear(ctx, true);
1157
- });
1158
-
1159
- // The toggle is namespaced separately from the bundled `1337` palette, which
1160
- // remains available in /settings.
1161
- pi.registerCommand("theme-1337", {
1162
- description: "Toggle the pi-theme-1337 redesign (theme + framed editor)",
1163
- handler: async (_args, ctx) => {
1164
- enabled = !enabled;
1165
- if (enabled) apply(ctx);
1166
- else clear(ctx);
1167
- try {
1168
- ctx.ui.notify(`pi-theme-1337 ${enabled ? "on" : "off"}`, "info");
1169
- } catch {
1170
- /* cosmetic */
1171
- }
1172
- },
1173
- });
1174
-
1175
- // Clean-copy escape hatch: native terminal selection grabs the rendered cells
1176
- // (frame `│`, left padding, a newline per visual row), so it cannot yield the
1177
- // raw input. This shortcut copies the editor's logical buffer verbatim instead.
1178
- const copyKey = copyShortcut();
1179
- if (copyKey) {
1180
- pi.registerShortcut(copyKey as KeyId, {
1181
- description: "pi-theme-1337: copy the input buffer as clean text (no frame glyphs)",
1182
- handler: async (ctx) => {
1183
- if (!enabled) return;
1184
- const text = activeEditor?.getText() ?? "";
1185
- if (!text) return;
1186
- try {
1187
- await copyToClipboard(text);
1188
- ctx.ui.notify("pi-theme-1337: input copied", "info");
1189
- } catch {
1190
- /* cosmetic */
1191
- }
1192
- },
1193
- });
1194
- }
1195
- }
1
+ /**
2
+ * pi-theme-1337 — a redesign for Pi's terminal UI.
3
+ *
4
+ * Two parts, the way the Pi docs split it:
5
+ * - bundled THEMES (`themes/*.json`): palettes on one 51-token contract, the
6
+ * default being a yellow-green phosphor with amber accents;
7
+ * - an EXTENSION (this file): it re-houses Pi's editor in a centered rounded
8
+ * panel (see `editor.ts`) that carries the only chrome worth keeping — the
9
+ * model identity in its top border, a prompt sigil, the working spinner,
10
+ * the workspace, usage, cost estimate and the subscription quota a provider
11
+ * reports (plus the active persona) inside
12
+ * — restyles the built-in tool rows, folds settled exploration, and marks
13
+ * where each run ended. The default footer and spinner row are hidden. A
14
+ * keyboard shortcut copies the input buffer as clean text (the logical
15
+ * buffer, free of frame glyphs and wraps).
16
+ *
17
+ * All on documented primitives: `setTheme`, `setEditorComponent` (with
18
+ * `getEditorComponent`, so another extension's editor is never erased), `setFooter`,
19
+ * `setWorkingVisible`, `setHiddenThinkingLabel`, `registerShortcut`, `setTitle`,
20
+ * and `appendEntry` + `registerEntryRenderer` for the end-of-run summary row.
21
+ * Everything is restored on `/theme-1337` off or shutdown. TUI-only; a no-op elsewhere.
22
+ */
23
+
24
+ import { readFileSync, statSync } from "node:fs";
25
+ import { basename, dirname, isAbsolute, resolve as resolvePath } from "node:path";
26
+ import { copyToClipboard, getLanguageFromPath, highlightCode, keyHint, type ExtensionAPI, type ExtensionContext, type ReadonlyFooterDataProvider } from "@earendil-works/pi-coding-agent";
27
+ import {
28
+ Box,
29
+ Container,
30
+ Text,
31
+ getCapabilities,
32
+ getCellDimensions,
33
+ getImageDimensions,
34
+ Image,
35
+ type ImageDimensions,
36
+ type ImageProtocol,
37
+ truncateToWidth as piTruncateToWidth,
38
+ type TUI,
39
+ visibleWidth as piVisibleWidth,
40
+ } from "@earendil-works/pi-tui";
41
+ import type { KeyId } from "@earendil-works/pi-tui";
42
+ import { avatarImageColumns, layoutAvatarRows, type AvatarFrames, type AvatarState, parseAvatar, selectAvatar } from "./avatar.ts";
43
+ import { OSC11_RESET, osc11Set, resolveBackground, resolveBackgroundHex } from "./background.ts";
44
+ import { activityEnabled, autoThemeEnabled, backgroundEnv, chooseStartupTheme, copyShortcut, draftTokensEnabled, gitStatusEnabled, groupsEnabled, headerEnabled, hiddenThinkingLabel, isDisabled, maxBoxWidth, polishEnabled, quotaEnabled, resetConfigCache, statusStyle, summaryEnabled, titleEnabled } from "./config.ts";
45
+ import { makeFramedEditorFactory, type EditorFactory } from "./editor.ts";
46
+ import { costTotal, formatCost, formatRunDelta, parseBackgroundStatus, parsePersonaCost, type ContextUsageLike } from "./format.ts";
47
+ import { CODEX_RATE_LIMITS_EVENT, CODEX_STREAM_API, EMPTY_QUOTA, nextQuota, nextQuotaEvent, nextQuotaMessage, quotaView, type QuotaState, type QuotaView } from "./quota.ts";
48
+ import { forceFullRedraw, installOutOfBandRedrawGuard, type RedrawWritable } from "./redraw-guard.ts";
49
+ import { createRunCollector, createRunSummaryRow, RUN_SUMMARY_TYPE } from "./run-summary.ts";
50
+ import { DEFAULT_SPINNER, parseSpinner, spinnerFrame, type SpinnerProfile } from "./spinner.ts";
51
+ import { defaultTitle, terminalTitle, type TitlePhase } from "./terminal-title.ts";
52
+ import { useTerminalMetrics } from "./width.ts";
53
+ import { createActivityTracker, createRunClock, currentActivity } from "./tool-activity.ts";
54
+ import { createFlatToolView, createSwitchableToolView } from "./tool-adapter.ts";
55
+ import { createToolRunRegistry, type ToolRunRegistry } from "./tool-groups.ts";
56
+ import { isPolishedTool } from "./tool-lexicon.ts";
57
+ import { createToolView } from "./tool-view.ts";
58
+ import { createGitStatusCache } from "./git-status-cache.ts";
59
+ import { createGitStatusReader } from "./git-status-reader.ts";
60
+ import { createHeaderController } from "./header-controller.ts";
61
+
62
+ // Measure with the renderer's own ruler, never a copy of it. A row measured one
63
+ // column short pads past the terminal edge, wraps, and desynchronizes pi's
64
+ // differential renderer — which is how stale border rows survive a repaint (pi
65
+ // throws outright on an over-wide line). The mirror in width.ts stays only as
66
+ // the dependency-free fallback the pure unit tests run on.
67
+ // `stripAnsi` is deliberately absent: pi-tui no longer exports a sequence stripper, and the
68
+ // built-in one is a pure string transform with no terminal state to get wrong.
69
+ useTerminalMetrics({
70
+ visibleWidth: piVisibleWidth,
71
+ truncateToWidth: (text, max, ellipsis = "…") => piTruncateToWidth(text, max, ellipsis),
72
+ });
73
+
74
+ const AVATAR_WIDGET_KEY = "pi1337-avatar";
75
+ const AVATAR_COLS = 18; // max width of the avatar image, in terminal columns
76
+ const AVATAR_ROWS = 10; // max height of the avatar image, in terminal rows
77
+ const MAX_AVATAR_IMAGE_BYTES = 8 * 1024 * 1024;
78
+ const MIME_BY_EXT: Record<string, string> = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp" };
79
+
80
+ /** The bits of pi-1337 config a theme file may carry (read via its `sourcePath`). */
81
+ interface ThemeConfig {
82
+ pageBg?: string; // export.pageBg — the palette's `void`
83
+ background?: string; // pi1337.background — "on"/"auto"/a hex
84
+ avatar?: AvatarFrames; // pi1337.avatar — parsed frames (PNG or ASCII)
85
+ avatarAlign?: "left" | "center"; // pi1337.avatar.align — horizontal placement of the avatar widget
86
+ avatarPlacement?: "aboveEditor" | "belowEditor"; // pi1337.avatar.placement — which side of the editor
87
+ spinner?: SpinnerProfile;
88
+ }
89
+
90
+ interface LoadedAvatarImage {
91
+ component: Image;
92
+ dimensions: ImageDimensions;
93
+ }
94
+
95
+ interface RenderedAvatarAscii {
96
+ lines: string[];
97
+ }
98
+
99
+ const PERSONA_STATUS_KEY = "persona"; // published by pi-persona
100
+ const COST_STATUS_KEY = "persona-cost"; // pending background-leg cost estimate published by pi-persona
101
+ const BACKGROUND_STATUS_KEY = "persona-background"; // "agents=3 timers=1": work pi-persona still runs in the background
102
+ const MIN_MARGIN = 2;
103
+
104
+ /** Any extension's editor factory, as the host hands it back (its root export omits the named type). */
105
+ type HostEditorFactory = NonNullable<ReturnType<ExtensionContext["ui"]["getEditorComponent"]>>;
106
+
107
+ export default function pi1337(pi: ExtensionAPI) {
108
+ // A fresh factory (startup or `/reload`) re-reads config.json, so an edit to
109
+ // the file takes effect without restarting Pi. The loader bumps its cache
110
+ // generation on reload, so this module is re-evaluated anyway; resetting
111
+ // explicitly keeps that guarantee from depending on loader internals.
112
+ resetConfigCache();
113
+ if (isDisabled()) return;
114
+
115
+ let enabled = true;
116
+ let working = false;
117
+ let runActive = false;
118
+ let waitingForUser = false;
119
+ let compacting = false;
120
+ let spin = 0;
121
+ let timer: ReturnType<typeof setInterval> | undefined;
122
+ let activeTui: TUI | undefined;
123
+ let disposeOutOfBandRedrawGuard: (() => void) | undefined;
124
+ let activeEditor: { getText(): string } | undefined;
125
+ let footerData: ReadonlyFooterDataProvider | undefined;
126
+ let footerGeneration = 0;
127
+ let ownedFooterGeneration: number | undefined;
128
+ let branchUnsub: (() => void) | undefined; // git-branch change subscription (re-render the status row)
129
+ let themeApplied = false;
130
+ let previousTheme: string | undefined;
131
+ let appliedTheme: string | undefined; // the palette we actually switched to (undefined = no switch to undo)
132
+ let chromeActive = false; // true only while the framed editor + footer are installed (tui mode)
133
+ let bgPainted = false; // true only while we hold an OSC 11 tint that clear() must reset
134
+ let themeConfig: ThemeConfig = {}; // pi-1337 config read from the active theme file at apply()
135
+ let themeDir: string | undefined; // dir of the active theme file, to resolve relative avatar images
136
+ let themeConfigSource: string | undefined; // sourcePath the config was read from (detects a live /settings switch)
137
+ let themeRefreshQueued = false;
138
+ let themeRefreshGeneration = 0;
139
+ let themeRefreshContext: ExtensionContext | undefined;
140
+ let avatarShown = false; // whether the avatar widget is currently installed
141
+ let avatarState: AvatarState = "idle"; // task-lifecycle state the avatar reflects
142
+ let turnErrored = false; // a tool/compaction errored → show the error frame when the run settles
143
+ const avatarImageCache = new Map<string, LoadedAvatarImage | null>(); // resolved path → decoded component (null = unrenderable)
144
+ let cachedSessionName: string | undefined;
145
+ let cachedContextUsage: ContextUsageLike | undefined;
146
+ // The session-entry sum is walked only on agent/turn/session events; the
147
+ // persona-cost status is compared on each footer pass and added on top.
148
+ let cachedEntriesCost = 0;
149
+ let cachedPersonaCost: string | undefined; // raw persona-cost status the totals were built from
150
+ let cachedTotal = 0;
151
+ let cachedCost = "";
152
+ let runBaseline: number | undefined; // the total when the run began; undefined = no run to measure
153
+ let cachedRunDelta = "";
154
+ let costRenderQueued = false;
155
+ let cachedThinkingLevel: string | undefined; // host's level, cached off the 90 ms render path
156
+ // An assistant message has ended since the last refresh: Pi persists it right
157
+ // after its message_end listeners return, so the next tool call can show it.
158
+ let statsStale = false;
159
+ // The editor slot is shared: only a factory of ours is ours to remove, and
160
+ // what stood there before us comes back on toggle-off.
161
+ let ourEditorFactory: EditorFactory | undefined; // the factory apply() installed
162
+ let previousEditorFactory: HostEditorFactory | undefined; // never one of ours
163
+ const ownEditorFactories = new WeakSet<object>(); // every factory this instance made
164
+ // Read once, like the other settings: /reload applies a change.
165
+ const maxWidth = maxBoxWidth();
166
+ const rowStyle = statusStyle();
167
+ const draftTokens = draftTokensEnabled();
168
+ const header = headerEnabled() ? createHeaderController({ maxWidth, minMargin: MIN_MARGIN }) : undefined;
169
+ const gitReader = gitStatusEnabled() ? createGitStatusReader((...args) => pi.exec(...args)) : undefined;
170
+ const gitStatus = gitReader ? createGitStatusCache({ read: gitReader.read, notify: () => requestRender() }) : undefined;
171
+ const refreshGit = (ctx: ExtensionContext, force = false): void => {
172
+ if (enabled && chromeActive && !displaced && ctx.hasUI && ctx.mode === "tui") {
173
+ void gitStatus?.request(ctx.cwd, { force });
174
+ }
175
+ };
176
+ const stopGit = (): void => {
177
+ gitStatus?.reset();
178
+ gitReader?.cancel();
179
+ };
180
+ // Both presentation toggles are read once, like polish: /reload applies a change.
181
+ const activityTracker = activityEnabled() ? createActivityTracker() : undefined; // names a long-running tool in the status row
182
+ // The same slot's run clock ("Working… 45s"), under the same toggle. Like the
183
+ // cost baseline it is the run's, not the chrome's: it survives a toggle, and a
184
+ // run that began while the redesign was off never gets one.
185
+ const runClock = activityTracker ? createRunClock() : undefined;
186
+ let toolRuns: ToolRunRegistry | undefined; // folds settled exploration rows (polished lane only)
187
+ const adapterTools = new Set<string>(); // tool names whose rows our adapter renders
188
+ // Read once, like the other toggles: /reload applies a change.
189
+ const summaryOn = summaryEnabled();
190
+ const titleOn = titleEnabled(); // off: setTitle is never called at all
191
+ // Fed from live events whatever the toggle, so a run toggled on halfway is
192
+ // still summarized whole; the title only needs its outcome.
193
+ const runCollector = summaryOn || titleOn ? createRunCollector() : undefined;
194
+ let finished: "done" | "failed" | undefined; // the title's after-run state, until the next run or user input
195
+ let titleSession: string | undefined; // survives clear(): the default title is written after it
196
+ let titleCwdBase = "";
197
+ let lastTitle: string | undefined; // the title the terminal holds as far as we know (dedupe)
198
+ let titleLabel: string | undefined; // the activity label the title was last decided with
199
+ let titleBackground: string | undefined; // the raw persona-background status the title was last decided with
200
+ let titleRefreshQueued = false;
201
+ let titleRefreshGeneration = 0;
202
+ // Read once, like the other toggles: /reload applies a change. Off registers
203
+ // no response or stream handler at all.
204
+ const quotaOn = quotaEnabled();
205
+ // What providers have said about the subscription, per provider. It is session
206
+ // state like the run baseline: recorded while the redesign is toggled off, so
207
+ // apply() finds it current, and kept across a model switch away and back.
208
+ let quotaState: QuotaState = EMPTY_QUOTA;
209
+ /** The model the turn in flight was started with: whose response the next headers are. */
210
+ let quotaRequestModel: { provider?: string; api?: string } | undefined;
211
+ let cachedQuota: QuotaView | undefined; // the current model's view; the render path reads only this
212
+ let cachedQuotaKey = "";
213
+ // Another extension installed its editor over ours: the footer and Pi's working
214
+ // row went back to the host until the next apply() (see the footer's render).
215
+ let displaced = false;
216
+ let displacementQueued = false;
217
+ let displacementGeneration = 0;
218
+
219
+ // Registered at load, not in apply(): on a session switch Pi paints the
220
+ // history before session_start, and a row whose renderer returns nothing
221
+ // then is never added. Gated on the toggle for the same reason; apply() and
222
+ // clear() invalidate the transcript, which rebuilds every entry row.
223
+ const expandHint = () => keyHint("app.tools.expand", "to expand"); // the host's own wording
224
+ if (summaryOn) {
225
+ pi.registerEntryRenderer(RUN_SUMMARY_TYPE, (entry, options, theme) => {
226
+ if (!enabled) return undefined;
227
+ // Pi 1.5.2 passes no outputPad to entry renderers; use one if a host ever does.
228
+ const pad = (options as { outputPad?: unknown }).outputPad;
229
+ return createRunSummaryRow(entry.data, options.expanded, theme, typeof pad === "number" ? pad : 1, expandHint);
230
+ });
231
+ }
232
+
233
+ // Pi keeps a row's renderer descriptor for its entire lifetime. Install a
234
+ // stable adapter once, including for history drawn before session_start;
235
+ // changing only the resolver on toggle would leave existing rows unchanged.
236
+ if (polishEnabled()) {
237
+ const toolStateKeys = new Map<string, symbol>();
238
+ // Folding rides the polished lane: one registry decides which rows fold,
239
+ // fed by the same tool and message events the host builds its rows from.
240
+ if (groupsEnabled()) toolRuns = createToolRunRegistry();
241
+ const groups = toolRuns;
242
+ pi.registerToolRenderer((name, next) => {
243
+ const baseline = next();
244
+ const foreign = !isPolishedTool(name) && (baseline?.renderCall || baseline?.renderResult) ? baseline : undefined;
245
+ // Purpose-built extension renderers (persona, MCP, etc.) keep their content.
246
+ // One that frames itself, or leaves a slot to the host's private fallback
247
+ // formatter (which no adapter lane can recompose byte for byte), is not ours.
248
+ if (foreign && (foreign.renderShell === "self" || !foreign.renderCall || !foreign.renderResult)) return foreign;
249
+ let stateKey = toolStateKeys.get(name);
250
+ if (!stateKey) {
251
+ stateKey = Symbol(`pi1337-tool-row:${name}`);
252
+ toolStateKeys.set(name, stateKey);
253
+ }
254
+ // The rest are drawn in our flat shell while the redesign is active and in the
255
+ // host's box otherwise. They stay out of adapterTools: such a row never folds,
256
+ // and its tool_execution_start closes the exploration run above it.
257
+ if (foreign) {
258
+ return createFlatToolView(foreign, () => chromeActive, { Box, Container, Text, toolName: name, expandHint,
259
+ imagesSupported: () => getCapabilities().images !== null }, stateKey);
260
+ }
261
+ adapterTools.add(name);
262
+ return createSwitchableToolView(createToolView(name, expandHint, {
263
+ highlightCode: (code, path) => {
264
+ const language = getLanguageFromPath(path);
265
+ return language ? highlightCode(code, language) : code.split("\n");
266
+ },
267
+ }), baseline,
268
+ () => chromeActive, { Box, Container, Text, toolName: name, expandHint,
269
+ imagesSupported: () => getCapabilities().images !== null, groups }, stateKey);
270
+ });
271
+ }
272
+
273
+ // Read the theme's page background and optional adjacent .pi1337 sidecar.
274
+ // Keep reading a legacy root pi1337 block when no sidecar exists, so custom
275
+ // themes created before the strict Pi 1.0 schema migration still work.
276
+ const readThemeConfig = (ctx: ExtensionContext): ThemeConfig => {
277
+ const path = ctx.ui.theme.sourcePath;
278
+ if (!path) return {};
279
+ try {
280
+ const json = JSON.parse(readFileSync(path, "utf8")) as {
281
+ export?: { pageBg?: unknown };
282
+ pi1337?: { background?: unknown; avatar?: unknown; spinner?: unknown };
283
+ };
284
+ let extras = json.pi1337;
285
+ try {
286
+ const sidecarPath = /\.json$/i.test(path) ? path.replace(/\.json$/i, ".pi1337") : `${path}.pi1337`;
287
+ extras = JSON.parse(readFileSync(sidecarPath, "utf8")) as typeof extras;
288
+ } catch (error) {
289
+ // A missing sidecar permits older custom themes; a malformed one does
290
+ // not silently activate stale metadata from the theme JSON.
291
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") extras = undefined;
292
+ }
293
+ const avatar = extras?.avatar;
294
+ const avatarObj = avatar && typeof avatar === "object" && !Array.isArray(avatar) ? (avatar as { align?: unknown; placement?: unknown }) : undefined;
295
+ return {
296
+ spinner: parseSpinner(extras?.spinner),
297
+ pageBg: typeof json.export?.pageBg === "string" ? json.export.pageBg : undefined,
298
+ background: typeof extras?.background === "string" ? extras.background : undefined,
299
+ avatar: parseAvatar(avatar),
300
+ avatarAlign: avatarObj?.align === "center" ? "center" : "left",
301
+ // Default below the editor: a kitty-image widget placed *above* the editor
302
+ // disturbs the box's redraw beneath it (reserved image rows + cursor math),
303
+ // leaving the input frame corrupted until a resize forces a full repaint.
304
+ avatarPlacement: avatarObj?.placement === "aboveEditor" ? "aboveEditor" : "belowEditor",
305
+ };
306
+ } catch {
307
+ return {}; // unreadable/foreign theme file → no tint, no avatar
308
+ }
309
+ };
310
+
311
+ // Opt-in tint of the terminal window background so the empty margins around the
312
+ // frame match the palette instead of the terminal's own color. Enabled by env
313
+ // `PI_1337_BG` OR the theme's `pi1337.background` (env wins). Written once per
314
+ // install; always reversed in clear() (unpaintBackground/OSC 111).
315
+ const paintBackground = (): void => {
316
+ if (bgPainted || !enabled || !chromeActive || !activeTui) return;
317
+ const bg = resolveBackground(backgroundEnv(), themeConfig.background);
318
+ if (!bg.enabled) return;
319
+ const hex = resolveBackgroundHex(bg.hex, themeConfig.pageBg);
320
+ if (!hex) return;
321
+ try {
322
+ activeTui.terminal.write(osc11Set(hex));
323
+ bgPainted = true;
324
+ } catch {
325
+ /* cosmetic — a terminal that rejects OSC 11 just keeps its background */
326
+ }
327
+ };
328
+
329
+ const unpaintBackground = (): void => {
330
+ if (!bgPainted) return;
331
+ bgPainted = false;
332
+ try {
333
+ activeTui?.terminal.write(OSC11_RESET); // reset to the terminal's configured default
334
+ } catch {
335
+ /* cosmetic */
336
+ }
337
+ };
338
+
339
+ // Re-tint after a theme change: drop the old color, then paint the new palette's.
340
+ const repaintBackground = (): void => {
341
+ unpaintBackground();
342
+ paintBackground();
343
+ };
344
+
345
+ // Theme-driven ASCII avatar (e.g. a Fallout vault-boy). Shown in a widget next to
346
+ // the editor (below by default) and swapped on the agent's working state; only present when the
347
+ // active theme ships `pi1337.avatar`. Colored with the palette accent here (the
348
+ // pure avatar module stays color-free). Removed in clear() — fully reversible.
349
+ // A PNG frame is delegated to pi-tui's Image component, which owns the protocol-
350
+ // specific cursor/row accounting and re-renders when main/fullscreen capability
351
+ // changes. Bytes are loaded once per path; terminals without image support use
352
+ // the configured ASCII fallback. Custom images are capped before reading.
353
+ const loadAvatarImage = (imagePath: string): LoadedAvatarImage | undefined => {
354
+ const abs = isAbsolute(imagePath) ? imagePath : themeDir ? resolvePath(themeDir, imagePath) : imagePath;
355
+ const cached = avatarImageCache.get(abs);
356
+ if (cached !== undefined) return cached ?? undefined;
357
+ let result: LoadedAvatarImage | null = null;
358
+ try {
359
+ const stat = statSync(abs);
360
+ if (!stat.isFile() || stat.size <= 0 || stat.size > MAX_AVATAR_IMAGE_BYTES) throw new Error("avatar image outside size limit");
361
+ const b64 = readFileSync(abs).toString("base64");
362
+ const ext = abs.split(".").pop()?.toLowerCase() ?? "";
363
+ const mime = MIME_BY_EXT[ext] ?? "image/png";
364
+ const dims = getImageDimensions(b64, mime);
365
+ if (dims) {
366
+ result = {
367
+ component: new Image(b64, mime, { fallbackColor: (text) => text }, { maxWidthCells: AVATAR_COLS, maxHeightCells: AVATAR_ROWS, filename: abs }, dims),
368
+ dimensions: dims,
369
+ };
370
+ }
371
+ } catch {
372
+ result = null; // unreadable/invalid/oversized file → ASCII fallback
373
+ }
374
+ avatarImageCache.set(abs, result);
375
+ return result ?? undefined;
376
+ };
377
+
378
+ // Pi's Image can return either a protocol payload or a textual fallback.
379
+ // Center actual images by their reserved cell width, but measure/clip fallback
380
+ // text just like ASCII; never truncate an image escape sequence in half.
381
+ const avatarWidget = (image: LoadedAvatarImage | undefined, ascii: RenderedAvatarAscii | undefined) => () => {
382
+ let imageProtocol: ImageProtocol | undefined;
383
+ return {
384
+ invalidate() {
385
+ imageProtocol = undefined;
386
+ image?.component.invalidate();
387
+ },
388
+ render(width: number): string[] {
389
+ const liveProtocol = getCapabilities().images;
390
+ if (liveProtocol !== imageProtocol) {
391
+ imageProtocol = liveProtocol;
392
+ image?.component.invalidate();
393
+ }
394
+ const imageUsable = image !== undefined && imageProtocol !== null && getCapabilities().images === imageProtocol;
395
+ const lines = imageUsable ? image.component.render(width) : ascii?.lines;
396
+ if (!lines) return [];
397
+ const maxImageCols = Math.min(AVATAR_COLS, Math.max(1, width - 2));
398
+ const imageColumns = imageUsable
399
+ ? avatarImageColumns(image.dimensions, getCellDimensions(), maxImageCols, AVATAR_ROWS, imageProtocol)
400
+ : undefined;
401
+ return layoutAvatarRows(lines, width, { align: themeConfig.avatarAlign, imageColumns });
402
+ },
403
+ };
404
+ };
405
+
406
+ const updateAvatar = (ctx: ExtensionContext): void => {
407
+ if (!ctx.hasUI || ctx.mode !== "tui") return;
408
+ const source = enabled && chromeActive ? selectAvatar(themeConfig.avatar, avatarState) : undefined;
409
+ let image: LoadedAvatarImage | undefined;
410
+ let ascii: RenderedAvatarAscii | undefined;
411
+ if (source) {
412
+ image = source.image ? loadAvatarImage(source.image) : undefined; // Pi Image handles Kitty/iTerm cursor accounting
413
+ if (source.lines) {
414
+ ascii = {
415
+ lines: source.lines.map((l) => ctx.ui.theme.fg("accent", l)),
416
+ };
417
+ }
418
+ }
419
+ if (!image && !ascii) {
420
+ if (avatarShown) {
421
+ ctx.ui.setWidget(AVATAR_WIDGET_KEY, undefined);
422
+ avatarShown = false;
423
+ }
424
+ return;
425
+ }
426
+ ctx.ui.setWidget(AVATAR_WIDGET_KEY, avatarWidget(image, ascii), {
427
+ placement: themeConfig.avatarPlacement ?? "belowEditor",
428
+ });
429
+ avatarShown = true;
430
+ };
431
+
432
+ // Pi exposes no theme-change event, so a live `/settings` switch would otherwise
433
+ // keep the old palette's tint + avatar. Detect it by the theme's sourcePath and
434
+ // re-read: cheap string compare per call, real work only when it actually changed.
435
+ const refreshThemeConfig = (ctx: ExtensionContext, force = false): void => {
436
+ if (!ctx.hasUI || ctx.mode !== "tui") return;
437
+ const src = ctx.ui.theme.sourcePath;
438
+ if (!force && src === themeConfigSource) return;
439
+ themeConfigSource = src;
440
+ avatarImageCache.clear(); // a live palette switch must not retain every custom image ever seen
441
+ const previousSpinner = themeConfig.spinner ?? DEFAULT_SPINNER;
442
+ themeConfig = readThemeConfig(ctx);
443
+ const nextSpinner = themeConfig.spinner ?? DEFAULT_SPINNER;
444
+ if (previousSpinner !== nextSpinner) {
445
+ spin = 0;
446
+ if (working && chromeActive && !waitingForUser && !displaced) startSpinner();
447
+ else stopSpinner();
448
+ }
449
+ themeDir = src ? dirname(src) : undefined;
450
+ if (!force) {
451
+ repaintBackground(); // the palette's void (tint) may have changed
452
+ updateAvatar(ctx); // swap to the new theme's avatar (or remove it)
453
+ }
454
+ };
455
+
456
+ const stopSpinner = () => {
457
+ if (timer) {
458
+ clearInterval(timer);
459
+ timer = undefined;
460
+ }
461
+ };
462
+
463
+ const requestRender = () => {
464
+ activeTui?.requestRender();
465
+ };
466
+
467
+ const requestFullRender = (): void => {
468
+ forceFullRedraw(activeTui);
469
+ };
470
+
471
+ const cancelThemeConfigRefresh = (): void => {
472
+ themeRefreshQueued = false;
473
+ themeRefreshContext = undefined;
474
+ themeRefreshGeneration++;
475
+ };
476
+
477
+ // A theme switch has no Pi event. The empty footer may detect `sourcePath`
478
+ // during render, but filesystem reads, OSC writes and widget mutation must run
479
+ // only after that render has unwound. A generation token makes clear()/reload
480
+ // invalidate an already queued microtask without retaining a stale context.
481
+ const scheduleThemeConfigRefresh = (ctx: ExtensionContext): void => {
482
+ themeRefreshContext = ctx;
483
+ if (themeRefreshQueued) return;
484
+ themeRefreshQueued = true;
485
+ const generation = ++themeRefreshGeneration;
486
+ queueMicrotask(() => {
487
+ if (!themeRefreshQueued || generation !== themeRefreshGeneration) return;
488
+ themeRefreshQueued = false;
489
+ const next = themeRefreshContext;
490
+ themeRefreshContext = undefined;
491
+ if (!next || !enabled || !chromeActive) return;
492
+ refreshThemeConfig(next);
493
+ requestFullRender();
494
+ });
495
+ };
496
+
497
+ // The terminal title follows the run: decided on the events that change it,
498
+ // written only when the text changes, and Pi's own title whenever idle or off.
499
+ // The events that define a phase (run start/end, prompt start/end) write it
500
+ // even unchanged: Pi's own refresh (on win32, after its update check) may
501
+ // have overwritten it unseen, and the dedupe would otherwise keep it lost.
502
+ const titlePhase = (): TitlePhase => {
503
+ if (!enabled || !chromeActive) return "idle";
504
+ if (waitingForUser) return "waiting";
505
+ if (runActive || compacting) return "running";
506
+ return finished ?? "idle";
507
+ };
508
+
509
+ // Cheap enough for the render path: a phase check and one map lookup.
510
+ const desiredTitleLabel = (): string | undefined =>
511
+ titlePhase() === "running" ? activityTracker?.current(Date.now())?.label : undefined;
512
+
513
+ // After a clean run the title depends on what pi-persona still has running:
514
+ // its raw status, read only in that phase. One map lookup, so the footer can
515
+ // compare it on every pass; only the parsed counts ever reach the title.
516
+ const desiredTitleBackground = (): string | undefined =>
517
+ titlePhase() === "done" ? footerData?.getExtensionStatuses().get(BACKGROUND_STATUS_KEY) || undefined : undefined;
518
+
519
+ const updateTitle = (ctx: ExtensionContext, phaseChange = false): void => {
520
+ if (!titleOn || !ctx.hasUI || ctx.mode !== "tui") return;
521
+ titleLabel = desiredTitleLabel();
522
+ titleBackground = desiredTitleBackground();
523
+ const next = terminalTitle({
524
+ phase: titlePhase(), label: titleLabel, background: parseBackgroundStatus(titleBackground),
525
+ session: titleSession, cwdBase: titleCwdBase,
526
+ });
527
+ // A burst of calls must not rewrite the tab; toggled off, nothing re-asserts.
528
+ if (next === lastTitle && !(phaseChange && enabled && chromeActive)) return;
529
+ lastTitle = next;
530
+ try {
531
+ ctx.ui.setTitle(next);
532
+ } catch {
533
+ /* cosmetic */
534
+ }
535
+ };
536
+
537
+ const cancelTitleRefresh = (): void => {
538
+ titleRefreshQueued = false;
539
+ titleRefreshGeneration++;
540
+ };
541
+
542
+ // The activity label appears only after its grace period, with no event to
543
+ // announce it, and pi-persona's background status changes with none either.
544
+ // The footer notices the change during render; the terminal write waits
545
+ // until that render has unwound, like a theme switch.
546
+ const scheduleTitleRefresh = (ctx: ExtensionContext): void => {
547
+ if (titleRefreshQueued) return;
548
+ titleRefreshQueued = true;
549
+ const generation = ++titleRefreshGeneration;
550
+ queueMicrotask(() => {
551
+ if (!titleRefreshQueued || generation !== titleRefreshGeneration) return;
552
+ titleRefreshQueued = false;
553
+ if (enabled && chromeActive) updateTitle(ctx);
554
+ });
555
+ };
556
+
557
+ // If another extension owns the footer, the framed editor is the remaining
558
+ // render signal. Keep the check to live state comparisons here; theme-file
559
+ // reads and terminal/widget changes stay in the queued refresh above.
560
+ // Labels from the cached sums only: never a session walk, so it is safe on any path.
561
+ const recomputeCost = (): void => {
562
+ cachedTotal = costTotal([], cachedEntriesCost) + parsePersonaCost(cachedPersonaCost);
563
+ cachedCost = formatCost(cachedTotal);
564
+ cachedRunDelta = runBaseline === undefined ? "" : formatRunDelta(cachedTotal - runBaseline);
565
+ };
566
+
567
+ // pi-persona republishes persona-cost when a background leg settles, possibly
568
+ // while the parent is idle and no agent/turn event will follow. The footer
569
+ // renders after the editor in a pass, so a change repaints once more after it.
570
+ const syncPersonaCost = (data: ReadonlyFooterDataProvider): void => {
571
+ const status = data.getExtensionStatuses().get(COST_STATUS_KEY);
572
+ if (status === cachedPersonaCost) return;
573
+ cachedPersonaCost = status;
574
+ recomputeCost();
575
+ if (costRenderQueued) return;
576
+ costRenderQueued = true;
577
+ queueMicrotask(() => {
578
+ costRenderQueued = false;
579
+ if (enabled && chromeActive) requestRender();
580
+ });
581
+ };
582
+
583
+ const observeExtensionRender = (ctx: ExtensionContext, data?: ReadonlyFooterDataProvider): void => {
584
+ if (ctx.ui.theme.sourcePath !== themeConfigSource) scheduleThemeConfigRefresh(ctx);
585
+ if (titleOn && (desiredTitleLabel() !== titleLabel || desiredTitleBackground() !== titleBackground)) scheduleTitleRefresh(ctx);
586
+ if (data) syncPersonaCost(data);
587
+ };
588
+
589
+ // If another extension owns the footer, the framed editor is the remaining
590
+ // render signal. Keep the check to live state comparisons here; theme-file
591
+ // reads and terminal/widget changes stay in the queued refresh above.
592
+ const observeUnownedFrame = (ctx: ExtensionContext): void => {
593
+ if (!enabled || !chromeActive || ownedFooterGeneration !== undefined) return;
594
+ observeExtensionRender(ctx, footerData);
595
+ };
596
+
597
+ const refreshSessionStats = (ctx: ExtensionContext): void => {
598
+ cachedSessionName = ctx.sessionManager.getSessionName();
599
+ cachedContextUsage = ctx.getContextUsage();
600
+ cachedEntriesCost = costTotal(ctx.sessionManager.getEntries());
601
+ cachedPersonaCost = footerData?.getExtensionStatuses().get(COST_STATUS_KEY);
602
+ recomputeCost();
603
+ // A model switch clamps the level before model_select fires, so every
604
+ // refresh point re-reads it; thinking_level_select covers changes in between.
605
+ cachedThinkingLevel = ctx.thinkingLevel;
606
+ };
607
+
608
+ // The quota view belongs to the current model's provider and is rebuilt only
609
+ // on events: a response, a message's end, a model or session change, a run or
610
+ // turn boundary. A window's expiry is therefore noticed at the next of those,
611
+ // never by a timer, and the 90 ms render path reads the cached view alone.
612
+ // Like every quota handler it does nothing outside the TUI and cannot throw.
613
+ const refreshQuota = (ctx: ExtensionContext): void => {
614
+ if (!quotaOn) return;
615
+ try {
616
+ if (!ctx.hasUI || ctx.mode !== "tui") return;
617
+ const model = ctx.model as { provider?: string; api?: string } | undefined;
618
+ const next = quotaView(quotaState, { provider: model?.provider, api: model?.api }, Date.now());
619
+ // Everything the row paints from: the three forms, and which figures have aged.
620
+ const key = next ? `${next.limit}|${next.two}|${next.one}|${next.windows.map((window) => (window.aged ? "a" : "f")).join("")}` : "";
621
+ if (key === cachedQuotaKey) return;
622
+ cachedQuotaKey = key;
623
+ cachedQuota = next;
624
+ if (enabled && chromeActive) requestRender();
625
+ } catch {
626
+ /* cosmetic: the row keeps the last view */
627
+ }
628
+ };
629
+
630
+ // Third-party diagnostics occasionally bypass Pi's UI and write directly to
631
+ // stderr. Those bytes must remain untouched, but they move the real terminal
632
+ // cursor behind pi-tui's differential renderer. While our frame is active,
633
+ // observe that one out-of-band channel and force a clean repaint after the
634
+ // current write burst. Never wrap stdout: pi-tui itself renders there.
635
+ const startOutOfBandRedrawGuard = (): void => {
636
+ disposeOutOfBandRedrawGuard ??= installOutOfBandRedrawGuard(
637
+ process.stderr as unknown as RedrawWritable,
638
+ requestFullRender,
639
+ );
640
+ };
641
+
642
+ const stopOutOfBandRedrawGuard = (): void => {
643
+ disposeOutOfBandRedrawGuard?.();
644
+ disposeOutOfBandRedrawGuard = undefined;
645
+ };
646
+
647
+ // Single source of motion: always restart from a clean timer so we never stack intervals.
648
+ const startSpinner = () => {
649
+ stopSpinner();
650
+ const profile = themeConfig.spinner ?? DEFAULT_SPINNER;
651
+ timer = setInterval(() => {
652
+ spin = (spin + 1) % profile.frames.length;
653
+ requestRender();
654
+ }, profile.intervalMs);
655
+ };
656
+
657
+ // Pi may retry, compact, or continue after agent_end. Only agent_settled ends
658
+ // the run. Prompts pause animation without losing the underlying activity;
659
+ // manual compaction can also be active while there is no agent run at all.
660
+ const syncActivity = (ctx: ExtensionContext, phaseChange = false): void => {
661
+ scheduleDisplacementCheck(ctx);
662
+ updateTitle(ctx, phaseChange); // off or toggled off, this settles on Pi's own title
663
+ if (!enabled || !chromeActive) return;
664
+ working = (runActive || compacting) && !waitingForUser;
665
+ // Displaced, nothing of ours shows the spinner: Pi's working row does.
666
+ if (working && !displaced) {
667
+ if (!timer) startSpinner();
668
+ } else stopSpinner();
669
+ avatarState = compacting ? "confused" : waitingForUser ? "idle" : working ? "working" : turnErrored ? "error" : "idle";
670
+ updateAvatar(ctx);
671
+ requestRender();
672
+ };
673
+
674
+ function applyTheme(ctx: ExtensionContext): void {
675
+ if (!autoThemeEnabled() || themeApplied) return;
676
+ const current = ctx.ui.theme.name;
677
+ // Env pin > Pi's current bundled choice > config-file fallback > light theme
678
+ // kept > green. A palette selected via /settings must survive reload even when
679
+ // config.json contains an older startup preference; setTheme persists any target to Pi.
680
+ const target = chooseStartupTheme(current, ctx.ui.theme.appearance);
681
+ if (current === target) {
682
+ themeApplied = true;
683
+ appliedTheme = undefined; // nothing switched, nothing to undo
684
+ return;
685
+ }
686
+ const result = ctx.ui.setTheme(target);
687
+ themeApplied = result.success;
688
+ if (result.success) {
689
+ previousTheme = current; // only remember the prior theme once the switch actually took
690
+ appliedTheme = target;
691
+ } else {
692
+ try {
693
+ ctx.ui.notify(`pi-theme-1337: could not load theme "${target}" (${result.error ?? "unknown"})`, "warning");
694
+ } catch {
695
+ /* cosmetic */
696
+ }
697
+ }
698
+ }
699
+
700
+ function restoreTheme(ctx: ExtensionContext): void {
701
+ if (!themeApplied) return;
702
+ themeApplied = false;
703
+ // Only revert if the live theme is still the one we switched to. If the user
704
+ // (or another extension) changed themes while pi-1337 was active — including
705
+ // picking another bundled palette — leave their newer choice untouched.
706
+ if (previousTheme && appliedTheme && previousTheme !== appliedTheme && ctx.ui.theme.name === appliedTheme) {
707
+ ctx.ui.setTheme(previousTheme);
708
+ }
709
+ previousTheme = undefined;
710
+ appliedTheme = undefined;
711
+ }
712
+
713
+ // A host (or a test double) without getEditorComponent cannot say who holds
714
+ // the editor slot: `known: false` keeps the behaviour from before it existed.
715
+ const currentEditorFactory = (ctx: ExtensionContext): { known: boolean; factory?: HostEditorFactory } => {
716
+ const ui = ctx.ui as { getEditorComponent?: () => HostEditorFactory | undefined };
717
+ if (typeof ui.getEditorComponent !== "function") return { known: false };
718
+ try {
719
+ return { known: true, factory: ui.getEditorComponent() };
720
+ } catch {
721
+ return { known: false };
722
+ }
723
+ };
724
+
725
+ // The framed editor is the only place the redesign shows the workspace, usage,
726
+ // cost and spinner. When another extension installs its editor after ours,
727
+ // that frame is no longer mounted, yet apply() has emptied the footer and
728
+ // hidden Pi's working row: the user would be left with none of it. The
729
+ // footer's render notices (one identity compare per UI pass) and this runs
730
+ // once that render has unwound: the footer and the working row go back to the
731
+ // host and our spinner stops. Tool rows, the theme, the title and the summary
732
+ // stay ours, and the frame is taken again only by the next apply() — a toggle
733
+ // or a session_start — never by itself.
734
+ const editorDisplaced = (ctx: ExtensionContext): boolean => {
735
+ if (displaced || !ourEditorFactory) return false;
736
+ const installed = currentEditorFactory(ctx);
737
+ return installed.known && installed.factory !== ourEditorFactory;
738
+ };
739
+
740
+ const cancelDisplacementCheck = (): void => {
741
+ displacementQueued = false;
742
+ displacementGeneration++;
743
+ };
744
+
745
+ function scheduleDisplacementCheck(ctx: ExtensionContext): void {
746
+ if (displacementQueued) return;
747
+ displacementQueued = true;
748
+ const generation = ++displacementGeneration;
749
+ queueMicrotask(() => {
750
+ if (!displacementQueued || generation !== displacementGeneration) return;
751
+ displacementQueued = false;
752
+ // Checked again: the slot may have come back to us since the render that saw it.
753
+ if (!enabled || !chromeActive || !editorDisplaced(ctx)) return;
754
+ displaced = true;
755
+ stopSpinner();
756
+ stopGit();
757
+ header?.clear();
758
+ try {
759
+ if (ownedFooterGeneration !== undefined) ctx.ui.setFooter(undefined);
760
+ ctx.ui.setWorkingVisible(true);
761
+ } catch {
762
+ /* cosmetic */
763
+ }
764
+ branchUnsub?.();
765
+ branchUnsub = undefined;
766
+ requestRender();
767
+ });
768
+ }
769
+
770
+ function apply(ctx: ExtensionContext): void {
771
+ if (!ctx.hasUI || ctx.mode !== "tui") return;
772
+ spin = 0;
773
+ displaced = false; // apply() takes the frame, the footer and the working row again
774
+ cancelDisplacementCheck();
775
+ applyTheme(ctx);
776
+
777
+ // Read the palette's pi-1337 config now that the (possibly switched) theme is live.
778
+ refreshThemeConfig(ctx, true);
779
+ refreshSessionStats(ctx);
780
+ refreshQuota(ctx); // recorded while toggled off too: the row opens on current figures
781
+ ctx.ui.setWorkingVisible(false); // working moves into the frame's spinner
782
+ ctx.ui.setHiddenThinkingLabel(hiddenThinkingLabel());
783
+ header?.install(ctx);
784
+
785
+ // Empty footer — the editor frame carries the status. The factory also
786
+ // captures `footerData` so the editor can read the persona status from it.
787
+ const thisFooterGeneration = ++footerGeneration;
788
+ ctx.ui.setFooter((tui, _theme, data) => {
789
+ ownedFooterGeneration = thisFooterGeneration;
790
+ footerData = data;
791
+ activeTui = tui;
792
+ paintBackground(); // tui is now bound; tint the window if enabled by env or theme
793
+ // The footer re-renders on every UI pass — including a live /settings theme
794
+ // switch, which fires no event — detect it here, then apply it after render.
795
+ const renderFooter = () => {
796
+ observeExtensionRender(ctx, data);
797
+ // Another extension's editor over ours has no event either; acted on after this render.
798
+ if (editorDisplaced(ctx)) scheduleDisplacementCheck(ctx);
799
+ return [] as string[];
800
+ };
801
+ // Branch switches happen outside any agent activity; without this the
802
+ // status row would show the old branch until the next unrelated render.
803
+ branchUnsub?.();
804
+ branchUnsub = data.onBranchChange(() => {
805
+ refreshGit(ctx, true);
806
+ requestRender();
807
+ });
808
+ return {
809
+ invalidate() {},
810
+ render: renderFooter,
811
+ dispose() {
812
+ if (ownedFooterGeneration === thisFooterGeneration) {
813
+ ownedFooterGeneration = undefined;
814
+ // Another extension may replace both chrome slots synchronously.
815
+ // Its footer replacement is the last public signal we get before
816
+ // our render hook is gone, so check editor ownership next turn.
817
+ if (chromeActive) scheduleDisplacementCheck(ctx);
818
+ }
819
+ },
820
+ };
821
+ });
822
+
823
+ // Whatever holds the slot now comes back on toggle-off, unless it is ours
824
+ // (a second apply() without a clear() between: session_start in one session).
825
+ const installedEditor = currentEditorFactory(ctx);
826
+ if (!installedEditor.known || !installedEditor.factory) previousEditorFactory = undefined;
827
+ else if (!ownEditorFactories.has(installedEditor.factory)) previousEditorFactory = installedEditor.factory;
828
+ ourEditorFactory =
829
+ makeFramedEditorFactory({
830
+ ctx,
831
+ getPersona: () => footerData?.getExtensionStatuses().get(PERSONA_STATUS_KEY) || undefined,
832
+ getGitBranch: () => footerData?.getGitBranch(),
833
+ getGitStatus: () => gitStatus?.get(ctx.cwd),
834
+ statusStyle: rowStyle,
835
+ draftTokens,
836
+ getSessionName: () => cachedSessionName,
837
+ getContextUsage: () => cachedContextUsage,
838
+ getCost: () => cachedCost,
839
+ getRunDelta: () => cachedRunDelta,
840
+ getQuota: () => cachedQuota,
841
+ getThinkingLevel: () => cachedThinkingLevel,
842
+ isWorking: () => working,
843
+ isWaitingForUser: () => waitingForUser,
844
+ // Revealed by the spinner's own repaint once a call outlasts its grace
845
+ // period, or the run its own; the editor only consults it while working
846
+ // (so never during a blocking prompt). Compaction is Pi's indicator's to
847
+ // announce: the run clock stays out of it.
848
+ getActivity: activityTracker && (() => currentActivity(activityTracker, compacting ? undefined : runClock, Date.now())),
849
+ spinnerFrame: () => spinnerFrame(themeConfig.spinner ?? DEFAULT_SPINNER, spin),
850
+ spinnerRows: () => (themeConfig.spinner ?? DEFAULT_SPINNER).frameRows(spin),
851
+ spinnerColor: () => (themeConfig.spinner ?? DEFAULT_SPINNER).color,
852
+ spinnerHeight: () => (themeConfig.spinner ?? DEFAULT_SPINNER).height,
853
+ spinnerColumns: () => (themeConfig.spinner ?? DEFAULT_SPINNER).columns,
854
+ onFrameRender: () => observeUnownedFrame(ctx),
855
+ bindTui: (tui) => {
856
+ activeTui = tui;
857
+ paintBackground(); // editor may bind the tui before the footer factory runs
858
+ },
859
+ bindEditor: (editor) => {
860
+ activeEditor = editor;
861
+ },
862
+ maxWidth,
863
+ minMargin: MIN_MARGIN,
864
+ });
865
+ ownEditorFactories.add(ourEditorFactory);
866
+ ctx.ui.setEditorComponent(ourEditorFactory);
867
+
868
+ chromeActive = true;
869
+ refreshGit(ctx, true);
870
+ startOutOfBandRedrawGuard();
871
+ paintBackground(); // covers a re-enable where the footer factory already ran (activeTui bound)
872
+ syncActivity(ctx); // restore the current run/prompt/compaction state on toggle-on
873
+ // Invalidate existing transcript rows: a full redraw alone does not rebuild
874
+ // component caches, including history created before session_start.
875
+ activeTui?.invalidate();
876
+ // Also repairs any raw startup diagnostic emitted before the guard was bound.
877
+ requestFullRender();
878
+ }
879
+
880
+ function clear(ctx: ExtensionContext, shutdown = false): void {
881
+ stopGit();
882
+ header?.clear();
883
+ stopOutOfBandRedrawGuard();
884
+ cancelThemeConfigRefresh();
885
+ cancelDisplacementCheck();
886
+ displaced = false;
887
+ working = false; // reset spinner state so a re-enable never shows a frozen frame
888
+ spin = 0;
889
+ chromeActive = false;
890
+ avatarState = "idle";
891
+ turnErrored = false;
892
+ finished = undefined;
893
+ cancelTitleRefresh();
894
+ stopSpinner();
895
+ if (ctx.hasUI && ctx.mode === "tui") {
896
+ unpaintBackground(); // reset the OSC 11 tint before we drop the tui handle
897
+ // Pi never resets the title itself: leave its own behind, once, if ours is showing.
898
+ updateTitle(ctx);
899
+ updateAvatar(ctx); // chromeActive=false → removes the avatar widget
900
+ // The editor is ours to give back only while our factory still holds the
901
+ // slot: one another extension installed after us stays where it is.
902
+ const installedEditor = currentEditorFactory(ctx);
903
+ if (installedEditor.known ? ourEditorFactory !== undefined && installedEditor.factory === ourEditorFactory : true) {
904
+ // Toggle-off hands the slot back to the editor that held it before us.
905
+ // Shutdown never builds another extension's editor: the slot is emptied.
906
+ let restored = false;
907
+ if (!shutdown && previousEditorFactory) {
908
+ try {
909
+ ctx.ui.setEditorComponent(previousEditorFactory);
910
+ restored = true;
911
+ } catch {
912
+ /* its factory failed: Pi's own editor instead */
913
+ }
914
+ }
915
+ if (!restored) ctx.ui.setEditorComponent(undefined);
916
+ }
917
+ if (ownedFooterGeneration !== undefined) ctx.ui.setFooter(undefined);
918
+ ctx.ui.setWorkingVisible(true);
919
+ ctx.ui.setHiddenThinkingLabel();
920
+ // Restore original tool callbacks/shells before dropping the TUI handle.
921
+ activeTui?.invalidate();
922
+ requestFullRender();
923
+ }
924
+ themeConfig = {};
925
+ themeDir = undefined;
926
+ themeConfigSource = undefined;
927
+ avatarImageCache.clear();
928
+ cachedSessionName = undefined;
929
+ cachedContextUsage = undefined;
930
+ cachedEntriesCost = 0;
931
+ cachedPersonaCost = undefined;
932
+ cachedTotal = 0;
933
+ cachedCost = "";
934
+ cachedRunDelta = ""; // the baseline is session state and survives a toggle
935
+ cachedThinkingLevel = undefined;
936
+ activityTracker?.clear();
937
+ toolRuns?.reset();
938
+ branchUnsub?.();
939
+ branchUnsub = undefined;
940
+ footerData = undefined;
941
+ activeTui = undefined;
942
+ activeEditor = undefined;
943
+ ourEditorFactory = undefined;
944
+ previousEditorFactory = undefined;
945
+ if (ctx.hasUI) restoreTheme(ctx);
946
+ }
947
+
948
+ pi.on("session_start", (_event, ctx) => {
949
+ stopGit();
950
+ runActive = !ctx.isIdle();
951
+ waitingForUser = false;
952
+ compacting = false;
953
+ activityTracker?.clear();
954
+ toolRuns?.reset(); // rows rebuilt from history stay unfolded: no events replay for them
955
+ runBaseline = undefined; // a new, resumed or forked session has no run to measure yet
956
+ runClock?.stop(); // nor a start to count from, even when Pi is mid-run
957
+ runCollector?.reset();
958
+ finished = undefined;
959
+ titleSession = ctx.sessionManager.getSessionName();
960
+ titleCwdBase = basename(ctx.cwd);
961
+ // Pi writes exactly this right after binding extensions: nothing to write now.
962
+ lastTitle = defaultTitle(titleSession, titleCwdBase);
963
+ refreshQuota(ctx); // the session's model may be another provider's; apply() re-reads it when on
964
+ if (enabled) apply(ctx);
965
+ });
966
+
967
+ // Subscription quota, from what the provider already sends with each response.
968
+ // Both handlers are synchronous and constant-time, never throw (pi-ai awaits
969
+ // the first before it reads the stream) and do nothing outside the TUI. They
970
+ // keep recording while the redesign is toggled off, like prompt and compaction
971
+ // state, so apply() finds current figures. No request is ever made for this.
972
+ if (quotaOn) {
973
+ pi.on("after_provider_response", (event, ctx) => {
974
+ try {
975
+ if (!ctx.hasUI || ctx.mode !== "tui") return;
976
+ // The event names no provider. Inside a turn the response answers the
977
+ // model that turn started with — the user may have switched since;
978
+ // outside one (cache warming) it is the current model's.
979
+ const model = quotaRequestModel ?? (ctx.model as { provider?: string; api?: string } | undefined);
980
+ quotaState = nextQuota(quotaState, { status: event.status, headers: event.headers, api: model?.api, provider: model?.provider }, Date.now());
981
+ refreshQuota(ctx);
982
+ } catch {
983
+ /* cosmetic: a response must never fail over the status row */
984
+ }
985
+ });
986
+ // Fires for every raw stream chunk of every provider: two comparisons, then out.
987
+ pi.on("provider_stream_event", (event, ctx) => {
988
+ if (event.api !== CODEX_STREAM_API) return;
989
+ try {
990
+ if ((event.data as { type?: unknown } | null | undefined)?.type !== CODEX_RATE_LIMITS_EVENT) return;
991
+ if (!ctx.hasUI || ctx.mode !== "tui") return;
992
+ quotaState = nextQuotaEvent(quotaState, event, Date.now());
993
+ refreshQuota(ctx);
994
+ } catch {
995
+ /* cosmetic */
996
+ }
997
+ });
998
+ }
999
+
1000
+ pi.on("agent_start", (_event, ctx) => {
1001
+ // Pi re-enters its loop inside one run (an auto-retry, a mid-run compaction,
1002
+ // drained steering or follow-ups), emitting agent_start each time; only the
1003
+ // first after a settle begins the run, and the rest keep accumulating.
1004
+ const opening = !runActive;
1005
+ runActive = true;
1006
+ turnErrored = false; // fresh turn: clear any lingering error frame
1007
+ activityTracker?.clear(); // a call that never reported its end must not name the next run
1008
+ refreshQuota(ctx); // a window whose reset has passed leaves here, not on a timer
1009
+ if (opening) {
1010
+ finished = undefined;
1011
+ runCollector?.start(Date.now());
1012
+ }
1013
+ if (enabled && chromeActive) refreshSessionStats(ctx);
1014
+ if (opening) {
1015
+ // The delta measures this run: it starts at zero and replaces the last one.
1016
+ // Started while off, the run has no baseline, never the previous run's.
1017
+ runBaseline = enabled && chromeActive ? cachedTotal : undefined;
1018
+ if (enabled && chromeActive) recomputeCost();
1019
+ // The clock follows the same rule: started while off, the run has none.
1020
+ if (enabled && chromeActive) runClock?.start(Date.now());
1021
+ else runClock?.stop();
1022
+ }
1023
+ syncActivity(ctx, opening);
1024
+ });
1025
+
1026
+ pi.on("agent_end", (_event, ctx) => {
1027
+ refreshQuota(ctx);
1028
+ if (!enabled || !chromeActive) return;
1029
+ refreshSessionStats(ctx);
1030
+ syncActivity(ctx);
1031
+ });
1032
+
1033
+ pi.on("agent_settled", (event, ctx) => {
1034
+ refreshGit(ctx, true);
1035
+ runActive = false;
1036
+ compacting = false;
1037
+ activityTracker?.clear();
1038
+ runClock?.stop();
1039
+ toolRuns?.closeAll(); // nothing more can join the last run
1040
+ refreshQuota(ctx);
1041
+ if (enabled && chromeActive) refreshSessionStats(ctx);
1042
+ // An interrupted run goes straight back to Pi's own title.
1043
+ const outcome = runCollector?.outcome(event.aborted);
1044
+ finished = outcome === "done" || outcome === "failed" ? outcome : undefined;
1045
+ // What pi-persona still runs in the background, as of now: the row must not
1046
+ // say "Done" over it. Read-only, and absent without pi-persona.
1047
+ const stillRunning = parseBackgroundStatus(footerData?.getExtensionStatuses().get(BACKGROUND_STATUS_KEY));
1048
+ // The status row's own run delta, taken after the refresh above.
1049
+ const summary = runCollector?.finish(Date.now(), event.aborted, runBaseline === undefined ? 0 : cachedTotal - runBaseline, stillRunning);
1050
+ // The one deliberate session-file write: a custom entry, which never
1051
+ // becomes model input. Synchronous in this handler, never from a timer, and
1052
+ // it touches no message queue, so pi-persona's follow-ups are undisturbed.
1053
+ if (summary && summaryOn && enabled && chromeActive && ctx.hasUI && ctx.mode === "tui") {
1054
+ try {
1055
+ pi.appendEntry(RUN_SUMMARY_TYPE, summary);
1056
+ } catch {
1057
+ /* cosmetic: a failed write must not stall settlement */
1058
+ }
1059
+ }
1060
+ syncActivity(ctx, true);
1061
+ });
1062
+
1063
+ // Submitting input ends the after-run title, as a new run would.
1064
+ if (titleOn) {
1065
+ pi.on("input", (_event, ctx) => {
1066
+ if (!finished) return;
1067
+ finished = undefined;
1068
+ updateTitle(ctx);
1069
+ });
1070
+ }
1071
+
1072
+ pi.on("ui_prompt_start", (_event, ctx) => {
1073
+ waitingForUser = true;
1074
+ syncActivity(ctx, true);
1075
+ });
1076
+
1077
+ pi.on("ui_prompt_end", (_event, ctx) => {
1078
+ waitingForUser = false;
1079
+ syncActivity(ctx, true);
1080
+ });
1081
+
1082
+ // Context compaction reads as the model "thinking hard" — show the confused frame
1083
+ // for its duration, then return to the working frame the turn resumes in.
1084
+ pi.on("session_before_compact", (_event, ctx) => {
1085
+ toolRuns?.closeAll(); // Pi paints a compaction row (or its failure) below the rows so far
1086
+ compacting = true;
1087
+ syncActivity(ctx);
1088
+ });
1089
+
1090
+ pi.on("session_compact", (_event, ctx) => {
1091
+ toolRuns?.reset(); // the chat is rebuilt from the retained entries, unfolded
1092
+ compacting = false;
1093
+ if (enabled && chromeActive) refreshSessionStats(ctx);
1094
+ syncActivity(ctx);
1095
+ });
1096
+
1097
+ pi.on("session_compact_failed", (event, ctx) => {
1098
+ compacting = false;
1099
+ if (!event.aborted) turnErrored = true;
1100
+ syncActivity(ctx);
1101
+ });
1102
+
1103
+ // The summary's model time: each turn runs from here to its assistant message's end.
1104
+ pi.on("turn_start", (_event, ctx) => {
1105
+ runCollector?.turnStart(Date.now());
1106
+ const model = ctx.model as { provider?: string; api?: string } | undefined;
1107
+ quotaRequestModel = model ? { provider: model.provider, api: model.api } : undefined;
1108
+ refreshQuota(ctx);
1109
+ });
1110
+
1111
+ pi.on("turn_end", (event, ctx) => {
1112
+ runCollector?.turnEnd(event.message);
1113
+ quotaRequestModel = undefined;
1114
+ refreshQuota(ctx);
1115
+ if (!enabled || !chromeActive) return;
1116
+ refreshSessionStats(ctx);
1117
+ requestRender();
1118
+ });
1119
+
1120
+ pi.on("session_tree", (_event, ctx) => {
1121
+ // The host is about to rebuild the chat from the new branch: a fold's tally
1122
+ // row may not be on it, so rebuilt rows start unfolded.
1123
+ toolRuns?.reset();
1124
+ refreshQuota(ctx); // the branch may have been written by another provider's model
1125
+ if (!enabled || !chromeActive) return;
1126
+ refreshSessionStats(ctx);
1127
+ requestRender();
1128
+ });
1129
+
1130
+ pi.on("session_info_changed", (event, ctx) => {
1131
+ titleSession = event.name;
1132
+ // Pi rewrote its own title just before this handler: re-apply ours over it.
1133
+ lastTitle = defaultTitle(titleSession, titleCwdBase);
1134
+ updateTitle(ctx);
1135
+ if (!enabled || !chromeActive) return;
1136
+ cachedSessionName = event.name;
1137
+ requestRender();
1138
+ });
1139
+
1140
+ pi.on("model_select", (_event, ctx) => {
1141
+ // The state is per provider: switching away hides its figures, switching back finds them.
1142
+ refreshQuota(ctx);
1143
+ if (!enabled || !chromeActive) return;
1144
+ refreshSessionStats(ctx);
1145
+ requestRender();
1146
+ });
1147
+
1148
+ pi.on("thinking_level_select", (event) => {
1149
+ if (!enabled || !chromeActive) return;
1150
+ cachedThinkingLevel = event.level;
1151
+ requestRender();
1152
+ });
1153
+
1154
+ pi.on("tool_execution_start", (event, ctx) => {
1155
+ // The end event carries no arguments: the summary keeps what it needs from here.
1156
+ runCollector?.toolStart(event.toolCallId, event.toolName, event.args, ctx.cwd);
1157
+ if (!enabled) return;
1158
+ // Nested codemode calls are shown inside their parent's row, never as rows
1159
+ // of their own: they feed neither the label nor the runs.
1160
+ if (!event.parentToolCallId) {
1161
+ // The response that launched this call is in the session by now: show its
1162
+ // tokens and spend while the call runs, not the figures from before it.
1163
+ // Once per assistant message; the spinner's repaint carries it.
1164
+ if (statsStale && chromeActive) {
1165
+ statsStale = false;
1166
+ refreshSessionStats(ctx);
1167
+ }
1168
+ activityTracker?.onStart(event.toolCallId, event.toolName, event.args, Date.now());
1169
+ toolRuns?.onToolStart(event.toolCallId, event.toolName,
1170
+ { args: event.args, cwd: ctx.cwd, rendersHere: adapterTools.has(event.toolName) });
1171
+ }
1172
+ });
1173
+
1174
+ pi.on("tool_execution_end", (event, ctx) => {
1175
+ // Nested calls count too, and only live: their results are not persisted.
1176
+ runCollector?.toolEnd(event.toolCallId, event.toolName, event.result, event.isError, !!event.parentToolCallId);
1177
+ if (!enabled) return;
1178
+ // Read/search tools cannot change the worktree; custom tools may do so.
1179
+ if (!["read", "grep", "find", "ls"].includes(event.toolName)) refreshGit(ctx);
1180
+ if (event.isError) turnErrored = true; // remembered until agent_settled shows the error frame
1181
+ // The fold registry is settled by the row itself, once it shows the result.
1182
+ if (!event.parentToolCallId) activityTracker?.onEnd(event.toolCallId);
1183
+ });
1184
+
1185
+ // Whatever paints a transcript row ends the run above it. A streaming assistant
1186
+ // message is empty at its start, so the update is what catches the first thinking
1187
+ // or text the moment it appears; start covers user and custom messages, end the
1188
+ // providers that do not stream. The registry returns at once while no run is open.
1189
+ const closeRunOnPaintedMessage = (event: { message: unknown }): void => {
1190
+ if (enabled) toolRuns?.onMessage(event.message);
1191
+ };
1192
+ pi.on("message_start", closeRunOnPaintedMessage);
1193
+ pi.on("message_update", (event) => {
1194
+ // The summary's thinking time: only the stream's thinking_start/end are read.
1195
+ runCollector?.streamEvent(event.assistantMessageEvent, Date.now());
1196
+ closeRunOnPaintedMessage(event);
1197
+ });
1198
+ pi.on("message_end", (event, ctx) => {
1199
+ // An assistant message's end closes its turn's model interval and carries its usage.
1200
+ runCollector?.messageEnd(event.message, Date.now());
1201
+ // Not refreshed here: Pi appends the message to the session after this returns.
1202
+ if ((event.message as { role?: unknown } | undefined)?.role === "assistant") {
1203
+ statsStale = true;
1204
+ // A usage-limit error is the only quota signal some routes give; any other
1205
+ // ending of that provider's assistant message clears it.
1206
+ if (quotaOn) {
1207
+ try {
1208
+ if (ctx.hasUI && ctx.mode === "tui") {
1209
+ quotaState = nextQuotaMessage(quotaState, event.message, (ctx.model as { provider?: string } | undefined)?.provider, Date.now());
1210
+ refreshQuota(ctx);
1211
+ }
1212
+ } catch {
1213
+ /* cosmetic */
1214
+ }
1215
+ }
1216
+ }
1217
+ closeRunOnPaintedMessage(event);
1218
+ });
1219
+
1220
+ pi.on("session_shutdown", (_event, ctx) => {
1221
+ runActive = false;
1222
+ waitingForUser = false;
1223
+ compacting = false;
1224
+ runClock?.stop();
1225
+ clear(ctx, true);
1226
+ });
1227
+
1228
+ // The toggle is namespaced separately from the bundled `1337` palette, which
1229
+ // remains available in /settings.
1230
+ pi.registerCommand("theme-1337", {
1231
+ description: "Toggle the pi-theme-1337 redesign (theme + framed editor)",
1232
+ handler: async (_args, ctx) => {
1233
+ enabled = !enabled;
1234
+ if (enabled) apply(ctx);
1235
+ else clear(ctx);
1236
+ try {
1237
+ ctx.ui.notify(`pi-theme-1337 ${enabled ? "on" : "off"}`, "info");
1238
+ } catch {
1239
+ /* cosmetic */
1240
+ }
1241
+ },
1242
+ });
1243
+
1244
+ // Clean-copy escape hatch: native terminal selection grabs the rendered cells
1245
+ // (frame `│`, left padding, a newline per visual row), so it cannot yield the
1246
+ // raw input. This shortcut copies the editor's logical buffer verbatim instead.
1247
+ const copyKey = copyShortcut();
1248
+ if (copyKey) {
1249
+ pi.registerShortcut(copyKey as KeyId, {
1250
+ description: "pi-theme-1337: copy the input buffer as clean text (no frame glyphs)",
1251
+ handler: async (ctx) => {
1252
+ if (!enabled) return;
1253
+ const text = activeEditor?.getText() ?? "";
1254
+ if (!text) return;
1255
+ try {
1256
+ await copyToClipboard(text);
1257
+ ctx.ui.notify("pi-theme-1337: input copied", "info");
1258
+ } catch {
1259
+ /* cosmetic */
1260
+ }
1261
+ },
1262
+ });
1263
+ }
1264
+ }