@lenylvt/pi-tui 0.64.0

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