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