@livos/pi-tui 0.79.8

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