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