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