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