@heyhuynhgiabuu/pi-pretty 0.6.24 → 0.6.25

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.
@@ -0,0 +1,691 @@
1
+ /**
2
+ * omp-style shimmer working indicator (widget takeover).
3
+ *
4
+ * Ports the shimmer sweep from oh-my-pi's `modes/theme/shimmer.ts`: the sweep
5
+ * is discretized into one pre-rendered frame per band position, cycled at
6
+ * 1000/30 ms so the band travels 30 cells/second — omp's exact speed.
7
+ *
8
+ * Why a widget: the host `Loader` extends `Text` with a hardcoded paddingX=1,
9
+ * and `setWorkingIndicator({ frames })` cannot change host component layout.
10
+ * To render the row flush-left we hide the host loader
11
+ * (`setWorkingVisible(false)`) and install our own zero-padding component via
12
+ * `setWidget(..., "aboveEditor")`, animating it with a 33ms interval.
13
+ *
14
+ * Frame layout: `<dim spinner> <shimmer text> <dim interrupt hint>`, one full
15
+ * sweep per phrase — `texts` rotates through phrases chapter by chapter with
16
+ * a continuous spinner phase.
17
+ */
18
+
19
+ import { truncateToWidth } from "@earendil-works/pi-tui";
20
+ import { FG_BLUE, FG_DIM, FG_MUTED, type ThinkingIndicatorConfig, type WorkingIndicatorConfig } from "./config.js";
21
+ import { dimAccentHex, hexToAnsiFg, sessionAccentHex } from "./session-color.js";
22
+
23
+ // ─── Sweep tunables (oh-my-pi shimmer.ts) ────────────────────────────────────
24
+ const CLASSIC_PADDING = 10;
25
+ const CLASSIC_BAND_HALF_WIDTH = 6;
26
+ const KITT_HEAD_HALF = 0.6;
27
+ const KITT_TRAIL_LEN = 7;
28
+ const TIER_HIGH = 0.65;
29
+ const TIER_MID = 0.22;
30
+
31
+ /** One cell per frame at 33ms = omp's 30 cells/second band speed. */
32
+ export const WORKING_INTERVAL_MS = Math.round(1000 / 30);
33
+
34
+ const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
35
+ /** Spinner glyph advances every N frames (~99ms ≈ pi's default 80ms cadence). */
36
+ const SPINNER_STEP = 3;
37
+
38
+ const RESET_FG = "\x1b[39m";
39
+ const BOLD_OPEN = "\x1b[1m";
40
+ const BOLD_CLOSE = "\x1b[22m";
41
+ const ITALIC_OPEN = "\x1b[3m";
42
+ const ITALIC_CLOSE = "\x1b[23m";
43
+ /** Fallback for pi's thinkingText tier when no theme is available. */
44
+ const FG_THINKING_FALLBACK = "\x1b[38;2;148;148;184m";
45
+
46
+ // ─── Settings ────────────────────────────────────────────────────────────────
47
+
48
+ export type WorkingIndicatorMode = "shimmer" | "kitt" | "static";
49
+
50
+ /** Tier colors as config values: a pi theme color name or a `#rrggbb` hex. */
51
+ export interface WorkingIndicatorPalette {
52
+ low: string;
53
+ mid: string;
54
+ high: string;
55
+ }
56
+
57
+ export interface WorkingIndicatorSettings {
58
+ enabled: boolean;
59
+ /** Phrases rotated chapter-by-chapter across the sweep. */
60
+ texts: string[];
61
+ mode: WorkingIndicatorMode;
62
+ palette: WorkingIndicatorPalette;
63
+ bold: boolean;
64
+ hint: boolean;
65
+ /** Tint mid/high tiers (and dim the spinner) with a per-session accent color. */
66
+ sessionAccent: boolean;
67
+ /** True when the user explicitly configured `mid`/`high` — accent then stays off. */
68
+ tiersCustomized?: boolean;
69
+ }
70
+
71
+ export const WORKING_INDICATOR_DEFAULTS: WorkingIndicatorSettings = {
72
+ enabled: true,
73
+ texts: ["Working…"],
74
+ mode: "shimmer",
75
+ palette: { low: "dim", mid: "muted", high: "accent" },
76
+ bold: true,
77
+ hint: true,
78
+ sessionAccent: true,
79
+ tiersCustomized: false,
80
+ };
81
+
82
+ const MODES: readonly WorkingIndicatorMode[] = ["shimmer", "kitt", "static"];
83
+
84
+ function isMode(value: unknown): value is WorkingIndicatorMode {
85
+ return typeof value === "string" && (MODES as readonly string[]).includes(value);
86
+ }
87
+
88
+ function envFlag(value: string | undefined): boolean | undefined {
89
+ const v = value?.trim().toLowerCase();
90
+ if (!v) return undefined;
91
+ if (v === "off" || v === "false" || v === "0") return false;
92
+ if (v === "on" || v === "true" || v === "1") return true;
93
+ return undefined;
94
+ }
95
+
96
+ /** Longest working label we build frames for (the sweep is one frame per code point + padding). */
97
+ const MAX_TEXT_CODE_POINTS = 120;
98
+
99
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: control chars are exactly what we sanitize out of user text
100
+ const CONTROL_CHARS_RE = /[\u0000-\u001f\u007f]/;
101
+
102
+ /**
103
+ * Accept a configured label only if it renders safely in the single-line
104
+ * working row: no control characters (including newlines) and bounded length.
105
+ * Returns undefined for anything invalid, falling back to the default.
106
+ */
107
+ function sanitizeText(value: unknown): string | undefined {
108
+ const text = typeof value === "string" ? value.trim() : undefined;
109
+ if (!text) return undefined;
110
+ if (CONTROL_CHARS_RE.test(text)) return undefined;
111
+ if ([...text].length > MAX_TEXT_CODE_POINTS) return undefined;
112
+ return text;
113
+ }
114
+
115
+ /** Sanitize a `string | string[]` config value into a valid phrase list. */
116
+ function sanitizeTexts(input: unknown): string[] | undefined {
117
+ const list = Array.isArray(input) ? input : [input];
118
+ const out: string[] = [];
119
+ for (const item of list) {
120
+ const text = sanitizeText(item);
121
+ if (text) out.push(text);
122
+ }
123
+ return out.length > 0 ? out : undefined;
124
+ }
125
+
126
+ /**
127
+ * Resolve final settings from `pi-pretty.json`'s flat `workingIndicator` object
128
+ * and env overrides. Precedence: env var > config > default; empty or invalid
129
+ * env values mean unset (matching pi-pretty's config conventions).
130
+ */
131
+ export function resolveWorkingIndicatorSettings(
132
+ config: WorkingIndicatorConfig | undefined,
133
+ env: NodeJS.ProcessEnv = process.env,
134
+ ): WorkingIndicatorSettings {
135
+ const settings: WorkingIndicatorSettings = {
136
+ ...WORKING_INDICATOR_DEFAULTS,
137
+ palette: { ...WORKING_INDICATOR_DEFAULTS.palette },
138
+ };
139
+ const envEnabled = envFlag(env.PRETTY_WORKING_INDICATOR);
140
+ if (envEnabled !== undefined) settings.enabled = envEnabled;
141
+ else if (typeof config?.enabled === "boolean") settings.enabled = config.enabled;
142
+
143
+ const envMode = isMode(env.PRETTY_WORKING_INDICATOR_MODE) ? env.PRETTY_WORKING_INDICATOR_MODE : undefined;
144
+ settings.mode = envMode ?? (isMode(config?.mode) ? config.mode : settings.mode);
145
+
146
+ const envTexts = sanitizeTexts(env.PRETTY_WORKING_INDICATOR_TEXT?.split(",").map((part) => part.trim()));
147
+ settings.texts = envTexts ?? sanitizeTexts(config?.text) ?? settings.texts;
148
+
149
+ for (const tier of ["low", "mid", "high"] as const) {
150
+ const value = config?.[tier];
151
+ if (typeof value === "string" && value.trim() !== "") settings.palette[tier] = value;
152
+ }
153
+ if (typeof config?.bold === "boolean") settings.bold = config.bold;
154
+ if (typeof config?.hint === "boolean") settings.hint = config.hint;
155
+ if (typeof config?.sessionAccent === "boolean") settings.sessionAccent = config.sessionAccent;
156
+ settings.tiersCustomized = typeof config?.mid === "string" || typeof config?.high === "string";
157
+ return settings;
158
+ }
159
+
160
+ // ─── Palette resolution ──────────────────────────────────────────────────────
161
+
162
+ /** Tier colors as raw ANSI open sequences. */
163
+ export interface ResolvedPalette {
164
+ low: string;
165
+ mid: string;
166
+ high: string;
167
+ }
168
+
169
+ interface ThemeAnsiSource {
170
+ /** Narrowed tier names; pi's Theme (ThemeColor) satisfies this structurally. */
171
+ getFgAnsi?: (name: "dim" | "muted" | "accent" | "thinkingText") => string;
172
+ }
173
+
174
+ function colorToAnsi(value: string, theme: ThemeAnsiSource | undefined, fallback: string): string {
175
+ const hex = hexToAnsiFg(value);
176
+ if (hex) return hex;
177
+ try {
178
+ // Pi's ThemeColor is a closed TS union, but getFgAnsi accepts any registered
179
+ // theme color at runtime; unknown names throw or return non-ANSI garbage,
180
+ // both handled below.
181
+ const getFgAnsi = theme?.getFgAnsi as ((name: string) => string) | undefined;
182
+ const viaTheme = getFgAnsi?.(value);
183
+ if (viaTheme?.startsWith("\x1b[")) return viaTheme;
184
+ } catch {
185
+ // Unknown theme color name: fall through to the built-in constant.
186
+ }
187
+ return fallback;
188
+ }
189
+
190
+ /**
191
+ * Resolve tier colors to ANSI open sequences. `#rrggbb` wins, then the active
192
+ * pi theme (`getFgAnsi`), then pi-pretty's built-in constants.
193
+ */
194
+ export function resolvePaletteAnsi(palette: WorkingIndicatorPalette, theme?: ThemeAnsiSource): ResolvedPalette {
195
+ return {
196
+ low: colorToAnsi(palette.low, theme, FG_DIM),
197
+ mid: colorToAnsi(palette.mid, theme, FG_MUTED),
198
+ high: colorToAnsi(palette.high, theme, FG_BLUE),
199
+ };
200
+ }
201
+
202
+ // ─── Frame building ──────────────────────────────────────────────────────────
203
+
204
+ type Tier = "low" | "mid" | "high";
205
+
206
+ function tierFor(intensity: number): Tier {
207
+ if (intensity >= TIER_HIGH) return "high";
208
+ if (intensity >= TIER_MID) return "mid";
209
+ return "low";
210
+ }
211
+
212
+ /** Smooth cosine bump sweeping left → right with edge padding. */
213
+ function classicIntensity(index: number, pos: number): number {
214
+ const dist = Math.abs(index + CLASSIC_PADDING - pos);
215
+ if (dist >= CLASSIC_BAND_HALF_WIDTH) return 0;
216
+ return 0.5 * (1 + Math.cos((Math.PI * dist) / CLASSIC_BAND_HALF_WIDTH));
217
+ }
218
+
219
+ /**
220
+ * Knight Rider K.I.T.T. scanner: a single bright head ping-pongs across the
221
+ * text with a quadratic-decay trail behind it (oh-my-pi shimmer.ts).
222
+ */
223
+ function kittIntensity(index: number, head: number, goingRight: boolean): number {
224
+ const delta = index - head;
225
+ if (Math.abs(delta) <= KITT_HEAD_HALF) return 1;
226
+ const behind = goingRight ? -delta : delta;
227
+ if (behind <= KITT_HEAD_HALF) return 0;
228
+ const t = (behind - KITT_HEAD_HALF) / KITT_TRAIL_LEN;
229
+ if (t >= 1) return 0;
230
+ const f = 1 - t;
231
+ return f * f;
232
+ }
233
+
234
+ /** UTF-16 [start, end] index pairs per code point (surrogate-pair safe). */
235
+ function codePointRanges(text: string): Array<[number, number]> {
236
+ const ranges: Array<[number, number]> = [];
237
+ let i = 0;
238
+ while (i < text.length) {
239
+ const c = text.charCodeAt(i);
240
+ if (c >= 0xd800 && c <= 0xdbff && i + 1 < text.length) {
241
+ const c2 = text.charCodeAt(i + 1);
242
+ if (c2 >= 0xdc00 && c2 <= 0xdfff) {
243
+ ranges.push([i, i + 2]);
244
+ i += 2;
245
+ continue;
246
+ }
247
+ }
248
+ ranges.push([i, i + 1]);
249
+ i += 1;
250
+ }
251
+ return ranges;
252
+ }
253
+
254
+ export interface WorkingFrameOptions {
255
+ mode: WorkingIndicatorMode;
256
+ /** Resolved ANSI open sequences per tier. */
257
+ ansi: ResolvedPalette;
258
+ bold?: boolean;
259
+ spinner?: boolean;
260
+ /** Spinner glyph color; defaults to `ansi.low` (omp tints it with the dim accent). */
261
+ spinnerColor?: string;
262
+ /** Wrap every frame in italic (pi's hidden-thinking label is italic). */
263
+ italic?: boolean;
264
+ /** Pre-colored suffix (e.g. the dim interrupt hint) appended to every frame. */
265
+ hint?: string;
266
+ intervalMs?: number;
267
+ }
268
+
269
+ /**
270
+ * Build the frame list for the working row: one full sweep per phrase, in
271
+ * order, with the spinner phase running continuously across chapter
272
+ * boundaries. Same-tier runs share one ANSI pair (omp's run coalescing).
273
+ */
274
+ export function buildWorkingFrames(
275
+ texts: string[],
276
+ options: WorkingFrameOptions,
277
+ ): { frames: string[]; intervalMs: number } {
278
+ const intervalMs = options.intervalMs ?? WORKING_INTERVAL_MS;
279
+ const bold = options.bold ?? true;
280
+ const suffix = options.hint ?? "";
281
+ const withSpinner = options.spinner ?? true;
282
+ const spinnerColor = options.spinnerColor ?? options.ansi.low;
283
+ const highOpen = bold ? `${BOLD_OPEN}${options.ansi.high}` : options.ansi.high;
284
+ const highClose = bold ? `${BOLD_CLOSE}${RESET_FG}` : RESET_FG;
285
+ const seq: Record<Tier, { open: string; close: string }> = {
286
+ low: { open: options.ansi.low, close: RESET_FG },
287
+ mid: { open: options.ansi.mid, close: RESET_FG },
288
+ high: { open: highOpen, close: highClose },
289
+ };
290
+
291
+ const spinnerPrefix = (frameIndex: number): string => {
292
+ if (!withSpinner) return "";
293
+ const glyph = SPINNER_FRAMES[Math.floor(frameIndex / SPINNER_STEP) % SPINNER_FRAMES.length] ?? "";
294
+ return `${spinnerColor}${glyph}${RESET_FG} `;
295
+ };
296
+
297
+ const paintFrame = (text: string, ranges: Array<[number, number]>, tiers: Tier[]): string => {
298
+ const total = ranges.length;
299
+ let out = "";
300
+ let runStart = 0;
301
+ let runTier: Tier | null = null;
302
+ const flush = (endIndex: number): void => {
303
+ if (runTier === null || endIndex <= runStart) return;
304
+ const s = seq[runTier];
305
+ out += `${s.open}${text.slice(ranges[runStart][0], ranges[endIndex - 1][1])}${s.close}`;
306
+ };
307
+ for (let i = 0; i < total; i++) {
308
+ if (tiers[i] !== runTier) {
309
+ flush(i);
310
+ runTier = tiers[i] ?? null;
311
+ runStart = i;
312
+ }
313
+ }
314
+ flush(total);
315
+ return options.italic ? `${ITALIC_OPEN}${out}${ITALIC_CLOSE}` : out;
316
+ };
317
+
318
+ const frames: string[] = [];
319
+ let spinnerIndex = 0;
320
+
321
+ for (const raw of texts) {
322
+ const text = raw.trim();
323
+ const ranges = codePointRanges(text);
324
+ const total = ranges.length;
325
+ if (total === 0) continue;
326
+
327
+ if (options.mode === "static") {
328
+ // Static mode: one unanimated frame — only the first phrase renders.
329
+ frames.push(
330
+ `${spinnerPrefix(spinnerIndex++)}${paintFrame(
331
+ text,
332
+ ranges,
333
+ Array.from({ length: total }, () => "mid" as Tier),
334
+ )}${suffix}`,
335
+ );
336
+ return { frames, intervalMs };
337
+ }
338
+
339
+ if (options.mode === "kitt") {
340
+ const range = total - 1;
341
+ if (range <= 0) {
342
+ frames.push(
343
+ `${spinnerPrefix(spinnerIndex++)}${paintFrame(
344
+ text,
345
+ ranges,
346
+ Array.from({ length: total }, () => "high" as Tier),
347
+ )}${suffix}`,
348
+ );
349
+ continue;
350
+ }
351
+ const cycleCells = 2 * range;
352
+ for (let sweep = 0; sweep < cycleCells; sweep++) {
353
+ const goingRight = sweep < range;
354
+ const head = goingRight ? sweep : cycleCells - sweep;
355
+ const tiers = Array.from({ length: total }, (_, i) => tierFor(kittIntensity(i, head, goingRight)));
356
+ frames.push(`${spinnerPrefix(spinnerIndex++)}${paintFrame(text, ranges, tiers)}${suffix}`);
357
+ }
358
+ } else {
359
+ const period = total + CLASSIC_PADDING * 2;
360
+ for (let pos = 0; pos < period; pos++) {
361
+ const tiers = Array.from({ length: total }, (_, i) => tierFor(classicIntensity(i, pos)));
362
+ frames.push(`${spinnerPrefix(spinnerIndex++)}${paintFrame(text, ranges, tiers)}${suffix}`);
363
+ }
364
+ }
365
+ }
366
+ return { frames, intervalMs };
367
+ }
368
+
369
+ // ─── Widget ──────────────────────────────────────────────────────────────────
370
+
371
+ /** Slice of the pi-tui TUI instance the widget needs. */
372
+ export interface WidgetTuiLike {
373
+ requestRender(): void;
374
+ }
375
+
376
+ /**
377
+ * Zero-padding working-row component. The host renders whatever `render()`
378
+ * returns with no margins, so the row sits flush-left — the thing the frames
379
+ * API could not do.
380
+ */
381
+ export class WorkingWidget {
382
+ #frames: string[] = [];
383
+ #index = 0;
384
+ #intervalMs = WORKING_INTERVAL_MS;
385
+ #interval: ReturnType<typeof setInterval> | undefined;
386
+ #tui: WidgetTuiLike | undefined;
387
+ #started = false;
388
+ #disposed = false;
389
+
390
+ setFrames(frames: string[], intervalMs: number): void {
391
+ this.#frames = frames;
392
+ this.#intervalMs = intervalMs;
393
+ this.#index = 0;
394
+ }
395
+
396
+ attach(tui: WidgetTuiLike): void {
397
+ this.#tui = tui;
398
+ }
399
+
400
+ start(): void {
401
+ if (this.#disposed || this.#started) return;
402
+ this.#started = true;
403
+ this.#index = 0;
404
+ // A single frame has nothing to cycle — skip the 30fps render churn.
405
+ if (this.#frames.length <= 1) return;
406
+ this.#interval = setInterval(() => {
407
+ this.#index = (this.#index + 1) % Math.max(1, this.#frames.length);
408
+ this.#tui?.requestRender();
409
+ }, this.#intervalMs);
410
+ }
411
+
412
+ stop(): void {
413
+ this.#started = false;
414
+ if (this.#interval) {
415
+ clearInterval(this.#interval);
416
+ this.#interval = undefined;
417
+ }
418
+ }
419
+
420
+ /** Flush-left single line; invisible (no lines) while stopped. */
421
+ render(width: number): string[] {
422
+ if (!this.#started || this.#frames.length === 0) return [];
423
+ const frame = this.#frames[this.#index % this.#frames.length] ?? "";
424
+ return [truncateToWidth(frame, Math.max(1, width))];
425
+ }
426
+
427
+ invalidate(): void {
428
+ // Stateless per render — nothing to invalidate.
429
+ }
430
+
431
+ dispose(): void {
432
+ this.stop();
433
+ this.#disposed = true;
434
+ }
435
+ }
436
+
437
+ // ─── Thinking label ───────────────────────────────────────────────────────────
438
+
439
+ export interface ThinkingIndicatorSettings {
440
+ enabled: boolean;
441
+ }
442
+
443
+ export const THINKING_INDICATOR_DEFAULTS: ThinkingIndicatorSettings = { enabled: true };
444
+
445
+ /**
446
+ * Resolve thinking-label shimmer settings from `pi-pretty.json`'s
447
+ * `thinkingIndicator` object and env overrides (env > config > default).
448
+ */
449
+ export function resolveThinkingIndicatorSettings(
450
+ config: ThinkingIndicatorConfig | undefined,
451
+ env: NodeJS.ProcessEnv = process.env,
452
+ ): ThinkingIndicatorSettings {
453
+ const settings: ThinkingIndicatorSettings = { ...THINKING_INDICATOR_DEFAULTS };
454
+ const envEnabled = envFlag(env.PRETTY_THINKING_INDICATOR);
455
+ if (envEnabled !== undefined) settings.enabled = envEnabled;
456
+ else if (typeof config?.enabled === "boolean") settings.enabled = config.enabled;
457
+ return settings;
458
+ }
459
+
460
+ export interface ThinkingUiLike {
461
+ theme?: WorkingThemeLike;
462
+ setHiddenThinkingLabel(label?: string): void;
463
+ }
464
+
465
+ export interface ThinkingLabelAnimator {
466
+ /** Apply the next shimmer frame to the hidden-thinking label. */
467
+ tick(): void;
468
+ /** Restore pi's default static label. */
469
+ restore(): void;
470
+ /** Pre-rendered label frames (exposed for diagnostics). */
471
+ readonly frames: readonly string[];
472
+ }
473
+
474
+ const THINKING_LABEL = "Thinking...";
475
+
476
+ /**
477
+ * True while a streaming assistant message is currently emitting a thinking
478
+ * block (its last content block). Used to gate label ticks to the thinking
479
+ * phase — once text or tool calls stream, the label is frozen back to pi's
480
+ * default instead of rebuilding the transcript for a row nobody watches.
481
+ */
482
+ export function thinkingBlockActive(message: unknown): boolean {
483
+ const content = (message as { content?: Array<{ type?: string }> } | undefined)?.content;
484
+ if (!Array.isArray(content) || content.length === 0) return false;
485
+ return content[content.length - 1]?.type === "thinking";
486
+ }
487
+
488
+ /**
489
+ * Animate pi's hidden-thinking label ("Thinking...") with the same shimmer as
490
+ * the working row. Pi renders the label as static italic `thinkingText` text;
491
+ * the only extension lever is `setHiddenThinkingLabel(label)`, which rebuilds
492
+ * chat children — the streaming component already rebuilds per delta, so the
493
+ * animator is driven at a throttled cadence (100ms) from index.ts while the
494
+ * agent streams and thinking blocks are hidden.
495
+ *
496
+ * Tiers: low = theme `thinkingText` (pi's own label look), mid/high = session
497
+ * accent when enabled; every frame is italic like pi's label; no spinner.
498
+ */
499
+ export function createThinkingLabelAnimator(
500
+ ui: ThinkingUiLike,
501
+ workSettings: WorkingIndicatorSettings,
502
+ sessionName?: string,
503
+ thinking?: ThinkingIndicatorSettings,
504
+ ): ThinkingLabelAnimator {
505
+ const noop: ThinkingLabelAnimator = {
506
+ tick() {},
507
+ restore() {},
508
+ frames: [],
509
+ };
510
+ if (thinking && !thinking.enabled) return noop;
511
+ if (typeof ui.setHiddenThinkingLabel !== "function") return noop;
512
+
513
+ const ansiResolved = resolvePaletteAnsi(workSettings.palette, ui.theme);
514
+ let ansi: ResolvedPalette = {
515
+ ...ansiResolved,
516
+ low: colorToAnsi("thinkingText", ui.theme, FG_THINKING_FALLBACK),
517
+ };
518
+ if (workSettings.sessionAccent && sessionName && !workSettings.tiersCustomized) {
519
+ const accent = hexToAnsiFg(sessionAccentHex(sessionName));
520
+ if (accent) ansi = { ...ansi, mid: accent, high: accent };
521
+ }
522
+ const { frames } = buildWorkingFrames([THINKING_LABEL], {
523
+ mode: workSettings.mode,
524
+ ansi,
525
+ bold: workSettings.bold,
526
+ spinner: false,
527
+ italic: true,
528
+ });
529
+ if (frames.length === 0) return noop;
530
+
531
+ let index = 0;
532
+ let applied = false;
533
+ return {
534
+ frames,
535
+ tick(): void {
536
+ // A single frame (static mode) never changes — skip redundant rebuilds.
537
+ if (applied && frames.length === 1) return;
538
+ ui.setHiddenThinkingLabel(frames[index % frames.length]);
539
+ index++;
540
+ applied = true;
541
+ },
542
+ restore(): void {
543
+ // undefined → pi falls back to its default static label.
544
+ ui.setHiddenThinkingLabel(undefined);
545
+ },
546
+ };
547
+ }
548
+
549
+ // ─── Installation ────────────────────────────────────────────────────────────
550
+
551
+ /** Structural slice of pi's Theme needed for the hint, palette, and thinking label. */
552
+ export interface WorkingThemeLike {
553
+ /** Narrowed to the only color the hint needs; pi's ThemeColor satisfies it. */
554
+ fg?: (name: "dim", text: string) => string;
555
+ getFgAnsi?: (name: "dim" | "muted" | "accent" | "thinkingText") => string;
556
+ }
557
+
558
+ export interface WorkingUiLike {
559
+ theme?: WorkingThemeLike;
560
+ setWorkingVisible(visible: boolean): void;
561
+ setWidget(
562
+ key: string,
563
+ factory: ((tui: WidgetTuiLike, theme: unknown) => WorkingWidget) | undefined,
564
+ options?: { placement?: "aboveEditor" | "belowEditor" },
565
+ ): void;
566
+ }
567
+
568
+ export interface KeybindingsLike {
569
+ getKeys(name: string): string[];
570
+ }
571
+
572
+ export interface WorkingIndicatorController {
573
+ /** Streaming began — show and animate the row. */
574
+ start(): void;
575
+ /** Streaming ended — hide the row and pause the animation. */
576
+ stop(): void;
577
+ /** Remove the widget and stop the animation. */
578
+ dispose(): void;
579
+ /** Pre-rendered frames (exposed for diagnostics). */
580
+ readonly frames: readonly string[];
581
+ }
582
+
583
+ const WIDGET_KEY = "pi-pretty-working";
584
+
585
+ async function loadHostKeybindings(): Promise<KeybindingsLike | undefined> {
586
+ try {
587
+ const tui = (await import("@earendil-works/pi-tui")) as typeof import("@earendil-works/pi-tui");
588
+ return tui.getKeybindings?.();
589
+ } catch {
590
+ return undefined;
591
+ }
592
+ }
593
+
594
+ function formatKeyText(keys: string[]): string {
595
+ const darwin = process.platform === "darwin";
596
+ return keys
597
+ .join("/")
598
+ .split("/")
599
+ .map((key) =>
600
+ key
601
+ .split("+")
602
+ .map((part) => (darwin && part.toLowerCase() === "alt" ? "option" : part))
603
+ .join("+"),
604
+ )
605
+ .join("/");
606
+ }
607
+
608
+ async function resolveHint(
609
+ ui: WorkingUiLike,
610
+ deps?: { getKeybindings?: () => KeybindingsLike | undefined | Promise<KeybindingsLike | undefined> },
611
+ ): Promise<string | undefined> {
612
+ try {
613
+ const loader = deps?.getKeybindings ?? loadHostKeybindings;
614
+ const keybindings = await loader();
615
+ const keys = keybindings?.getKeys?.("app.interrupt");
616
+ if (!keys?.length) return undefined;
617
+ const text = ` (${formatKeyText(keys)} to interrupt)`;
618
+ return ui.theme?.fg ? ui.theme.fg("dim", text) : text;
619
+ } catch {
620
+ return undefined;
621
+ }
622
+ }
623
+
624
+ /**
625
+ * Take over pi's working row with our own flush-left shimmer widget.
626
+ *
627
+ * Installs a zero-padding component above the editor and hides the host
628
+ * loader; returns a controller the host lifecycle drives (`start` on
629
+ * agent_start, `stop` on agent_end). No-op (host defaults untouched) when
630
+ * disabled or the phrase list is empty.
631
+ */
632
+ export async function installWorkingIndicator(
633
+ ui: WorkingUiLike,
634
+ settings: WorkingIndicatorSettings,
635
+ deps?: { getKeybindings?: () => KeybindingsLike | undefined | Promise<KeybindingsLike | undefined> },
636
+ sessionName?: string,
637
+ ): Promise<WorkingIndicatorController> {
638
+ const noopController: WorkingIndicatorController = {
639
+ start() {},
640
+ stop() {},
641
+ dispose() {},
642
+ frames: [],
643
+ };
644
+ if (!settings.enabled) return noopController;
645
+ const texts = settings.texts.map((t) => t.trim()).filter((t) => t.length > 0);
646
+ if (texts.length === 0) return noopController;
647
+
648
+ const ansiResolved = resolvePaletteAnsi(settings.palette, ui.theme);
649
+ let ansi = ansiResolved;
650
+ let spinnerColor: string | undefined;
651
+ if (settings.sessionAccent && sessionName && !settings.tiersCustomized) {
652
+ const accentHex = sessionAccentHex(sessionName);
653
+ const accent = hexToAnsiFg(accentHex);
654
+ if (accent) {
655
+ ansi = { ...ansi, mid: accent, high: accent };
656
+ spinnerColor = hexToAnsiFg(dimAccentHex(accentHex));
657
+ }
658
+ }
659
+ const hint = settings.hint ? await resolveHint(ui, deps) : undefined;
660
+ const { frames, intervalMs } = buildWorkingFrames(texts, {
661
+ mode: settings.mode,
662
+ ansi,
663
+ bold: settings.bold,
664
+ spinnerColor,
665
+ hint,
666
+ });
667
+ if (frames.length === 0) return noopController;
668
+
669
+ const widget = new WorkingWidget();
670
+ widget.setFrames(frames, intervalMs);
671
+ // Widget first, visibility second: if setWidget throws (older host without
672
+ // the API) the host loader was never hidden and pi's default remains.
673
+ ui.setWidget(
674
+ WIDGET_KEY,
675
+ (tui) => {
676
+ widget.attach(tui);
677
+ return widget;
678
+ },
679
+ { placement: "aboveEditor" },
680
+ );
681
+ ui.setWorkingVisible(false);
682
+ return {
683
+ start: () => widget.start(),
684
+ stop: () => widget.stop(),
685
+ dispose: () => {
686
+ widget.dispose();
687
+ ui.setWidget(WIDGET_KEY, undefined);
688
+ },
689
+ frames,
690
+ };
691
+ }