@sayknow-cli/tui 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +903 -0
  2. package/README.md +704 -0
  3. package/dist/types/autocomplete.d.ts +82 -0
  4. package/dist/types/bracketed-paste.d.ts +26 -0
  5. package/dist/types/components/box.d.ts +20 -0
  6. package/dist/types/components/cancellable-loader.d.ts +21 -0
  7. package/dist/types/components/editor.d.ts +111 -0
  8. package/dist/types/components/image.d.ts +16 -0
  9. package/dist/types/components/input.d.ts +16 -0
  10. package/dist/types/components/loader.d.ts +14 -0
  11. package/dist/types/components/markdown.d.ts +64 -0
  12. package/dist/types/components/select-list.d.ts +46 -0
  13. package/dist/types/components/settings-list.d.ts +39 -0
  14. package/dist/types/components/spacer.d.ts +11 -0
  15. package/dist/types/components/tab-bar.d.ts +56 -0
  16. package/dist/types/components/text.d.ts +13 -0
  17. package/dist/types/components/truncated-text.d.ts +10 -0
  18. package/dist/types/editor-component.d.ts +36 -0
  19. package/dist/types/fuzzy.d.ts +15 -0
  20. package/dist/types/index.d.ts +26 -0
  21. package/dist/types/keybindings.d.ts +189 -0
  22. package/dist/types/keys.d.ts +208 -0
  23. package/dist/types/kill-ring.d.ts +27 -0
  24. package/dist/types/metrics.d.ts +85 -0
  25. package/dist/types/stdin-buffer.d.ts +50 -0
  26. package/dist/types/symbols.d.ts +23 -0
  27. package/dist/types/terminal-capabilities.d.ts +75 -0
  28. package/dist/types/terminal.d.ts +76 -0
  29. package/dist/types/ttyid.d.ts +9 -0
  30. package/dist/types/tui.d.ts +181 -0
  31. package/dist/types/utils.d.ts +75 -0
  32. package/package.json +74 -0
  33. package/src/autocomplete.ts +896 -0
  34. package/src/bracketed-paste.ts +47 -0
  35. package/src/components/box.ts +173 -0
  36. package/src/components/cancellable-loader.ts +40 -0
  37. package/src/components/editor.ts +2820 -0
  38. package/src/components/image.ts +90 -0
  39. package/src/components/input.ts +465 -0
  40. package/src/components/loader.ts +103 -0
  41. package/src/components/markdown.ts +1061 -0
  42. package/src/components/select-list.ts +249 -0
  43. package/src/components/settings-list.ts +211 -0
  44. package/src/components/spacer.ts +28 -0
  45. package/src/components/tab-bar.ts +175 -0
  46. package/src/components/text.ts +110 -0
  47. package/src/components/truncated-text.ts +61 -0
  48. package/src/editor-component.ts +71 -0
  49. package/src/fuzzy.ts +143 -0
  50. package/src/index.ts +41 -0
  51. package/src/keybindings.ts +279 -0
  52. package/src/keys.ts +537 -0
  53. package/src/kill-ring.ts +46 -0
  54. package/src/metrics.ts +382 -0
  55. package/src/stdin-buffer.ts +444 -0
  56. package/src/symbols.ts +24 -0
  57. package/src/terminal-capabilities.ts +537 -0
  58. package/src/terminal.ts +807 -0
  59. package/src/ttyid.ts +73 -0
  60. package/src/tui.ts +1765 -0
  61. package/src/utils.ts +389 -0
