@asm-agent/tui 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/README.md +795 -0
  2. package/dist/autocomplete.d.ts +61 -0
  3. package/dist/autocomplete.d.ts.map +1 -0
  4. package/dist/autocomplete.js +601 -0
  5. package/dist/autocomplete.js.map +1 -0
  6. package/dist/components/box.d.ts +24 -0
  7. package/dist/components/box.d.ts.map +1 -0
  8. package/dist/components/box.js +114 -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 +275 -0
  15. package/dist/components/editor.d.ts.map +1 -0
  16. package/dist/components/editor.js +1968 -0
  17. package/dist/components/editor.js.map +1 -0
  18. package/dist/components/image.d.ts +34 -0
  19. package/dist/components/image.d.ts.map +1 -0
  20. package/dist/components/image.js +96 -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 +385 -0
  25. package/dist/components/input.js.map +1 -0
  26. package/dist/components/loader.d.ts +29 -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 +100 -0
  31. package/dist/components/markdown.d.ts.map +1 -0
  32. package/dist/components/markdown.js +773 -0
  33. package/dist/components/markdown.js.map +1 -0
  34. package/dist/components/select-list.d.ts +61 -0
  35. package/dist/components/select-list.d.ts.map +1 -0
  36. package/dist/components/select-list.js +206 -0
  37. package/dist/components/select-list.js.map +1 -0
  38. package/dist/components/settings-list.d.ts +49 -0
  39. package/dist/components/settings-list.d.ts.map +1 -0
  40. package/dist/components/settings-list.js +170 -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 +21 -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 +77 -0
  49. package/dist/components/text.js.map +1 -0
  50. package/dist/components/truncated-text.d.ts +14 -0
  51. package/dist/components/truncated-text.d.ts.map +1 -0
  52. package/dist/components/truncated-text.js +44 -0
  53. package/dist/components/truncated-text.js.map +1 -0
  54. package/dist/editor-component.d.ts +51 -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/fullscreen.d.ts +105 -0
  59. package/dist/fullscreen.d.ts.map +1 -0
  60. package/dist/fullscreen.js +597 -0
  61. package/dist/fullscreen.js.map +1 -0
  62. package/dist/fuzzy.d.ts +26 -0
  63. package/dist/fuzzy.d.ts.map +1 -0
  64. package/dist/fuzzy.js +114 -0
  65. package/dist/fuzzy.js.map +1 -0
  66. package/dist/index.d.ts +29 -0
  67. package/dist/index.d.ts.map +1 -0
  68. package/dist/index.js +27 -0
  69. package/dist/index.js.map +1 -0
  70. package/dist/keybindings.d.ts +239 -0
  71. package/dist/keybindings.d.ts.map +1 -0
  72. package/dist/keybindings.js +222 -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 +1163 -0
  77. package/dist/keys.js.map +1 -0
  78. package/dist/kill-ring.d.ts +26 -0
  79. package/dist/kill-ring.d.ts.map +1 -0
  80. package/dist/kill-ring.js +42 -0
  81. package/dist/kill-ring.js.map +1 -0
  82. package/dist/latex.d.ts +21 -0
  83. package/dist/latex.d.ts.map +1 -0
  84. package/dist/latex.js +797 -0
  85. package/dist/latex.js.map +1 -0
  86. package/dist/mouse.d.ts +24 -0
  87. package/dist/mouse.d.ts.map +1 -0
  88. package/dist/mouse.js +34 -0
  89. package/dist/mouse.js.map +1 -0
  90. package/dist/render-cache.d.ts +9 -0
  91. package/dist/render-cache.d.ts.map +1 -0
  92. package/dist/render-cache.js +23 -0
  93. package/dist/render-cache.js.map +1 -0
  94. package/dist/selection-metadata.d.ts +22 -0
  95. package/dist/selection-metadata.d.ts.map +1 -0
  96. package/dist/selection-metadata.js +141 -0
  97. package/dist/selection-metadata.js.map +1 -0
  98. package/dist/slash-command-context.d.ts +12 -0
  99. package/dist/slash-command-context.d.ts.map +1 -0
  100. package/dist/slash-command-context.js +32 -0
  101. package/dist/slash-command-context.js.map +1 -0
  102. package/dist/stdin-buffer.d.ts +50 -0
  103. package/dist/stdin-buffer.d.ts.map +1 -0
  104. package/dist/stdin-buffer.js +313 -0
  105. package/dist/stdin-buffer.js.map +1 -0
  106. package/dist/terminal-colors.d.ts +31 -0
  107. package/dist/terminal-colors.d.ts.map +1 -0
  108. package/dist/terminal-colors.js +161 -0
  109. package/dist/terminal-colors.js.map +1 -0
  110. package/dist/terminal-image.d.ts +85 -0
  111. package/dist/terminal-image.d.ts.map +1 -0
  112. package/dist/terminal-image.js +324 -0
  113. package/dist/terminal-image.js.map +1 -0
  114. package/dist/terminal.d.ts +113 -0
  115. package/dist/terminal.d.ts.map +1 -0
  116. package/dist/terminal.js +486 -0
  117. package/dist/terminal.js.map +1 -0
  118. package/dist/tui.d.ts +310 -0
  119. package/dist/tui.d.ts.map +1 -0
  120. package/dist/tui.js +1673 -0
  121. package/dist/tui.js.map +1 -0
  122. package/dist/undo-stack.d.ts +16 -0
  123. package/dist/undo-stack.d.ts.map +1 -0
  124. package/dist/undo-stack.js +26 -0
  125. package/dist/undo-stack.js.map +1 -0
  126. package/dist/utils.d.ts +98 -0
  127. package/dist/utils.d.ts.map +1 -0
  128. package/dist/utils.js +1233 -0
  129. package/dist/utils.js.map +1 -0
  130. package/package.json +52 -0
