@heyhuynhgiabuu/pi-pretty 0.6.24 → 0.6.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/README.md +64 -1
- package/dist/config.d.ts +19 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +38 -0
- package/dist/config.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +263 -1
- package/dist/index.js.map +1 -1
- package/dist/session-color.d.ts +30 -0
- package/dist/session-color.d.ts.map +1 -0
- package/dist/session-color.js +170 -0
- package/dist/session-color.js.map +1 -0
- package/dist/tools/bash.js +1 -1
- package/dist/tools/bash.js.map +1 -1
- package/dist/tools/find.js +4 -4
- package/dist/tools/find.js.map +1 -1
- package/dist/tools/grep.js +1 -1
- package/dist/tools/grep.js.map +1 -1
- package/dist/tools/ls.js +2 -2
- package/dist/tools/ls.js.map +1 -1
- package/dist/tools/read.js +2 -2
- package/dist/tools/read.js.map +1 -1
- package/dist/types.d.ts +4 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/working-indicator.d.ts +241 -0
- package/dist/working-indicator.d.ts.map +1 -0
- package/dist/working-indicator.js +679 -0
- package/dist/working-indicator.js.map +1 -0
- package/package.json +7 -6
- package/src/config.ts +48 -0
- package/src/index.ts +284 -2
- package/src/session-color.ts +172 -0
- package/src/tools/bash.ts +1 -1
- package/src/tools/find.ts +4 -4
- package/src/tools/grep.ts +1 -1
- package/src/tools/ls.ts +2 -2
- package/src/tools/read.ts +2 -2
- package/src/types.ts +4 -0
- package/src/working-indicator.ts +884 -0
|
@@ -0,0 +1,884 @@
|
|
|
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
|
+
/** Estimate streamed output tokens: provider `usage.output` when exposed, else visible chars ÷ 4. */
|
|
370
|
+
export function workingTokens(message: unknown): number {
|
|
371
|
+
const usage = (message as { usage?: { output?: unknown } } | undefined)?.usage;
|
|
372
|
+
const output = Number(usage?.output);
|
|
373
|
+
if (Number.isFinite(output) && output > 0) return Math.round(output);
|
|
374
|
+
const content = (message as { content?: Array<{ type?: string; text?: unknown; thinking?: unknown }> } | undefined)
|
|
375
|
+
?.content;
|
|
376
|
+
if (!Array.isArray(content)) return 0;
|
|
377
|
+
let chars = 0;
|
|
378
|
+
for (const block of content) {
|
|
379
|
+
if (block?.type === "text" && typeof block.text === "string") chars += block.text.length;
|
|
380
|
+
else if (block?.type === "thinking" && typeof block.thinking === "string") chars += block.thinking.length;
|
|
381
|
+
}
|
|
382
|
+
return Math.round(chars / 4);
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// ─── Widget ──────────────────────────────────────────────────────────────────
|
|
386
|
+
|
|
387
|
+
/** Slice of the pi-tui TUI instance the widget needs. */
|
|
388
|
+
export interface WidgetTuiLike {
|
|
389
|
+
requestRender(): void;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* Zero-padding working-row component. The host renders whatever `render()`
|
|
394
|
+
* returns with no margins, so the row sits flush-left — the thing the frames
|
|
395
|
+
* API could not do.
|
|
396
|
+
*/
|
|
397
|
+
export class WorkingWidget {
|
|
398
|
+
#frames: string[] = [];
|
|
399
|
+
#index = 0;
|
|
400
|
+
#intervalMs = WORKING_INTERVAL_MS;
|
|
401
|
+
#interval: ReturnType<typeof setInterval> | undefined;
|
|
402
|
+
#tui: WidgetTuiLike | undefined;
|
|
403
|
+
#started = false;
|
|
404
|
+
#disposed = false;
|
|
405
|
+
#stats: string | undefined;
|
|
406
|
+
|
|
407
|
+
setFrames(frames: string[], intervalMs: number): void {
|
|
408
|
+
this.#frames = frames;
|
|
409
|
+
this.#intervalMs = intervalMs;
|
|
410
|
+
this.#index = 0;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
attach(tui: WidgetTuiLike): void {
|
|
414
|
+
this.#tui = tui;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** Ask the host for a render — lets non-widget consumers (the thinking label
|
|
418
|
+
* ticker) reuse this widget's TUI handle instead of relying on natural
|
|
419
|
+
* streaming renders. */
|
|
420
|
+
requestRender(): void {
|
|
421
|
+
this.#tui?.requestRender();
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/** Dynamic right-side status segment (e.g. live token count), styled dim at
|
|
425
|
+
* render time so theme changes don't bake stale ANSI into it. */
|
|
426
|
+
setStats(text: string | undefined): void {
|
|
427
|
+
this.#stats = text || undefined;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
start(): void {
|
|
431
|
+
if (this.#disposed || this.#started) return;
|
|
432
|
+
this.#started = true;
|
|
433
|
+
this.#index = 0;
|
|
434
|
+
// A single frame has nothing to cycle — skip the 30fps render churn.
|
|
435
|
+
if (this.#frames.length <= 1) return;
|
|
436
|
+
this.#interval = setInterval(() => {
|
|
437
|
+
this.#index = (this.#index + 1) % Math.max(1, this.#frames.length);
|
|
438
|
+
this.#tui?.requestRender();
|
|
439
|
+
}, this.#intervalMs);
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
stop(): void {
|
|
443
|
+
this.#started = false;
|
|
444
|
+
if (this.#interval) {
|
|
445
|
+
clearInterval(this.#interval);
|
|
446
|
+
this.#interval = undefined;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** Flush-left single line; invisible (no lines) while stopped. */
|
|
451
|
+
render(width: number): string[] {
|
|
452
|
+
if (!this.#started || this.#frames.length === 0) return [];
|
|
453
|
+
const frame = this.#frames[this.#index % this.#frames.length] ?? "";
|
|
454
|
+
const suffix = this.#stats ? `${FG_DIM}${this.#stats}${RESET_FG}` : "";
|
|
455
|
+
return [truncateToWidth(frame + suffix, Math.max(1, width))];
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
invalidate(): void {
|
|
459
|
+
// Stateless per render — nothing to invalidate.
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
dispose(): void {
|
|
463
|
+
this.stop();
|
|
464
|
+
this.#disposed = true;
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// ─── Thinking label ───────────────────────────────────────────────────────────
|
|
469
|
+
|
|
470
|
+
export interface ThinkingIndicatorSettings {
|
|
471
|
+
enabled: boolean;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
export const THINKING_INDICATOR_DEFAULTS: ThinkingIndicatorSettings = { enabled: true };
|
|
475
|
+
|
|
476
|
+
/**
|
|
477
|
+
* Resolve thinking-label shimmer settings from `pi-pretty.json`'s
|
|
478
|
+
* `thinkingIndicator` object and env overrides (env > config > default).
|
|
479
|
+
*/
|
|
480
|
+
export function resolveThinkingIndicatorSettings(
|
|
481
|
+
config: ThinkingIndicatorConfig | undefined,
|
|
482
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
483
|
+
): ThinkingIndicatorSettings {
|
|
484
|
+
const settings: ThinkingIndicatorSettings = { ...THINKING_INDICATOR_DEFAULTS };
|
|
485
|
+
const envEnabled = envFlag(env.PRETTY_THINKING_INDICATOR);
|
|
486
|
+
if (envEnabled !== undefined) settings.enabled = envEnabled;
|
|
487
|
+
else if (typeof config?.enabled === "boolean") settings.enabled = config.enabled;
|
|
488
|
+
return settings;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
export interface ThinkingUiLike {
|
|
492
|
+
theme?: WorkingThemeLike;
|
|
493
|
+
setHiddenThinkingLabel(label?: string): void;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
// ─── Per-row hidden-thinking labels ──────────────────────────────────────────
|
|
497
|
+
|
|
498
|
+
/** Controller for the host-component label interception. */
|
|
499
|
+
export interface PerRowThinkingLabels {
|
|
500
|
+
/** Mark the message currently streaming a thinking block (its row animates). */
|
|
501
|
+
setActive(timestamp: number): void;
|
|
502
|
+
/** Freeze a message's completed thinking duration in ms (its row shows
|
|
503
|
+
* `Thought for Xs` derived from this). */
|
|
504
|
+
complete(timestamp: number, durationMs: number): void;
|
|
505
|
+
/** Drop the active mark (run ended); completed rows keep their durations. */
|
|
506
|
+
clearActive(): void;
|
|
507
|
+
/** Restore the original prototype setter. */
|
|
508
|
+
uninstall(): void;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
const PER_ROW_PATCH = Symbol.for("pi-pretty.per-row-thinking-labels");
|
|
512
|
+
|
|
513
|
+
interface RowInternals {
|
|
514
|
+
lastMessage?: { timestamp?: unknown };
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/**
|
|
518
|
+
* Intercept the host's per-row label fan-out method
|
|
519
|
+
* (`AssistantMessageComponent.prototype.setHiddenThinkingLabel`): each row
|
|
520
|
+
* substitutes the incoming global label with its own — the streaming row
|
|
521
|
+
* animates, completed rows stay frozen at their own `Thought for Xs`, unknown
|
|
522
|
+
* rows fall back to pi's default. Any per-call failure passes the incoming
|
|
523
|
+
* label through unchanged, so a host internals change degrades to pi-pretty's
|
|
524
|
+
* global-label behavior instead of breaking. Durations live per session.
|
|
525
|
+
*/
|
|
526
|
+
export function installPerRowThinkingLabels(componentClass: unknown): PerRowThinkingLabels | undefined {
|
|
527
|
+
const proto = (componentClass as { prototype?: { setHiddenThinkingLabel?: unknown } } | undefined)?.prototype;
|
|
528
|
+
const original = proto?.setHiddenThinkingLabel;
|
|
529
|
+
if (typeof componentClass !== "function" || !proto || typeof original !== "function") return undefined;
|
|
530
|
+
const existing = (original as { [PER_ROW_PATCH]?: PerRowThinkingLabels })[PER_ROW_PATCH];
|
|
531
|
+
// Reuse the installed patch but start from clean state: a session_start
|
|
532
|
+
// without an intervening shutdown (defensive) must not resurrect stale rows.
|
|
533
|
+
if (existing) {
|
|
534
|
+
existing.clearActive();
|
|
535
|
+
return existing;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
const state: { activeTs?: number; completed: Map<number, number> } = { completed: new Map() };
|
|
539
|
+
const patched = function (this: unknown, label: string | undefined): void {
|
|
540
|
+
const own = ownLabel(this, label);
|
|
541
|
+
(original as (this: unknown, label: string | undefined) => void).call(this, own);
|
|
542
|
+
};
|
|
543
|
+
const ownLabel = (component: unknown, incoming: string | undefined): string | undefined => {
|
|
544
|
+
try {
|
|
545
|
+
const ts = (component as RowInternals | undefined)?.lastMessage?.timestamp;
|
|
546
|
+
if (typeof ts !== "number") return incoming;
|
|
547
|
+
if (ts === state.activeTs) return incoming;
|
|
548
|
+
const ms = state.completed.get(ts);
|
|
549
|
+
return ms === undefined ? THINKING_LABEL : `Thought for ${formatThinkingDuration(ms)}`;
|
|
550
|
+
} catch {
|
|
551
|
+
return incoming;
|
|
552
|
+
}
|
|
553
|
+
};
|
|
554
|
+
const controller: PerRowThinkingLabels = {
|
|
555
|
+
setActive(timestamp: number): void {
|
|
556
|
+
state.activeTs = timestamp;
|
|
557
|
+
},
|
|
558
|
+
complete(timestamp: number, durationMs: number): void {
|
|
559
|
+
state.completed.set(timestamp, durationMs);
|
|
560
|
+
},
|
|
561
|
+
clearActive(): void {
|
|
562
|
+
state.activeTs = undefined;
|
|
563
|
+
},
|
|
564
|
+
uninstall(): void {
|
|
565
|
+
if (proto.setHiddenThinkingLabel === patched) {
|
|
566
|
+
proto.setHiddenThinkingLabel = original as { setHiddenThinkingLabel?: unknown }["setHiddenThinkingLabel"];
|
|
567
|
+
}
|
|
568
|
+
state.completed.clear();
|
|
569
|
+
state.activeTs = undefined;
|
|
570
|
+
},
|
|
571
|
+
};
|
|
572
|
+
(patched as { [PER_ROW_PATCH]?: PerRowThinkingLabels })[PER_ROW_PATCH] = controller;
|
|
573
|
+
proto.setHiddenThinkingLabel = patched as NonNullable<{ setHiddenThinkingLabel?: unknown }["setHiddenThinkingLabel"]>;
|
|
574
|
+
return controller;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
export interface ThinkingLabelAnimator {
|
|
578
|
+
/** Apply the next shimmer frame, rebuilding frames when the label changes. */
|
|
579
|
+
tick(label?: string): void;
|
|
580
|
+
/** Apply a non-animated label (the host supplies its normal thinking style). */
|
|
581
|
+
show(label: string): void;
|
|
582
|
+
/** Restore pi's default static label. */
|
|
583
|
+
restore(): void;
|
|
584
|
+
/** Current pre-rendered label frames (exposed for diagnostics). */
|
|
585
|
+
readonly frames: readonly string[];
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
export interface ThinkingTimer {
|
|
589
|
+
/** Render the active label with the current elapsed duration. */
|
|
590
|
+
tick(): void;
|
|
591
|
+
/** Freeze the elapsed duration; returns the total in milliseconds, or
|
|
592
|
+
* undefined when the timer was already terminal. */
|
|
593
|
+
complete(): number | undefined;
|
|
594
|
+
/** Restore pi's default label and make the timer terminal. */
|
|
595
|
+
restore(): void;
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
const THINKING_LABEL = "Thinking...";
|
|
599
|
+
|
|
600
|
+
/** Format elapsed milliseconds as whole seconds with compact padded units. */
|
|
601
|
+
export function formatThinkingDuration(elapsedMs: number): string {
|
|
602
|
+
const totalSeconds = Math.floor(elapsedMs / 1000);
|
|
603
|
+
const seconds = totalSeconds % 60;
|
|
604
|
+
const totalMinutes = Math.floor(totalSeconds / 60);
|
|
605
|
+
const minutes = totalMinutes % 60;
|
|
606
|
+
const hours = Math.floor(totalMinutes / 60);
|
|
607
|
+
if (hours > 0) return `${hours}h ${String(minutes).padStart(2, "0")}m ${String(seconds).padStart(2, "0")}s`;
|
|
608
|
+
if (totalMinutes > 0) return `${totalMinutes}m ${String(seconds).padStart(2, "0")}s`;
|
|
609
|
+
return `${seconds}s`;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/**
|
|
613
|
+
* Couple elapsed-time wording to the label animator through an injected clock.
|
|
614
|
+
* The timer starts on the first thinking delta, freezes once, and is terminal
|
|
615
|
+
* after completion or restore. `startElapsedMs` resumes a later run in the
|
|
616
|
+
* same message from its accumulated thinking time (per-message semantics:
|
|
617
|
+
* the host renders one label line per thinking run, all sharing the message
|
|
618
|
+
* label, so a fresh-zero restart would visibly rewind earlier lines).
|
|
619
|
+
*/
|
|
620
|
+
export function createThinkingTimer(
|
|
621
|
+
animator: ThinkingLabelAnimator,
|
|
622
|
+
now: () => number = Date.now,
|
|
623
|
+
startElapsedMs = 0,
|
|
624
|
+
): ThinkingTimer {
|
|
625
|
+
const startedAt = now() - startElapsedMs;
|
|
626
|
+
let terminal = false;
|
|
627
|
+
const elapsed = (): number => now() - startedAt;
|
|
628
|
+
const duration = (): string => formatThinkingDuration(elapsed());
|
|
629
|
+
return {
|
|
630
|
+
tick(): void {
|
|
631
|
+
if (terminal) return;
|
|
632
|
+
animator.tick(`${THINKING_LABEL} ${duration()}`);
|
|
633
|
+
},
|
|
634
|
+
complete(): number | undefined {
|
|
635
|
+
if (terminal) return undefined;
|
|
636
|
+
terminal = true;
|
|
637
|
+
const ms = elapsed();
|
|
638
|
+
animator.show(`Thought for ${formatThinkingDuration(ms)}`);
|
|
639
|
+
return ms;
|
|
640
|
+
},
|
|
641
|
+
restore(): void {
|
|
642
|
+
terminal = true;
|
|
643
|
+
animator.restore();
|
|
644
|
+
},
|
|
645
|
+
};
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
/**
|
|
649
|
+
* True while a streaming assistant message is currently emitting a thinking
|
|
650
|
+
* block (its last content block). Used to gate label ticks to the thinking
|
|
651
|
+
* phase — once text or tool calls stream, the label is frozen back to pi's
|
|
652
|
+
* default instead of rebuilding the transcript for a row nobody watches.
|
|
653
|
+
*/
|
|
654
|
+
export function thinkingBlockActive(message: unknown): boolean {
|
|
655
|
+
const content = (message as { content?: Array<{ type?: string }> } | undefined)?.content;
|
|
656
|
+
if (!Array.isArray(content) || content.length === 0) return false;
|
|
657
|
+
return content[content.length - 1]?.type === "thinking";
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/**
|
|
661
|
+
* Animate pi's hidden-thinking label ("Thinking...") with the same shimmer as
|
|
662
|
+
* the working row. Pi renders the label as static italic `thinkingText` text;
|
|
663
|
+
* the only extension lever is `setHiddenThinkingLabel(label)`, which rebuilds
|
|
664
|
+
* chat children, so index.ts drives it at 30fps only while the streaming
|
|
665
|
+
* message's last block is thinking. The elapsed label is rebuilt only when its
|
|
666
|
+
* whole-second text changes; the shimmer frame still advances every tick.
|
|
667
|
+
*
|
|
668
|
+
* Tiers: low = theme `thinkingText` (pi's own label look), mid/high = session
|
|
669
|
+
* accent when enabled; every frame is italic like pi's label; no spinner.
|
|
670
|
+
*/
|
|
671
|
+
export function createThinkingLabelAnimator(
|
|
672
|
+
ui: ThinkingUiLike,
|
|
673
|
+
workSettings: WorkingIndicatorSettings,
|
|
674
|
+
sessionName?: string,
|
|
675
|
+
thinking?: ThinkingIndicatorSettings,
|
|
676
|
+
): ThinkingLabelAnimator {
|
|
677
|
+
const noop: ThinkingLabelAnimator = {
|
|
678
|
+
tick() {},
|
|
679
|
+
show() {},
|
|
680
|
+
restore() {},
|
|
681
|
+
frames: [],
|
|
682
|
+
};
|
|
683
|
+
if (thinking && !thinking.enabled) return noop;
|
|
684
|
+
if (typeof ui.setHiddenThinkingLabel !== "function") return noop;
|
|
685
|
+
|
|
686
|
+
const ansiResolved = resolvePaletteAnsi(workSettings.palette, ui.theme);
|
|
687
|
+
let ansi: ResolvedPalette = {
|
|
688
|
+
...ansiResolved,
|
|
689
|
+
low: colorToAnsi("thinkingText", ui.theme, FG_THINKING_FALLBACK),
|
|
690
|
+
};
|
|
691
|
+
if (workSettings.sessionAccent && sessionName && !workSettings.tiersCustomized) {
|
|
692
|
+
const accent = hexToAnsiFg(sessionAccentHex(sessionName));
|
|
693
|
+
if (accent) ansi = { ...ansi, mid: accent, high: accent };
|
|
694
|
+
}
|
|
695
|
+
const buildLabelFrames = (label: string): string[] =>
|
|
696
|
+
buildWorkingFrames([label], {
|
|
697
|
+
mode: workSettings.mode,
|
|
698
|
+
ansi,
|
|
699
|
+
bold: workSettings.bold,
|
|
700
|
+
spinner: false,
|
|
701
|
+
italic: true,
|
|
702
|
+
}).frames;
|
|
703
|
+
|
|
704
|
+
let currentLabel = THINKING_LABEL;
|
|
705
|
+
let frames = buildLabelFrames(currentLabel);
|
|
706
|
+
|
|
707
|
+
let index = 0;
|
|
708
|
+
let appliedLabel: string | undefined;
|
|
709
|
+
return {
|
|
710
|
+
get frames(): readonly string[] {
|
|
711
|
+
return frames;
|
|
712
|
+
},
|
|
713
|
+
tick(label = THINKING_LABEL): void {
|
|
714
|
+
if (label !== currentLabel) {
|
|
715
|
+
frames = buildLabelFrames(label);
|
|
716
|
+
currentLabel = label;
|
|
717
|
+
}
|
|
718
|
+
// A static frame changes only when its elapsed-time label changes.
|
|
719
|
+
if (appliedLabel === currentLabel && frames.length === 1) return;
|
|
720
|
+
ui.setHiddenThinkingLabel(frames[index % frames.length]);
|
|
721
|
+
index++;
|
|
722
|
+
appliedLabel = currentLabel;
|
|
723
|
+
},
|
|
724
|
+
show(label: string): void {
|
|
725
|
+
ui.setHiddenThinkingLabel(label);
|
|
726
|
+
},
|
|
727
|
+
restore(): void {
|
|
728
|
+
// undefined → pi falls back to its default static label.
|
|
729
|
+
ui.setHiddenThinkingLabel(undefined);
|
|
730
|
+
},
|
|
731
|
+
};
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
// ─── Installation ────────────────────────────────────────────────────────────
|
|
735
|
+
|
|
736
|
+
/** Structural slice of pi's Theme needed for the hint, palette, and thinking label. */
|
|
737
|
+
export interface WorkingThemeLike {
|
|
738
|
+
/** Narrowed to the only color the hint needs; pi's ThemeColor satisfies it. */
|
|
739
|
+
fg?: (name: "dim", text: string) => string;
|
|
740
|
+
getFgAnsi?: (name: "dim" | "muted" | "accent" | "thinkingText") => string;
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
export interface WorkingUiLike {
|
|
744
|
+
theme?: WorkingThemeLike;
|
|
745
|
+
setWorkingVisible(visible: boolean): void;
|
|
746
|
+
setWidget(
|
|
747
|
+
key: string,
|
|
748
|
+
factory: ((tui: WidgetTuiLike, theme: unknown) => WorkingWidget) | undefined,
|
|
749
|
+
options?: { placement?: "aboveEditor" | "belowEditor" },
|
|
750
|
+
): void;
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
export interface KeybindingsLike {
|
|
754
|
+
getKeys(name: string): string[];
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
export interface WorkingIndicatorController {
|
|
758
|
+
/** Streaming began — show and animate the row. */
|
|
759
|
+
start(): void;
|
|
760
|
+
/** Streaming ended — hide the row and pause the animation. */
|
|
761
|
+
stop(): void;
|
|
762
|
+
/** Remove the widget and stop the animation. */
|
|
763
|
+
dispose(): void;
|
|
764
|
+
/** Update the dim right-side status segment (live token count). */
|
|
765
|
+
setStats(text: string | undefined): void;
|
|
766
|
+
/** Request a host render via the widget's TUI handle. */
|
|
767
|
+
requestRender(): void;
|
|
768
|
+
/** Pre-rendered frames (exposed for diagnostics). */
|
|
769
|
+
readonly frames: readonly string[];
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
const WIDGET_KEY = "pi-pretty-working";
|
|
773
|
+
|
|
774
|
+
async function loadHostKeybindings(): Promise<KeybindingsLike | undefined> {
|
|
775
|
+
try {
|
|
776
|
+
const tui = (await import("@earendil-works/pi-tui")) as typeof import("@earendil-works/pi-tui");
|
|
777
|
+
return tui.getKeybindings?.();
|
|
778
|
+
} catch {
|
|
779
|
+
return undefined;
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
function formatKeyText(keys: string[]): string {
|
|
784
|
+
const darwin = process.platform === "darwin";
|
|
785
|
+
return keys
|
|
786
|
+
.join("/")
|
|
787
|
+
.split("/")
|
|
788
|
+
.map((key) =>
|
|
789
|
+
key
|
|
790
|
+
.split("+")
|
|
791
|
+
.map((part) => (darwin && part.toLowerCase() === "alt" ? "option" : part))
|
|
792
|
+
.join("+"),
|
|
793
|
+
)
|
|
794
|
+
.join("/");
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
async function resolveHint(
|
|
798
|
+
ui: WorkingUiLike,
|
|
799
|
+
deps?: { getKeybindings?: () => KeybindingsLike | undefined | Promise<KeybindingsLike | undefined> },
|
|
800
|
+
): Promise<string | undefined> {
|
|
801
|
+
try {
|
|
802
|
+
const loader = deps?.getKeybindings ?? loadHostKeybindings;
|
|
803
|
+
const keybindings = await loader();
|
|
804
|
+
const keys = keybindings?.getKeys?.("app.interrupt");
|
|
805
|
+
if (!keys?.length) return undefined;
|
|
806
|
+
const text = ` (${formatKeyText(keys)} to interrupt)`;
|
|
807
|
+
return ui.theme?.fg ? ui.theme.fg("dim", text) : text;
|
|
808
|
+
} catch {
|
|
809
|
+
return undefined;
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
/**
|
|
814
|
+
* Take over pi's working row with our own flush-left shimmer widget.
|
|
815
|
+
*
|
|
816
|
+
* Installs a zero-padding component above the editor and hides the host
|
|
817
|
+
* loader; returns a controller the host lifecycle drives (`start` on
|
|
818
|
+
* agent_start, `stop` on agent_end). No-op (host defaults untouched) when
|
|
819
|
+
* disabled or the phrase list is empty.
|
|
820
|
+
*/
|
|
821
|
+
export async function installWorkingIndicator(
|
|
822
|
+
ui: WorkingUiLike,
|
|
823
|
+
settings: WorkingIndicatorSettings,
|
|
824
|
+
deps?: { getKeybindings?: () => KeybindingsLike | undefined | Promise<KeybindingsLike | undefined> },
|
|
825
|
+
sessionName?: string,
|
|
826
|
+
): Promise<WorkingIndicatorController> {
|
|
827
|
+
const noopController: WorkingIndicatorController = {
|
|
828
|
+
start() {},
|
|
829
|
+
stop() {},
|
|
830
|
+
dispose() {},
|
|
831
|
+
setStats() {},
|
|
832
|
+
requestRender() {},
|
|
833
|
+
frames: [],
|
|
834
|
+
};
|
|
835
|
+
if (!settings.enabled) return noopController;
|
|
836
|
+
const texts = settings.texts.map((t) => t.trim()).filter((t) => t.length > 0);
|
|
837
|
+
if (texts.length === 0) return noopController;
|
|
838
|
+
|
|
839
|
+
const ansiResolved = resolvePaletteAnsi(settings.palette, ui.theme);
|
|
840
|
+
let ansi = ansiResolved;
|
|
841
|
+
let spinnerColor: string | undefined;
|
|
842
|
+
if (settings.sessionAccent && sessionName && !settings.tiersCustomized) {
|
|
843
|
+
const accentHex = sessionAccentHex(sessionName);
|
|
844
|
+
const accent = hexToAnsiFg(accentHex);
|
|
845
|
+
if (accent) {
|
|
846
|
+
ansi = { ...ansi, mid: accent, high: accent };
|
|
847
|
+
spinnerColor = hexToAnsiFg(dimAccentHex(accentHex));
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
const hint = settings.hint ? await resolveHint(ui, deps) : undefined;
|
|
851
|
+
const { frames, intervalMs } = buildWorkingFrames(texts, {
|
|
852
|
+
mode: settings.mode,
|
|
853
|
+
ansi,
|
|
854
|
+
bold: settings.bold,
|
|
855
|
+
spinnerColor,
|
|
856
|
+
hint,
|
|
857
|
+
});
|
|
858
|
+
if (frames.length === 0) return noopController;
|
|
859
|
+
|
|
860
|
+
const widget = new WorkingWidget();
|
|
861
|
+
widget.setFrames(frames, intervalMs);
|
|
862
|
+
// Widget first, visibility second: if setWidget throws (older host without
|
|
863
|
+
// the API) the host loader was never hidden and pi's default remains.
|
|
864
|
+
ui.setWidget(
|
|
865
|
+
WIDGET_KEY,
|
|
866
|
+
(tui) => {
|
|
867
|
+
widget.attach(tui);
|
|
868
|
+
return widget;
|
|
869
|
+
},
|
|
870
|
+
{ placement: "aboveEditor" },
|
|
871
|
+
);
|
|
872
|
+
ui.setWorkingVisible(false);
|
|
873
|
+
return {
|
|
874
|
+
start: () => widget.start(),
|
|
875
|
+
stop: () => widget.stop(),
|
|
876
|
+
dispose: () => {
|
|
877
|
+
widget.dispose();
|
|
878
|
+
ui.setWidget(WIDGET_KEY, undefined);
|
|
879
|
+
},
|
|
880
|
+
setStats: (text: string | undefined) => widget.setStats(text),
|
|
881
|
+
requestRender: () => widget.requestRender(),
|
|
882
|
+
frames,
|
|
883
|
+
};
|
|
884
|
+
}
|