package/src/tui.ts ADDED
@@ -0,0 +1,1765 @@
1
+ /**
2
+ * Minimal TUI implementation with differential rendering
3
+ */
4
+ import * as fs from "node:fs";
5
+ import * as path from "node:path";
6
+ import { performance } from "node:perf_hooks";
7
+ import { $flag, getDebugLogPath } from "@sayknow-cli/utils";
8
+ import { isKeyRelease, matchesKey } from "./keys";
9
+ import { renderMetrics } from "./metrics";
10
+ import type { Terminal } from "./terminal";
11
+ import { ImageProtocol, setCellDimensions, setTerminalImageProtocol, TERMINAL } from "./terminal-capabilities";
12
+ import {
13
+ Ellipsis,
14
+ extractSegments,
15
+ isPrintableAscii,
16
+ normalizeTerminalOutput,
17
+ sliceByColumn,
18
+ sliceWithWidth,
19
+ truncateToWidth,
20
+ visibleWidth,
21
+ } from "./utils";
22
+
23
+ const SEGMENT_RESET = "\x1b[0m";
24
+ /**
25
+ * Per-line terminator written at the end of every non-image line. Closes both
26
+ * SGR state and any in-flight OSC 8 hyperlink so styles/links cannot bleed
27
+ * across lines in scrollback. Applied by {@link TUI.#applyLineResets} before
28
+ * diffing so `#previousLines` mirrors what was actually written.
29
+ */
30
+ const LINE_TERMINATOR = "\x1b[0m\x1b]8;;\x07";
31
+
32
+ type InputListenerResult = { consume?: boolean; data?: string } | undefined;
33
+ type InputListener = (data: string) => InputListenerResult;
34
+
35
+ /**
36
+ * Component interface - all components must implement this
37
+ */
38
+ export interface Component {
39
+ /**
40
+ * Render the component to lines for the given viewport width
41
+ * @param width - Current viewport width
42
+ * @returns Array of strings, each representing a line
43
+ */
44
+ render(width: number): string[];
45
+
46
+ /**
47
+ * Optional handler for keyboard input when component has focus
48
+ */
49
+ handleInput?(data: string): void;
50
+
51
+ /**
52
+ * If true, component receives key release events (Kitty protocol).
53
+ * Default is false - release events are filtered out.
54
+ */
55
+ wantsKeyRelease?: boolean;
56
+
57
+ /**
58
+ * Invalidate any cached rendering state.
59
+ * Called when theme changes or when component needs to re-render from scratch.
60
+ */
61
+ invalidate(): void;
62
+
63
+ /**
64
+ * Optional cleanup hook. Called once when the component is permanently
65
+ * removed from the tree via removeChild/clear/dispose. Implementations MUST
66
+ * be idempotent. Components meant to be re-added should be detached, not
67
+ * removed/cleared.
68
+ */
69
+ dispose?(): void;
70
+ }
71
+
72
+ /**
73
+ * Interface for components that can receive focus and display a hardware cursor.
74
+ * When focused, the component should emit CURSOR_MARKER at the cursor position
75
+ * in its render output. TUI will find this marker and position the hardware
76
+ * cursor there for proper IME candidate window positioning.
77
+ */
78
+ export interface Focusable {
79
+ /** Set by TUI when focus changes. Component should emit CURSOR_MARKER when true. */
80
+ focused: boolean;
81
+ }
82
+
83
+ /** Type guard to check if a component implements Focusable */
84
+ export function isFocusable(component: Component | null): component is Component & Focusable {
85
+ return component !== null && "focused" in component;
86
+ }
87
+
88
+ /**
89
+ * Cursor position marker - APC (Application Program Command) sequence.
90
+ * This is a zero-width escape sequence that terminals ignore.
91
+ * Components emit this at the cursor position when focused.
92
+ * TUI finds and strips this marker, then positions the hardware cursor there.
93
+ */
94
+ export const CURSOR_MARKER = "\x1b_pi:c\x07";
95
+
96
+ export { visibleWidth };
97
+
98
+ /**
99
+ * Anchor position for overlays
100
+ */
101
+ export type OverlayAnchor =
102
+ | "center"
103
+ | "top-left"
104
+ | "top-right"
105
+ | "bottom-left"
106
+ | "bottom-right"
107
+ | "top-center"
108
+ | "bottom-center"
109
+ | "left-center"
110
+ | "right-center";
111
+
112
+ /**
113
+ * Margin configuration for overlays
114
+ */
115
+ export interface OverlayMargin {
116
+ top?: number;
117
+ right?: number;
118
+ bottom?: number;
119
+ left?: number;
120
+ }
121
+
122
+ /** Value that can be absolute (number) or percentage (string like "50%") */
123
+ export type SizeValue = number | `${number}%`;
124
+
125
+ /** Parse a SizeValue into absolute value given a reference size */
126
+ function parseSizeValue(value: SizeValue | undefined, referenceSize: number): number | undefined {
127
+ if (value === undefined) return undefined;
128
+ if (typeof value === "number") return value;
129
+ // Parse percentage string like "50%"
130
+ const match = value.match(/^(\d+(?:\.\d+)?)%$/);
131
+ if (match) {
132
+ return Math.floor((referenceSize * parseFloat(match[1])) / 100);
133
+ }
134
+ return undefined;
135
+ }
136
+
137
+ function isTermuxSession(): boolean {
138
+ return Boolean(process.env.TERMUX_VERSION);
139
+ }
140
+
141
+ /** Detect terminal multiplexers where scrollback clearing and height-change redraws are hostile. */
142
+ function isMultiplexerSession(): boolean {
143
+ return Boolean(Bun.env.TMUX || Bun.env.STY || Bun.env.ZELLIJ);
144
+ }
145
+
146
+ function useLegacyMultiplexerFullRender(): boolean {
147
+ return $flag("PI_TUI_LEGACY_MULTIPLEXER_FULL_RENDER");
148
+ }
149
+
150
+ /**
151
+ * Options for overlay positioning and sizing.
152
+ * Values can be absolute numbers or percentage strings (e.g., "50%").
153
+ */
154
+ export interface OverlayOptions {
155
+ // === Sizing ===
156
+ /** Width in columns, or percentage of terminal width (e.g., "50%") */
157
+ width?: SizeValue;
158
+ /** Minimum width in columns */
159
+ minWidth?: number;
160
+ /** Maximum height in rows, or percentage of terminal height (e.g., "50%") */
161
+ maxHeight?: SizeValue;
162
+
163
+ // === Positioning - anchor-based ===
164
+ /** Anchor point for positioning (default: 'center') */
165
+ anchor?: OverlayAnchor;
166
+ /** Horizontal offset from anchor position (positive = right) */
167
+ offsetX?: number;
168
+ /** Vertical offset from anchor position (positive = down) */
169
+ offsetY?: number;
170
+
171
+ // === Positioning - percentage or absolute ===
172
+ /** Row position: absolute number, or percentage (e.g., "25%" = 25% from top) */
173
+ row?: SizeValue;
174
+ /** Column position: absolute number, or percentage (e.g., "50%" = centered horizontally) */
175
+ col?: SizeValue;
176
+
177
+ // === Margin from terminal edges ===
178
+ /** Margin from terminal edges. Number applies to all sides. */
179
+ margin?: OverlayMargin | number;
180
+
181
+ // === Visibility ===
182
+ /**
183
+ * Control overlay visibility based on terminal dimensions.
184
+ * If provided, overlay is only rendered when this returns true.
185
+ * Called each render cycle with current terminal dimensions.
186
+ */
187
+ visible?: (termWidth: number, termHeight: number) => boolean;
188
+ }
189
+
190
+ /**
191
+ * Handle returned by showOverlay for controlling the overlay
192
+ */
193
+ export interface OverlayHandle {
194
+ /** Permanently remove the overlay (cannot be shown again) */
195
+ hide(): void;
196
+ /** Temporarily hide or show the overlay */
197
+ setHidden(hidden: boolean): void;
198
+ /** Check if overlay is temporarily hidden */
199
+ isHidden(): boolean;
200
+ }
201
+
202
+ /**
203
+ * Container - a component that contains other components
204
+ */
205
+ export class Container implements Component {
206
+ children: Component[] = [];
207
+ #disposed = false;
208
+
209
+ addChild(component: Component): void {
210
+ this.children.push(component);
211
+ }
212
+
213
+ removeChild(component: Component): void {
214
+ const index = this.children.indexOf(component);
215
+ if (index !== -1) {
216
+ this.children.splice(index, 1);
217
+ component.dispose?.();
218
+ }
219
+ }
220
+
221
+ /** Remove a child without disposing it (for detach-then-readd reuse). */
222
+ detachChild(component: Component): void {
223
+ const index = this.children.indexOf(component);
224
+ if (index !== -1) {
225
+ this.children.splice(index, 1);
226
+ }
227
+ }
228
+
229
+ clear(): void {
230
+ for (const child of this.children) {
231
+ child.dispose?.();
232
+ }
233
+ this.children = [];
234
+ }
235
+
236
+ /** Remove all children without disposing them (for detach-then-readd reuse). */
237
+ detachAll(): void {
238
+ this.children = [];
239
+ }
240
+
241
+ dispose(): void {
242
+ if (this.#disposed) return;
243
+ this.#disposed = true;
244
+ for (const child of this.children) {
245
+ child.dispose?.();
246
+ }
247
+ }
248
+
249
+ invalidate(): void {
250
+ for (const child of this.children) {
251
+ child.invalidate?.();
252
+ }
253
+ }
254
+
255
+ render(width: number): string[] {
256
+ width = Math.max(1, width);
257
+ const lines: string[] = [];
258
+ for (const child of this.children) {
259
+ const childLines = child.render(width);
260
+ for (let i = 0; i < childLines.length; i++) {
261
+ lines.push(childLines[i]);
262
+ }
263
+ }
264
+ return lines;
265
+ }
266
+ }
267
+
268
+ type LineNormalizationCacheEntry = {
269
+ normalized: string;
270
+ terminated: string;
271
+ };
272
+
273
+ /**
274
+ * TUI - Main class for managing terminal UI with differential rendering
275
+ */
276
+ export class TUI extends Container {
277
+ terminal: Terminal;
278
+ #previousLines: string[] = [];
279
+ /**
280
+ * Raw (pre-normalization) lines from the previous frame, kept only when the
281
+ * virtual-viewport flag is on. Used to detect whether the off-screen prefix is
282
+ * unchanged (by raw value equality, with a fast reference short-circuit when components
283
+ * return stable string instances) so its normalized form can be reused (bounded normalize).
284
+ */
285
+ #previousRaw: string[] = [];
286
+ #lineNormalizationCache = new Map<string, LineNormalizationCacheEntry>();
287
+ #lineTruncationCache = new Map<string, string>();
288
+ #lineNormalizationCacheLimit = 0;
289
+ #lineTruncationCacheLimit = 0;
290
+ #previousWidth = 0;
291
+ #previousHeight = 0;
292
+ #focusedComponent: Component | null = null;
293
+ #inputListeners = new Set<InputListener>();
294
+
295
+ /** Global callback for debug key (Shift+Ctrl+D). Called before input is forwarded to focused component. */
296
+ onDebug?: () => void;
297
+ #renderRequested = false;
298
+ #renderTimer: NodeJS.Timeout | undefined;
299
+ #lastRenderAt = 0;
300
+ static readonly #MIN_RENDER_INTERVAL_MS = 16;
301
+ // Input-priority scheduling: an input keystroke must never be starved behind a
302
+ // pending normal (frame-budget) render timer. When set, an input-priority render
303
+ // is queued for the next tick and supersedes any pending normal timer.
304
+ #inputRenderPending = false;
305
+
306
+ #cursorRow = 0; // Logical cursor row (end of rendered content)
307
+ #hardwareCursorRow = 0; // Actual terminal cursor row (may differ due to IME positioning)
308
+ #viewportTopRow = 0; // Content row currently mapped to screen row 0
309
+ #sixelProbePendingDa = false;
310
+ #sixelProbePendingGraphics = false;
311
+ #sixelProbeBuffer = "";
312
+ #sixelProbeTimeout?: NodeJS.Timeout;
313
+ #sixelProbeUnsubscribe?: () => void;
314
+ #showHardwareCursor = $flag("PI_HARDWARE_CURSOR");
315
+ #clearOnShrink = $flag("PI_CLEAR_ON_SHRINK"); // Clear empty rows when content shrinks (default: off)
316
+ // Opt-in: reuse the previous normalized off-screen prefix and only normalize/diff the
317
+ // visible window, bounding per-frame work on huge transcripts. Output stays byte-identical.
318
+ #virtualViewport = $flag("PI_TUI_VIRTUAL_VIEWPORT");
319
+ #maxLinesRendered = 0; // Line count from last render, used for viewport calculation
320
+ #fullRedrawCount = 0;
321
+ #stopped = false;
322
+ #terminalUnavailable = false;
323
+
324
+ // Overlay stack for modal components rendered on top of base content
325
+ overlayStack: {
326
+ component: Component;
327
+ options?: OverlayOptions;
328
+ preFocus: Component | null;
329
+ hidden: boolean;
330
+ }[] = [];
331
+
332
+ constructor(terminal: Terminal, showHardwareCursor?: boolean) {
333
+ super();
334
+ this.terminal = terminal;
335
+ if (showHardwareCursor !== undefined) {
336
+ this.#showHardwareCursor = showHardwareCursor;
337
+ }
338
+ }
339
+
340
+ get fullRedraws(): number {
341
+ return this.#fullRedrawCount;
342
+ }
343
+
344
+ getShowHardwareCursor(): boolean {
345
+ return this.#showHardwareCursor;
346
+ }
347
+
348
+ setShowHardwareCursor(enabled: boolean): void {
349
+ if (this.#showHardwareCursor === enabled) return;
350
+ this.#showHardwareCursor = enabled;
351
+ if (!enabled) {
352
+ this.#hideCursor();
353
+ }
354
+ this.requestRender();
355
+ }
356
+
357
+ getClearOnShrink(): boolean {
358
+ return this.#clearOnShrink;
359
+ }
360
+
361
+ /**
362
+ * Set whether to trigger full re-render when content shrinks.
363
+ * When true (default), empty rows are cleared when content shrinks.
364
+ * When false, empty rows remain (reduces redraws on slower terminals).
365
+ */
366
+ setClearOnShrink(enabled: boolean): void {
367
+ this.#clearOnShrink = enabled;
368
+ }
369
+
370
+ setFocus(component: Component | null): void {
371
+ // Clear focused flag on old component
372
+ if (isFocusable(this.#focusedComponent)) {
373
+ this.#focusedComponent.focused = false;
374
+ }
375
+
376
+ this.#focusedComponent = component;
377
+
378
+ // Set focused flag on new component
379
+ if (isFocusable(component)) {
380
+ component.focused = true;
381
+ }
382
+ }
383
+
384
+ /**
385
+ * Show an overlay component with configurable positioning and sizing.
386
+ * Returns a handle to control the overlay's visibility.
387
+ */
388
+ showOverlay(component: Component, options?: OverlayOptions): OverlayHandle {
389
+ const entry = { component, options, preFocus: this.#focusedComponent, hidden: false };
390
+ this.overlayStack.push(entry);
391
+ // Only focus if overlay is actually visible
392
+ if (this.#isOverlayVisible(entry)) {
393
+ this.setFocus(component);
394
+ }
395
+ this.#hideCursor();
396
+ this.requestRender();
397
+
398
+ // Return handle for controlling this overlay
399
+ return {
400
+ hide: () => {
401
+ const index = this.overlayStack.indexOf(entry);
402
+ if (index !== -1) {
403
+ this.overlayStack.splice(index, 1);
404
+ // Restore focus if this overlay had focus
405
+ if (this.#focusedComponent === component) {
406
+ const topVisible = this.#getTopmostVisibleOverlay();
407
+ this.setFocus(topVisible?.component ?? entry.preFocus);
408
+ }
409
+ if (this.overlayStack.length === 0) this.#hideCursor();
410
+ this.requestRender();
411
+ }
412
+ },
413
+ setHidden: (hidden: boolean) => {
414
+ if (entry.hidden === hidden) return;
415
+ entry.hidden = hidden;
416
+ // Update focus when hiding/showing
417
+ if (hidden) {
418
+ // If this overlay had focus, move focus to next visible or preFocus
419
+ if (this.#focusedComponent === component) {
420
+ const topVisible = this.#getTopmostVisibleOverlay();
421
+ this.setFocus(topVisible?.component ?? entry.preFocus);
422
+ }
423
+ } else {
424
+ // Restore focus to this overlay when showing (if it's actually visible)
425
+ if (this.#isOverlayVisible(entry)) {
426
+ this.setFocus(component);
427
+ }
428
+ }
429
+ this.requestRender();
430
+ },
431
+ isHidden: () => entry.hidden,
432
+ };
433
+ }
434
+
435
+ /** Hide the topmost overlay and restore previous focus. */
436
+ hideOverlay(): void {
437
+ const overlay = this.overlayStack.pop();
438
+ if (!overlay) return;
439
+ // Find topmost visible overlay, or fall back to preFocus
440
+ const topVisible = this.#getTopmostVisibleOverlay();
441
+ this.setFocus(topVisible?.component ?? overlay.preFocus);
442
+ if (this.overlayStack.length === 0) this.#hideCursor();
443
+ this.requestRender();
444
+ }
445
+
446
+ /** Check if there are any visible overlays */
447
+ hasOverlay(): boolean {
448
+ return this.overlayStack.some(o => this.#isOverlayVisible(o));
449
+ }
450
+
451
+ /** Check if an overlay entry is currently visible */
452
+ #isOverlayVisible(entry: (typeof this.overlayStack)[number]): boolean {
453
+ if (entry.hidden) return false;
454
+ if (entry.options?.visible) {
455
+ return entry.options.visible(this.terminal.columns, this.terminal.rows);
456
+ }
457
+ return true;
458
+ }
459
+
460
+ /** Find the topmost visible overlay, if any */
461
+ #getTopmostVisibleOverlay(): (typeof this.overlayStack)[number] | undefined {
462
+ for (let i = this.overlayStack.length - 1; i >= 0; i--) {
463
+ if (this.#isOverlayVisible(this.overlayStack[i])) {
464
+ return this.overlayStack[i];
465
+ }
466
+ }
467
+ return undefined;
468
+ }
469
+
470
+ override invalidate(): void {
471
+ super.invalidate();
472
+ for (const overlay of this.overlayStack) overlay.component.invalidate?.();
473
+ }
474
+
475
+ start(): void {
476
+ this.#stopped = false;
477
+ this.#terminalUnavailable = false;
478
+ this.terminal.start(
479
+ data => this.#handleInput(data),
480
+ () => this.requestRender(),
481
+ );
482
+ this.#hideCursor();
483
+ this.#querySixelSupport();
484
+ this.#queryCellSize();
485
+ this.requestRender(true);
486
+ }
487
+
488
+ get terminalAvailable(): boolean {
489
+ return !this.#terminalUnavailable && this.terminal.available;
490
+ }
491
+
492
+ #markTerminalUnavailable(): void {
493
+ this.#terminalUnavailable = true;
494
+ this.#stopped = true;
495
+ this.#renderRequested = false;
496
+ if (this.#renderTimer) {
497
+ clearTimeout(this.#renderTimer);
498
+ this.#renderTimer = undefined;
499
+ if (renderMetrics.enabled) renderMetrics.setTimerGauge("tui.renderTimer", 0);
500
+ }
501
+ this.#clearSixelProbeState();
502
+ }
503
+
504
+ #writeTerminal(data: string): boolean {
505
+ return this.#guardTerminalOperation(() => this.terminal.write(data));
506
+ }
507
+
508
+ #hideCursor(): boolean {
509
+ return this.#guardTerminalOperation(() => this.terminal.hideCursor());
510
+ }
511
+
512
+ #showCursor(): boolean {
513
+ return this.#guardTerminalOperation(() => this.terminal.showCursor());
514
+ }
515
+
516
+ #guardTerminalOperation(operation: () => void): boolean {
517
+ if (!this.terminalAvailable) {
518
+ this.#markTerminalUnavailable();
519
+ return false;
520
+ }
521
+ try {
522
+ operation();
523
+ } catch {
524
+ this.#markTerminalUnavailable();
525
+ return false;
526
+ }
527
+ if (!this.terminal.available) {
528
+ this.#markTerminalUnavailable();
529
+ return false;
530
+ }
531
+ return true;
532
+ }
533
+
534
+ addInputListener(listener: InputListener): () => void {
535
+ this.#inputListeners.add(listener);
536
+ return () => {
537
+ this.#inputListeners.delete(listener);
538
+ };
539
+ }
540
+
541
+ removeInputListener(listener: InputListener): void {
542
+ this.#inputListeners.delete(listener);
543
+ }
544
+
545
+ #querySixelSupport(): void {
546
+ if (TERMINAL.imageProtocol) return;
547
+ if (process.platform !== "win32") return;
548
+ if (!Bun.env.WT_SESSION) return;
549
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return;
550
+
551
+ this.#clearSixelProbeState();
552
+ this.#sixelProbePendingDa = true;
553
+ this.#sixelProbePendingGraphics = true;
554
+ this.#sixelProbeUnsubscribe = this.addInputListener(data => this.#handleSixelProbeInput(data));
555
+ if (!this.#writeTerminal("\x1b[c")) return;
556
+ if (!this.#writeTerminal("\x1b[?2;1;0S")) return;
557
+ this.#sixelProbeTimeout = setTimeout(() => {
558
+ this.#finishSixelProbe(false);
559
+ }, 250);
560
+ }
561
+
562
+ #handleSixelProbeInput(data: string): InputListenerResult {
563
+ if (!this.#sixelProbePendingDa && !this.#sixelProbePendingGraphics) {
564
+ return undefined;
565
+ }
566
+
567
+ this.#sixelProbeBuffer += data;
568
+ let passthrough = "";
569
+ let probeOutcome: boolean | null = null;
570
+
571
+ while (this.#sixelProbeBuffer.length > 0) {
572
+ const daMatch = this.#sixelProbeBuffer.match(/\x1b\[\?([0-9;]+)c/u);
573
+ const graphicsMatch = this.#sixelProbeBuffer.match(/\x1b\[\?2;(\d+);([0-9;]+)S/u);
574
+
575
+ if (!daMatch && !graphicsMatch) break;
576
+
577
+ const daIndex = daMatch?.index ?? Number.POSITIVE_INFINITY;
578
+ const graphicsIndex = graphicsMatch?.index ?? Number.POSITIVE_INFINITY;
579
+ const useDa = daIndex <= graphicsIndex;
580
+ const match = useDa ? daMatch : graphicsMatch;
581
+ if (!match || match.index === undefined) break;
582
+
583
+ passthrough += this.#sixelProbeBuffer.slice(0, match.index);
584
+ this.#sixelProbeBuffer = this.#sixelProbeBuffer.slice(match.index + match[0].length);
585
+
586
+ if (useDa && this.#sixelProbePendingDa) {
587
+ this.#sixelProbePendingDa = false;
588
+ const attributes = (match[1] ?? "")
589
+ .split(";")
590
+ .map(value => Number.parseInt(value, 10))
591
+ .filter(value => Number.isFinite(value));
592
+ const hasSixelAttribute = attributes.includes(4);
593
+ if (hasSixelAttribute) {
594
+ this.#sixelProbePendingGraphics = false;
595
+ probeOutcome = true;
596
+ } else if (!this.#sixelProbePendingGraphics) {
597
+ probeOutcome = false;
598
+ }
599
+ } else if (!useDa && this.#sixelProbePendingGraphics) {
600
+ this.#sixelProbePendingGraphics = false;
601
+ const status = Number.parseInt(match[1] ?? "", 10);
602
+ const supportsSixel = !Number.isNaN(status) && status !== 0;
603
+ if (supportsSixel) {
604
+ this.#sixelProbePendingDa = false;
605
+ probeOutcome = true;
606
+ } else if (!this.#sixelProbePendingDa) {
607
+ probeOutcome = false;
608
+ }
609
+ }
610
+ }
611
+
612
+ if (this.#sixelProbePendingDa || this.#sixelProbePendingGraphics) {
613
+ const partialStart = this.#getSixelProbePartialStart(this.#sixelProbeBuffer);
614
+ if (partialStart >= 0) {
615
+ passthrough += this.#sixelProbeBuffer.slice(0, partialStart);
616
+ this.#sixelProbeBuffer = this.#sixelProbeBuffer.slice(partialStart);
617
+ } else {
618
+ passthrough += this.#sixelProbeBuffer;
619
+ this.#sixelProbeBuffer = "";
620
+ }
621
+ } else {
622
+ passthrough += this.#sixelProbeBuffer;
623
+ this.#sixelProbeBuffer = "";
624
+ }
625
+
626
+ if (probeOutcome !== null) {
627
+ this.#finishSixelProbe(probeOutcome);
628
+ }
629
+
630
+ if (passthrough.length === 0) {
631
+ return { consume: true };
632
+ }
633
+
634
+ return { data: passthrough };
635
+ }
636
+
637
+ #getSixelProbePartialStart(buffer: string): number {
638
+ const lastEsc = buffer.lastIndexOf("\x1b");
639
+ if (lastEsc < 0) return -1;
640
+ const tail = buffer.slice(lastEsc);
641
+ if (/^\x1b\[\?[0-9;]*$/u.test(tail)) {
642
+ return lastEsc;
643
+ }
644
+ return -1;
645
+ }
646
+
647
+ #clearSixelProbeState(): void {
648
+ if (this.#sixelProbeTimeout) {
649
+ clearTimeout(this.#sixelProbeTimeout);
650
+ this.#sixelProbeTimeout = undefined;
651
+ }
652
+ if (this.#sixelProbeUnsubscribe) {
653
+ this.#sixelProbeUnsubscribe();
654
+ this.#sixelProbeUnsubscribe = undefined;
655
+ }
656
+ this.#sixelProbePendingDa = false;
657
+ this.#sixelProbePendingGraphics = false;
658
+ this.#sixelProbeBuffer = "";
659
+ }
660
+
661
+ #finishSixelProbe(supported: boolean): void {
662
+ this.#clearSixelProbeState();
663
+ if (!supported || TERMINAL.imageProtocol) return;
664
+
665
+ setTerminalImageProtocol(ImageProtocol.Sixel);
666
+ this.#queryCellSize();
667
+ this.invalidate();
668
+ this.requestRender(true);
669
+ }
670
+ #queryCellSize(): void {
671
+ // Only query if terminal supports images (cell size is only used for image rendering)
672
+ if (!TERMINAL.imageProtocol) {
673
+ return;
674
+ }
675
+ // Query terminal for cell size in pixels: CSI 16 t
676
+ // Response format: CSI 6 ; height ; width t
677
+ this.#writeTerminal("\x1b[16t");
678
+ }
679
+
680
+ stop(): void {
681
+ this.#clearSixelProbeState();
682
+ this.#stopped = true;
683
+ if (this.#renderTimer) {
684
+ clearTimeout(this.#renderTimer);
685
+ this.#renderTimer = undefined;
686
+ if (renderMetrics.enabled) renderMetrics.setTimerGauge("tui.renderTimer", 0);
687
+ }
688
+ // Move cursor to the end of the content to prevent overwriting/artifacts on exit
689
+ if (this.#previousLines.length > 0) {
690
+ const targetRow = this.#previousLines.length; // Line after the last content
691
+ const lineDiff = targetRow - this.#hardwareCursorRow;
692
+ if (lineDiff > 0) {
693
+ this.#writeTerminal(`\x1b[${lineDiff}B`);
694
+ } else if (lineDiff < 0) {
695
+ this.#writeTerminal(`\x1b[${-lineDiff}A`);
696
+ }
697
+ this.#writeTerminal("\r\n");
698
+ }
699
+
700
+ this.#showCursor();
701
+ try {
702
+ this.terminal.stop();
703
+ } catch {
704
+ this.#markTerminalUnavailable();
705
+ }
706
+ // Teardown: release the retained rendered transcript so a stopped TUI does
707
+ // not pin a flat copy of every emitted line for the process lifetime.
708
+ // Safe across temporary stop/start (Ctrl-Z resume, external editor): start()
709
+ // issues a forced render that rebuilds this state and fully redraws, and
710
+ // focus/listener state is intentionally preserved so input routing survives
711
+ // a resume.
712
+ this.#previousLines = [];
713
+ this.#previousRaw = [];
714
+ this.#lineNormalizationCache.clear();
715
+ this.#lineTruncationCache.clear();
716
+ this.#previousWidth = 0;
717
+ this.#previousHeight = 0;
718
+ }
719
+
720
+ requestRender(force = false, source = "unknown"): void {
721
+ if (!this.terminalAvailable) {
722
+ this.#markTerminalUnavailable();
723
+ return;
724
+ }
725
+ if (renderMetrics.enabled) renderMetrics.recordRequest(source);
726
+ if (force) {
727
+ // A forced full redraw supersedes any queued input-priority render.
728
+ this.#inputRenderPending = false;
729
+ this.#previousLines = [];
730
+ this.#previousRaw = [];
731
+ this.#lineNormalizationCache.clear();
732
+ this.#lineTruncationCache.clear();
733
+ this.#previousWidth = -1; // -1 triggers widthChanged, forcing a full clear
734
+ this.#previousHeight = -1; // -1 triggers heightChanged, forcing a full clear
735
+ this.#lineNormalizationCacheLimit = 0;
736
+ this.#lineTruncationCacheLimit = 0;
737
+ this.#cursorRow = 0;
738
+ this.#hardwareCursorRow = 0;
739
+ this.#viewportTopRow = 0;
740
+ this.#maxLinesRendered = 0;
741
+ if (this.#renderTimer) {
742
+ clearTimeout(this.#renderTimer);
743
+ this.#renderTimer = undefined;
744
+ if (renderMetrics.enabled) renderMetrics.setTimerGauge("tui.renderTimer", 0);
745
+ }
746
+ this.#renderRequested = true;
747
+ process.nextTick(() => {
748
+ if (this.#stopped || !this.#renderRequested) {
749
+ return;
750
+ }
751
+ this.#renderRequested = false;
752
+ this.#lastRenderAt = performance.now();
753
+ const t0 = renderMetrics.now();
754
+ this.#doRender();
755
+ if (renderMetrics.enabled) renderMetrics.recordRender(renderMetrics.now() - t0);
756
+ });
757
+ return;
758
+ }
759
+ // Input-priority path: expedite so the keystroke echoes within the next tick
760
+ // instead of waiting for (or behind) the frame-budget timer. Re-entrant input
761
+ // requests in the same turn coalesce via #inputRenderPending, so at most one
762
+ // expedited render commits per event-loop turn (no repaint storms). This only
763
+ // changes WHEN #doRender runs; the render output path is unchanged.
764
+ if (source === "input" || source === "editor.input") {
765
+ if (!this.#inputRenderPending) {
766
+ this.#inputRenderPending = true;
767
+ this.#renderRequested = true;
768
+ process.nextTick(() => this.#commitExpeditedRender());
769
+ }
770
+ return;
771
+ }
772
+ if (this.#renderRequested) return;
773
+ this.#renderRequested = true;
774
+ process.nextTick(() => this.#scheduleRender());
775
+ }
776
+
777
+ #scheduleRender(): void {
778
+ if (this.#stopped || this.#renderTimer || !this.#renderRequested) {
779
+ return;
780
+ }
781
+ const elapsed = performance.now() - this.#lastRenderAt;
782
+ const delay = Math.max(0, TUI.#MIN_RENDER_INTERVAL_MS - elapsed);
783
+ this.#renderTimer = setTimeout(() => {
784
+ this.#renderTimer = undefined;
785
+ if (renderMetrics.enabled) renderMetrics.setTimerGauge("tui.renderTimer", 0);
786
+ if (this.#stopped || !this.#renderRequested) {
787
+ return;
788
+ }
789
+ this.#renderRequested = false;
790
+ this.#lastRenderAt = performance.now();
791
+ const t0 = renderMetrics.now();
792
+ this.#doRender();
793
+ if (renderMetrics.enabled) renderMetrics.recordRender(renderMetrics.now() - t0);
794
+ if (this.#renderRequested) {
795
+ this.#scheduleRender();
796
+ }
797
+ }, delay);
798
+ if (renderMetrics.enabled) renderMetrics.setTimerGauge("tui.renderTimer", 1);
799
+ }
800
+
801
+ // Commit a single input-priority render on the next tick, cancelling any normal
802
+ // frame-budget timer scheduled in the same turn. nextTick always precedes a
803
+ // pending setTimeout, so the keystroke is never starved behind streaming renders.
804
+ #commitExpeditedRender(): void {
805
+ if (!this.#inputRenderPending) return; // cancelled (e.g., by a forced render)
806
+ this.#inputRenderPending = false;
807
+ if (this.#stopped || !this.#renderRequested) {
808
+ return;
809
+ }
810
+ if (this.#renderTimer) {
811
+ clearTimeout(this.#renderTimer);
812
+ this.#renderTimer = undefined;
813
+ if (renderMetrics.enabled) renderMetrics.setTimerGauge("tui.renderTimer", 0);
814
+ }
815
+ this.#renderRequested = false;
816
+ this.#lastRenderAt = performance.now();
817
+ const t0 = renderMetrics.now();
818
+ this.#doRender();
819
+ if (renderMetrics.enabled) renderMetrics.recordRender(renderMetrics.now() - t0);
820
+ }
821
+
822
+ #handleInput(data: string): void {
823
+ if (this.#inputListeners.size > 0) {
824
+ let current = data;
825
+ for (const listener of this.#inputListeners) {
826
+ const result = listener(current);
827
+ if (result?.consume) {
828
+ return;
829
+ }
830
+ if (result?.data !== undefined) {
831
+ current = result.data;
832
+ }
833
+ }
834
+ if (current.length === 0) {
835
+ return;
836
+ }
837
+ data = current;
838
+ }
839
+
840
+ // Consume terminal cell size responses without blocking unrelated input.
841
+ if (this.#consumeCellSizeResponse(data)) {
842
+ return;
843
+ }
844
+
845
+ // Global debug key handler (Shift+Ctrl+D)
846
+ if (matchesKey(data, "shift+ctrl+d") && this.onDebug) {
847
+ this.onDebug();
848
+ return;
849
+ }
850
+
851
+ // If focused component is an overlay, verify it's still visible
852
+ // (visibility can change due to terminal resize or visible() callback)
853
+ const focusedOverlay = this.overlayStack.find(o => o.component === this.#focusedComponent);
854
+ if (focusedOverlay && !this.#isOverlayVisible(focusedOverlay)) {
855
+ // Focused overlay is no longer visible, redirect to topmost visible overlay
856
+ const topVisible = this.#getTopmostVisibleOverlay();
857
+ if (topVisible) {
858
+ this.setFocus(topVisible.component);
859
+ } else {
860
+ // No visible overlays, restore to preFocus
861
+ this.setFocus(focusedOverlay.preFocus);
862
+ }
863
+ }
864
+
865
+ // Pass input to focused component (including Ctrl+C)
866
+ // The focused component can decide how to handle Ctrl+C
867
+ if (this.#focusedComponent?.handleInput) {
868
+ // Filter out key release events unless component opts in
869
+ if (isKeyRelease(data) && !this.#focusedComponent.wantsKeyRelease) {
870
+ return;
871
+ }
872
+ this.#focusedComponent.handleInput(data);
873
+ this.requestRender(false, "input");
874
+ }
875
+ }
876
+
877
+ #consumeCellSizeResponse(data: string): boolean {
878
+ // Response format: ESC [ 6 ; height ; width t
879
+ const match = data.match(/^\x1b\[6;(\d+);(\d+)t$/);
880
+ if (!match) {
881
+ return false;
882
+ }
883
+
884
+ const heightPx = parseInt(match[1], 10);
885
+ const widthPx = parseInt(match[2], 10);
886
+ if (heightPx <= 0 || widthPx <= 0) {
887
+ return true;
888
+ }
889
+
890
+ setCellDimensions({ widthPx, heightPx });
891
+ // Invalidate all components so images re-render with correct dimensions.
892
+ this.invalidate();
893
+ this.requestRender();
894
+ return true;
895
+ }
896
+
897
+ /**
898
+ * Resolve overlay layout from options.
899
+ * Returns { width, row, col, maxHeight } for rendering.
900
+ */
901
+ #resolveOverlayLayout(
902
+ options: OverlayOptions | undefined,
903
+ overlayHeight: number,
904
+ termWidth: number,
905
+ termHeight: number,
906
+ ): { width: number; row: number; col: number; maxHeight: number | undefined } {
907
+ const opt = options ?? {};
908
+
909
+ // Parse margin (clamp to non-negative)
910
+ const margin =
911
+ typeof opt.margin === "number"
912
+ ? { top: opt.margin, right: opt.margin, bottom: opt.margin, left: opt.margin }
913
+ : (opt.margin ?? {});
914
+ const marginTop = Math.max(0, margin.top ?? 0);
915
+ const marginRight = Math.max(0, margin.right ?? 0);
916
+ const marginBottom = Math.max(0, margin.bottom ?? 0);
917
+ const marginLeft = Math.max(0, margin.left ?? 0);
918
+
919
+ // Available space after margins
920
+ const availWidth = Math.max(1, termWidth - marginLeft - marginRight);
921
+ const availHeight = Math.max(1, termHeight - marginTop - marginBottom);
922
+
923
+ // === Resolve width ===
924
+ let width = parseSizeValue(opt.width, termWidth) ?? Math.min(80, availWidth);
925
+ // Apply minWidth
926
+ if (opt.minWidth !== undefined) {
927
+ width = Math.max(width, opt.minWidth);
928
+ }
929
+ // Clamp to available space
930
+ width = Math.max(1, Math.min(width, availWidth));
931
+
932
+ // === Resolve maxHeight ===
933
+ let maxHeight = parseSizeValue(opt.maxHeight, termHeight);
934
+ // Clamp to available space
935
+ if (maxHeight !== undefined) {
936
+ maxHeight = Math.max(1, Math.min(maxHeight, availHeight));
937
+ }
938
+
939
+ // Effective overlay height (may be clamped by maxHeight)
940
+ const effectiveHeight = maxHeight !== undefined ? Math.min(overlayHeight, maxHeight) : overlayHeight;
941
+
942
+ // === Resolve position ===
943
+ let row: number;
944
+ let col: number;
945
+
946
+ if (opt.row !== undefined) {
947
+ if (typeof opt.row === "string") {
948
+ // Percentage: 0% = top, 100% = bottom (overlay stays within bounds)
949
+ const match = opt.row.match(/^(\d+(?:\.\d+)?)%$/);
950
+ if (match) {
951
+ const maxRow = Math.max(0, availHeight - effectiveHeight);
952
+ const percent = parseFloat(match[1]) / 100;
953
+ row = marginTop + Math.floor(maxRow * percent);
954
+ } else {
955
+ // Invalid format, fall back to center
956
+ row = this.#resolveAnchorRow("center", effectiveHeight, availHeight, marginTop);
957
+ }
958
+ } else {
959
+ // Absolute row position
960
+ row = opt.row;
961
+ }
962
+ } else {
963
+ // Anchor-based (default: center)
964
+ const anchor = opt.anchor ?? "center";
965
+ row = this.#resolveAnchorRow(anchor, effectiveHeight, availHeight, marginTop);
966
+ }
967
+
968
+ if (opt.col !== undefined) {
969
+ if (typeof opt.col === "string") {
970
+ // Percentage: 0% = left, 100% = right (overlay stays within bounds)
971
+ const match = opt.col.match(/^(\d+(?:\.\d+)?)%$/);
972
+ if (match) {
973
+ const maxCol = Math.max(0, availWidth - width);
974
+ const percent = parseFloat(match[1]) / 100;
975
+ col = marginLeft + Math.floor(maxCol * percent);
976
+ } else {
977
+ // Invalid format, fall back to center
978
+ col = this.#resolveAnchorCol("center", width, availWidth, marginLeft);
979
+ }
980
+ } else {
981
+ // Absolute column position
982
+ col = opt.col;
983
+ }
984
+ } else {
985
+ // Anchor-based (default: center)
986
+ const anchor = opt.anchor ?? "center";
987
+ col = this.#resolveAnchorCol(anchor, width, availWidth, marginLeft);
988
+ }
989
+
990
+ // Apply offsets
991
+ if (opt.offsetY !== undefined) row += opt.offsetY;
992
+ if (opt.offsetX !== undefined) col += opt.offsetX;
993
+
994
+ // Clamp to terminal bounds (respecting margins)
995
+ row = Math.max(marginTop, Math.min(row, termHeight - marginBottom - effectiveHeight));
996
+ col = Math.max(marginLeft, Math.min(col, termWidth - marginRight - width));
997
+
998
+ return { width, row, col, maxHeight };
999
+ }
1000
+
1001
+ #resolveAnchorRow(anchor: OverlayAnchor, height: number, availHeight: number, marginTop: number): number {
1002
+ switch (anchor) {
1003
+ case "top-left":
1004
+ case "top-center":
1005
+ case "top-right":
1006
+ return marginTop;
1007
+ case "bottom-left":
1008
+ case "bottom-center":
1009
+ case "bottom-right":
1010
+ return marginTop + availHeight - height;
1011
+ case "left-center":
1012
+ case "center":
1013
+ case "right-center":
1014
+ return marginTop + Math.floor((availHeight - height) / 2);
1015
+ }
1016
+ }
1017
+
1018
+ #resolveAnchorCol(anchor: OverlayAnchor, width: number, availWidth: number, marginLeft: number): number {
1019
+ switch (anchor) {
1020
+ case "top-left":
1021
+ case "left-center":
1022
+ case "bottom-left":
1023
+ return marginLeft;
1024
+ case "top-right":
1025
+ case "right-center":
1026
+ case "bottom-right":
1027
+ return marginLeft + availWidth - width;
1028
+ case "top-center":
1029
+ case "center":
1030
+ case "bottom-center":
1031
+ return marginLeft + Math.floor((availWidth - width) / 2);
1032
+ }
1033
+ }
1034
+
1035
+ /** Composite all overlays into content lines (in stack order, later = on top). */
1036
+ #compositeOverlays(lines: string[], termWidth: number, termHeight: number): string[] {
1037
+ if (this.overlayStack.length === 0) return lines;
1038
+ const result = [...lines];
1039
+
1040
+ // Pre-render all visible overlays and calculate positions
1041
+ const rendered: { overlayLines: string[]; row: number; col: number; w: number }[] = [];
1042
+ let minLinesNeeded = result.length;
1043
+
1044
+ for (const entry of this.overlayStack) {
1045
+ // Skip invisible overlays (hidden or visible() returns false)
1046
+ if (!this.#isOverlayVisible(entry)) continue;
1047
+
1048
+ const { component, options } = entry;
1049
+
1050
+ // Get layout with height=0 first to determine width and maxHeight
1051
+ // (width and maxHeight don't depend on overlay height)
1052
+ const { width, maxHeight } = this.#resolveOverlayLayout(options, 0, termWidth, termHeight);
1053
+
1054
+ // Render component at calculated width
1055
+ let overlayLines = component.render(width);
1056
+
1057
+ // Apply maxHeight if specified
1058
+ if (maxHeight !== undefined && overlayLines.length > maxHeight) {
1059
+ overlayLines = overlayLines.slice(0, maxHeight);
1060
+ }
1061
+
1062
+ // Get final row/col with actual overlay height
1063
+ const { row, col } = this.#resolveOverlayLayout(options, overlayLines.length, termWidth, termHeight);
1064
+
1065
+ rendered.push({ overlayLines, row, col, w: width });
1066
+ minLinesNeeded = Math.max(minLinesNeeded, row + overlayLines.length);
1067
+ }
1068
+
1069
+ // Ensure result is tall enough for overlay placement.
1070
+ // NOTE: Do not pad to maxLinesRendered.
1071
+ // maxLinesRendered tracks the terminal "working area" (max lines ever rendered) and can be much larger
1072
+ // than the current content. Padding to it can cause the renderer to output hundreds/thousands of blank
1073
+ // lines, effectively scrolling the terminal when an overlay is shown.
1074
+ const workingHeight = Math.max(result.length, minLinesNeeded);
1075
+
1076
+ // Extend result with empty lines if content is too short for overlay placement
1077
+ while (result.length < workingHeight) {
1078
+ result.push("");
1079
+ }
1080
+
1081
+ const viewportStart = Math.max(0, workingHeight - termHeight);
1082
+
1083
+ // Track which lines were modified for final verification
1084
+ const modifiedLines = new Set<number>();
1085
+
1086
+ // Composite each overlay
1087
+ for (const { overlayLines, row, col, w } of rendered) {
1088
+ for (let i = 0; i < overlayLines.length; i++) {
1089
+ const idx = viewportStart + row + i;
1090
+ if (idx >= 0 && idx < result.length) {
1091
+ // Defensive: truncate overlay line to declared width before compositing
1092
+ // (components should already respect width, but this ensures it)
1093
+ const truncatedOverlayLine =
1094
+ visibleWidth(overlayLines[i]) > w ? sliceByColumn(overlayLines[i], 0, w, true) : overlayLines[i];
1095
+ result[idx] = this.#compositeLineAt(result[idx], truncatedOverlayLine, col, w, termWidth);
1096
+ modifiedLines.add(idx);
1097
+ }
1098
+ }
1099
+ }
1100
+
1101
+ // Final verification: ensure no composited line exceeds terminal width
1102
+ // This is a belt-and-suspenders safeguard - compositeLineAt should already
1103
+ // guarantee this, but we verify here to prevent crashes from any edge cases
1104
+ // Only check lines that were actually modified (optimization)
1105
+ for (const idx of modifiedLines) {
1106
+ const lineWidth = visibleWidth(result[idx]);
1107
+ if (lineWidth > termWidth) {
1108
+ result[idx] = sliceByColumn(result[idx], 0, termWidth, true);
1109
+ }
1110
+ }
1111
+
1112
+ return result;
1113
+ }
1114
+
1115
+ /** Splice overlay content into a base line at a specific column. Single-pass optimized. */
1116
+ #compositeLineAt(
1117
+ baseLine: string,
1118
+ overlayLine: string,
1119
+ startCol: number,
1120
+ overlayWidth: number,
1121
+ totalWidth: number,
1122
+ ): string {
1123
+ if (TERMINAL.isImageLine(baseLine)) return baseLine;
1124
+
1125
+ // Single pass through baseLine extracts both before and after segments
1126
+ const afterStart = startCol + overlayWidth;
1127
+ const base = extractSegments(baseLine, startCol, afterStart, totalWidth - afterStart, true);
1128
+
1129
+ // Extract overlay with width tracking (strict=true to exclude wide chars at boundary)
1130
+ const overlay = sliceWithWidth(overlayLine, 0, overlayWidth, true);
1131
+
1132
+ // Pad segments to target widths
1133
+ const beforePad = Math.max(0, startCol - base.beforeWidth);
1134
+ const overlayPad = Math.max(0, overlayWidth - overlay.width);
1135
+ const actualBeforeWidth = Math.max(startCol, base.beforeWidth);
1136
+ const actualOverlayWidth = Math.max(overlayWidth, overlay.width);
1137
+ const afterTarget = Math.max(0, totalWidth - actualBeforeWidth - actualOverlayWidth);
1138
+ const afterPad = Math.max(0, afterTarget - base.afterWidth);
1139
+
1140
+ // Compose result
1141
+ const r = SEGMENT_RESET;
1142
+ const result =
1143
+ base.before +
1144
+ " ".repeat(beforePad) +
1145
+ r +
1146
+ overlay.text +
1147
+ " ".repeat(overlayPad) +
1148
+ r +
1149
+ base.after +
1150
+ " ".repeat(afterPad);
1151
+
1152
+ // CRITICAL: Always verify and truncate to terminal width.
1153
+ // This is the final safeguard against width overflow which would crash the TUI.
1154
+ // Width tracking can drift from actual visible width due to:
1155
+ // - Complex ANSI/OSC sequences (hyperlinks, colors)
1156
+ // - Wide characters at segment boundaries
1157
+ // - Edge cases in segment extraction
1158
+ const resultWidth = visibleWidth(result);
1159
+ if (resultWidth <= totalWidth) {
1160
+ return result;
1161
+ }
1162
+ // Truncate with strict=true to ensure we don't exceed totalWidth
1163
+ return sliceByColumn(result, 0, totalWidth, true);
1164
+ }
1165
+
1166
+ /**
1167
+ * Find and extract cursor position from rendered lines.
1168
+ * Searches for CURSOR_MARKER, calculates its position, and strips it from the output.
1169
+ * Only scans the bottom terminal height lines (visible viewport).
1170
+ * @param lines - Rendered lines to search
1171
+ * @param height - Terminal height (visible viewport size)
1172
+ * @returns Cursor position { row, col } or null if no marker found
1173
+ */
1174
+ #extractCursorPosition(lines: string[], height: number): { row: number; col: number } | null {
1175
+ // Only scan the bottom `height` lines (visible viewport)
1176
+ const viewportTop = Math.max(0, lines.length - height);
1177
+ for (let row = lines.length - 1; row >= viewportTop; row--) {
1178
+ const line = lines[row];
1179
+ const markerIndex = line.indexOf(CURSOR_MARKER);
1180
+ if (markerIndex !== -1) {
1181
+ // Calculate visual column (width of text before marker)
1182
+ const beforeMarker = line.slice(0, markerIndex);
1183
+ const col = visibleWidth(beforeMarker);
1184
+
1185
+ // Strip marker from the line
1186
+ lines[row] = line.slice(0, markerIndex) + line.slice(markerIndex + CURSOR_MARKER.length);
1187
+
1188
+ return { row, col };
1189
+ }
1190
+ }
1191
+ return null;
1192
+ }
1193
+
1194
+ /**
1195
+ * Append the per-line terminator ({@link LINE_TERMINATOR}) to every
1196
+ * non-image line and normalize for terminal rendering. Mutates the input
1197
+ * array in place so downstream diffing/storage sees exactly the bytes
1198
+ * written to the terminal — without this, the diff cache disagrees with
1199
+ * emitted output and OSC 8 hyperlink state can leak across lines.
1200
+ */
1201
+ #normalizeLineForRender(line: string): LineNormalizationCacheEntry {
1202
+ const cached = this.#lineNormalizationCache.get(line);
1203
+ if (cached !== undefined) return cached;
1204
+ const normalized = normalizeTerminalOutput(line);
1205
+ const terminated = normalized + (normalized.includes("\x1b]8;") ? LINE_TERMINATOR : SEGMENT_RESET);
1206
+ this.#lineNormalizationCache.set(line, { normalized, terminated });
1207
+ return { normalized, terminated };
1208
+ }
1209
+
1210
+ #lineFitsWidth(normalizedLine: string, width: number): boolean {
1211
+ return isPrintableAscii(normalizedLine) && normalizedLine.length <= width
1212
+ ? true
1213
+ : visibleWidth(normalizedLine) <= width;
1214
+ }
1215
+
1216
+ #truncateNormalizedLine(normalizedLine: string, width: number): string {
1217
+ const key = `${width}\0${normalizedLine}`;
1218
+ const cached = this.#lineTruncationCache.get(key);
1219
+ if (cached !== undefined) return cached;
1220
+ const truncated = truncateToWidth(normalizedLine, width, Ellipsis.Omit);
1221
+ const terminated = truncated + (truncated.includes("\x1b]8;") ? LINE_TERMINATOR : SEGMENT_RESET);
1222
+ this.#lineTruncationCache.set(key, terminated);
1223
+ return terminated;
1224
+ }
1225
+
1226
+ #trimLineCachesForRender(lineCount: number): void {
1227
+ const limit = Math.max(1, lineCount * 2);
1228
+ this.#lineNormalizationCacheLimit = limit;
1229
+ this.#lineTruncationCacheLimit = limit;
1230
+ while (this.#lineNormalizationCache.size > limit) {
1231
+ const key = this.#lineNormalizationCache.keys().next().value;
1232
+ if (key === undefined) break;
1233
+ this.#lineNormalizationCache.delete(key);
1234
+ }
1235
+ while (this.#lineTruncationCache.size > limit) {
1236
+ const key = this.#lineTruncationCache.keys().next().value;
1237
+ if (key === undefined) break;
1238
+ this.#lineTruncationCache.delete(key);
1239
+ }
1240
+ }
1241
+
1242
+ getLineRenderCacheStats(): {
1243
+ normalizationSize: number;
1244
+ truncationSize: number;
1245
+ normalizationLimit: number;
1246
+ truncationLimit: number;
1247
+ } {
1248
+ return {
1249
+ normalizationSize: this.#lineNormalizationCache.size,
1250
+ truncationSize: this.#lineTruncationCache.size,
1251
+ normalizationLimit: this.#lineNormalizationCacheLimit,
1252
+ truncationLimit: this.#lineTruncationCacheLimit,
1253
+ };
1254
+ }
1255
+
1256
+ /** Normalize + width-fit a single line for emission (image lines pass through). */
1257
+ #normalizeLineForEmit(line: string, width: number): string {
1258
+ if (TERMINAL.isImageLine(line)) return line;
1259
+ const { normalized, terminated } = this.#normalizeLineForRender(line);
1260
+ return this.#lineFitsWidth(normalized, width) ? terminated : this.#truncateNormalizedLine(normalized, width);
1261
+ }
1262
+
1263
+ #applyLineResetsAndTruncate(lines: string[], width: number): string[] {
1264
+ for (let i = 0; i < lines.length; i++) {
1265
+ lines[i] = this.#normalizeLineForEmit(lines[i], width);
1266
+ }
1267
+ this.#trimLineCachesForRender(lines.length);
1268
+ return lines;
1269
+ }
1270
+
1271
+ #doRender(): void {
1272
+ if (this.#stopped || !this.terminalAvailable) return;
1273
+ const width = this.terminal.columns;
1274
+ const height = this.terminal.rows;
1275
+ let viewportTop = Math.max(0, this.#maxLinesRendered - height);
1276
+ let prevViewportTop = this.#viewportTopRow;
1277
+ let hardwareCursorRow = this.#hardwareCursorRow;
1278
+ const computeLineDiff = (targetRow: number): number => {
1279
+ const currentScreenRow = hardwareCursorRow - prevViewportTop;
1280
+ const targetScreenRow = targetRow - viewportTop;
1281
+ return targetScreenRow - currentScreenRow;
1282
+ };
1283
+
1284
+ // Render all components to get new lines
1285
+ const renderTreeStart = renderMetrics.now();
1286
+ let newLines = this.render(width);
1287
+ if (renderMetrics.enabled) renderMetrics.recordHelper("renderTree", renderMetrics.now() - renderTreeStart);
1288
+
1289
+ // Composite overlays into the rendered lines (before differential compare)
1290
+ if (this.overlayStack.length > 0) {
1291
+ newLines = this.#compositeOverlays(newLines, width, height);
1292
+ }
1293
+
1294
+ // Extract cursor position (marker must be found before diff comparison)
1295
+ const cursorPos = this.#extractCursorPosition(newLines, height);
1296
+
1297
+ // Terminate every non-image line so #previousLines mirrors emitted bytes
1298
+ // (closes SGR + OSC 8 hyperlink state). Must run after cursor extraction
1299
+ // because the marker is embedded mid-line, and before any diff/full render
1300
+ // path so cache comparisons stay byte-accurate.
1301
+ // Width/height change detection (used for both normalization reuse and full-redraw decisions).
1302
+ const widthChanged = this.#previousWidth !== 0 && this.#previousWidth !== width;
1303
+ const heightChanged = this.#previousHeight !== 0 && this.#previousHeight !== height;
1304
+
1305
+ // Normalize/truncate lines for emission. With the opt-in virtual-viewport flag
1306
+ // (PI_TUI_VIRTUAL_VIEWPORT) we reuse the previous frame's normalized prefix when the
1307
+ // off-screen raw prefix is unchanged (raw value equality per line; fast reference
1308
+ // short-circuit for cached components), so only the visible window is
1309
+ // re-normalized and the diff starts at the window. Output is byte-identical to the
1310
+ // full path (reused entries are deterministic normalizations of identical raw lines).
1311
+ const VIEWPORT_NORMALIZE_OVERSCAN = 8;
1312
+ const rawLines = newLines;
1313
+ const total = rawLines.length;
1314
+ let diffStart = 0;
1315
+ let usedWindowNormalize = false;
1316
+ if (
1317
+ this.#virtualViewport &&
1318
+ !widthChanged &&
1319
+ this.#previousRaw.length > 0 &&
1320
+ this.#previousLines.length === this.#previousRaw.length
1321
+ ) {
1322
+ const winTop = Math.max(0, total - height - VIEWPORT_NORMALIZE_OVERSCAN);
1323
+ if (winTop <= this.#previousLines.length && winTop <= this.#previousRaw.length) {
1324
+ let stable = true;
1325
+ for (let i = 0; i < winTop; i++) {
1326
+ if (rawLines[i] !== this.#previousRaw[i]) {
1327
+ stable = false;
1328
+ break;
1329
+ }
1330
+ }
1331
+ if (stable) {
1332
+ const windowed = this.#previousLines.slice(0, winTop);
1333
+ for (let i = winTop; i < total; i++) {
1334
+ windowed.push(this.#normalizeLineForEmit(rawLines[i], width));
1335
+ }
1336
+ this.#trimLineCachesForRender(total);
1337
+ newLines = windowed;
1338
+ diffStart = winTop;
1339
+ usedWindowNormalize = true;
1340
+ }
1341
+ }
1342
+ }
1343
+ if (!usedWindowNormalize) {
1344
+ newLines = this.#applyLineResetsAndTruncate(this.#virtualViewport ? rawLines.slice() : rawLines, width);
1345
+ }
1346
+ if (this.#virtualViewport) {
1347
+ this.#previousRaw = rawLines;
1348
+ }
1349
+ if (renderMetrics.enabled) {
1350
+ renderMetrics.recordLineCount("rendered", total);
1351
+ renderMetrics.recordLineCount("normalized", total - diffStart);
1352
+ renderMetrics.recordLineCount("measured", total - diffStart);
1353
+ if (usedWindowNormalize) renderMetrics.recordLineCount("offscreenScan", diffStart);
1354
+ }
1355
+
1356
+ // Helper to clear scrollback and viewport and render all new lines
1357
+ const fullRender = (clear: boolean, reason = "full render"): void => {
1358
+ this.#fullRedrawCount += 1;
1359
+ if (renderMetrics.enabled) renderMetrics.recordFullRedraw(reason);
1360
+ let buffer = "\x1b[?2026h"; // Begin synchronized output
1361
+ // Skip clearing scrollback (3J) in multiplexers — users actively navigate scrollback history
1362
+ if (clear) buffer += isMultiplexerSession() ? "\x1b[2J\x1b[H" : "\x1b[2J\x1b[H\x1b[3J";
1363
+ for (let i = 0; i < newLines.length; i++) {
1364
+ if (i > 0) buffer += "\r\n";
1365
+ // Lines were pre-terminated/normalized by #applyLineResets; image
1366
+ // lines were left untouched there.
1367
+ buffer += newLines[i];
1368
+ }
1369
+ this.#cursorRow = Math.max(0, newLines.length - 1);
1370
+ const { seq, toRow } = this.#cursorControlSequence(cursorPos, newLines.length, this.#cursorRow);
1371
+ this.#hardwareCursorRow = toRow;
1372
+ buffer += seq;
1373
+ buffer += "\x1b[?2026l"; // End synchronized output
1374
+ if (!this.#writeTerminal(buffer)) return;
1375
+ // Reset max lines when clearing, otherwise track growth
1376
+ if (clear) {
1377
+ this.#maxLinesRendered = newLines.length;
1378
+ } else {
1379
+ this.#maxLinesRendered = Math.max(this.#maxLinesRendered, newLines.length);
1380
+ }
1381
+ this.#viewportTopRow = Math.max(0, this.#maxLinesRendered - height);
1382
+ this.#previousLines = newLines;
1383
+ this.#previousWidth = width;
1384
+ this.#previousHeight = height;
1385
+ };
1386
+
1387
+ const multiplexerViewportRepaint = (reason: string): void => {
1388
+ this.#fullRedrawCount += 1;
1389
+ if (renderMetrics.enabled) renderMetrics.recordFullRedraw(reason);
1390
+ const nextViewportTop = Math.max(0, newLines.length - height);
1391
+ const currentScreenRow = Math.max(0, Math.min(height - 1, hardwareCursorRow - prevViewportTop));
1392
+ let buffer = "\x1b[?2026h";
1393
+ if (currentScreenRow > 0) {
1394
+ buffer += `\x1b[${currentScreenRow}A`;
1395
+ }
1396
+ buffer += "\r";
1397
+ for (let screenRow = 0; screenRow < height; screenRow++) {
1398
+ if (screenRow > 0) buffer += "\r\n";
1399
+ buffer += "\x1b[2K";
1400
+ const lineIndex = nextViewportTop + screenRow;
1401
+ if (lineIndex >= newLines.length) continue;
1402
+ const line = newLines[lineIndex];
1403
+ const isImage = TERMINAL.isImageLine(line);
1404
+ if (!isImage && visibleWidth(line) > width) {
1405
+ let truncatedLine = truncateToWidth(line, width, Ellipsis.Omit);
1406
+ truncatedLine += truncatedLine.includes("\x1b]8;") ? LINE_TERMINATOR : SEGMENT_RESET;
1407
+ buffer += truncatedLine;
1408
+ } else {
1409
+ buffer += line;
1410
+ }
1411
+ }
1412
+
1413
+ const finalPhysicalRow = nextViewportTop + Math.max(0, height - 1);
1414
+ let cursorSeq = "\x1b[?25l";
1415
+ let cursorToRow = finalPhysicalRow;
1416
+ if (cursorPos && cursorPos.row >= nextViewportTop && cursorPos.row < nextViewportTop + height) {
1417
+ const cursor = this.#cursorControlSequence(cursorPos, newLines.length, finalPhysicalRow);
1418
+ cursorSeq = cursor.seq;
1419
+ cursorToRow = cursor.toRow;
1420
+ }
1421
+ this.#hardwareCursorRow = cursorToRow;
1422
+ buffer += cursorSeq;
1423
+ buffer += "\x1b[?2026l";
1424
+ if (!this.#writeTerminal(buffer)) return;
1425
+
1426
+ if ($flag("PI_DEBUG_REDRAW")) {
1427
+ const logPath = getDebugLogPath();
1428
+ const msg = `[${new Date().toISOString()}] multiplexerViewportRepaint: ${reason} (prev=${this.#previousLines.length}, new=${newLines.length}, height=${height}, viewportTop=${nextViewportTop})\n`;
1429
+ fs.appendFileSync(logPath, msg);
1430
+ }
1431
+ // In multiplexers this deliberately prioritizes the live viewport over
1432
+ // historical scrollback repair. After offscreen changes, #previousLines
1433
+ // tracks the desired logical transcript, not every byte emitted into the
1434
+ // multiplexer scrollback.
1435
+ this.#cursorRow = Math.max(0, newLines.length - 1);
1436
+ this.#maxLinesRendered = newLines.length;
1437
+ this.#viewportTopRow = nextViewportTop;
1438
+ this.#previousLines = newLines;
1439
+ this.#previousWidth = width;
1440
+ this.#previousHeight = height;
1441
+ };
1442
+
1443
+ const debugRedraw = $flag("PI_DEBUG_REDRAW");
1444
+ const logRedraw = (reason: string): void => {
1445
+ if (!debugRedraw) return;
1446
+ const logPath = getDebugLogPath();
1447
+ const msg = `[${new Date().toISOString()}] fullRender: ${reason} (prev=${this.#previousLines.length}, new=${newLines.length}, height=${height})\n`;
1448
+ fs.appendFileSync(logPath, msg);
1449
+ };
1450
+
1451
+ // First render - just output everything without clearing (assumes clean screen)
1452
+ if (this.#previousLines.length === 0 && !widthChanged && !heightChanged) {
1453
+ logRedraw("first render");
1454
+ fullRender(false, "first render");
1455
+ return;
1456
+ }
1457
+
1458
+ // Width changes always need a full re-render because wrapping changes.
1459
+ if (widthChanged) {
1460
+ logRedraw(`terminal width changed (${this.#previousWidth} -> ${width})`);
1461
+ fullRender(true, "terminal width changed");
1462
+ return;
1463
+ }
1464
+
1465
+ // Height changes normally need a full re-render to keep the visible viewport aligned,
1466
+ // but Termux changes height when the software keyboard shows or hides.
1467
+ // In that environment, a full redraw causes the entire history to replay on every toggle.
1468
+ if (heightChanged) {
1469
+ if (isMultiplexerSession() && !useLegacyMultiplexerFullRender()) {
1470
+ multiplexerViewportRepaint(`terminal height changed (${this.#previousHeight} -> ${height})`);
1471
+ return;
1472
+ }
1473
+ if (!isTermuxSession() && !isMultiplexerSession()) {
1474
+ logRedraw(`terminal height changed (${this.#previousHeight} -> ${height})`);
1475
+ fullRender(true, "terminal height changed");
1476
+ return;
1477
+ }
1478
+ }
1479
+
1480
+ // Content shrunk below the previous render and no overlays - re-render to clear empty rows
1481
+ // (overlays need the padding, so only do this when no overlays are active)
1482
+ // Configurable via setClearOnShrink() or PI_CLEAR_ON_SHRINK=0 env var
1483
+ if (this.#clearOnShrink && newLines.length < this.#previousLines.length && this.overlayStack.length === 0) {
1484
+ logRedraw(`clearOnShrink (prev=${this.#previousLines.length}, new=${newLines.length})`);
1485
+ fullRender(true, "clearOnShrink");
1486
+ return;
1487
+ }
1488
+
1489
+ // Find first and last changed lines
1490
+ let firstChanged = -1;
1491
+ let lastChanged = -1;
1492
+ const maxLines = Math.max(newLines.length, this.#previousLines.length);
1493
+ if (renderMetrics.enabled) renderMetrics.recordLineCount("diffed", maxLines - diffStart);
1494
+ // When the off-screen prefix was reused (virtual viewport), it is verified
1495
+ // unchanged (raw value equality), so the diff can safely start at the window boundary.
1496
+ for (let i = diffStart; i < maxLines; i++) {
1497
+ const oldLine = i < this.#previousLines.length ? this.#previousLines[i] : "";
1498
+ const newLine = i < newLines.length ? newLines[i] : "";
1499
+
1500
+ if (oldLine !== newLine) {
1501
+ if (firstChanged === -1) {
1502
+ firstChanged = i;
1503
+ }
1504
+ lastChanged = i;
1505
+ }
1506
+ }
1507
+ const appendedLines = newLines.length > this.#previousLines.length;
1508
+ if (appendedLines) {
1509
+ if (firstChanged === -1) {
1510
+ firstChanged = this.#previousLines.length;
1511
+ }
1512
+ lastChanged = newLines.length - 1;
1513
+ }
1514
+ const appendStart = appendedLines && firstChanged === this.#previousLines.length && firstChanged > 0;
1515
+
1516
+ // No changes - but still need to update hardware cursor position if it moved
1517
+ if (firstChanged === -1) {
1518
+ this.#writeCursorPosition(cursorPos, newLines.length);
1519
+ this.#viewportTopRow = Math.max(0, this.#maxLinesRendered - height);
1520
+ return;
1521
+ }
1522
+
1523
+ // All changes are in deleted lines (nothing to render, just clear)
1524
+ if (firstChanged >= newLines.length) {
1525
+ if (this.#previousLines.length > newLines.length) {
1526
+ let buffer = "\x1b[?2026h";
1527
+ // Move to end of new content (clamp to 0 for empty content)
1528
+ const targetRow = Math.max(0, newLines.length - 1);
1529
+ const lineDiff = computeLineDiff(targetRow);
1530
+ if (lineDiff > 0) buffer += `\x1b[${lineDiff}B`;
1531
+ else if (lineDiff < 0) buffer += `\x1b[${-lineDiff}A`;
1532
+ buffer += "\r";
1533
+ // Clear extra lines without scrolling
1534
+ const extraLines = this.#previousLines.length - newLines.length;
1535
+ if (extraLines > height) {
1536
+ logRedraw(`extraLines > height (${extraLines} > ${height})`);
1537
+ if (isMultiplexerSession() && !useLegacyMultiplexerFullRender()) {
1538
+ multiplexerViewportRepaint(`extraLines > height (${extraLines} > ${height})`);
1539
+ } else {
1540
+ fullRender(true, "extraLines > height");
1541
+ }
1542
+ return;
1543
+ }
1544
+ const clearStartOffset = newLines.length > 0 && extraLines > 0 ? 1 : 0;
1545
+ if (clearStartOffset > 0) {
1546
+ buffer += `\x1b[${clearStartOffset}B`;
1547
+ }
1548
+ for (let i = 0; i < extraLines; i++) {
1549
+ buffer += "\r\x1b[2K";
1550
+ if (i < extraLines - 1) buffer += "\x1b[1B";
1551
+ }
1552
+ const moveUp = extraLines - 1 + clearStartOffset;
1553
+ if (moveUp > 0) {
1554
+ buffer += `\x1b[${moveUp}A`;
1555
+ }
1556
+ this.#cursorRow = targetRow;
1557
+ const { seq, toRow } = this.#cursorControlSequence(cursorPos, newLines.length, targetRow);
1558
+ this.#hardwareCursorRow = toRow;
1559
+ buffer += seq;
1560
+ buffer += "\x1b[?2026l";
1561
+ if (!this.#writeTerminal(buffer)) return;
1562
+ }
1563
+ this.#previousLines = newLines;
1564
+ this.#previousWidth = width;
1565
+ this.#previousHeight = height;
1566
+ this.#maxLinesRendered = newLines.length;
1567
+ this.#viewportTopRow = Math.max(0, newLines.length - height);
1568
+ return;
1569
+ }
1570
+
1571
+ // Differential rendering can only touch what was actually visible.
1572
+ // Any change above the previous viewport requires a full redraw so terminal
1573
+ // scrollback ends up consistent with the new transcript state.
1574
+ if (firstChanged < prevViewportTop) {
1575
+ logRedraw(`firstChanged < viewportTop (${firstChanged} < ${prevViewportTop})`);
1576
+ if (isMultiplexerSession() && !useLegacyMultiplexerFullRender()) {
1577
+ multiplexerViewportRepaint(`firstChanged < viewportTop (${firstChanged} < ${prevViewportTop})`);
1578
+ } else {
1579
+ fullRender(true, "firstChanged < viewportTop");
1580
+ }
1581
+ return;
1582
+ }
1583
+
1584
+ // Render from first changed line to end
1585
+ // Build buffer with all updates wrapped in synchronized output
1586
+ let buffer = "\x1b[?2026h"; // Begin synchronized output
1587
+ const prevViewportBottom = prevViewportTop + height - 1;
1588
+ const moveTargetRow = appendStart ? firstChanged - 1 : firstChanged;
1589
+ if (moveTargetRow > prevViewportBottom) {
1590
+ const currentScreenRow = Math.max(0, Math.min(height - 1, hardwareCursorRow - prevViewportTop));
1591
+ const moveToBottom = height - 1 - currentScreenRow;
1592
+ if (moveToBottom > 0) {
1593
+ buffer += `\x1b[${moveToBottom}B`;
1594
+ }
1595
+ const scroll = moveTargetRow - prevViewportBottom;
1596
+ buffer += "\r\n".repeat(scroll);
1597
+ prevViewportTop += scroll;
1598
+ viewportTop += scroll;
1599
+ hardwareCursorRow = moveTargetRow;
1600
+ }
1601
+
1602
+ // Move cursor to first changed line (use hardwareCursorRow for actual position)
1603
+ const lineDiff = computeLineDiff(moveTargetRow);
1604
+ if (lineDiff > 0) {
1605
+ buffer += `\x1b[${lineDiff}B`; // Move down
1606
+ } else if (lineDiff < 0) {
1607
+ buffer += `\x1b[${-lineDiff}A`; // Move up
1608
+ }
1609
+
1610
+ buffer += appendStart ? "\r\n" : "\r"; // Move to column 0
1611
+
1612
+ // Only render changed lines (firstChanged to lastChanged), not all lines to end
1613
+ // This reduces flicker when only a single line changes (e.g., spinner animation)
1614
+ const renderEnd = Math.min(lastChanged, newLines.length - 1);
1615
+ for (let i = firstChanged; i <= renderEnd; i++) {
1616
+ if (i > firstChanged) buffer += "\r\n";
1617
+ buffer += "\x1b[2K"; // Clear current line
1618
+ const line = newLines[i];
1619
+ let truncatedLine = line;
1620
+ const isImage = TERMINAL.isImageLine(line);
1621
+ if (!isImage && visibleWidth(line) > width) {
1622
+ if (debugRedraw) {
1623
+ const debugData = [
1624
+ `[TUI Truncate] ${new Date().toISOString()}`,
1625
+ `Line ${i} truncated: ${visibleWidth(line)} > ${width}`,
1626
+ `Content preview: ${line.slice(0, 100)}...`,
1627
+ "",
1628
+ ].join("\n");
1629
+ try {
1630
+ fs.appendFileSync(getDebugLogPath(), debugData);
1631
+ } catch {
1632
+ // Ignore write errors - truncation should still work
1633
+ }
1634
+ }
1635
+ truncatedLine = truncateToWidth(line, width, Ellipsis.Omit);
1636
+ // Re-append the terminator: truncateToWidth removes trailing
1637
+ // content past the visible-width budget, which may also drop the
1638
+ // terminator appended by #applyLineResets. Match the conditional
1639
+ // OSC 8 close strategy used there.
1640
+ truncatedLine += truncatedLine.includes("\x1b]8;") ? LINE_TERMINATOR : SEGMENT_RESET;
1641
+ }
1642
+ // Non-image lines are pre-terminated/normalized by #applyLineResets;
1643
+ // truncated lines re-append LINE_TERMINATOR above.
1644
+ buffer += truncatedLine;
1645
+ }
1646
+
1647
+ // Track where cursor ended up after rendering
1648
+ let finalCursorRow = renderEnd;
1649
+
1650
+ // If we had more lines before, clear them and move cursor back
1651
+ if (this.#previousLines.length > newLines.length) {
1652
+ // Move to end of new content first if we stopped before it
1653
+ if (renderEnd < newLines.length - 1) {
1654
+ const moveDown = newLines.length - 1 - renderEnd;
1655
+ buffer += `\x1b[${moveDown}B`;
1656
+ finalCursorRow = newLines.length - 1;
1657
+ }
1658
+ const extraLines = this.#previousLines.length - newLines.length;
1659
+ for (let i = newLines.length; i < this.#previousLines.length; i++) {
1660
+ buffer += "\r\n\x1b[2K";
1661
+ }
1662
+ // Move cursor back to end of new content
1663
+ buffer += `\x1b[${extraLines}A`;
1664
+ }
1665
+
1666
+ const { seq, toRow } = this.#cursorControlSequence(cursorPos, newLines.length, finalCursorRow);
1667
+ this.#hardwareCursorRow = toRow;
1668
+ buffer += seq;
1669
+ buffer += "\x1b[?2026l"; // End synchronized output
1670
+
1671
+ if ($flag("PI_TUI_DEBUG")) {
1672
+ const debugDir = "/tmp/tui";
1673
+ fs.mkdirSync(debugDir, { recursive: true });
1674
+ const debugPath = path.join(debugDir, `render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`);
1675
+ const debugData = [
1676
+ `firstChanged: ${firstChanged}`,
1677
+ `viewportTop: ${viewportTop}`,
1678
+ `cursorRow: ${this.#cursorRow}`,
1679
+ `height: ${height}`,
1680
+ `lineDiff: ${lineDiff}`,
1681
+ `hardwareCursorRow: ${hardwareCursorRow}`,
1682
+ `hardwareCursorRow (post): ${this.#hardwareCursorRow}`,
1683
+ `renderEnd: ${renderEnd}`,
1684
+ `finalCursorRow: ${finalCursorRow}`,
1685
+ `cursorPos: ${JSON.stringify(cursorPos)}`,
1686
+ `newLines.length: ${newLines.length}`,
1687
+ `previousLines.length: ${this.#previousLines.length}`,
1688
+ "",
1689
+ "=== newLines ===",
1690
+ JSON.stringify(newLines, null, 2),
1691
+ "",
1692
+ "=== previousLines ===",
1693
+ JSON.stringify(this.#previousLines, null, 2),
1694
+ "",
1695
+ "=== buffer ===",
1696
+ JSON.stringify(buffer),
1697
+ ].join("\n");
1698
+ fs.writeFileSync(debugPath, debugData);
1699
+ }
1700
+
1701
+ // Write entire buffer at once
1702
+ if (!this.#writeTerminal(buffer)) return;
1703
+
1704
+ // Track cursor position for next render.
1705
+ // cursorRow tracks end of content (for viewport calculation).
1706
+ // #hardwareCursorRow was already updated by #cursorControlSequence above.
1707
+ this.#cursorRow = Math.max(0, newLines.length - 1);
1708
+ // Track content height for viewport calculation
1709
+ this.#maxLinesRendered = newLines.length;
1710
+ this.#viewportTopRow = Math.max(0, newLines.length - height);
1711
+
1712
+ this.#previousLines = newLines;
1713
+ this.#previousWidth = width;
1714
+ this.#previousHeight = height;
1715
+ }
1716
+
1717
+ /**
1718
+ * Build cursor control sequences to position the hardware cursor for the IME
1719
+ * candidate window. Returns escape sequences and the resulting cursor row for
1720
+ * the caller to update `#hardwareCursorRow`. The sequences should be appended
1721
+ * into the caller's own synchronized output block to avoid a flicker between
1722
+ * content and cursor frames.
1723
+ */
1724
+ #cursorControlSequence(
1725
+ cursorPos: { row: number; col: number } | null,
1726
+ totalLines: number,
1727
+ fromRow: number,
1728
+ ): { seq: string; toRow: number } {
1729
+ // No IME target or no content — hide cursor regardless of preference
1730
+ if (!cursorPos || totalLines <= 0) return { seq: "\x1b[?25l", toRow: fromRow };
1731
+
1732
+ // Clamp cursor position to valid range
1733
+ const targetRow = Math.max(0, Math.min(cursorPos.row, totalLines - 1));
1734
+ const targetCol = Math.max(0, cursorPos.col);
1735
+
1736
+ // Move cursor from current position to target
1737
+ const rowDelta = targetRow - fromRow;
1738
+ let seq = "";
1739
+ if (rowDelta > 0) {
1740
+ seq += `\x1b[${rowDelta}B`; // Move down
1741
+ } else if (rowDelta < 0) {
1742
+ seq += `\x1b[${-rowDelta}A`; // Move up
1743
+ }
1744
+ // Move to absolute column (1-indexed)
1745
+ seq += `\x1b[${targetCol + 1}G`;
1746
+ seq += this.#showHardwareCursor ? "\x1b[?25h" : "\x1b[?25l";
1747
+
1748
+ return { seq, toRow: targetRow };
1749
+ }
1750
+
1751
+ /**
1752
+ * Write the hardware cursor position to the terminal as a standalone
1753
+ * synchronized output block. Use when there is no surrounding render buffer
1754
+ * to embed the sequences into.
1755
+ */
1756
+ #writeCursorPosition(cursorPos: { row: number; col: number } | null, totalLines: number): void {
1757
+ if (!cursorPos || totalLines <= 0) {
1758
+ this.#hideCursor();
1759
+ return;
1760
+ }
1761
+ const { seq, toRow } = this.#cursorControlSequence(cursorPos, totalLines, this.#hardwareCursorRow);
1762
+ this.#hardwareCursorRow = toRow;
1763
+ this.#writeTerminal(`\x1b[?2026h${seq}\x1b[?2026l`);
1764
+ }
1765
+ }