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