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