package/dist/tui.js ADDED
@@ -0,0 +1,1673 @@
1
+ /**
2
+ * Minimal TUI implementation with differential rendering
3
+ */
4
+ import { execFile } from "node:child_process";
5
+ import * as fs from "node:fs";
6
+ import * as os from "node:os";
7
+ import * as path from "node:path";
8
+ import { performance } from "node:perf_hooks";
9
+ import { withFullscreenImageFallback } from "./components/image.js";
10
+ import { FullscreenViewport } from "./fullscreen.js";
11
+ import { getKeybindings } from "./keybindings.js";
12
+ import { isKeyRelease, matchesKey } from "./keys.js";
13
+ import { isMouseSequence, isWheelDown, isWheelUp, MOUSE_BUTTON_LEFT, parseSgrMouseEvent } from "./mouse.js";
14
+ import { deleteKittyImage, getCapabilities, isImageLine, setCellDimensions } from "./terminal-image.js";
15
+ import { extractSegments, normalizeTerminalOutput, sliceByColumn, sliceWithWidth, stripAnsi, visibleContentSpan, visibleWidth, } from "./utils.js";
16
+ const KITTY_SEQUENCE_PREFIX = "\x1b_G";
17
+ function extractKittyImageIds(line) {
18
+ const sequenceStart = line.indexOf(KITTY_SEQUENCE_PREFIX);
19
+ if (sequenceStart === -1)
20
+ return [];
21
+ const paramsStart = sequenceStart + KITTY_SEQUENCE_PREFIX.length;
22
+ const paramsEnd = line.indexOf(";", paramsStart);
23
+ if (paramsEnd === -1)
24
+ return [];
25
+ const params = line.slice(paramsStart, paramsEnd);
26
+ for (const param of params.split(",")) {
27
+ const [key, value] = param.split("=", 2);
28
+ if (key !== "i" || value === undefined)
29
+ continue;
30
+ const id = Number(value);
31
+ if (Number.isInteger(id) && id > 0 && id <= 0xffffffff) {
32
+ return [id];
33
+ }
34
+ }
35
+ return [];
36
+ }
37
+ /** Type guard to check if a component implements Focusable */
38
+ export function isFocusable(component) {
39
+ return component !== null && "focused" in component;
40
+ }
41
+ /**
42
+ * Cursor position marker - APC (Application Program Command) sequence.
43
+ * This is a zero-width escape sequence that terminals ignore.
44
+ * Components emit this at the cursor position when focused.
45
+ * TUI finds and strips this marker, then positions the hardware cursor there.
46
+ */
47
+ export const CURSOR_MARKER = "\x1b_pi:c\x07";
48
+ export { visibleWidth };
49
+ /** Parse a SizeValue into absolute value given a reference size */
50
+ function parseSizeValue(value, referenceSize) {
51
+ if (value === undefined)
52
+ return undefined;
53
+ if (typeof value === "number")
54
+ return value;
55
+ // Parse percentage string like "50%"
56
+ const match = value.match(/^(\d+(?:\.\d+)?)%$/);
57
+ if (match) {
58
+ return Math.floor((referenceSize * parseFloat(match[1])) / 100);
59
+ }
60
+ return undefined;
61
+ }
62
+ function isTermuxSession() {
63
+ return Boolean(process.env.TERMUX_VERSION);
64
+ }
65
+ /**
66
+ * Container - a component that contains other components
67
+ */
68
+ export class Container {
69
+ children = [];
70
+ selectionRegions = [];
71
+ addChild(component) {
72
+ this.children.push(component);
73
+ this.selectionRegions = [];
74
+ }
75
+ removeChild(component) {
76
+ const index = this.children.indexOf(component);
77
+ if (index !== -1) {
78
+ this.children.splice(index, 1);
79
+ this.selectionRegions = [];
80
+ }
81
+ }
82
+ clear() {
83
+ this.children = [];
84
+ this.selectionRegions = [];
85
+ }
86
+ invalidate() {
87
+ this.selectionRegions = [];
88
+ for (const child of this.children) {
89
+ child.invalidate?.();
90
+ }
91
+ }
92
+ render(width) {
93
+ const lines = [];
94
+ const selectionRegions = [];
95
+ for (const child of this.children) {
96
+ const lineOffset = lines.length;
97
+ const childLines = child.render(width);
98
+ for (const region of child.getSelectionRegions?.() ?? []) {
99
+ selectionRegions.push({
100
+ ...region,
101
+ line: region.line + lineOffset,
102
+ tableTop: region.tableTop + lineOffset,
103
+ tableBottom: region.tableBottom + lineOffset,
104
+ });
105
+ }
106
+ for (const line of childLines) {
107
+ lines.push(line);
108
+ }
109
+ }
110
+ this.selectionRegions = selectionRegions;
111
+ return lines;
112
+ }
113
+ getSelectionRegions() {
114
+ return this.selectionRegions;
115
+ }
116
+ }
117
+ /**
118
+ * TUI - Main class for managing terminal UI with differential rendering
119
+ */
120
+ export class TUI extends Container {
121
+ terminal;
122
+ previousLines = [];
123
+ previousKittyImageIds = new Set();
124
+ previousWidth = 0;
125
+ previousHeight = 0;
126
+ focusedComponent = null;
127
+ inputListeners = new Set();
128
+ /** Global callback for debug key (Shift+Ctrl+D). Called before input is forwarded to focused component. */
129
+ onDebug;
130
+ /** Copies fullscreen mouse selections; when unset, OSC 52 is written directly. */
131
+ onCopy;
132
+ /** Opens hyperlinks clicked in the fullscreen viewport; when unset, the platform opener is used. */
133
+ onOpenUrl;
134
+ renderRequested = false;
135
+ renderTimer;
136
+ lastRenderAt = 0;
137
+ static MIN_RENDER_INTERVAL_MS = 16;
138
+ cursorRow = 0; // Logical cursor row (end of rendered content)
139
+ hardwareCursorRow = 0; // Actual terminal cursor row (may differ due to IME positioning)
140
+ showHardwareCursor = process.env.PI_HARDWARE_CURSOR === "1";
141
+ clearOnShrink = process.env.PI_CLEAR_ON_SHRINK === "1"; // Clear empty rows when content shrinks (default: off)
142
+ maxLinesRendered = 0; // Track terminal's working area (max lines ever rendered)
143
+ previousViewportTop = 0; // Track previous viewport top for resize-aware cursor moves
144
+ fullRedrawCount = 0;
145
+ preserveViewportOnNextRender = false; // One-shot: repaint visible viewport in place instead of replaying scrollback
146
+ stopped = false;
147
+ fullscreenLeftMouseDragged = false;
148
+ fullscreenPressedHyperlink = null;
149
+ overlaySelectionRegions = [];
150
+ // While set, doRender paints fixed frames via the viewport; the inline
151
+ // differ's bookkeeping stays frozen in `inlineState` until exit.
152
+ fullscreen = null;
153
+ static WHEEL_SCROLL_LINES = 3;
154
+ static SELECTION_AUTO_SCROLL_DELAY_MS = 150;
155
+ static SELECTION_AUTO_SCROLL_INTERVAL_MS = 50;
156
+ selectionAutoScrollTimer;
157
+ selectionAutoScrollDirection = null;
158
+ selectionAutoScrollRow = 0;
159
+ selectionAutoScrollColumn = 0;
160
+ // Overlay stack for modal components rendered on top of base content
161
+ focusOrderCounter = 0;
162
+ overlayStack = [];
163
+ constructor(terminal, showHardwareCursor) {
164
+ super();
165
+ this.terminal = terminal;
166
+ if (showHardwareCursor !== undefined) {
167
+ this.showHardwareCursor = showHardwareCursor;
168
+ }
169
+ }
170
+ get fullRedraws() {
171
+ return this.fullRedrawCount;
172
+ }
173
+ getShowHardwareCursor() {
174
+ return this.showHardwareCursor;
175
+ }
176
+ setShowHardwareCursor(enabled) {
177
+ if (this.showHardwareCursor === enabled)
178
+ return;
179
+ this.showHardwareCursor = enabled;
180
+ if (!enabled) {
181
+ this.terminal.hideCursor();
182
+ }
183
+ this.requestRender();
184
+ }
185
+ getClearOnShrink() {
186
+ return this.clearOnShrink;
187
+ }
188
+ /**
189
+ * Set whether to trigger full re-render when content shrinks.
190
+ * When true (default), empty rows are cleared when content shrinks.
191
+ * When false, empty rows remain (reduces redraws on slower terminals).
192
+ */
193
+ setClearOnShrink(enabled) {
194
+ this.clearOnShrink = enabled;
195
+ }
196
+ setFocus(component) {
197
+ // Clear focused flag on old component
198
+ if (isFocusable(this.focusedComponent)) {
199
+ this.focusedComponent.focused = false;
200
+ }
201
+ this.focusedComponent = component;
202
+ // Set focused flag on new component
203
+ if (isFocusable(component)) {
204
+ component.focused = true;
205
+ }
206
+ }
207
+ /**
208
+ * Show an overlay component with configurable positioning and sizing.
209
+ * Returns a handle to control the overlay's visibility.
210
+ */
211
+ showOverlay(component, options) {
212
+ const entry = {
213
+ component,
214
+ options,
215
+ preFocus: this.focusedComponent,
216
+ hidden: false,
217
+ focusOrder: ++this.focusOrderCounter,
218
+ };
219
+ this.overlayStack.push(entry);
220
+ // Only focus if overlay is actually visible
221
+ if (!options?.nonCapturing && this.isOverlayVisible(entry)) {
222
+ this.setFocus(component);
223
+ }
224
+ this.syncFullscreenMouseTracking();
225
+ this.terminal.hideCursor();
226
+ this.requestRender();
227
+ // Return handle for controlling this overlay
228
+ return {
229
+ hide: () => {
230
+ const index = this.overlayStack.indexOf(entry);
231
+ if (index !== -1) {
232
+ this.overlayStack.splice(index, 1);
233
+ // Restore focus if this overlay had focus
234
+ if (this.focusedComponent === component) {
235
+ const topVisible = this.getTopmostVisibleOverlay();
236
+ this.setFocus(topVisible?.component ?? entry.preFocus);
237
+ }
238
+ if (this.overlayStack.length === 0)
239
+ this.terminal.hideCursor();
240
+ this.syncFullscreenMouseTracking();
241
+ this.requestRender();
242
+ }
243
+ },
244
+ setHidden: (hidden) => {
245
+ if (entry.hidden === hidden)
246
+ return;
247
+ entry.hidden = hidden;
248
+ // Update focus when hiding/showing
249
+ if (hidden) {
250
+ // If this overlay had focus, move focus to next visible or preFocus
251
+ if (this.focusedComponent === component) {
252
+ const topVisible = this.getTopmostVisibleOverlay();
253
+ this.setFocus(topVisible?.component ?? entry.preFocus);
254
+ }
255
+ }
256
+ else {
257
+ // Restore focus to this overlay when showing (if it's actually visible)
258
+ if (!options?.nonCapturing && this.isOverlayVisible(entry)) {
259
+ entry.focusOrder = ++this.focusOrderCounter;
260
+ this.setFocus(component);
261
+ }
262
+ }
263
+ this.syncFullscreenMouseTracking();
264
+ this.requestRender();
265
+ },
266
+ isHidden: () => entry.hidden,
267
+ focus: () => {
268
+ if (!this.overlayStack.includes(entry) || !this.isOverlayVisible(entry))
269
+ return;
270
+ if (this.focusedComponent !== component) {
271
+ this.setFocus(component);
272
+ }
273
+ entry.focusOrder = ++this.focusOrderCounter;
274
+ this.syncFullscreenMouseTracking();
275
+ this.requestRender();
276
+ },
277
+ unfocus: () => {
278
+ if (this.focusedComponent !== component)
279
+ return;
280
+ const topVisible = this.getTopmostVisibleOverlay();
281
+ this.setFocus(topVisible && topVisible !== entry ? topVisible.component : entry.preFocus);
282
+ this.syncFullscreenMouseTracking();
283
+ this.requestRender();
284
+ },
285
+ isFocused: () => this.focusedComponent === component,
286
+ };
287
+ }
288
+ /** Hide the topmost overlay and restore previous focus. */
289
+ hideOverlay() {
290
+ const overlay = this.overlayStack.pop();
291
+ if (!overlay)
292
+ return;
293
+ if (this.focusedComponent === overlay.component) {
294
+ // Find topmost visible overlay, or fall back to preFocus
295
+ const topVisible = this.getTopmostVisibleOverlay();
296
+ this.setFocus(topVisible?.component ?? overlay.preFocus);
297
+ }
298
+ if (this.overlayStack.length === 0)
299
+ this.terminal.hideCursor();
300
+ this.syncFullscreenMouseTracking();
301
+ this.requestRender();
302
+ }
303
+ /** Check if there are any visible overlays */
304
+ hasOverlay() {
305
+ return this.overlayStack.some((o) => this.isOverlayVisible(o));
306
+ }
307
+ /** Check if an overlay entry is currently visible */
308
+ isOverlayVisible(entry) {
309
+ if (entry.hidden)
310
+ return false;
311
+ if (entry.options?.visible) {
312
+ return entry.options.visible(this.terminal.columns, this.terminal.rows);
313
+ }
314
+ return true;
315
+ }
316
+ /** Find the topmost visible capturing overlay, if any */
317
+ getTopmostVisibleOverlay() {
318
+ for (let i = this.overlayStack.length - 1; i >= 0; i--) {
319
+ if (this.overlayStack[i].options?.nonCapturing)
320
+ continue;
321
+ if (this.isOverlayVisible(this.overlayStack[i])) {
322
+ return this.overlayStack[i];
323
+ }
324
+ }
325
+ return undefined;
326
+ }
327
+ shouldEnableFullscreenMouseTracking() {
328
+ if (!this.fullscreen?.mouse)
329
+ return false;
330
+ return !this.overlayStack.some((entry) => entry.options?.suspendFullscreenMouse === true && this.isOverlayVisible(entry));
331
+ }
332
+ isFullscreenOverlayFocused() {
333
+ return this.overlayStack.some((entry) => entry.component === this.focusedComponent);
334
+ }
335
+ syncFullscreenMouseTracking() {
336
+ const enabled = this.shouldEnableFullscreenMouseTracking();
337
+ if (!enabled) {
338
+ this.stopSelectionAutoScroll();
339
+ this.fullscreenLeftMouseDragged = false;
340
+ this.fullscreenPressedHyperlink = null;
341
+ this.fullscreen?.viewport.clearSelection();
342
+ }
343
+ else if (this.isFullscreenOverlayFocused()) {
344
+ this.stopSelectionAutoScroll();
345
+ }
346
+ this.terminal.setMouseTracking(enabled);
347
+ }
348
+ invalidate() {
349
+ super.invalidate();
350
+ for (const overlay of this.overlayStack)
351
+ overlay.component.invalidate?.();
352
+ }
353
+ start() {
354
+ this.stopped = false;
355
+ this.terminal.start((data) => this.handleInput(data), () => this.requestRender());
356
+ this.terminal.hideCursor();
357
+ this.queryCellSize();
358
+ this.requestRender();
359
+ }
360
+ addInputListener(listener) {
361
+ this.inputListeners.add(listener);
362
+ return () => {
363
+ this.inputListeners.delete(listener);
364
+ };
365
+ }
366
+ removeInputListener(listener) {
367
+ this.inputListeners.delete(listener);
368
+ }
369
+ queryCellSize() {
370
+ // Only query if terminal supports images (cell size is only used for image rendering)
371
+ if (!getCapabilities().images) {
372
+ return;
373
+ }
374
+ // Query terminal for cell size in pixels: CSI 16 t
375
+ // Response format: CSI 6 ; height ; width t
376
+ this.terminal.write("\x1b[16t");
377
+ }
378
+ stop(options = {}) {
379
+ const preserveAltScreen = options.preserveAltScreen === true && this.terminal.altScreenActive;
380
+ const flushFullscreen = options.flushFullscreen ?? !preserveAltScreen;
381
+ this.exitFullscreen({ flush: flushFullscreen, leaveAltScreen: !preserveAltScreen });
382
+ this.stopped = true;
383
+ if (this.renderTimer) {
384
+ clearTimeout(this.renderTimer);
385
+ this.renderTimer = undefined;
386
+ }
387
+ // Move cursor to the end of the content to prevent overwriting/artifacts on exit
388
+ if (!preserveAltScreen && this.previousLines.length > 0) {
389
+ const targetRow = this.previousLines.length; // Line after the last content
390
+ const lineDiff = targetRow - this.hardwareCursorRow;
391
+ if (lineDiff > 0) {
392
+ this.terminal.write(`\x1b[${lineDiff}B`);
393
+ }
394
+ else if (lineDiff < 0) {
395
+ this.terminal.write(`\x1b[${-lineDiff}A`);
396
+ }
397
+ this.terminal.write("\r\n");
398
+ }
399
+ if (preserveAltScreen) {
400
+ this.terminal.hideCursor();
401
+ }
402
+ else {
403
+ this.terminal.showCursor();
404
+ }
405
+ this.terminal.stop({ preserveAltScreen });
406
+ }
407
+ requestRender(force = false) {
408
+ if (force) {
409
+ this.fullscreen?.viewport.reset();
410
+ // Keep the previous frame metadata so the forced full repaint can
411
+ // clean up only the visible viewport and avoid touching scrollback.
412
+ this.previousWidth = -1; // -1 triggers widthChanged, forcing a full clear
413
+ this.cursorRow = 0;
414
+ this.hardwareCursorRow = 0;
415
+ this.maxLinesRendered = 0;
416
+ if (this.renderTimer) {
417
+ clearTimeout(this.renderTimer);
418
+ this.renderTimer = undefined;
419
+ }
420
+ this.renderRequested = true;
421
+ process.nextTick(() => {
422
+ if (this.stopped || !this.renderRequested) {
423
+ return;
424
+ }
425
+ this.renderRequested = false;
426
+ this.lastRenderAt = performance.now();
427
+ this.doRender();
428
+ });
429
+ return;
430
+ }
431
+ if (this.renderRequested)
432
+ return;
433
+ this.renderRequested = true;
434
+ process.nextTick(() => this.scheduleRender());
435
+ }
436
+ /**
437
+ * Request a render that keeps the user anchored at their current scroll
438
+ * position. Normally, when content above the visible viewport changes, the
439
+ * renderer may fall back to a full screen redraw that replays the entire
440
+ * transcript from the top. For deliberate toggles (e.g. expanding all tool
441
+ * output) that is jarring: it scrolls to the top and reprints everything.
442
+ * This instead repaints only the visible viewport in place, leaving
443
+ * scrollback untouched.
444
+ */
445
+ requestRenderPreservingViewport() {
446
+ this.preserveViewportOnNextRender = true;
447
+ this.requestRender();
448
+ }
449
+ /**
450
+ * Render a scrollable transcript window on the alternate screen with `dock`
451
+ * pinned to the bottom rows; the primary screen stays untouched until exit.
452
+ * Wheel tracking is enabled blind — probing is not viable (tmux never
453
+ * answers DECRQM) and unsupporting terminals ignore the mode-sets.
454
+ */
455
+ enterFullscreen(options) {
456
+ if (this.fullscreen)
457
+ return;
458
+ this.fullscreenLeftMouseDragged = false;
459
+ this.fullscreenPressedHyperlink = null;
460
+ this.fullscreen = {
461
+ viewport: new FullscreenViewport(),
462
+ scroll: options.scroll,
463
+ dock: options.dock,
464
+ mouse: options.mouse !== false,
465
+ viewportControls: options.viewportControls !== false,
466
+ inlineState: {
467
+ previousLines: this.previousLines,
468
+ previousKittyImageIds: this.previousKittyImageIds,
469
+ previousWidth: this.previousWidth,
470
+ previousHeight: this.previousHeight,
471
+ cursorRow: this.cursorRow,
472
+ hardwareCursorRow: this.hardwareCursorRow,
473
+ maxLinesRendered: this.maxLinesRendered,
474
+ previousViewportTop: this.previousViewportTop,
475
+ },
476
+ };
477
+ this.terminal.enterAltScreen();
478
+ this.terminal.hideCursor();
479
+ this.syncFullscreenMouseTracking();
480
+ this.requestRender();
481
+ }
482
+ /**
483
+ * Leave fullscreen. The inline differ resumes against the entry snapshot,
484
+ * so content produced while fullscreen flows into native scrollback.
485
+ */
486
+ exitFullscreen(options = {}) {
487
+ this.stopSelectionAutoScroll();
488
+ if (!this.fullscreen)
489
+ return;
490
+ const { inlineState } = this.fullscreen;
491
+ this.fullscreen = null;
492
+ this.syncFullscreenMouseTracking();
493
+ if (options.leaveAltScreen !== false) {
494
+ this.terminal.leaveAltScreen();
495
+ }
496
+ this.previousLines = inlineState.previousLines;
497
+ this.previousKittyImageIds = inlineState.previousKittyImageIds;
498
+ this.previousWidth = inlineState.previousWidth;
499
+ this.previousHeight = inlineState.previousHeight;
500
+ this.cursorRow = inlineState.cursorRow;
501
+ this.hardwareCursorRow = inlineState.hardwareCursorRow;
502
+ this.maxLinesRendered = inlineState.maxLinesRendered;
503
+ this.previousViewportTop = inlineState.previousViewportTop;
504
+ // synchronous so the flush also happens on shutdown, where a scheduled render never fires
505
+ if (options.flush !== false && !this.stopped) {
506
+ this.doRender();
507
+ }
508
+ }
509
+ isFullscreen() {
510
+ return this.fullscreen !== null;
511
+ }
512
+ /** Scroll the fullscreen transcript window (negative = up). */
513
+ scrollBy(lines) {
514
+ if (!this.fullscreen)
515
+ return;
516
+ this.fullscreen.viewport.scrollBy(lines);
517
+ this.requestRender();
518
+ }
519
+ scrollToTop() {
520
+ if (!this.fullscreen)
521
+ return;
522
+ this.fullscreen.viewport.scrollToTop();
523
+ this.requestRender();
524
+ }
525
+ scrollToBottom() {
526
+ if (!this.fullscreen)
527
+ return;
528
+ this.fullscreen.viewport.scrollToBottom();
529
+ this.requestRender();
530
+ }
531
+ /** Scroll state of the fullscreen window, or null when not fullscreen. */
532
+ getScrollInfo() {
533
+ return this.fullscreen?.viewport.scrollInfo() ?? null;
534
+ }
535
+ // Terminals gate their native link handling while mouse reporting is active
536
+ // (Ghostty only refreshes link hover when reporting is off or shift is held),
537
+ // so clicks the TUI consumes must open OSC 8 hyperlinks itself.
538
+ openHyperlink(url) {
539
+ if (/\p{Cc}/u.test(url))
540
+ return;
541
+ let href;
542
+ try {
543
+ const parsed = new URL(url);
544
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
545
+ return;
546
+ href = parsed.href;
547
+ }
548
+ catch {
549
+ return;
550
+ }
551
+ if (this.onOpenUrl) {
552
+ this.onOpenUrl(href);
553
+ return;
554
+ }
555
+ const [command, ...args] = process.platform === "darwin"
556
+ ? ["open", href]
557
+ : process.platform === "win32"
558
+ ? [
559
+ path.win32.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "rundll32.exe"),
560
+ "url.dll,FileProtocolHandler",
561
+ href,
562
+ ]
563
+ : ["xdg-open", href];
564
+ execFile(command, args, () => { });
565
+ }
566
+ copySelection(text) {
567
+ if (this.onCopy) {
568
+ this.onCopy(text);
569
+ return;
570
+ }
571
+ // fallback: OSC 52 works locally, over SSH, and through tmux (set-clipboard)
572
+ const base64 = Buffer.from(text, "utf8").toString("base64");
573
+ this.terminal.write(`\x1b]52;c;${base64}\x07`);
574
+ }
575
+ updateSelectionAutoScroll(viewport, screenRow, screenColumn) {
576
+ const direction = viewport.selectionAutoScrollDirection(screenRow);
577
+ this.selectionAutoScrollRow = screenRow;
578
+ this.selectionAutoScrollColumn = screenColumn;
579
+ if (direction === this.selectionAutoScrollDirection && this.selectionAutoScrollTimer)
580
+ return;
581
+ this.stopSelectionAutoScroll();
582
+ if (direction === null)
583
+ return;
584
+ this.selectionAutoScrollDirection = direction;
585
+ this.scheduleSelectionAutoScroll(TUI.SELECTION_AUTO_SCROLL_DELAY_MS);
586
+ }
587
+ scheduleSelectionAutoScroll(delay) {
588
+ this.selectionAutoScrollTimer = setTimeout(() => {
589
+ this.selectionAutoScrollTimer = undefined;
590
+ const fullscreen = this.fullscreen;
591
+ const direction = this.selectionAutoScrollDirection;
592
+ if (!fullscreen ||
593
+ this.isFullscreenOverlayFocused() ||
594
+ direction === null ||
595
+ fullscreen.viewport.selectionAutoScrollDirection(this.selectionAutoScrollRow) !== direction ||
596
+ !fullscreen.viewport.scrollSelection(direction, this.selectionAutoScrollColumn)) {
597
+ this.stopSelectionAutoScroll();
598
+ return;
599
+ }
600
+ this.requestRender();
601
+ this.scheduleSelectionAutoScroll(TUI.SELECTION_AUTO_SCROLL_INTERVAL_MS);
602
+ }, delay);
603
+ this.selectionAutoScrollTimer.unref();
604
+ }
605
+ stopSelectionAutoScroll() {
606
+ if (this.selectionAutoScrollTimer) {
607
+ clearTimeout(this.selectionAutoScrollTimer);
608
+ this.selectionAutoScrollTimer = undefined;
609
+ }
610
+ this.selectionAutoScrollDirection = null;
611
+ }
612
+ scheduleRender() {
613
+ if (this.stopped || this.renderTimer || !this.renderRequested) {
614
+ return;
615
+ }
616
+ const elapsed = performance.now() - this.lastRenderAt;
617
+ const delay = Math.max(0, TUI.MIN_RENDER_INTERVAL_MS - elapsed);
618
+ this.renderTimer = setTimeout(() => {
619
+ this.renderTimer = undefined;
620
+ if (this.stopped || !this.renderRequested) {
621
+ return;
622
+ }
623
+ this.renderRequested = false;
624
+ this.lastRenderAt = performance.now();
625
+ this.doRender();
626
+ if (this.renderRequested) {
627
+ this.scheduleRender();
628
+ }
629
+ }, delay);
630
+ }
631
+ handleInput(data) {
632
+ if (this.inputListeners.size > 0) {
633
+ let current = data;
634
+ for (const listener of this.inputListeners) {
635
+ const result = listener(current);
636
+ if (result?.consume) {
637
+ return;
638
+ }
639
+ if (result?.data !== undefined) {
640
+ current = result.data;
641
+ }
642
+ }
643
+ if (current.length === 0) {
644
+ return;
645
+ }
646
+ data = current;
647
+ }
648
+ // Consume terminal cell size responses without blocking unrelated input.
649
+ if (this.consumeCellSizeResponse(data)) {
650
+ return;
651
+ }
652
+ // Global debug key handler (Shift+Ctrl+D)
653
+ if (matchesKey(data, "shift+ctrl+d") && this.onDebug) {
654
+ this.onDebug();
655
+ return;
656
+ }
657
+ if (this.fullscreen && this.handleFullscreenInput(data)) {
658
+ return;
659
+ }
660
+ // If focused component is an overlay, verify it's still visible
661
+ // (visibility can change due to terminal resize or visible() callback)
662
+ const focusedOverlay = this.overlayStack.find((o) => o.component === this.focusedComponent);
663
+ if (focusedOverlay && !this.isOverlayVisible(focusedOverlay)) {
664
+ // Focused overlay is no longer visible, redirect to topmost visible overlay
665
+ const topVisible = this.getTopmostVisibleOverlay();
666
+ if (topVisible) {
667
+ this.setFocus(topVisible.component);
668
+ }
669
+ else {
670
+ // No visible overlays, restore to preFocus
671
+ this.setFocus(focusedOverlay.preFocus);
672
+ }
673
+ }
674
+ // Pass input to focused component (including Ctrl+C)
675
+ // The focused component can decide how to handle Ctrl+C
676
+ if (this.focusedComponent?.handleInput) {
677
+ // Filter out key release events unless component opts in
678
+ if (isKeyRelease(data) && !this.focusedComponent.wantsKeyRelease) {
679
+ return;
680
+ }
681
+ this.focusedComponent.handleInput(data);
682
+ this.requestRender();
683
+ }
684
+ }
685
+ // Mouse reports are always consumed (nothing downstream understands them);
686
+ // viewport keys are skipped while an overlay has focus so selectors keep
687
+ // their own pageUp/pageDown.
688
+ handleFullscreenInput(data) {
689
+ const fullscreen = this.fullscreen;
690
+ if (!fullscreen)
691
+ return false;
692
+ const overlayFocused = this.isFullscreenOverlayFocused();
693
+ if (isMouseSequence(data)) {
694
+ // consumed even when disabled — mouse reports are garbage downstream
695
+ const event = this.terminal.mouseTrackingActive ? parseSgrMouseEvent(data) : null;
696
+ const leftReleaseWasDrag = event?.button === MOUSE_BUTTON_LEFT && !event.press ? this.fullscreenLeftMouseDragged : false;
697
+ if (event?.button === MOUSE_BUTTON_LEFT && event.press) {
698
+ this.fullscreenLeftMouseDragged = event.motion;
699
+ if (!event.motion) {
700
+ this.fullscreenPressedHyperlink = fullscreen.viewport.hyperlinkAt(event.y - 1, event.x - 1);
701
+ }
702
+ }
703
+ if (event && !overlayFocused) {
704
+ const viewport = fullscreen.viewport;
705
+ if (isWheelUp(event)) {
706
+ this.stopSelectionAutoScroll();
707
+ this.scrollBy(-TUI.WHEEL_SCROLL_LINES);
708
+ }
709
+ else if (isWheelDown(event)) {
710
+ this.stopSelectionAutoScroll();
711
+ this.scrollBy(TUI.WHEEL_SCROLL_LINES);
712
+ }
713
+ else if (event.button === MOUSE_BUTTON_LEFT && event.press && !event.motion) {
714
+ this.stopSelectionAutoScroll();
715
+ if (!viewport.beginSelection(event.y - 1, event.x - 1)) {
716
+ viewport.beginFrameSelection(event.y - 1, event.x - 1);
717
+ }
718
+ this.requestRender();
719
+ }
720
+ else if (event.button === MOUSE_BUTTON_LEFT && event.press && event.motion) {
721
+ viewport.extendActiveSelection(event.y - 1, event.x - 1);
722
+ this.updateSelectionAutoScroll(viewport, event.y - 1, event.x - 1);
723
+ this.requestRender();
724
+ }
725
+ else if (!event.press && viewport.hasSelection()) {
726
+ this.stopSelectionAutoScroll();
727
+ const text = viewport.endActiveSelection();
728
+ if (text)
729
+ this.copySelection(text);
730
+ this.requestRender();
731
+ }
732
+ else if (!event.press) {
733
+ this.stopSelectionAutoScroll();
734
+ viewport.clearSelection();
735
+ if (event.button === MOUSE_BUTTON_LEFT && !event.motion && !leftReleaseWasDrag) {
736
+ const url = this.fullscreenPressedHyperlink ?? viewport.hyperlinkAt(event.y - 1, event.x - 1);
737
+ if (url)
738
+ this.openHyperlink(url);
739
+ }
740
+ }
741
+ }
742
+ else if (event && overlayFocused) {
743
+ this.stopSelectionAutoScroll();
744
+ const viewport = fullscreen.viewport;
745
+ if (event.button === MOUSE_BUTTON_LEFT && event.press && !event.motion) {
746
+ if (!viewport.beginFrameSelection(event.y - 1, event.x - 1)) {
747
+ viewport.beginSelection(event.y - 1, event.x - 1);
748
+ }
749
+ this.requestRender();
750
+ }
751
+ else if (event.button === MOUSE_BUTTON_LEFT && event.press && event.motion) {
752
+ viewport.extendActiveSelection(event.y - 1, event.x - 1);
753
+ this.requestRender();
754
+ }
755
+ else if (!event.press && viewport.hasSelection()) {
756
+ const text = viewport.endActiveSelection();
757
+ if (text)
758
+ this.copySelection(text);
759
+ this.requestRender();
760
+ }
761
+ else if (!event.press) {
762
+ viewport.clearSelection();
763
+ if (event.button === MOUSE_BUTTON_LEFT && !event.motion && !leftReleaseWasDrag) {
764
+ const url = this.fullscreenPressedHyperlink ?? viewport.hyperlinkAt(event.y - 1, event.x - 1);
765
+ if (url)
766
+ this.openHyperlink(url);
767
+ }
768
+ }
769
+ }
770
+ if (event?.button === MOUSE_BUTTON_LEFT && !event.press) {
771
+ this.fullscreenLeftMouseDragged = false;
772
+ this.fullscreenPressedHyperlink = null;
773
+ }
774
+ return true;
775
+ }
776
+ this.stopSelectionAutoScroll();
777
+ if (overlayFocused || !fullscreen.viewportControls)
778
+ return false;
779
+ const keybindings = getKeybindings();
780
+ if (keybindings.matches(data, "tui.viewport.pageUp")) {
781
+ this.scrollBy(-fullscreen.viewport.pageSize());
782
+ return true;
783
+ }
784
+ if (keybindings.matches(data, "tui.viewport.pageDown")) {
785
+ this.scrollBy(fullscreen.viewport.pageSize());
786
+ return true;
787
+ }
788
+ if (keybindings.matches(data, "tui.viewport.top")) {
789
+ this.scrollToTop();
790
+ return true;
791
+ }
792
+ if (keybindings.matches(data, "tui.viewport.follow")) {
793
+ this.scrollToBottom();
794
+ return true;
795
+ }
796
+ return false;
797
+ }
798
+ consumeCellSizeResponse(data) {
799
+ // Response format: ESC [ 6 ; height ; width t
800
+ const match = data.match(/^\x1b\[6;(\d+);(\d+)t$/);
801
+ if (!match) {
802
+ return false;
803
+ }
804
+ const heightPx = parseInt(match[1], 10);
805
+ const widthPx = parseInt(match[2], 10);
806
+ if (heightPx <= 0 || widthPx <= 0) {
807
+ return true;
808
+ }
809
+ setCellDimensions({ widthPx, heightPx });
810
+ // Invalidate all components so images re-render with correct dimensions.
811
+ this.invalidate();
812
+ this.requestRender();
813
+ return true;
814
+ }
815
+ /**
816
+ * Resolve overlay layout from options.
817
+ * Returns { width, row, col, maxHeight } for rendering.
818
+ */
819
+ resolveOverlayLayout(options, overlayHeight, termWidth, termHeight) {
820
+ const opt = options ?? {};
821
+ // Parse margin (clamp to non-negative)
822
+ const margin = typeof opt.margin === "number"
823
+ ? { top: opt.margin, right: opt.margin, bottom: opt.margin, left: opt.margin }
824
+ : (opt.margin ?? {});
825
+ const marginTop = Math.max(0, margin.top ?? 0);
826
+ const marginRight = Math.max(0, margin.right ?? 0);
827
+ const marginBottom = Math.max(0, margin.bottom ?? 0);
828
+ const marginLeft = Math.max(0, margin.left ?? 0);
829
+ // Available space after margins
830
+ const availWidth = Math.max(1, termWidth - marginLeft - marginRight);
831
+ const availHeight = Math.max(1, termHeight - marginTop - marginBottom);
832
+ // === Resolve width ===
833
+ let width = parseSizeValue(opt.width, termWidth) ?? Math.min(80, availWidth);
834
+ // Apply minWidth
835
+ if (opt.minWidth !== undefined) {
836
+ width = Math.max(width, opt.minWidth);
837
+ }
838
+ // Clamp to available space
839
+ width = Math.max(1, Math.min(width, availWidth));
840
+ // === Resolve maxHeight ===
841
+ let maxHeight = parseSizeValue(opt.maxHeight, termHeight);
842
+ // Clamp to available space
843
+ if (maxHeight !== undefined) {
844
+ maxHeight = Math.max(1, Math.min(maxHeight, availHeight));
845
+ }
846
+ // Effective overlay height (may be clamped by maxHeight)
847
+ const effectiveHeight = maxHeight !== undefined ? Math.min(overlayHeight, maxHeight) : overlayHeight;
848
+ // === Resolve position ===
849
+ let row;
850
+ let col;
851
+ if (opt.row !== undefined) {
852
+ if (typeof opt.row === "string") {
853
+ // Percentage: 0% = top, 100% = bottom (overlay stays within bounds)
854
+ const match = opt.row.match(/^(\d+(?:\.\d+)?)%$/);
855
+ if (match) {
856
+ const maxRow = Math.max(0, availHeight - effectiveHeight);
857
+ const percent = parseFloat(match[1]) / 100;
858
+ row = marginTop + Math.floor(maxRow * percent);
859
+ }
860
+ else {
861
+ // Invalid format, fall back to center
862
+ row = this.resolveAnchorRow("center", effectiveHeight, availHeight, marginTop);
863
+ }
864
+ }
865
+ else {
866
+ // Absolute row position
867
+ row = opt.row;
868
+ }
869
+ }
870
+ else {
871
+ // Anchor-based (default: center)
872
+ const anchor = opt.anchor ?? "center";
873
+ row = this.resolveAnchorRow(anchor, effectiveHeight, availHeight, marginTop);
874
+ }
875
+ if (opt.col !== undefined) {
876
+ if (typeof opt.col === "string") {
877
+ // Percentage: 0% = left, 100% = right (overlay stays within bounds)
878
+ const match = opt.col.match(/^(\d+(?:\.\d+)?)%$/);
879
+ if (match) {
880
+ const maxCol = Math.max(0, availWidth - width);
881
+ const percent = parseFloat(match[1]) / 100;
882
+ col = marginLeft + Math.floor(maxCol * percent);
883
+ }
884
+ else {
885
+ // Invalid format, fall back to center
886
+ col = this.resolveAnchorCol("center", width, availWidth, marginLeft);
887
+ }
888
+ }
889
+ else {
890
+ // Absolute column position
891
+ col = opt.col;
892
+ }
893
+ }
894
+ else {
895
+ // Anchor-based (default: center)
896
+ const anchor = opt.anchor ?? "center";
897
+ col = this.resolveAnchorCol(anchor, width, availWidth, marginLeft);
898
+ }
899
+ // Apply offsets
900
+ if (opt.offsetY !== undefined)
901
+ row += opt.offsetY;
902
+ if (opt.offsetX !== undefined)
903
+ col += opt.offsetX;
904
+ // Clamp to terminal bounds (respecting margins)
905
+ row = Math.max(marginTop, Math.min(row, termHeight - marginBottom - effectiveHeight));
906
+ col = Math.max(marginLeft, Math.min(col, termWidth - marginRight - width));
907
+ return { width, row, col, maxHeight };
908
+ }
909
+ resolveAnchorRow(anchor, height, availHeight, marginTop) {
910
+ switch (anchor) {
911
+ case "top-left":
912
+ case "top-center":
913
+ case "top-right":
914
+ return marginTop;
915
+ case "bottom-left":
916
+ case "bottom-center":
917
+ case "bottom-right":
918
+ return marginTop + availHeight - height;
919
+ case "left-center":
920
+ case "center":
921
+ case "right-center":
922
+ return marginTop + Math.floor((availHeight - height) / 2);
923
+ }
924
+ }
925
+ resolveAnchorCol(anchor, width, availWidth, marginLeft) {
926
+ switch (anchor) {
927
+ case "top-left":
928
+ case "left-center":
929
+ case "bottom-left":
930
+ return marginLeft;
931
+ case "top-right":
932
+ case "right-center":
933
+ case "bottom-right":
934
+ return marginLeft + availWidth - width;
935
+ case "top-center":
936
+ case "center":
937
+ case "bottom-center":
938
+ return marginLeft + Math.floor((availWidth - width) / 2);
939
+ }
940
+ }
941
+ /** Composite all overlays into content lines (sorted by focusOrder, higher = on top). */
942
+ compositeOverlays(lines, termWidth, termHeight) {
943
+ if (this.overlayStack.length === 0)
944
+ return lines;
945
+ const result = [...lines];
946
+ const overlaySelectionRegions = [...this.overlaySelectionRegions];
947
+ // Pre-render all visible overlays and calculate positions
948
+ const rendered = [];
949
+ let minLinesNeeded = result.length;
950
+ const visibleEntries = this.overlayStack.filter((e) => this.isOverlayVisible(e));
951
+ visibleEntries.sort((a, b) => a.focusOrder - b.focusOrder);
952
+ for (const entry of visibleEntries) {
953
+ const { component, options } = entry;
954
+ const scrollback = options?.scrollback === true;
955
+ let aboveMarker;
956
+ if (options?.aboveMarker) {
957
+ for (let line = result.length - 1; line >= 0; line--) {
958
+ const markerIndex = result[line].indexOf(options.aboveMarker);
959
+ if (markerIndex === -1)
960
+ continue;
961
+ aboveMarker = {
962
+ line,
963
+ col: visibleWidth(result[line].slice(0, markerIndex)),
964
+ offsetY: options.offsetY ?? 0,
965
+ };
966
+ result[line] =
967
+ result[line].slice(0, markerIndex) + result[line].slice(markerIndex + options.aboveMarker.length);
968
+ break;
969
+ }
970
+ if (!aboveMarker)
971
+ continue;
972
+ }
973
+ // Get layout with height=0 first to determine width and maxHeight
974
+ // (width and maxHeight don't depend on overlay height)
975
+ const { width, maxHeight } = this.resolveOverlayLayout(options, 0, termWidth, termHeight);
976
+ // Render component at calculated width
977
+ let overlayLines = component.render(width);
978
+ // Apply maxHeight if specified
979
+ if (maxHeight !== undefined && overlayLines.length > maxHeight) {
980
+ overlayLines = overlayLines.slice(0, maxHeight);
981
+ }
982
+ // Get final row/col with actual overlay height
983
+ const { row, col } = this.resolveOverlayLayout(options, overlayLines.length, termWidth, termHeight);
984
+ rendered.push({ component, overlayLines, row, col, w: width, scrollback, aboveMarker });
985
+ if (!aboveMarker) {
986
+ minLinesNeeded = Math.max(minLinesNeeded, row + overlayLines.length);
987
+ }
988
+ }
989
+ // Pad to at least terminal height so overlays have screen-relative positions.
990
+ // Excludes maxLinesRendered: the historical high-water mark caused self-reinforcing
991
+ // inflation that pushed content into scrollback on terminal widen.
992
+ const workingHeight = Math.max(result.length, termHeight, minLinesNeeded);
993
+ // Extend result with empty lines if content is too short for overlay placement or working area
994
+ while (result.length < workingHeight) {
995
+ result.push("");
996
+ }
997
+ const viewportStart = Math.max(0, workingHeight - termHeight);
998
+ // Composite each overlay
999
+ for (const renderedOverlay of rendered) {
1000
+ const { component, w, scrollback, aboveMarker } = renderedOverlay;
1001
+ let { overlayLines, row, col } = renderedOverlay;
1002
+ if (aboveMarker) {
1003
+ const markerRow = Math.max(1, aboveMarker.line - viewportStart + aboveMarker.offsetY);
1004
+ if (markerRow >= termHeight)
1005
+ continue;
1006
+ while (overlayLines.length > markerRow && stripAnsi(overlayLines[0] ?? "").trim().length === 0) {
1007
+ overlayLines = overlayLines.slice(1);
1008
+ }
1009
+ while (overlayLines.length > markerRow && stripAnsi(overlayLines.at(-1) ?? "").trim().length === 0) {
1010
+ overlayLines = overlayLines.slice(0, -1);
1011
+ }
1012
+ if (overlayLines.length > markerRow) {
1013
+ overlayLines = overlayLines.slice(overlayLines.length - markerRow);
1014
+ }
1015
+ row = markerRow - overlayLines.length;
1016
+ col = Math.max(0, Math.min(aboveMarker.col, termWidth - w));
1017
+ }
1018
+ const overlayStart = scrollback && !aboveMarker ? Math.max(0, workingHeight - (row + overlayLines.length)) : viewportStart;
1019
+ for (let i = 0; i < overlayLines.length; i++) {
1020
+ const idx = overlayStart + row + i;
1021
+ if (idx >= 0 && idx < result.length) {
1022
+ // Defensive: truncate overlay line to declared width before compositing
1023
+ // (components should already respect width, but this ensures it)
1024
+ const truncatedOverlayLine = visibleWidth(overlayLines[i]) > w ? sliceByColumn(overlayLines[i], 0, w, true) : overlayLines[i];
1025
+ result[idx] = this.compositeLineAt(result[idx], truncatedOverlayLine, col, w, termWidth);
1026
+ this.subtractSelectionCoverage(overlaySelectionRegions, idx, col, col + w);
1027
+ const span = component === this.focusedComponent ? this.selectableSpan(truncatedOverlayLine, w) : null;
1028
+ if (span) {
1029
+ overlaySelectionRegions.push({ line: idx, col: col + span.from, width: span.to - span.from });
1030
+ }
1031
+ }
1032
+ }
1033
+ }
1034
+ this.overlaySelectionRegions = overlaySelectionRegions;
1035
+ return result;
1036
+ }
1037
+ selectableSpan(line, maxWidth) {
1038
+ return visibleContentSpan(line, maxWidth);
1039
+ }
1040
+ createDockSelectionRegions(frame, transcriptWindowHeight, width) {
1041
+ const regions = [];
1042
+ for (let row = Math.max(0, transcriptWindowHeight); row < frame.length; row++) {
1043
+ const span = this.selectableSpan(frame[row] ?? "", width);
1044
+ if (span) {
1045
+ regions.push({ line: row, col: span.from, width: span.to - span.from });
1046
+ }
1047
+ }
1048
+ return regions;
1049
+ }
1050
+ subtractSelectionCoverage(regions, line, coverStart, coverEnd) {
1051
+ for (let i = regions.length - 1; i >= 0; i--) {
1052
+ const region = regions[i];
1053
+ if (region.line !== line)
1054
+ continue;
1055
+ const regionStart = region.col;
1056
+ const regionEnd = region.col + region.width;
1057
+ if (coverEnd <= regionStart || coverStart >= regionEnd)
1058
+ continue;
1059
+ const replacements = [];
1060
+ if (regionStart < coverStart) {
1061
+ replacements.push({ line, col: regionStart, width: coverStart - regionStart });
1062
+ }
1063
+ if (coverEnd < regionEnd) {
1064
+ replacements.push({ line, col: coverEnd, width: regionEnd - coverEnd });
1065
+ }
1066
+ regions.splice(i, 1, ...replacements);
1067
+ }
1068
+ }
1069
+ static SEGMENT_RESET = "\x1b[0m\x1b]8;;\x07";
1070
+ applyLineResets(lines) {
1071
+ const reset = TUI.SEGMENT_RESET;
1072
+ for (let i = 0; i < lines.length; i++) {
1073
+ const line = lines[i];
1074
+ if (!isImageLine(line)) {
1075
+ lines[i] = normalizeTerminalOutput(line) + reset;
1076
+ }
1077
+ }
1078
+ return lines;
1079
+ }
1080
+ collectKittyImageIds(lines) {
1081
+ const ids = new Set();
1082
+ for (const line of lines) {
1083
+ for (const id of extractKittyImageIds(line)) {
1084
+ ids.add(id);
1085
+ }
1086
+ }
1087
+ return ids;
1088
+ }
1089
+ deleteKittyImages(ids) {
1090
+ let buffer = "";
1091
+ for (const id of ids) {
1092
+ buffer += deleteKittyImage(id);
1093
+ }
1094
+ return buffer;
1095
+ }
1096
+ expandLastChangedForKittyImages(firstChanged, lastChanged) {
1097
+ let expandedLastChanged = lastChanged;
1098
+ for (let i = firstChanged; i < this.previousLines.length; i++) {
1099
+ if (extractKittyImageIds(this.previousLines[i]).length > 0) {
1100
+ expandedLastChanged = Math.max(expandedLastChanged, i);
1101
+ }
1102
+ }
1103
+ return expandedLastChanged;
1104
+ }
1105
+ deleteChangedKittyImages(firstChanged, lastChanged) {
1106
+ if (firstChanged < 0 || lastChanged < firstChanged)
1107
+ return "";
1108
+ const ids = new Set();
1109
+ const maxLine = Math.min(lastChanged, this.previousLines.length - 1);
1110
+ for (let i = firstChanged; i <= maxLine; i++) {
1111
+ for (const id of extractKittyImageIds(this.previousLines[i] ?? "")) {
1112
+ ids.add(id);
1113
+ }
1114
+ }
1115
+ return this.deleteKittyImages(ids);
1116
+ }
1117
+ /** Splice overlay content into a base line at a specific column. Single-pass optimized. */
1118
+ compositeLineAt(baseLine, overlayLine, startCol, overlayWidth, totalWidth) {
1119
+ if (isImageLine(baseLine))
1120
+ return baseLine;
1121
+ // Single pass through baseLine extracts both before and after segments
1122
+ const afterStart = startCol + overlayWidth;
1123
+ const base = extractSegments(baseLine, startCol, afterStart, totalWidth - afterStart, true);
1124
+ // Extract overlay with width tracking (strict=true to exclude wide chars at boundary)
1125
+ const overlay = sliceWithWidth(overlayLine, 0, overlayWidth, true);
1126
+ // Pad segments to target widths
1127
+ const beforePad = Math.max(0, startCol - base.beforeWidth);
1128
+ const overlayPad = Math.max(0, overlayWidth - overlay.width);
1129
+ const actualBeforeWidth = Math.max(startCol, base.beforeWidth);
1130
+ const actualOverlayWidth = Math.max(overlayWidth, overlay.width);
1131
+ const afterTarget = Math.max(0, totalWidth - actualBeforeWidth - actualOverlayWidth);
1132
+ const afterPad = Math.max(0, afterTarget - base.afterWidth);
1133
+ // Compose result
1134
+ const r = TUI.SEGMENT_RESET;
1135
+ const result = base.before +
1136
+ " ".repeat(beforePad) +
1137
+ r +
1138
+ overlay.text +
1139
+ " ".repeat(overlayPad) +
1140
+ r +
1141
+ base.after +
1142
+ " ".repeat(afterPad);
1143
+ // CRITICAL: Always verify and truncate to terminal width.
1144
+ // This is the final safeguard against width overflow which would crash the TUI.
1145
+ // Width tracking can drift from actual visible width due to:
1146
+ // - Complex ANSI/OSC sequences (hyperlinks, colors)
1147
+ // - Wide characters at segment boundaries
1148
+ // - Edge cases in segment extraction
1149
+ const resultWidth = visibleWidth(result);
1150
+ if (resultWidth <= totalWidth) {
1151
+ return result;
1152
+ }
1153
+ // Truncate with strict=true to ensure we don't exceed totalWidth
1154
+ return sliceByColumn(result, 0, totalWidth, true);
1155
+ }
1156
+ /**
1157
+ * Find and extract cursor position from rendered lines.
1158
+ * Searches for CURSOR_MARKER, calculates its position, and strips it from the output.
1159
+ * Only scans the bottom terminal height lines (visible viewport).
1160
+ * @param lines - Rendered lines to search
1161
+ * @param height - Terminal height (visible viewport size)
1162
+ * @returns Cursor position { row, col } or null if no marker found
1163
+ */
1164
+ extractCursorPosition(lines, height) {
1165
+ // Only scan the bottom `height` lines (visible viewport)
1166
+ const viewportTop = Math.max(0, lines.length - height);
1167
+ for (let row = lines.length - 1; row >= viewportTop; row--) {
1168
+ const line = lines[row];
1169
+ const markerIndex = line.indexOf(CURSOR_MARKER);
1170
+ if (markerIndex !== -1) {
1171
+ // Calculate visual column (width of text before marker)
1172
+ const beforeMarker = line.slice(0, markerIndex);
1173
+ const col = visibleWidth(beforeMarker);
1174
+ // Strip marker from the line
1175
+ lines[row] = line.slice(0, markerIndex) + line.slice(markerIndex + CURSOR_MARKER.length);
1176
+ return { row, col };
1177
+ }
1178
+ }
1179
+ return null;
1180
+ }
1181
+ renderFullscreen() {
1182
+ const fullscreen = this.fullscreen;
1183
+ if (!fullscreen)
1184
+ return;
1185
+ const width = this.terminal.columns;
1186
+ const height = this.terminal.rows;
1187
+ this.syncFullscreenMouseTracking();
1188
+ this.overlaySelectionRegions = [];
1189
+ const transcript = [];
1190
+ const selectionRegions = [];
1191
+ const dock = withFullscreenImageFallback(() => {
1192
+ for (const component of fullscreen.scroll) {
1193
+ const lineOffset = transcript.length;
1194
+ const componentLines = component.render(width);
1195
+ for (const region of component.getSelectionRegions?.() ?? []) {
1196
+ selectionRegions.push({
1197
+ ...region,
1198
+ line: region.line + lineOffset,
1199
+ tableTop: region.tableTop + lineOffset,
1200
+ tableBottom: region.tableBottom + lineOffset,
1201
+ });
1202
+ }
1203
+ transcript.push(...componentLines);
1204
+ }
1205
+ return fullscreen.dock.render(width);
1206
+ });
1207
+ let frame = fullscreen.viewport.composeFrame(transcript, dock, height, selectionRegions);
1208
+ this.overlaySelectionRegions.push(...this.createDockSelectionRegions(frame, fullscreen.viewport.windowHeight(), width));
1209
+ const scrollInfo = fullscreen.viewport.scrollInfo();
1210
+ if (fullscreen.viewportControls && !scrollInfo.following) {
1211
+ // Follow hint composited over the bottom of the transcript window,
1212
+ // just above the dock. Overlays still paint on top of it.
1213
+ const followKey = getKeybindings().getKeys("tui.viewport.follow")[0] ?? "ctrl+shift+down";
1214
+ const label = ` ${followKey} to follow `;
1215
+ const labelWidth = visibleWidth(label);
1216
+ const row = fullscreen.viewport.windowHeight() - 1;
1217
+ if (row >= 0 && row < frame.length && labelWidth <= width) {
1218
+ const col = Math.floor((width - labelWidth) / 2);
1219
+ frame[row] = this.compositeLineAt(frame[row], `\x1b[7m${label}\x1b[27m`, col, labelWidth, width);
1220
+ }
1221
+ }
1222
+ if (this.overlayStack.length > 0) {
1223
+ frame = withFullscreenImageFallback(() => this.compositeOverlays(frame, width, height));
1224
+ }
1225
+ const cursorPos = this.extractCursorPosition(frame, height);
1226
+ fullscreen.viewport.applyFrameSelection(frame, height, this.overlaySelectionRegions);
1227
+ this.applyLineResets(frame);
1228
+ fullscreen.viewport.paint((data) => this.terminal.write(data), frame, width, height, cursorPos);
1229
+ if (cursorPos && this.showHardwareCursor) {
1230
+ this.terminal.showCursor();
1231
+ }
1232
+ else {
1233
+ this.terminal.hideCursor();
1234
+ }
1235
+ }
1236
+ doRender() {
1237
+ if (this.stopped)
1238
+ return;
1239
+ if (this.fullscreen) {
1240
+ this.preserveViewportOnNextRender = false;
1241
+ this.renderFullscreen();
1242
+ return;
1243
+ }
1244
+ // One-shot: consume here so it never leaks into a later render.
1245
+ this.overlaySelectionRegions = [];
1246
+ const preserveViewport = this.preserveViewportOnNextRender;
1247
+ this.preserveViewportOnNextRender = false;
1248
+ const width = this.terminal.columns;
1249
+ const height = this.terminal.rows;
1250
+ const widthChanged = this.previousWidth !== 0 && this.previousWidth !== width;
1251
+ const heightChanged = this.previousHeight !== 0 && this.previousHeight !== height;
1252
+ const previousBufferLength = this.previousHeight > 0 ? this.previousViewportTop + this.previousHeight : height;
1253
+ let prevViewportTop = heightChanged ? Math.max(0, previousBufferLength - height) : this.previousViewportTop;
1254
+ let viewportTop = prevViewportTop;
1255
+ let hardwareCursorRow = this.hardwareCursorRow;
1256
+ const computeLineDiff = (targetRow) => {
1257
+ const currentScreenRow = hardwareCursorRow - prevViewportTop;
1258
+ const targetScreenRow = targetRow - viewportTop;
1259
+ return targetScreenRow - currentScreenRow;
1260
+ };
1261
+ // Render all components to get new lines
1262
+ let newLines = this.render(width);
1263
+ // Composite overlays into the rendered lines (before differential compare)
1264
+ if (this.overlayStack.length > 0) {
1265
+ newLines = this.compositeOverlays(newLines, width, height);
1266
+ }
1267
+ // Extract cursor position before applying line resets (marker must be found first)
1268
+ const cursorPos = this.extractCursorPosition(newLines, height);
1269
+ newLines = this.applyLineResets(newLines);
1270
+ // Helper to clear the viewport and repaint the current screen. Do not
1271
+ // clear terminal scrollback: users rely on it to read long prior messages.
1272
+ const fullRender = (clear, preserveViewport = false) => {
1273
+ this.fullRedrawCount += 1;
1274
+ let buffer = "\x1b[?2026h"; // Begin synchronized output
1275
+ // Viewport-preserving repaint: rewrite only the visible viewport in
1276
+ // place, leaving terminal scrollback untouched. Keeps the user
1277
+ // anchored at their current focus instead of replaying the whole
1278
+ // (now-resized) transcript from the top. Only meaningful when there
1279
+ // is a previous frame on screen to paint over.
1280
+ if (preserveViewport && this.previousLines.length > 0) {
1281
+ const windowStart = Math.max(0, newLines.length - height);
1282
+ const visibleCount = newLines.length - windowStart;
1283
+ // Rows the previous frame occupied on screen.
1284
+ const prevScreenRows = Math.min(height, this.previousLines.length);
1285
+ // Only delete Kitty images within the repainted viewport. Images that
1286
+ // live in scrollback above the visible slice are never redrawn here, so
1287
+ // deleting them would leave broken history when the user scrolls up.
1288
+ buffer += this.deleteChangedKittyImages(prevViewportTop, prevViewportTop + prevScreenRows - 1);
1289
+ // Move the hardware cursor up to the top of the visible screen.
1290
+ // Use the local prevViewportTop (height-adjusted earlier in doRender)
1291
+ // rather than the field, so the move stays consistent with the rest
1292
+ // of the render when the terminal height changed this frame.
1293
+ const screenRow = Math.max(0, Math.min(prevScreenRows - 1, this.hardwareCursorRow - prevViewportTop));
1294
+ if (screenRow > 0)
1295
+ buffer += `\x1b[${screenRow}A`;
1296
+ buffer += "\r";
1297
+ // Clear the top row up front: the loop below clears it on its first
1298
+ // iteration, but when there is no content (visibleCount === 0) the
1299
+ // loop never runs and the leftover-clear moves down before clearing,
1300
+ // which would leave row 0 stale.
1301
+ if (visibleCount === 0)
1302
+ buffer += "\x1b[2K";
1303
+ for (let i = 0; i < visibleCount; i++) {
1304
+ if (i > 0)
1305
+ buffer += "\r\n";
1306
+ buffer += "\x1b[2K"; // Clear current line
1307
+ buffer += newLines[windowStart + i];
1308
+ }
1309
+ // Clear any rows the previous frame used below the new content.
1310
+ // Row 0 is already occupied (by content, or by the visibleCount === 0
1311
+ // clear above), so only clear the rows below it — clamping with
1312
+ // max(visibleCount, 1) avoids emitting a newline past the last screen
1313
+ // row, which would scroll the terminal.
1314
+ if (visibleCount < prevScreenRows) {
1315
+ const leftover = prevScreenRows - Math.max(visibleCount, 1);
1316
+ for (let i = 0; i < leftover; i++) {
1317
+ buffer += "\r\n\x1b[2K";
1318
+ }
1319
+ if (leftover > 0)
1320
+ buffer += `\x1b[${leftover}A`; // Back up to the last content row
1321
+ }
1322
+ buffer += "\x1b[?2026l"; // End synchronized output
1323
+ this.terminal.write(buffer);
1324
+ this.cursorRow = Math.max(0, newLines.length - 1);
1325
+ this.hardwareCursorRow = this.cursorRow;
1326
+ // Reset (not just grow) the high-water mark to the repainted content,
1327
+ // mirroring the full-redraw path. Otherwise a preserving collapse
1328
+ // leaves maxLinesRendered inflated, and the next plain render would
1329
+ // re-trigger clearOnShrink.
1330
+ this.maxLinesRendered = newLines.length;
1331
+ this.previousViewportTop = windowStart;
1332
+ this.positionHardwareCursor(cursorPos, newLines.length);
1333
+ this.previousLines = newLines;
1334
+ this.previousKittyImageIds = this.collectKittyImageIds(newLines);
1335
+ this.previousWidth = width;
1336
+ this.previousHeight = height;
1337
+ return;
1338
+ }
1339
+ const renderStart = clear && this.previousLines.length > 0 ? Math.max(0, newLines.length - height) : 0;
1340
+ if (clear) {
1341
+ const previousVisibleTop = Math.min(prevViewportTop, Math.max(0, this.previousLines.length - height));
1342
+ const previousVisibleBottom = Math.min(this.previousLines.length - 1, previousVisibleTop + height - 1);
1343
+ buffer += this.deleteChangedKittyImages(previousVisibleTop, previousVisibleBottom);
1344
+ buffer += "\x1b[2J\x1b[H"; // Clear screen and home while preserving scrollback
1345
+ }
1346
+ for (let i = renderStart; i < newLines.length; i++) {
1347
+ if (i > renderStart)
1348
+ buffer += "\r\n";
1349
+ buffer += newLines[i];
1350
+ }
1351
+ buffer += "\x1b[?2026l"; // End synchronized output
1352
+ this.terminal.write(buffer);
1353
+ this.cursorRow = Math.max(0, newLines.length - 1);
1354
+ this.hardwareCursorRow = this.cursorRow;
1355
+ // Reset max lines when clearing, otherwise track growth
1356
+ if (clear) {
1357
+ this.maxLinesRendered = newLines.length;
1358
+ }
1359
+ else {
1360
+ this.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);
1361
+ }
1362
+ const bufferLength = Math.max(height, newLines.length);
1363
+ this.previousViewportTop = Math.max(0, bufferLength - height);
1364
+ this.positionHardwareCursor(cursorPos, newLines.length);
1365
+ this.previousLines = newLines;
1366
+ this.previousKittyImageIds = this.collectKittyImageIds(newLines);
1367
+ this.previousWidth = width;
1368
+ this.previousHeight = height;
1369
+ };
1370
+ const debugRedraw = process.env.PI_DEBUG_REDRAW === "1";
1371
+ const logRedraw = (reason) => {
1372
+ if (!debugRedraw)
1373
+ return;
1374
+ const logPath = path.join(os.homedir(), ".prime", "agent", "pi-debug.log");
1375
+ const msg = `[${new Date().toISOString()}] fullRender: ${reason} (prev=${this.previousLines.length}, new=${newLines.length}, height=${height})\n`;
1376
+ fs.appendFileSync(logPath, msg);
1377
+ };
1378
+ // First render - just output everything without clearing (assumes clean screen)
1379
+ if (this.previousLines.length === 0 && !widthChanged && !heightChanged) {
1380
+ logRedraw("first render");
1381
+ fullRender(false);
1382
+ return;
1383
+ }
1384
+ // Width changes always need a full re-render because wrapping changes.
1385
+ if (widthChanged) {
1386
+ logRedraw(`terminal width changed (${this.previousWidth} -> ${width})`);
1387
+ fullRender(true);
1388
+ return;
1389
+ }
1390
+ // Height changes normally need a full re-render to keep the visible viewport aligned,
1391
+ // but Termux changes height when the software keyboard shows or hides.
1392
+ // In that environment, a full redraw causes the entire history to replay on every toggle.
1393
+ if (heightChanged && !isTermuxSession()) {
1394
+ logRedraw(`terminal height changed (${this.previousHeight} -> ${height})`);
1395
+ fullRender(true);
1396
+ return;
1397
+ }
1398
+ // Content shrunk below the working area and no overlays - re-render to clear empty rows
1399
+ // (overlays need the padding, so only do this when no overlays are active)
1400
+ // Configurable via setClearOnShrink() or PI_CLEAR_ON_SHRINK=0 env var
1401
+ if (this.clearOnShrink && newLines.length < this.maxLinesRendered && this.overlayStack.length === 0) {
1402
+ logRedraw(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`);
1403
+ fullRender(true, preserveViewport);
1404
+ return;
1405
+ }
1406
+ // Find first and last changed lines
1407
+ let firstChanged = -1;
1408
+ let lastChanged = -1;
1409
+ const maxLines = Math.max(newLines.length, this.previousLines.length);
1410
+ for (let i = 0; i < maxLines; i++) {
1411
+ const oldLine = i < this.previousLines.length ? this.previousLines[i] : "";
1412
+ const newLine = i < newLines.length ? newLines[i] : "";
1413
+ if (oldLine !== newLine) {
1414
+ if (firstChanged === -1) {
1415
+ firstChanged = i;
1416
+ }
1417
+ lastChanged = i;
1418
+ }
1419
+ }
1420
+ const appendedLines = newLines.length > this.previousLines.length;
1421
+ if (appendedLines) {
1422
+ if (firstChanged === -1) {
1423
+ firstChanged = this.previousLines.length;
1424
+ }
1425
+ lastChanged = newLines.length - 1;
1426
+ }
1427
+ if (firstChanged !== -1) {
1428
+ lastChanged = this.expandLastChangedForKittyImages(firstChanged, lastChanged);
1429
+ }
1430
+ const appendStart = appendedLines && firstChanged === this.previousLines.length && firstChanged > 0;
1431
+ // No changes - but still need to update hardware cursor position if it moved
1432
+ if (firstChanged === -1) {
1433
+ this.positionHardwareCursor(cursorPos, newLines.length);
1434
+ this.previousViewportTop = prevViewportTop;
1435
+ this.previousHeight = height;
1436
+ return;
1437
+ }
1438
+ // All changes are in deleted lines (nothing to render, just clear)
1439
+ if (firstChanged >= newLines.length) {
1440
+ if (this.previousLines.length > newLines.length) {
1441
+ let buffer = "\x1b[?2026h";
1442
+ buffer += this.deleteChangedKittyImages(firstChanged, lastChanged);
1443
+ // Move to end of new content (clamp to 0 for empty content)
1444
+ const targetRow = Math.max(0, newLines.length - 1);
1445
+ if (targetRow < prevViewportTop) {
1446
+ logRedraw(`deleted lines moved viewport up (${targetRow} < ${prevViewportTop})`);
1447
+ fullRender(true, preserveViewport);
1448
+ return;
1449
+ }
1450
+ const lineDiff = computeLineDiff(targetRow);
1451
+ if (lineDiff > 0)
1452
+ buffer += `\x1b[${lineDiff}B`;
1453
+ else if (lineDiff < 0)
1454
+ buffer += `\x1b[${-lineDiff}A`;
1455
+ buffer += "\r";
1456
+ // Clear extra lines without scrolling
1457
+ const extraLines = this.previousLines.length - newLines.length;
1458
+ if (extraLines > height) {
1459
+ logRedraw(`extraLines > height (${extraLines} > ${height})`);
1460
+ fullRender(true, preserveViewport);
1461
+ return;
1462
+ }
1463
+ if (extraLines > 0) {
1464
+ buffer += "\x1b[1B";
1465
+ }
1466
+ for (let i = 0; i < extraLines; i++) {
1467
+ buffer += "\r\x1b[2K";
1468
+ if (i < extraLines - 1)
1469
+ buffer += "\x1b[1B";
1470
+ }
1471
+ if (extraLines > 0) {
1472
+ buffer += `\x1b[${extraLines}A`;
1473
+ }
1474
+ buffer += "\x1b[?2026l";
1475
+ this.terminal.write(buffer);
1476
+ this.cursorRow = targetRow;
1477
+ this.hardwareCursorRow = targetRow;
1478
+ }
1479
+ this.positionHardwareCursor(cursorPos, newLines.length);
1480
+ this.previousLines = newLines;
1481
+ this.previousKittyImageIds = this.collectKittyImageIds(newLines);
1482
+ this.previousWidth = width;
1483
+ this.previousHeight = height;
1484
+ this.previousViewportTop = prevViewportTop;
1485
+ return;
1486
+ }
1487
+ // Differential rendering can only touch what was actually visible.
1488
+ // If the first changed line is above the previous viewport, the rows on
1489
+ // screen no longer correspond to newLines, so we have to repaint.
1490
+ //
1491
+ // When the transcript is taller than the viewport — e.g. attaching to a
1492
+ // long or still-streaming session, where off-screen tool results keep
1493
+ // resolving — replaying the whole transcript on every such change is what
1494
+ // makes the screen flicker and scroll from the
1495
+ // top. Repaint only the visible window in place instead, leaving
1496
+ // scrollback (and the user's history) untouched. Short transcripts that
1497
+ // fit on screen keep the cheap full redraw.
1498
+ //
1499
+ // Only do this while the transcript is growing (the streaming case). A
1500
+ // shrink — a rebuild or compaction that replaces the transcript with
1501
+ // fewer lines — leaves the now-removed lines stale in scrollback above the
1502
+ // visible window, so it still needs a full screen redraw. That is a
1503
+ // one-time event, so it costs no recurring flicker.
1504
+ if (firstChanged < prevViewportTop) {
1505
+ logRedraw(`firstChanged < viewportTop (${firstChanged} < ${prevViewportTop})`);
1506
+ const preserveScrollback = newLines.length > height && newLines.length >= this.previousLines.length;
1507
+ fullRender(true, preserveScrollback || preserveViewport);
1508
+ return;
1509
+ }
1510
+ // Render from first changed line to end
1511
+ // Build buffer with all updates wrapped in synchronized output
1512
+ let buffer = "\x1b[?2026h"; // Begin synchronized output
1513
+ buffer += this.deleteChangedKittyImages(firstChanged, lastChanged);
1514
+ const prevViewportBottom = prevViewportTop + height - 1;
1515
+ const moveTargetRow = appendStart ? firstChanged - 1 : firstChanged;
1516
+ if (moveTargetRow > prevViewportBottom) {
1517
+ const currentScreenRow = Math.max(0, Math.min(height - 1, hardwareCursorRow - prevViewportTop));
1518
+ const moveToBottom = height - 1 - currentScreenRow;
1519
+ if (moveToBottom > 0) {
1520
+ buffer += `\x1b[${moveToBottom}B`;
1521
+ }
1522
+ const scroll = moveTargetRow - prevViewportBottom;
1523
+ buffer += "\r\n".repeat(scroll);
1524
+ prevViewportTop += scroll;
1525
+ viewportTop += scroll;
1526
+ hardwareCursorRow = moveTargetRow;
1527
+ }
1528
+ // Move cursor to first changed line (use hardwareCursorRow for actual position)
1529
+ const lineDiff = computeLineDiff(moveTargetRow);
1530
+ if (lineDiff > 0) {
1531
+ buffer += `\x1b[${lineDiff}B`; // Move down
1532
+ }
1533
+ else if (lineDiff < 0) {
1534
+ buffer += `\x1b[${-lineDiff}A`; // Move up
1535
+ }
1536
+ buffer += appendStart ? "\r\n" : "\r"; // Move to column 0
1537
+ // Only render changed lines (firstChanged to lastChanged), not all lines to end
1538
+ // This reduces flicker when only a single line changes (e.g., spinner animation)
1539
+ const renderEnd = Math.min(lastChanged, newLines.length - 1);
1540
+ for (let i = firstChanged; i <= renderEnd; i++) {
1541
+ if (i > firstChanged)
1542
+ buffer += "\r\n";
1543
+ buffer += "\x1b[2K"; // Clear current line
1544
+ const line = newLines[i];
1545
+ const isImage = isImageLine(line);
1546
+ if (!isImage && visibleWidth(line) > width) {
1547
+ // Log all lines to crash file for debugging
1548
+ const crashLogPath = path.join(os.homedir(), ".prime", "agent", "pi-crash.log");
1549
+ const crashData = [
1550
+ `Crash at ${new Date().toISOString()}`,
1551
+ `Terminal width: ${width}`,
1552
+ `Line ${i} visible width: ${visibleWidth(line)}`,
1553
+ "",
1554
+ "=== All rendered lines ===",
1555
+ ...newLines.map((l, idx) => `[${idx}] (w=${visibleWidth(l)}) ${l}`),
1556
+ "",
1557
+ ].join("\n");
1558
+ fs.mkdirSync(path.dirname(crashLogPath), { recursive: true });
1559
+ fs.writeFileSync(crashLogPath, crashData);
1560
+ // Clean up terminal state before throwing
1561
+ this.stop();
1562
+ const errorMsg = [
1563
+ `Rendered line ${i} exceeds terminal width (${visibleWidth(line)} > ${width}).`,
1564
+ "",
1565
+ "This is likely caused by a custom TUI component not truncating its output.",
1566
+ "Use visibleWidth() to measure and truncateToWidth() to truncate lines.",
1567
+ "",
1568
+ `Debug log written to: ${crashLogPath}`,
1569
+ ].join("\n");
1570
+ throw new Error(errorMsg);
1571
+ }
1572
+ buffer += line;
1573
+ }
1574
+ // Track where cursor ended up after rendering
1575
+ let finalCursorRow = renderEnd;
1576
+ // If we had more lines before, clear them and move cursor back
1577
+ if (this.previousLines.length > newLines.length) {
1578
+ // Move to end of new content first if we stopped before it
1579
+ if (renderEnd < newLines.length - 1) {
1580
+ const moveDown = newLines.length - 1 - renderEnd;
1581
+ buffer += `\x1b[${moveDown}B`;
1582
+ finalCursorRow = newLines.length - 1;
1583
+ }
1584
+ const extraLines = this.previousLines.length - newLines.length;
1585
+ for (let i = newLines.length; i < this.previousLines.length; i++) {
1586
+ buffer += "\r\n\x1b[2K";
1587
+ }
1588
+ // Move cursor back to end of new content
1589
+ buffer += `\x1b[${extraLines}A`;
1590
+ }
1591
+ buffer += "\x1b[?2026l"; // End synchronized output
1592
+ if (process.env.PI_TUI_DEBUG === "1") {
1593
+ const debugDir = "/tmp/tui";
1594
+ fs.mkdirSync(debugDir, { recursive: true });
1595
+ const debugPath = path.join(debugDir, `render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`);
1596
+ const debugData = [
1597
+ `firstChanged: ${firstChanged}`,
1598
+ `viewportTop: ${viewportTop}`,
1599
+ `cursorRow: ${this.cursorRow}`,
1600
+ `height: ${height}`,
1601
+ `lineDiff: ${lineDiff}`,
1602
+ `hardwareCursorRow: ${hardwareCursorRow}`,
1603
+ `renderEnd: ${renderEnd}`,
1604
+ `finalCursorRow: ${finalCursorRow}`,
1605
+ `cursorPos: ${JSON.stringify(cursorPos)}`,
1606
+ `newLines.length: ${newLines.length}`,
1607
+ `previousLines.length: ${this.previousLines.length}`,
1608
+ "",
1609
+ "=== newLines ===",
1610
+ JSON.stringify(newLines, null, 2),
1611
+ "",
1612
+ "=== previousLines ===",
1613
+ JSON.stringify(this.previousLines, null, 2),
1614
+ "",
1615
+ "=== buffer ===",
1616
+ JSON.stringify(buffer),
1617
+ ].join("\n");
1618
+ fs.writeFileSync(debugPath, debugData);
1619
+ }
1620
+ // Write entire buffer at once
1621
+ this.terminal.write(buffer);
1622
+ // Track cursor position for next render
1623
+ // cursorRow tracks end of content (for viewport calculation)
1624
+ // hardwareCursorRow tracks actual terminal cursor position (for movement)
1625
+ this.cursorRow = Math.max(0, newLines.length - 1);
1626
+ this.hardwareCursorRow = finalCursorRow;
1627
+ // Track terminal's working area (grows but doesn't shrink unless cleared)
1628
+ this.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);
1629
+ this.previousViewportTop = Math.max(prevViewportTop, finalCursorRow - height + 1);
1630
+ // Position hardware cursor for IME
1631
+ this.positionHardwareCursor(cursorPos, newLines.length);
1632
+ this.previousLines = newLines;
1633
+ this.previousKittyImageIds = this.collectKittyImageIds(newLines);
1634
+ this.previousWidth = width;
1635
+ this.previousHeight = height;
1636
+ }
1637
+ /**
1638
+ * Position the hardware cursor for IME candidate window.
1639
+ * @param cursorPos The cursor position extracted from rendered output, or null
1640
+ * @param totalLines Total number of rendered lines
1641
+ */
1642
+ positionHardwareCursor(cursorPos, totalLines) {
1643
+ if (!cursorPos || totalLines <= 0) {
1644
+ this.terminal.hideCursor();
1645
+ return;
1646
+ }
1647
+ // Clamp cursor position to valid range
1648
+ const targetRow = Math.max(0, Math.min(cursorPos.row, totalLines - 1));
1649
+ const targetCol = Math.max(0, cursorPos.col);
1650
+ // Move cursor from current position to target
1651
+ const rowDelta = targetRow - this.hardwareCursorRow;
1652
+ let buffer = "";
1653
+ if (rowDelta > 0) {
1654
+ buffer += `\x1b[${rowDelta}B`; // Move down
1655
+ }
1656
+ else if (rowDelta < 0) {
1657
+ buffer += `\x1b[${-rowDelta}A`; // Move up
1658
+ }
1659
+ // Move to absolute column (1-indexed)
1660
+ buffer += `\x1b[${targetCol + 1}G`;
1661
+ if (buffer) {
1662
+ this.terminal.write(buffer);
1663
+ }
1664
+ this.hardwareCursorRow = targetRow;
1665
+ if (this.showHardwareCursor) {
1666
+ this.terminal.showCursor();
1667
+ }
1668
+ else {
1669
+ this.terminal.hideCursor();
1670
+ }
1671
+ }
1672
+ }
1673
+ //# sourceMappingURL=tui.js.map