@openachieve/tui 0.78.0

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