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