@f5-sales-demo/pi-tui 19.51.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/tui.ts ADDED
@@ -0,0 +1,1341 @@
1
+ /**
2
+ * Minimal TUI implementation with differential rendering
3
+ */
4
+ import * as fs from "node:fs";
5
+ import * as path from "node:path";
6
+ import { $flag, getDebugLogPath } from "@f5xc-salesdemos/pi-utils";
7
+ import { isKeyRelease, matchesKey } from "./keys";
8
+ import type { Terminal } from "./terminal";
9
+ import { ImageProtocol, setCellDimensions, setTerminalImageProtocol, TERMINAL } from "./terminal-capabilities";
10
+ import { extractSegments, sliceByColumn, sliceWithWidth, visibleWidth } from "./utils";
11
+
12
+ const SEGMENT_RESET = "\x1b[0m";
13
+
14
+ type InputListenerResult = { consume?: boolean; data?: string } | undefined;
15
+ type InputListener = (data: string) => InputListenerResult;
16
+
17
+ /**
18
+ * Component interface - all components must implement this
19
+ */
20
+ export interface Component {
21
+ /**
22
+ * Render the component to lines for the given viewport width
23
+ * @param width - Current viewport width
24
+ * @returns Array of strings, each representing a line
25
+ */
26
+ render(width: number): string[];
27
+
28
+ /**
29
+ * Optional handler for keyboard input when component has focus
30
+ */
31
+ handleInput?(data: string): void;
32
+
33
+ /**
34
+ * If true, component receives key release events (Kitty protocol).
35
+ * Default is false - release events are filtered out.
36
+ */
37
+ wantsKeyRelease?: boolean;
38
+
39
+ /**
40
+ * Invalidate any cached rendering state.
41
+ * Called when theme changes or when component needs to re-render from scratch.
42
+ */
43
+ invalidate(): void;
44
+ }
45
+
46
+ /**
47
+ * Interface for components that can receive focus and display a hardware cursor.
48
+ * When focused, the component should emit CURSOR_MARKER at the cursor position
49
+ * in its render output. TUI will find this marker and position the hardware
50
+ * cursor there for proper IME candidate window positioning.
51
+ */
52
+ export interface Focusable {
53
+ /** Set by TUI when focus changes. Component should emit CURSOR_MARKER when true. */
54
+ focused: boolean;
55
+ }
56
+
57
+ /** Type guard to check if a component implements Focusable */
58
+ export function isFocusable(component: Component | null): component is Component & Focusable {
59
+ return component !== null && "focused" in component;
60
+ }
61
+
62
+ /**
63
+ * Cursor position marker - APC (Application Program Command) sequence.
64
+ * This is a zero-width escape sequence that terminals ignore.
65
+ * Components emit this at the cursor position when focused.
66
+ * TUI finds and strips this marker, then positions the hardware cursor there.
67
+ */
68
+ export const CURSOR_MARKER = "\x1b_pi:c\x07";
69
+
70
+ export { visibleWidth };
71
+
72
+ /**
73
+ * Anchor position for overlays
74
+ */
75
+ export type OverlayAnchor =
76
+ | "center"
77
+ | "top-left"
78
+ | "top-right"
79
+ | "bottom-left"
80
+ | "bottom-right"
81
+ | "top-center"
82
+ | "bottom-center"
83
+ | "left-center"
84
+ | "right-center";
85
+
86
+ /**
87
+ * Margin configuration for overlays
88
+ */
89
+ export interface OverlayMargin {
90
+ top?: number;
91
+ right?: number;
92
+ bottom?: number;
93
+ left?: number;
94
+ }
95
+
96
+ /** Value that can be absolute (number) or percentage (string like "50%") */
97
+ export type SizeValue = number | `${number}%`;
98
+
99
+ /** Parse a SizeValue into absolute value given a reference size */
100
+ function parseSizeValue(value: SizeValue | undefined, referenceSize: number): number | undefined {
101
+ if (value === undefined) return undefined;
102
+ if (typeof value === "number") return value;
103
+ // Parse percentage string like "50%"
104
+ const match = value.match(/^(\d+(?:\.\d+)?)%$/);
105
+ if (match) {
106
+ return Math.floor((referenceSize * parseFloat(match[1])) / 100);
107
+ }
108
+ return undefined;
109
+ }
110
+
111
+ function isTermuxSession(): boolean {
112
+ return Boolean(process.env.TERMUX_VERSION);
113
+ }
114
+
115
+ /** Detect terminal multiplexers where scrollback clearing and height-change redraws are hostile. */
116
+ function isMultiplexer() {
117
+ return Boolean(Bun.env.TMUX || Bun.env.STY || Bun.env.ZELLIJ);
118
+ }
119
+
120
+ /**
121
+ * Options for overlay positioning and sizing.
122
+ * Values can be absolute numbers or percentage strings (e.g., "50%").
123
+ */
124
+ export interface OverlayOptions {
125
+ // === Sizing ===
126
+ /** Width in columns, or percentage of terminal width (e.g., "50%") */
127
+ width?: SizeValue;
128
+ /** Minimum width in columns */
129
+ minWidth?: number;
130
+ /** Maximum height in rows, or percentage of terminal height (e.g., "50%") */
131
+ maxHeight?: SizeValue;
132
+
133
+ // === Positioning - anchor-based ===
134
+ /** Anchor point for positioning (default: 'center') */
135
+ anchor?: OverlayAnchor;
136
+ /** Horizontal offset from anchor position (positive = right) */
137
+ offsetX?: number;
138
+ /** Vertical offset from anchor position (positive = down) */
139
+ offsetY?: number;
140
+
141
+ // === Positioning - percentage or absolute ===
142
+ /** Row position: absolute number, or percentage (e.g., "25%" = 25% from top) */
143
+ row?: SizeValue;
144
+ /** Column position: absolute number, or percentage (e.g., "50%" = centered horizontally) */
145
+ col?: SizeValue;
146
+
147
+ // === Margin from terminal edges ===
148
+ /** Margin from terminal edges. Number applies to all sides. */
149
+ margin?: OverlayMargin | number;
150
+
151
+ // === Visibility ===
152
+ /**
153
+ * Control overlay visibility based on terminal dimensions.
154
+ * If provided, overlay is only rendered when this returns true.
155
+ * Called each render cycle with current terminal dimensions.
156
+ */
157
+ visible?: (termWidth: number, termHeight: number) => boolean;
158
+ }
159
+
160
+ /**
161
+ * Handle returned by showOverlay for controlling the overlay
162
+ */
163
+ export interface OverlayHandle {
164
+ /** Permanently remove the overlay (cannot be shown again) */
165
+ hide(): void;
166
+ /** Temporarily hide or show the overlay */
167
+ setHidden(hidden: boolean): void;
168
+ /** Check if overlay is temporarily hidden */
169
+ isHidden(): boolean;
170
+ }
171
+
172
+ /**
173
+ * Container - a component that contains other components
174
+ */
175
+ export class Container implements Component {
176
+ children: Component[] = [];
177
+
178
+ addChild(component: Component): void {
179
+ this.children.push(component);
180
+ }
181
+
182
+ removeChild(component: Component): void {
183
+ const index = this.children.indexOf(component);
184
+ if (index !== -1) {
185
+ this.children.splice(index, 1);
186
+ }
187
+ }
188
+
189
+ clear(): void {
190
+ this.children = [];
191
+ }
192
+
193
+ invalidate(): void {
194
+ for (const child of this.children) {
195
+ child.invalidate?.();
196
+ }
197
+ }
198
+
199
+ render(width: number): string[] {
200
+ width = Math.max(1, width);
201
+ const lines: string[] = [];
202
+ for (const child of this.children) {
203
+ try {
204
+ lines.push(...child.render(width));
205
+ } catch {
206
+ // Swallow render errors from individual children to prevent process crash
207
+ }
208
+ }
209
+ return lines;
210
+ }
211
+ }
212
+
213
+ /**
214
+ * TUI - Main class for managing terminal UI with differential rendering
215
+ */
216
+ export class TUI extends Container {
217
+ terminal: Terminal;
218
+ #previousLines: string[] = [];
219
+ #previousWidth = 0;
220
+ #previousHeight = 0;
221
+ #focusedComponent: Component | null = null;
222
+ #inputListeners = new Set<InputListener>();
223
+
224
+ /** Global callback for debug key (Shift+Ctrl+D). Called before input is forwarded to focused component. */
225
+ onDebug?: () => void;
226
+ #renderRequested = false;
227
+ #cursorRow = 0; // Logical cursor row (end of rendered content)
228
+ #hardwareCursorRow = 0; // Actual terminal cursor row (may differ due to IME positioning)
229
+ #viewportTopRow = 0; // Content row currently mapped to screen row 0
230
+ #inputBuffer = ""; // Buffer for parsing terminal responses
231
+ #cellSizeQueryPending = false;
232
+ #sixelProbePendingDa = false;
233
+ #sixelProbePendingGraphics = false;
234
+ #sixelProbeBuffer = "";
235
+ #sixelProbeTimeout?: NodeJS.Timeout;
236
+ #sixelProbeUnsubscribe?: () => void;
237
+ #showHardwareCursor = $flag("PI_HARDWARE_CURSOR");
238
+ #clearOnShrink = $flag("PI_CLEAR_ON_SHRINK"); // Clear empty rows when content shrinks (default: off)
239
+ #maxLinesRendered = 0; // High-water line count used for clear-on-shrink policy
240
+ #fullRedrawCount = 0;
241
+ #stopped = false;
242
+
243
+ // Overlay stack for modal components rendered on top of base content
244
+ overlayStack: {
245
+ component: Component;
246
+ options?: OverlayOptions;
247
+ preFocus: Component | null;
248
+ hidden: boolean;
249
+ }[] = [];
250
+
251
+ constructor(terminal: Terminal, showHardwareCursor?: boolean) {
252
+ super();
253
+ this.terminal = terminal;
254
+ if (showHardwareCursor !== undefined) {
255
+ this.#showHardwareCursor = showHardwareCursor;
256
+ }
257
+ }
258
+
259
+ get fullRedraws(): number {
260
+ return this.#fullRedrawCount;
261
+ }
262
+
263
+ getShowHardwareCursor(): boolean {
264
+ return this.#showHardwareCursor;
265
+ }
266
+
267
+ setShowHardwareCursor(enabled: boolean): void {
268
+ if (this.#showHardwareCursor === enabled) return;
269
+ this.#showHardwareCursor = enabled;
270
+ if (!enabled) {
271
+ this.terminal.hideCursor();
272
+ }
273
+ this.requestRender();
274
+ }
275
+
276
+ getClearOnShrink(): boolean {
277
+ return this.#clearOnShrink;
278
+ }
279
+
280
+ /**
281
+ * Set whether to trigger full re-render when content shrinks.
282
+ * When true (default), empty rows are cleared when content shrinks.
283
+ * When false, empty rows remain (reduces redraws on slower terminals).
284
+ */
285
+ setClearOnShrink(enabled: boolean): void {
286
+ this.#clearOnShrink = enabled;
287
+ }
288
+
289
+ setFocus(component: Component | null): void {
290
+ // Clear focused flag on old component
291
+ if (isFocusable(this.#focusedComponent)) {
292
+ this.#focusedComponent.focused = false;
293
+ }
294
+
295
+ this.#focusedComponent = component;
296
+
297
+ // Set focused flag on new component
298
+ if (isFocusable(component)) {
299
+ component.focused = true;
300
+ }
301
+ }
302
+
303
+ /**
304
+ * Show an overlay component with configurable positioning and sizing.
305
+ * Returns a handle to control the overlay's visibility.
306
+ */
307
+ showOverlay(component: Component, options?: OverlayOptions): OverlayHandle {
308
+ const entry = { component, options, preFocus: this.#focusedComponent, hidden: false };
309
+ this.overlayStack.push(entry);
310
+ // Only focus if overlay is actually visible
311
+ if (this.#isOverlayVisible(entry)) {
312
+ this.setFocus(component);
313
+ }
314
+ this.terminal.hideCursor();
315
+ this.requestRender();
316
+
317
+ // Return handle for controlling this overlay
318
+ return {
319
+ hide: () => {
320
+ const index = this.overlayStack.indexOf(entry);
321
+ if (index !== -1) {
322
+ this.overlayStack.splice(index, 1);
323
+ // Restore focus if this overlay had focus
324
+ if (this.#focusedComponent === component) {
325
+ const topVisible = this.#getTopmostVisibleOverlay();
326
+ this.setFocus(topVisible?.component ?? entry.preFocus);
327
+ }
328
+ if (this.overlayStack.length === 0) this.terminal.hideCursor();
329
+ this.requestRender();
330
+ }
331
+ },
332
+ setHidden: (hidden: boolean) => {
333
+ if (entry.hidden === hidden) return;
334
+ entry.hidden = hidden;
335
+ // Update focus when hiding/showing
336
+ if (hidden) {
337
+ // If this overlay had focus, move focus to next visible or preFocus
338
+ if (this.#focusedComponent === component) {
339
+ const topVisible = this.#getTopmostVisibleOverlay();
340
+ this.setFocus(topVisible?.component ?? entry.preFocus);
341
+ }
342
+ } else {
343
+ // Restore focus to this overlay when showing (if it's actually visible)
344
+ if (this.#isOverlayVisible(entry)) {
345
+ this.setFocus(component);
346
+ }
347
+ }
348
+ this.requestRender();
349
+ },
350
+ isHidden: () => entry.hidden,
351
+ };
352
+ }
353
+
354
+ /** Hide the topmost overlay and restore previous focus. */
355
+ hideOverlay(): void {
356
+ const overlay = this.overlayStack.pop();
357
+ if (!overlay) return;
358
+ // Find topmost visible overlay, or fall back to preFocus
359
+ const topVisible = this.#getTopmostVisibleOverlay();
360
+ this.setFocus(topVisible?.component ?? overlay.preFocus);
361
+ if (this.overlayStack.length === 0) this.terminal.hideCursor();
362
+ this.requestRender();
363
+ }
364
+
365
+ /** Check if there are any visible overlays */
366
+ hasOverlay(): boolean {
367
+ return this.overlayStack.some(o => this.#isOverlayVisible(o));
368
+ }
369
+
370
+ /** Check if an overlay entry is currently visible */
371
+ #isOverlayVisible(entry: (typeof this.overlayStack)[number]): boolean {
372
+ if (entry.hidden) return false;
373
+ if (entry.options?.visible) {
374
+ return entry.options.visible(this.terminal.columns, this.terminal.rows);
375
+ }
376
+ return true;
377
+ }
378
+
379
+ /** Find the topmost visible overlay, if any */
380
+ #getTopmostVisibleOverlay(): (typeof this.overlayStack)[number] | undefined {
381
+ for (let i = this.overlayStack.length - 1; i >= 0; i--) {
382
+ if (this.#isOverlayVisible(this.overlayStack[i])) {
383
+ return this.overlayStack[i];
384
+ }
385
+ }
386
+ return undefined;
387
+ }
388
+
389
+ override invalidate(): void {
390
+ super.invalidate();
391
+ for (const overlay of this.overlayStack) overlay.component.invalidate?.();
392
+ }
393
+
394
+ start(clearScreen = true): void {
395
+ this.#stopped = false;
396
+ this.terminal.start(
397
+ data => {
398
+ // Guard: drop terminal capability responses that leaked through
399
+ // the terminal's own filters (e.g. after stop/start cycles).
400
+ if (
401
+ /^\x1b\[\?[\d;]*[a-z]$/i.test(data) || // DA1/Kitty: ESC[?...c or ESC[?...u
402
+ /^\x1b\](?:11|10|4);/.test(data) || // OSC color queries
403
+ /^\x1b\[>[\d;]*[a-z]$/i.test(data) // DA2: ESC[>...c
404
+ ) {
405
+ return;
406
+ }
407
+ this.#handleInput(data);
408
+ },
409
+ () => this.requestRender(),
410
+ );
411
+ this.terminal.hideCursor();
412
+ this.#querySixelSupport();
413
+ this.#queryCellSize();
414
+ this.requestRender(clearScreen);
415
+ }
416
+
417
+ addInputListener(listener: InputListener): () => void {
418
+ this.#inputListeners.add(listener);
419
+ return () => {
420
+ this.#inputListeners.delete(listener);
421
+ };
422
+ }
423
+
424
+ removeInputListener(listener: InputListener): void {
425
+ this.#inputListeners.delete(listener);
426
+ }
427
+
428
+ #querySixelSupport(): void {
429
+ if (TERMINAL.imageProtocol) return;
430
+ if (process.platform !== "win32") return;
431
+ if (!Bun.env.WT_SESSION) return;
432
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return;
433
+
434
+ this.#clearSixelProbeState();
435
+ this.#sixelProbePendingDa = true;
436
+ this.#sixelProbePendingGraphics = true;
437
+ this.#sixelProbeUnsubscribe = this.addInputListener(data => this.#handleSixelProbeInput(data));
438
+ this.terminal.write("\x1b[c");
439
+ this.terminal.write("\x1b[?2;1;0S");
440
+ this.#sixelProbeTimeout = setTimeout(() => {
441
+ this.#finishSixelProbe(false);
442
+ }, 250);
443
+ }
444
+
445
+ #handleSixelProbeInput(data: string): InputListenerResult {
446
+ if (!this.#sixelProbePendingDa && !this.#sixelProbePendingGraphics) {
447
+ return undefined;
448
+ }
449
+
450
+ this.#sixelProbeBuffer += data;
451
+ let passthrough = "";
452
+ let probeOutcome: boolean | null = null;
453
+
454
+ while (this.#sixelProbeBuffer.length > 0) {
455
+ const daMatch = this.#sixelProbeBuffer.match(/\x1b\[\?([0-9;]+)c/u);
456
+ const graphicsMatch = this.#sixelProbeBuffer.match(/\x1b\[\?2;(\d+);([0-9;]+)S/u);
457
+
458
+ if (!daMatch && !graphicsMatch) break;
459
+
460
+ const daIndex = daMatch?.index ?? Number.POSITIVE_INFINITY;
461
+ const graphicsIndex = graphicsMatch?.index ?? Number.POSITIVE_INFINITY;
462
+ const useDa = daIndex <= graphicsIndex;
463
+ const match = useDa ? daMatch : graphicsMatch;
464
+ if (!match || match.index === undefined) break;
465
+
466
+ passthrough += this.#sixelProbeBuffer.slice(0, match.index);
467
+ this.#sixelProbeBuffer = this.#sixelProbeBuffer.slice(match.index + match[0].length);
468
+
469
+ if (useDa && this.#sixelProbePendingDa) {
470
+ this.#sixelProbePendingDa = false;
471
+ const attributes = (match[1] ?? "")
472
+ .split(";")
473
+ .map(value => Number.parseInt(value, 10))
474
+ .filter(value => Number.isFinite(value));
475
+ const hasSixelAttribute = attributes.includes(4);
476
+ if (hasSixelAttribute) {
477
+ this.#sixelProbePendingGraphics = false;
478
+ probeOutcome = true;
479
+ } else if (!this.#sixelProbePendingGraphics) {
480
+ probeOutcome = false;
481
+ }
482
+ } else if (!useDa && this.#sixelProbePendingGraphics) {
483
+ this.#sixelProbePendingGraphics = false;
484
+ const status = Number.parseInt(match[1] ?? "", 10);
485
+ const supportsSixel = !Number.isNaN(status) && status !== 0;
486
+ if (supportsSixel) {
487
+ this.#sixelProbePendingDa = false;
488
+ probeOutcome = true;
489
+ } else if (!this.#sixelProbePendingDa) {
490
+ probeOutcome = false;
491
+ }
492
+ }
493
+ }
494
+
495
+ if (this.#sixelProbePendingDa || this.#sixelProbePendingGraphics) {
496
+ const partialStart = this.#getSixelProbePartialStart(this.#sixelProbeBuffer);
497
+ if (partialStart >= 0) {
498
+ passthrough += this.#sixelProbeBuffer.slice(0, partialStart);
499
+ this.#sixelProbeBuffer = this.#sixelProbeBuffer.slice(partialStart);
500
+ } else {
501
+ passthrough += this.#sixelProbeBuffer;
502
+ this.#sixelProbeBuffer = "";
503
+ }
504
+ } else {
505
+ passthrough += this.#sixelProbeBuffer;
506
+ this.#sixelProbeBuffer = "";
507
+ }
508
+
509
+ if (probeOutcome !== null) {
510
+ this.#finishSixelProbe(probeOutcome);
511
+ }
512
+
513
+ if (passthrough.length === 0) {
514
+ return { consume: true };
515
+ }
516
+
517
+ return { data: passthrough };
518
+ }
519
+
520
+ #getSixelProbePartialStart(buffer: string): number {
521
+ const lastEsc = buffer.lastIndexOf("\x1b");
522
+ if (lastEsc < 0) return -1;
523
+ const tail = buffer.slice(lastEsc);
524
+ if (/^\x1b\[\?[0-9;]*$/u.test(tail)) {
525
+ return lastEsc;
526
+ }
527
+ return -1;
528
+ }
529
+
530
+ #clearSixelProbeState(): void {
531
+ if (this.#sixelProbeTimeout) {
532
+ clearTimeout(this.#sixelProbeTimeout);
533
+ this.#sixelProbeTimeout = undefined;
534
+ }
535
+ if (this.#sixelProbeUnsubscribe) {
536
+ this.#sixelProbeUnsubscribe();
537
+ this.#sixelProbeUnsubscribe = undefined;
538
+ }
539
+ this.#sixelProbePendingDa = false;
540
+ this.#sixelProbePendingGraphics = false;
541
+ this.#sixelProbeBuffer = "";
542
+ }
543
+
544
+ #finishSixelProbe(supported: boolean): void {
545
+ this.#clearSixelProbeState();
546
+ if (!supported || TERMINAL.imageProtocol) return;
547
+
548
+ setTerminalImageProtocol(ImageProtocol.Sixel);
549
+ this.#queryCellSize();
550
+ this.invalidate();
551
+ this.requestRender(true);
552
+ }
553
+ #queryCellSize(): void {
554
+ // Only query if terminal supports images (cell size is only used for image rendering)
555
+ if (!TERMINAL.imageProtocol) {
556
+ return;
557
+ }
558
+ // Query terminal for cell size in pixels: CSI 16 t
559
+ // Response format: CSI 6 ; height ; width t
560
+ this.#cellSizeQueryPending = true;
561
+ this.terminal.write("\x1b[16t");
562
+ }
563
+
564
+ stop(): void {
565
+ this.#clearSixelProbeState();
566
+ this.#stopped = true;
567
+ // Move cursor to the end of the content to prevent overwriting/artifacts on exit
568
+ if (this.#previousLines.length > 0) {
569
+ const targetRow = this.#previousLines.length; // Line after the last content
570
+ const lineDiff = targetRow - this.#hardwareCursorRow;
571
+ if (lineDiff > 0) {
572
+ this.terminal.write(`\x1b[${lineDiff}B`);
573
+ } else if (lineDiff < 0) {
574
+ this.terminal.write(`\x1b[${-lineDiff}A`);
575
+ }
576
+ this.terminal.write("\r\n");
577
+ }
578
+
579
+ this.terminal.showCursor();
580
+ this.terminal.stop();
581
+ }
582
+
583
+ /**
584
+ * Suspend the UI to hand the TTY to a cooked-mode subprocess (e.g. an
585
+ * interactive `aws sso login`). Drains pending terminal input while still in
586
+ * raw mode, then stops — so a late capability-probe response (notably the
587
+ * periodic OSC 11 poll) cannot be echoed as gibberish during the cooked-mode
588
+ * window. Pair with start() once the subprocess exits.
589
+ */
590
+ async suspendForSubprocess(maxDrainMs = 150): Promise<void> {
591
+ await this.terminal.drainInput(maxDrainMs);
592
+ this.stop();
593
+ }
594
+
595
+ requestRender(force = false): void {
596
+ if (force) {
597
+ this.#previousLines = [];
598
+ this.#previousWidth = -1; // -1 triggers widthChanged, forcing a full clear
599
+ this.#previousHeight = -1; // -1 triggers heightChanged, forcing a full clear
600
+ this.#cursorRow = 0;
601
+ this.#hardwareCursorRow = 0;
602
+ this.#viewportTopRow = 0;
603
+ this.#maxLinesRendered = 0;
604
+ }
605
+ if (this.#renderRequested) return;
606
+ this.#renderRequested = true;
607
+ process.nextTick(() => {
608
+ this.#renderRequested = false;
609
+ this.#doRender();
610
+ });
611
+ }
612
+
613
+ #handleInput(data: string): void {
614
+ if (this.#inputListeners.size > 0) {
615
+ let current = data;
616
+ for (const listener of this.#inputListeners) {
617
+ const result = listener(current);
618
+ if (result?.consume) {
619
+ return;
620
+ }
621
+ if (result?.data !== undefined) {
622
+ current = result.data;
623
+ }
624
+ }
625
+ if (current.length === 0) {
626
+ return;
627
+ }
628
+ data = current;
629
+ }
630
+
631
+ // If we're waiting for cell size response, buffer input and parse
632
+ if (this.#cellSizeQueryPending) {
633
+ this.#inputBuffer += data;
634
+ const filtered = this.#parseCellSizeResponse();
635
+ if (filtered.length === 0) return;
636
+ data = filtered;
637
+ }
638
+
639
+ // Global debug key handler (Shift+Ctrl+D)
640
+ if (matchesKey(data, "shift+ctrl+d") && this.onDebug) {
641
+ this.onDebug();
642
+ return;
643
+ }
644
+
645
+ // If focused component is an overlay, verify it's still visible
646
+ // (visibility can change due to terminal resize or visible() callback)
647
+ const focusedOverlay = this.overlayStack.find(o => o.component === this.#focusedComponent);
648
+ if (focusedOverlay && !this.#isOverlayVisible(focusedOverlay)) {
649
+ // Focused overlay is no longer visible, redirect to topmost visible overlay
650
+ const topVisible = this.#getTopmostVisibleOverlay();
651
+ if (topVisible) {
652
+ this.setFocus(topVisible.component);
653
+ } else {
654
+ // No visible overlays, restore to preFocus
655
+ this.setFocus(focusedOverlay.preFocus);
656
+ }
657
+ }
658
+
659
+ // Pass input to focused component (including Ctrl+C)
660
+ // The focused component can decide how to handle Ctrl+C
661
+ if (this.#focusedComponent?.handleInput) {
662
+ // Filter out key release events unless component opts in
663
+ if (isKeyRelease(data) && !this.#focusedComponent.wantsKeyRelease) {
664
+ return;
665
+ }
666
+ this.#focusedComponent.handleInput(data);
667
+ this.requestRender();
668
+ }
669
+ }
670
+
671
+ #parseCellSizeResponse(): string {
672
+ // Response format: ESC [ 6 ; height ; width t
673
+ // Match the response pattern
674
+ const responsePattern = /\x1b\[6;(\d+);(\d+)t/;
675
+ const match = this.#inputBuffer.match(responsePattern);
676
+
677
+ if (match) {
678
+ const heightPx = parseInt(match[1], 10);
679
+ const widthPx = parseInt(match[2], 10);
680
+
681
+ if (heightPx > 0 && widthPx > 0) {
682
+ setCellDimensions({ widthPx, heightPx });
683
+ // Invalidate all components so images re-render with correct dimensions
684
+ this.invalidate();
685
+ this.requestRender();
686
+ }
687
+
688
+ // Remove the response from buffer
689
+ this.#inputBuffer = this.#inputBuffer.replace(responsePattern, "");
690
+ this.#cellSizeQueryPending = false;
691
+ }
692
+
693
+ // Check if we have a partial cell size response starting (wait for more data)
694
+ // Patterns that could be incomplete cell size response: \x1b, \x1b[, \x1b[6, \x1b[6;...(no t yet)
695
+ const partialCellSizePattern = /\x1b(\[6?;?[\d;]*)?$/;
696
+ if (partialCellSizePattern.test(this.#inputBuffer)) {
697
+ // Check if it's actually a complete different escape sequence (ends with a letter)
698
+ // Cell size response ends with 't', Kitty keyboard ends with 'u', arrows end with A-D, etc.
699
+ const lastChar = this.#inputBuffer[this.#inputBuffer.length - 1];
700
+ if (!/[a-zA-Z~]/.test(lastChar)) {
701
+ // Doesn't end with a terminator, might be incomplete - wait for more
702
+ return "";
703
+ }
704
+ }
705
+
706
+ // No cell size response found, return buffered data as user input
707
+ const result = this.#inputBuffer;
708
+ this.#inputBuffer = "";
709
+ this.#cellSizeQueryPending = false; // Give up waiting
710
+ return result;
711
+ }
712
+
713
+ /**
714
+ * Resolve overlay layout from options.
715
+ * Returns { width, row, col, maxHeight } for rendering.
716
+ */
717
+ #resolveOverlayLayout(
718
+ options: OverlayOptions | undefined,
719
+ overlayHeight: number,
720
+ termWidth: number,
721
+ termHeight: number,
722
+ ): { width: number; row: number; col: number; maxHeight: number | undefined } {
723
+ const opt = options ?? {};
724
+
725
+ // Parse margin (clamp to non-negative)
726
+ const margin =
727
+ typeof opt.margin === "number"
728
+ ? { top: opt.margin, right: opt.margin, bottom: opt.margin, left: opt.margin }
729
+ : (opt.margin ?? {});
730
+ const marginTop = Math.max(0, margin.top ?? 0);
731
+ const marginRight = Math.max(0, margin.right ?? 0);
732
+ const marginBottom = Math.max(0, margin.bottom ?? 0);
733
+ const marginLeft = Math.max(0, margin.left ?? 0);
734
+
735
+ // Available space after margins
736
+ const availWidth = Math.max(1, termWidth - marginLeft - marginRight);
737
+ const availHeight = Math.max(1, termHeight - marginTop - marginBottom);
738
+
739
+ // === Resolve width ===
740
+ let width = parseSizeValue(opt.width, termWidth) ?? Math.min(80, availWidth);
741
+ // Apply minWidth
742
+ if (opt.minWidth !== undefined) {
743
+ width = Math.max(width, opt.minWidth);
744
+ }
745
+ // Clamp to available space
746
+ width = Math.max(1, Math.min(width, availWidth));
747
+
748
+ // === Resolve maxHeight ===
749
+ let maxHeight = parseSizeValue(opt.maxHeight, termHeight);
750
+ // Clamp to available space
751
+ if (maxHeight !== undefined) {
752
+ maxHeight = Math.max(1, Math.min(maxHeight, availHeight));
753
+ }
754
+
755
+ // Effective overlay height (may be clamped by maxHeight)
756
+ const effectiveHeight = maxHeight !== undefined ? Math.min(overlayHeight, maxHeight) : overlayHeight;
757
+
758
+ // === Resolve position ===
759
+ let row: number;
760
+ let col: number;
761
+
762
+ if (opt.row !== undefined) {
763
+ if (typeof opt.row === "string") {
764
+ // Percentage: 0% = top, 100% = bottom (overlay stays within bounds)
765
+ const match = opt.row.match(/^(\d+(?:\.\d+)?)%$/);
766
+ if (match) {
767
+ const maxRow = Math.max(0, availHeight - effectiveHeight);
768
+ const percent = parseFloat(match[1]) / 100;
769
+ row = marginTop + Math.floor(maxRow * percent);
770
+ } else {
771
+ // Invalid format, fall back to center
772
+ row = this.#resolveAnchorRow("center", effectiveHeight, availHeight, marginTop);
773
+ }
774
+ } else {
775
+ // Absolute row position
776
+ row = opt.row;
777
+ }
778
+ } else {
779
+ // Anchor-based (default: center)
780
+ const anchor = opt.anchor ?? "center";
781
+ row = this.#resolveAnchorRow(anchor, effectiveHeight, availHeight, marginTop);
782
+ }
783
+
784
+ if (opt.col !== undefined) {
785
+ if (typeof opt.col === "string") {
786
+ // Percentage: 0% = left, 100% = right (overlay stays within bounds)
787
+ const match = opt.col.match(/^(\d+(?:\.\d+)?)%$/);
788
+ if (match) {
789
+ const maxCol = Math.max(0, availWidth - width);
790
+ const percent = parseFloat(match[1]) / 100;
791
+ col = marginLeft + Math.floor(maxCol * percent);
792
+ } else {
793
+ // Invalid format, fall back to center
794
+ col = this.#resolveAnchorCol("center", width, availWidth, marginLeft);
795
+ }
796
+ } else {
797
+ // Absolute column position
798
+ col = opt.col;
799
+ }
800
+ } else {
801
+ // Anchor-based (default: center)
802
+ const anchor = opt.anchor ?? "center";
803
+ col = this.#resolveAnchorCol(anchor, width, availWidth, marginLeft);
804
+ }
805
+
806
+ // Apply offsets
807
+ if (opt.offsetY !== undefined) row += opt.offsetY;
808
+ if (opt.offsetX !== undefined) col += opt.offsetX;
809
+
810
+ // Clamp to terminal bounds (respecting margins)
811
+ row = Math.max(marginTop, Math.min(row, termHeight - marginBottom - effectiveHeight));
812
+ col = Math.max(marginLeft, Math.min(col, termWidth - marginRight - width));
813
+
814
+ return { width, row, col, maxHeight };
815
+ }
816
+
817
+ #resolveAnchorRow(anchor: OverlayAnchor, height: number, availHeight: number, marginTop: number): number {
818
+ switch (anchor) {
819
+ case "top-left":
820
+ case "top-center":
821
+ case "top-right":
822
+ return marginTop;
823
+ case "bottom-left":
824
+ case "bottom-center":
825
+ case "bottom-right":
826
+ return marginTop + availHeight - height;
827
+ case "left-center":
828
+ case "center":
829
+ case "right-center":
830
+ return marginTop + Math.floor((availHeight - height) / 2);
831
+ }
832
+ }
833
+
834
+ #resolveAnchorCol(anchor: OverlayAnchor, width: number, availWidth: number, marginLeft: number): number {
835
+ switch (anchor) {
836
+ case "top-left":
837
+ case "left-center":
838
+ case "bottom-left":
839
+ return marginLeft;
840
+ case "top-right":
841
+ case "right-center":
842
+ case "bottom-right":
843
+ return marginLeft + availWidth - width;
844
+ case "top-center":
845
+ case "center":
846
+ case "bottom-center":
847
+ return marginLeft + Math.floor((availWidth - width) / 2);
848
+ }
849
+ }
850
+
851
+ /** Composite all overlays into content lines (in stack order, later = on top). */
852
+ #compositeOverlays(lines: string[], termWidth: number, termHeight: number): string[] {
853
+ if (this.overlayStack.length === 0) return lines;
854
+ const result = [...lines];
855
+
856
+ // Pre-render all visible overlays and calculate positions
857
+ const rendered: { overlayLines: string[]; row: number; col: number; w: number }[] = [];
858
+ let minLinesNeeded = result.length;
859
+
860
+ for (const entry of this.overlayStack) {
861
+ // Skip invisible overlays (hidden or visible() returns false)
862
+ if (!this.#isOverlayVisible(entry)) continue;
863
+
864
+ const { component, options } = entry;
865
+
866
+ // Get layout with height=0 first to determine width and maxHeight
867
+ // (width and maxHeight don't depend on overlay height)
868
+ const { width, maxHeight } = this.#resolveOverlayLayout(options, 0, termWidth, termHeight);
869
+
870
+ // Render component at calculated width
871
+ let overlayLines = component.render(width);
872
+
873
+ // Apply maxHeight if specified
874
+ if (maxHeight !== undefined && overlayLines.length > maxHeight) {
875
+ overlayLines = overlayLines.slice(0, maxHeight);
876
+ }
877
+
878
+ // Get final row/col with actual overlay height
879
+ const { row, col } = this.#resolveOverlayLayout(options, overlayLines.length, termWidth, termHeight);
880
+
881
+ rendered.push({ overlayLines, row, col, w: width });
882
+ minLinesNeeded = Math.max(minLinesNeeded, row + overlayLines.length);
883
+ }
884
+
885
+ // Ensure result is tall enough for overlay placement.
886
+ // NOTE: Do not pad to maxLinesRendered.
887
+ // maxLinesRendered tracks the terminal "working area" (max lines ever rendered) and can be much larger
888
+ // than the current content. Padding to it can cause the renderer to output hundreds/thousands of blank
889
+ // lines, effectively scrolling the terminal when an overlay is shown.
890
+ const workingHeight = Math.max(result.length, minLinesNeeded);
891
+
892
+ // Extend result with empty lines if content is too short for overlay placement
893
+ while (result.length < workingHeight) {
894
+ result.push("");
895
+ }
896
+
897
+ const viewportStart = Math.max(0, workingHeight - termHeight);
898
+
899
+ // Track which lines were modified for final verification
900
+ const modifiedLines = new Set<number>();
901
+
902
+ // Composite each overlay
903
+ for (const { overlayLines, row, col, w } of rendered) {
904
+ for (let i = 0; i < overlayLines.length; i++) {
905
+ const idx = viewportStart + row + i;
906
+ if (idx >= 0 && idx < result.length) {
907
+ // Defensive: truncate overlay line to declared width before compositing
908
+ // (components should already respect width, but this ensures it)
909
+ const truncatedOverlayLine =
910
+ visibleWidth(overlayLines[i]) > w ? sliceByColumn(overlayLines[i], 0, w, true) : overlayLines[i];
911
+ result[idx] = this.#compositeLineAt(result[idx], truncatedOverlayLine, col, w, termWidth);
912
+ modifiedLines.add(idx);
913
+ }
914
+ }
915
+ }
916
+
917
+ // Final verification: ensure no composited line exceeds terminal width
918
+ // This is a belt-and-suspenders safeguard - compositeLineAt should already
919
+ // guarantee this, but we verify here to prevent crashes from any edge cases
920
+ // Only check lines that were actually modified (optimization)
921
+ for (const idx of modifiedLines) {
922
+ const lineWidth = visibleWidth(result[idx]);
923
+ if (lineWidth > termWidth) {
924
+ result[idx] = sliceByColumn(result[idx], 0, termWidth, true);
925
+ }
926
+ }
927
+
928
+ return result;
929
+ }
930
+
931
+ /** Splice overlay content into a base line at a specific column. Single-pass optimized. */
932
+ #compositeLineAt(
933
+ baseLine: string,
934
+ overlayLine: string,
935
+ startCol: number,
936
+ overlayWidth: number,
937
+ totalWidth: number,
938
+ ): string {
939
+ if (TERMINAL.isImageLine(baseLine)) return baseLine;
940
+
941
+ // Single pass through baseLine extracts both before and after segments
942
+ const afterStart = startCol + overlayWidth;
943
+ const base = extractSegments(baseLine, startCol, afterStart, totalWidth - afterStart, true);
944
+
945
+ // Extract overlay with width tracking (strict=true to exclude wide chars at boundary)
946
+ const overlay = sliceWithWidth(overlayLine, 0, overlayWidth, true);
947
+
948
+ // Pad segments to target widths
949
+ const beforePad = Math.max(0, startCol - base.beforeWidth);
950
+ const overlayPad = Math.max(0, overlayWidth - overlay.width);
951
+ const actualBeforeWidth = Math.max(startCol, base.beforeWidth);
952
+ const actualOverlayWidth = Math.max(overlayWidth, overlay.width);
953
+ const afterTarget = Math.max(0, totalWidth - actualBeforeWidth - actualOverlayWidth);
954
+ const afterPad = Math.max(0, afterTarget - base.afterWidth);
955
+
956
+ // Compose result
957
+ const r = SEGMENT_RESET;
958
+ const result =
959
+ base.before +
960
+ " ".repeat(beforePad) +
961
+ r +
962
+ overlay.text +
963
+ " ".repeat(overlayPad) +
964
+ r +
965
+ base.after +
966
+ " ".repeat(afterPad);
967
+
968
+ // CRITICAL: Always verify and truncate to terminal width.
969
+ // This is the final safeguard against width overflow which would crash the TUI.
970
+ // Width tracking can drift from actual visible width due to:
971
+ // - Complex ANSI/OSC sequences (hyperlinks, colors)
972
+ // - Wide characters at segment boundaries
973
+ // - Edge cases in segment extraction
974
+ const resultWidth = visibleWidth(result);
975
+ if (resultWidth <= totalWidth) {
976
+ return result;
977
+ }
978
+ // Truncate with strict=true to ensure we don't exceed totalWidth
979
+ return sliceByColumn(result, 0, totalWidth, true);
980
+ }
981
+
982
+ /**
983
+ * Find and extract cursor position from rendered lines.
984
+ * Searches for CURSOR_MARKER, calculates its position, and strips it from the output.
985
+ * Only scans the bottom terminal height lines (visible viewport).
986
+ * @param lines - Rendered lines to search
987
+ * @param height - Terminal height (visible viewport size)
988
+ * @returns Cursor position { row, col } or null if no marker found
989
+ */
990
+ #extractCursorPosition(lines: string[], height: number): { row: number; col: number } | null {
991
+ // Only scan the bottom `height` lines (visible viewport)
992
+ const viewportTop = Math.max(0, lines.length - height);
993
+ for (let row = lines.length - 1; row >= viewportTop; row--) {
994
+ const line = lines[row];
995
+ const markerIndex = line.indexOf(CURSOR_MARKER);
996
+ if (markerIndex !== -1) {
997
+ // Calculate visual column (width of text before marker)
998
+ const beforeMarker = line.slice(0, markerIndex);
999
+ const col = visibleWidth(beforeMarker);
1000
+
1001
+ // Strip marker from the line
1002
+ lines[row] = line.slice(0, markerIndex) + line.slice(markerIndex + CURSOR_MARKER.length);
1003
+
1004
+ return { row, col };
1005
+ }
1006
+ }
1007
+ return null;
1008
+ }
1009
+
1010
+ #doRender(): void {
1011
+ if (this.#stopped) return;
1012
+ const width = this.terminal.columns;
1013
+ const height = this.terminal.rows;
1014
+ let viewportTop = Math.max(0, this.#maxLinesRendered - height);
1015
+ let prevViewportTop = this.#viewportTopRow;
1016
+ let hardwareCursorRow = this.#hardwareCursorRow;
1017
+ const computeLineDiff = (targetRow: number): number => {
1018
+ const currentScreenRow = hardwareCursorRow - prevViewportTop;
1019
+ const targetScreenRow = targetRow - viewportTop;
1020
+ return targetScreenRow - currentScreenRow;
1021
+ };
1022
+
1023
+ // Render all components to get new lines
1024
+ let newLines = this.render(width);
1025
+
1026
+ // Clamp any oversized lines before dirty-checking so the truncated form
1027
+ // matches what we store in #previousLines, preventing perpetual repaints.
1028
+ // Strip CURSOR_MARKER before measuring — visibleWidth miscounts APC sequences
1029
+ // as visible chars; the marker is extracted later in #extractCursorPosition.
1030
+ for (let i = 0; i < newLines.length; i++) {
1031
+ if (TERMINAL.isImageLine(newLines[i])) continue;
1032
+ const stripped = newLines[i].replaceAll(CURSOR_MARKER, "");
1033
+ if (visibleWidth(stripped) > width) {
1034
+ const hadMarker = newLines[i] !== stripped;
1035
+ newLines[i] = sliceByColumn(stripped, 0, width, true) + (hadMarker ? CURSOR_MARKER : "");
1036
+ }
1037
+ }
1038
+
1039
+ // Composite overlays into the rendered lines (before differential compare)
1040
+ if (this.overlayStack.length > 0) {
1041
+ newLines = this.#compositeOverlays(newLines, width, height);
1042
+ }
1043
+
1044
+ // Extract cursor position (marker must be found before diff comparison)
1045
+ const cursorPos = this.#extractCursorPosition(newLines, height);
1046
+
1047
+ // Width changed - need full re-render (line wrapping changes)
1048
+ const widthChanged = this.#previousWidth !== 0 && this.#previousWidth !== width;
1049
+ const heightChanged = this.#previousHeight !== 0 && this.#previousHeight !== height;
1050
+
1051
+ // Helper to clear scrollback and viewport and render all new lines
1052
+ const fullRender = (clear: boolean): void => {
1053
+ this.#fullRedrawCount += 1;
1054
+ let buffer = "\x1b[?2026h"; // Begin synchronized output
1055
+ // Skip clearing scrollback (3J) in multiplexers — users actively navigate scrollback history
1056
+ if (clear) buffer += isMultiplexer() ? "\x1b[2J\x1b[H" : "\x1b[2J\x1b[H\x1b[3J";
1057
+ const reset = SEGMENT_RESET;
1058
+ for (let i = 0; i < newLines.length; i++) {
1059
+ if (i > 0) buffer += "\r\n";
1060
+ const line = newLines[i];
1061
+ buffer += TERMINAL.isImageLine(line) ? line : line + reset;
1062
+ }
1063
+ buffer += "\x1b[?2026l"; // End synchronized output
1064
+ this.terminal.write(buffer);
1065
+ this.#cursorRow = Math.max(0, newLines.length - 1);
1066
+ this.#hardwareCursorRow = this.#cursorRow;
1067
+ // Reset max lines when clearing, otherwise track growth
1068
+ if (clear) {
1069
+ this.#maxLinesRendered = newLines.length;
1070
+ } else {
1071
+ this.#maxLinesRendered = Math.max(this.#maxLinesRendered, newLines.length);
1072
+ }
1073
+ this.#viewportTopRow = Math.max(0, this.#maxLinesRendered - height);
1074
+ this.#positionHardwareCursor(cursorPos, newLines.length);
1075
+ this.#previousLines = newLines;
1076
+ this.#previousWidth = width;
1077
+ this.#previousHeight = height;
1078
+ };
1079
+
1080
+ const debugRedraw = $flag("PI_DEBUG_REDRAW");
1081
+ const logRedraw = (reason: string): void => {
1082
+ if (!debugRedraw) return;
1083
+ const logPath = getDebugLogPath();
1084
+ const msg = `[${new Date().toISOString()}] fullRender: ${reason} (prev=${this.#previousLines.length}, new=${newLines.length}, height=${height})\n`;
1085
+ fs.appendFileSync(logPath, msg);
1086
+ };
1087
+
1088
+ // First render - just output everything without clearing (assumes clean screen)
1089
+ if (this.#previousLines.length === 0 && !widthChanged && !heightChanged) {
1090
+ logRedraw("first render");
1091
+ fullRender(false);
1092
+ return;
1093
+ }
1094
+
1095
+ // Width changes always need a full re-render because wrapping changes.
1096
+ if (widthChanged) {
1097
+ logRedraw(`terminal width changed (${this.#previousWidth} -> ${width})`);
1098
+ fullRender(true);
1099
+ return;
1100
+ }
1101
+
1102
+ // Height changes normally need a full re-render to keep the visible viewport aligned,
1103
+ // but Termux changes height when the software keyboard shows or hides.
1104
+ // In that environment, a full redraw causes the entire history to replay on every toggle.
1105
+ if (heightChanged && !isTermuxSession() && !isMultiplexer()) {
1106
+ logRedraw(`terminal height changed (${this.#previousHeight} -> ${height})`);
1107
+ fullRender(true);
1108
+ return;
1109
+ }
1110
+
1111
+ // Content shrunk below the working area and no overlays - re-render to clear empty rows
1112
+ // (overlays need the padding, so only do this when no overlays are active)
1113
+ // Configurable via setClearOnShrink() or PI_CLEAR_ON_SHRINK=0 env var
1114
+ if (this.#clearOnShrink && newLines.length < this.#maxLinesRendered && this.overlayStack.length === 0) {
1115
+ logRedraw(`clearOnShrink (maxLinesRendered=${this.#maxLinesRendered})`);
1116
+ fullRender(true);
1117
+ return;
1118
+ }
1119
+
1120
+ // Find first and last changed lines
1121
+ let firstChanged = -1;
1122
+ let lastChanged = -1;
1123
+ const maxLines = Math.max(newLines.length, this.#previousLines.length);
1124
+ for (let i = 0; i < maxLines; i++) {
1125
+ const oldLine = i < this.#previousLines.length ? this.#previousLines[i] : "";
1126
+ const newLine = i < newLines.length ? newLines[i] : "";
1127
+
1128
+ if (oldLine !== newLine) {
1129
+ if (firstChanged === -1) {
1130
+ firstChanged = i;
1131
+ }
1132
+ lastChanged = i;
1133
+ }
1134
+ }
1135
+ const appendedLines = newLines.length > this.#previousLines.length;
1136
+ if (appendedLines) {
1137
+ if (firstChanged === -1) {
1138
+ firstChanged = this.#previousLines.length;
1139
+ }
1140
+ lastChanged = newLines.length - 1;
1141
+ }
1142
+ const appendStart = appendedLines && firstChanged === this.#previousLines.length && firstChanged > 0;
1143
+
1144
+ // No changes - but still need to update hardware cursor position if it moved
1145
+ if (firstChanged === -1) {
1146
+ this.#positionHardwareCursor(cursorPos, newLines.length);
1147
+ this.#viewportTopRow = Math.max(0, this.#maxLinesRendered - height);
1148
+ return;
1149
+ }
1150
+
1151
+ // All changes are in deleted lines (nothing to render, just clear)
1152
+ if (firstChanged >= newLines.length) {
1153
+ if (this.#previousLines.length > newLines.length) {
1154
+ let buffer = "\x1b[?2026h";
1155
+ // Move to end of new content (clamp to 0 for empty content)
1156
+ const targetRow = Math.max(0, newLines.length - 1);
1157
+ const lineDiff = computeLineDiff(targetRow);
1158
+ if (lineDiff > 0) buffer += `\x1b[${lineDiff}B`;
1159
+ else if (lineDiff < 0) buffer += `\x1b[${-lineDiff}A`;
1160
+ buffer += "\r";
1161
+ // Clear extra lines without scrolling
1162
+ const extraLines = this.#previousLines.length - newLines.length;
1163
+ if (extraLines > height) {
1164
+ logRedraw(`extraLines > height (${extraLines} > ${height})`);
1165
+ fullRender(true);
1166
+ return;
1167
+ }
1168
+ const clearStartOffset = newLines.length > 0 && extraLines > 0 ? 1 : 0;
1169
+ if (clearStartOffset > 0) {
1170
+ buffer += `\x1b[${clearStartOffset}B`;
1171
+ }
1172
+ for (let i = 0; i < extraLines; i++) {
1173
+ buffer += "\r\x1b[2K";
1174
+ if (i < extraLines - 1) buffer += "\x1b[1B";
1175
+ }
1176
+ const moveUp = extraLines - 1 + clearStartOffset;
1177
+ if (moveUp > 0) {
1178
+ buffer += `\x1b[${moveUp}A`;
1179
+ }
1180
+ buffer += "\x1b[?2026l";
1181
+ this.terminal.write(buffer);
1182
+ this.#cursorRow = targetRow;
1183
+ this.#hardwareCursorRow = targetRow;
1184
+ }
1185
+ this.#positionHardwareCursor(cursorPos, newLines.length);
1186
+ this.#previousLines = newLines;
1187
+ this.#previousWidth = width;
1188
+ this.#previousHeight = height;
1189
+ this.#viewportTopRow = Math.max(0, this.#maxLinesRendered - height);
1190
+ return;
1191
+ }
1192
+
1193
+ // Check if firstChanged is above what was previously visible
1194
+ // Use previousLines.length (not maxLinesRendered) to avoid false positives after content shrinks
1195
+ const previousContentViewportTop = Math.max(0, this.#previousLines.length - height);
1196
+ if (firstChanged < previousContentViewportTop) {
1197
+ // First change is above previous viewport - need full re-render
1198
+ logRedraw(`firstChanged < viewportTop (${firstChanged} < ${previousContentViewportTop})`);
1199
+ fullRender(true);
1200
+ return;
1201
+ }
1202
+
1203
+ // Render from first changed line to end
1204
+ // Build buffer with all updates wrapped in synchronized output
1205
+ let buffer = "\x1b[?2026h"; // Begin synchronized output
1206
+ const prevViewportBottom = prevViewportTop + height - 1;
1207
+ const moveTargetRow = appendStart ? firstChanged - 1 : firstChanged;
1208
+ if (moveTargetRow > prevViewportBottom) {
1209
+ const currentScreenRow = Math.max(0, Math.min(height - 1, hardwareCursorRow - prevViewportTop));
1210
+ const moveToBottom = height - 1 - currentScreenRow;
1211
+ if (moveToBottom > 0) {
1212
+ buffer += `\x1b[${moveToBottom}B`;
1213
+ }
1214
+ const scroll = moveTargetRow - prevViewportBottom;
1215
+ buffer += "\r\n".repeat(scroll);
1216
+ prevViewportTop += scroll;
1217
+ viewportTop += scroll;
1218
+ hardwareCursorRow = moveTargetRow;
1219
+ }
1220
+
1221
+ // Move cursor to first changed line (use hardwareCursorRow for actual position)
1222
+ const lineDiff = computeLineDiff(moveTargetRow);
1223
+ if (lineDiff > 0) {
1224
+ buffer += `\x1b[${lineDiff}B`; // Move down
1225
+ } else if (lineDiff < 0) {
1226
+ buffer += `\x1b[${-lineDiff}A`; // Move up
1227
+ }
1228
+
1229
+ buffer += appendStart ? "\r\n" : "\r"; // Move to column 0
1230
+
1231
+ // Only render changed lines (firstChanged to lastChanged), not all lines to end
1232
+ // This reduces flicker when only a single line changes (e.g., spinner animation)
1233
+ const renderEnd = Math.min(lastChanged, newLines.length - 1);
1234
+ for (let i = firstChanged; i <= renderEnd; i++) {
1235
+ if (i > firstChanged) buffer += "\r\n";
1236
+ buffer += "\x1b[2K"; // Clear current line
1237
+ const line = newLines[i];
1238
+ buffer += TERMINAL.isImageLine(line) ? line : line + SEGMENT_RESET;
1239
+ }
1240
+
1241
+ // Track where cursor ended up after rendering
1242
+ let finalCursorRow = renderEnd;
1243
+
1244
+ // If we had more lines before, clear them and move cursor back
1245
+ if (this.#previousLines.length > newLines.length) {
1246
+ // Move to end of new content first if we stopped before it
1247
+ if (renderEnd < newLines.length - 1) {
1248
+ const moveDown = newLines.length - 1 - renderEnd;
1249
+ buffer += `\x1b[${moveDown}B`;
1250
+ finalCursorRow = newLines.length - 1;
1251
+ }
1252
+ const extraLines = this.#previousLines.length - newLines.length;
1253
+ for (let i = newLines.length; i < this.#previousLines.length; i++) {
1254
+ buffer += "\r\n\x1b[2K";
1255
+ }
1256
+ // Move cursor back to end of new content
1257
+ buffer += `\x1b[${extraLines}A`;
1258
+ }
1259
+
1260
+ buffer += "\x1b[?2026l"; // End synchronized output
1261
+
1262
+ if ($flag("PI_TUI_DEBUG")) {
1263
+ const debugDir = "/tmp/tui";
1264
+ fs.mkdirSync(debugDir, { recursive: true });
1265
+ const debugPath = path.join(debugDir, `render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`);
1266
+ const debugData = [
1267
+ `firstChanged: ${firstChanged}`,
1268
+ `viewportTop: ${viewportTop}`,
1269
+ `cursorRow: ${this.#cursorRow}`,
1270
+ `height: ${height}`,
1271
+ `lineDiff: ${lineDiff}`,
1272
+ `hardwareCursorRow: ${hardwareCursorRow}`,
1273
+ `renderEnd: ${renderEnd}`,
1274
+ `finalCursorRow: ${finalCursorRow}`,
1275
+ `cursorPos: ${JSON.stringify(cursorPos)}`,
1276
+ `newLines.length: ${newLines.length}`,
1277
+ `previousLines.length: ${this.#previousLines.length}`,
1278
+ "",
1279
+ "=== newLines ===",
1280
+ JSON.stringify(newLines, null, 2),
1281
+ "",
1282
+ "=== previousLines ===",
1283
+ JSON.stringify(this.#previousLines, null, 2),
1284
+ "",
1285
+ "=== buffer ===",
1286
+ JSON.stringify(buffer),
1287
+ ].join("\n");
1288
+ fs.writeFileSync(debugPath, debugData);
1289
+ }
1290
+
1291
+ // Write entire buffer at once
1292
+ this.terminal.write(buffer);
1293
+
1294
+ // Track cursor position for next render
1295
+ // cursorRow tracks end of content (for viewport calculation)
1296
+ // hardwareCursorRow tracks actual terminal cursor position (for movement)
1297
+ this.#cursorRow = Math.max(0, newLines.length - 1);
1298
+ this.#hardwareCursorRow = finalCursorRow;
1299
+ // Track terminal's working area (grows but doesn't shrink unless cleared)
1300
+ this.#maxLinesRendered = Math.max(this.#maxLinesRendered, newLines.length);
1301
+ this.#viewportTopRow = Math.max(0, this.#maxLinesRendered - height);
1302
+
1303
+ // Position hardware cursor for IME
1304
+ this.#positionHardwareCursor(cursorPos, newLines.length);
1305
+
1306
+ this.#previousLines = newLines;
1307
+ this.#previousWidth = width;
1308
+ this.#previousHeight = height;
1309
+ }
1310
+
1311
+ /**
1312
+ * Position the hardware cursor for IME candidate window.
1313
+ * @param cursorPos The cursor position extracted from rendered output, or null
1314
+ * @param totalLines Total number of rendered lines
1315
+ */
1316
+ #positionHardwareCursor(cursorPos: { row: number; col: number } | null, totalLines: number): void {
1317
+ if (!cursorPos || totalLines <= 0) {
1318
+ this.terminal.hideCursor();
1319
+ return;
1320
+ }
1321
+
1322
+ // Clamp cursor position to valid range
1323
+ const targetRow = Math.max(0, Math.min(cursorPos.row, totalLines - 1));
1324
+ const targetCol = Math.max(0, cursorPos.col);
1325
+
1326
+ // Move cursor from current position to target
1327
+ const rowDelta = targetRow - this.#hardwareCursorRow;
1328
+ let buffer = "";
1329
+ if (rowDelta > 0) {
1330
+ buffer += `\x1b[${rowDelta}B`; // Move down
1331
+ } else if (rowDelta < 0) {
1332
+ buffer += `\x1b[${-rowDelta}A`; // Move up
1333
+ }
1334
+ // Move to absolute column (1-indexed)
1335
+ buffer += `\x1b[${targetCol + 1}G`;
1336
+ buffer += this.#showHardwareCursor ? "\x1b[?25h" : "\x1b[?25l";
1337
+
1338
+ this.terminal.write(`\x1b[?2026h${buffer}\x1b[?2026l`);
1339
+ this.#hardwareCursorRow = targetRow;
1340
+ }
1341
+ }