@fleetagent/pi-tui 0.1.9 → 0.2.1

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 (109) hide show
  1. package/README.md +47 -7
  2. package/dist/autocomplete.d.ts +17 -23
  3. package/dist/autocomplete.d.ts.map +1 -1
  4. package/dist/autocomplete.js +129 -195
  5. package/dist/autocomplete.js.map +1 -1
  6. package/dist/components/alt-screen-flash.d.ts +13 -0
  7. package/dist/components/alt-screen-flash.d.ts.map +1 -0
  8. package/dist/components/alt-screen-flash.js +37 -0
  9. package/dist/components/alt-screen-flash.js.map +1 -0
  10. package/dist/components/editor.d.ts +47 -4
  11. package/dist/components/editor.d.ts.map +1 -1
  12. package/dist/components/editor.js +615 -585
  13. package/dist/components/editor.js.map +1 -1
  14. package/dist/components/h-stack.d.ts +7 -0
  15. package/dist/components/h-stack.d.ts.map +1 -0
  16. package/dist/components/h-stack.js +43 -0
  17. package/dist/components/h-stack.js.map +1 -0
  18. package/dist/components/image.d.ts +4 -0
  19. package/dist/components/image.d.ts.map +1 -1
  20. package/dist/components/image.js +38 -51
  21. package/dist/components/image.js.map +1 -1
  22. package/dist/components/input.d.ts +9 -0
  23. package/dist/components/input.d.ts.map +1 -1
  24. package/dist/components/input.js +121 -147
  25. package/dist/components/input.js.map +1 -1
  26. package/dist/components/markdown.d.ts +34 -0
  27. package/dist/components/markdown.d.ts.map +1 -1
  28. package/dist/components/markdown.js +491 -429
  29. package/dist/components/markdown.js.map +1 -1
  30. package/dist/components/scroll-view.d.ts +53 -0
  31. package/dist/components/scroll-view.d.ts.map +1 -0
  32. package/dist/components/scroll-view.js +173 -0
  33. package/dist/components/scroll-view.js.map +1 -0
  34. package/dist/components/select-list.d.ts.map +1 -1
  35. package/dist/components/select-list.js.map +1 -1
  36. package/dist/components/settings-list.d.ts +2 -0
  37. package/dist/components/settings-list.d.ts.map +1 -1
  38. package/dist/components/settings-list.js +31 -29
  39. package/dist/components/settings-list.js.map +1 -1
  40. package/dist/components/stack.d.ts +32 -0
  41. package/dist/components/stack.d.ts.map +1 -0
  42. package/dist/components/stack.js +122 -0
  43. package/dist/components/stack.js.map +1 -0
  44. package/dist/components/v-stack.d.ts +8 -0
  45. package/dist/components/v-stack.d.ts.map +1 -0
  46. package/dist/components/v-stack.js +27 -0
  47. package/dist/components/v-stack.js.map +1 -0
  48. package/dist/fuzzy.d.ts.map +1 -1
  49. package/dist/fuzzy.js +37 -46
  50. package/dist/fuzzy.js.map +1 -1
  51. package/dist/index.d.ts +10 -3
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +11 -2
  54. package/dist/index.js.map +1 -1
  55. package/dist/keybindings.d.ts +54 -4
  56. package/dist/keybindings.d.ts.map +1 -1
  57. package/dist/keybindings.js +39 -4
  58. package/dist/keybindings.js.map +1 -1
  59. package/dist/keys.d.ts.map +1 -1
  60. package/dist/keys.js +359 -479
  61. package/dist/keys.js.map +1 -1
  62. package/dist/kill-ring.d.ts +6 -4
  63. package/dist/kill-ring.d.ts.map +1 -1
  64. package/dist/kill-ring.js +0 -7
  65. package/dist/kill-ring.js.map +1 -1
  66. package/dist/latex.d.ts +10 -0
  67. package/dist/latex.d.ts.map +1 -0
  68. package/dist/latex.js +1406 -0
  69. package/dist/latex.js.map +1 -0
  70. package/dist/layout-node.d.ts +43 -0
  71. package/dist/layout-node.d.ts.map +1 -0
  72. package/dist/layout-node.js +6 -0
  73. package/dist/layout-node.js.map +1 -0
  74. package/dist/layout.d.ts +40 -0
  75. package/dist/layout.d.ts.map +1 -0
  76. package/dist/layout.js +386 -0
  77. package/dist/layout.js.map +1 -0
  78. package/dist/stdin-buffer.d.ts +8 -0
  79. package/dist/stdin-buffer.d.ts.map +1 -1
  80. package/dist/stdin-buffer.js +116 -159
  81. package/dist/stdin-buffer.js.map +1 -1
  82. package/dist/terminal-image.d.ts +41 -19
  83. package/dist/terminal-image.d.ts.map +1 -1
  84. package/dist/terminal-image.js +171 -32
  85. package/dist/terminal-image.js.map +1 -1
  86. package/dist/terminal.d.ts +3 -0
  87. package/dist/terminal.d.ts.map +1 -1
  88. package/dist/terminal.js +27 -23
  89. package/dist/terminal.js.map +1 -1
  90. package/dist/tui-alt-screen.d.ts +114 -0
  91. package/dist/tui-alt-screen.d.ts.map +1 -0
  92. package/dist/tui-alt-screen.js +950 -0
  93. package/dist/tui-alt-screen.js.map +1 -0
  94. package/dist/tui-main-screen.d.ts +52 -0
  95. package/dist/tui-main-screen.d.ts.map +1 -0
  96. package/dist/tui-main-screen.js +511 -0
  97. package/dist/tui-main-screen.js.map +1 -0
  98. package/dist/tui.d.ts +112 -44
  99. package/dist/tui.d.ts.map +1 -1
  100. package/dist/tui.js +489 -699
  101. package/dist/tui.js.map +1 -1
  102. package/dist/utils.d.ts +29 -17
  103. package/dist/utils.d.ts.map +1 -1
  104. package/dist/utils.js +605 -528
  105. package/dist/utils.js.map +1 -1
  106. package/dist/word-navigation.d.ts.map +1 -1
  107. package/dist/word-navigation.js +37 -39
  108. package/dist/word-navigation.js.map +1 -1
  109. package/package.json +1 -1
package/dist/tui.d.ts CHANGED
@@ -28,11 +28,11 @@ export interface Component {
28
28
  */
29
29
  invalidate(): void;
30
30
  }
31
- type InputListenerResult = {
31
+ export type TuiInputListenerResult = {
32
32
  consume?: boolean;
33
33
  data?: string;
34
34
  } | undefined;
35
- type InputListener = (data: string) => InputListenerResult;
35
+ export type TuiInputListener = (data: string) => TuiInputListenerResult;
36
36
  /**
37
37
  * Interface for components that can receive focus and display a hardware cursor.
38
38
  * When focused, the component should emit CURSOR_MARKER at the cursor position
@@ -100,6 +100,11 @@ export interface OverlayOptions {
100
100
  /** If true, don't capture keyboard focus when shown */
101
101
  nonCapturing?: boolean;
102
102
  }
103
+ /** Options for {@link OverlayHandle.unfocus}. */
104
+ export interface OverlayUnfocusOptions {
105
+ /** Explicit target to focus after releasing this overlay. */
106
+ target: Component | null;
107
+ }
103
108
  /**
104
109
  * Handle returned by showOverlay for controlling the overlay
105
110
  */
@@ -112,11 +117,15 @@ export interface OverlayHandle {
112
117
  isHidden(): boolean;
113
118
  /** Focus this overlay and bring it to the visual front */
114
119
  focus(): void;
115
- /** Release focus to the previous target */
116
- unfocus(): void;
120
+ /** Release focus to the next visible capturing overlay or previous target, or to an explicit target when provided */
121
+ unfocus(options?: OverlayUnfocusOptions): void;
117
122
  /** Check if this overlay currently has focus */
118
123
  isFocused(): boolean;
119
124
  }
125
+ export interface RenderedCursorPosition {
126
+ row: number;
127
+ col: number;
128
+ }
120
129
  /**
121
130
  * Container - a component that contains other components
122
131
  */
@@ -128,34 +137,75 @@ export declare class Container implements Component {
128
137
  invalidate(): void;
129
138
  render(width: number): string[];
130
139
  }
131
- /**
132
- * TUI - Main class for managing terminal UI with differential rendering
133
- */
134
- export declare class TUI extends Container {
140
+ /** Composite overlay content into a terminal line at a fixed column. */
141
+ export declare function compositeTuiLine(baseLine: string, overlayLine: string, startCol: number, overlayWidth: number, totalWidth: number): string;
142
+ export type TuiMode = "regular" | "fullscreen";
143
+ export interface TuiStopOptions {
144
+ /** Restore the previous main buffer without replaying renderer content. */
145
+ preserveScreen?: boolean;
146
+ }
147
+ export interface TUI extends Component {
148
+ readonly mode: TuiMode;
149
+ children: Component[];
150
+ terminal: Terminal;
151
+ onDebug?: () => void;
152
+ readonly fullRedraws: number;
153
+ readonly hasOverlayEntries: boolean;
154
+ addChild(component: Component): void;
155
+ removeChild(component: Component): void;
156
+ clear(): void;
157
+ getShowHardwareCursor(): boolean;
158
+ setShowHardwareCursor(enabled: boolean): void;
159
+ getClearOnShrink(): boolean;
160
+ setClearOnShrink(enabled: boolean): void;
161
+ getFocusedComponent(): Component | null;
162
+ setFocus(component: Component | null): void;
163
+ showOverlay(component: Component, options?: OverlayOptions): OverlayHandle;
164
+ hideOverlay(): void;
165
+ hasOverlay(): boolean;
166
+ start(): void;
167
+ stop(options?: TuiStopOptions): void;
168
+ renderNow(force?: boolean): void;
169
+ requestRender(force?: boolean): void;
170
+ addInputListener(listener: TuiInputListener): () => void;
171
+ removeInputListener(listener: TuiInputListener): void;
172
+ }
173
+ export declare const VIEWPORT_TUI: unique symbol;
174
+ export interface ViewportTUI extends TUI {
175
+ readonly [VIEWPORT_TUI]: true;
176
+ setLayoutRoot(component: Component | undefined): void;
177
+ }
178
+ export declare function isViewportTUI(tui: TUI): tui is ViewportTUI;
179
+ export declare abstract class TuiBase extends Container implements TUI {
180
+ abstract readonly mode: TuiMode;
135
181
  terminal: Terminal;
136
- private previousLines;
137
- private previousKittyImageIds;
138
- private previousWidth;
139
- private previousHeight;
140
182
  private focusedComponent;
141
183
  private inputListeners;
142
184
  /** Global callback for debug key (Shift+Ctrl+D). Called before input is forwarded to focused component. */
143
185
  onDebug?: () => void;
144
186
  private renderRequested;
187
+ private immediateRenderScheduled;
145
188
  private renderTimer;
146
189
  private lastRenderAt;
147
190
  private static readonly MIN_RENDER_INTERVAL_MS;
148
- private cursorRow;
149
- private hardwareCursorRow;
150
191
  private showHardwareCursor;
151
192
  private clearOnShrink;
152
- private maxLinesRendered;
153
- private previousViewportTop;
154
- private fullRedrawCount;
155
- private stopped;
193
+ protected fullRedrawCount: number;
194
+ protected stopped: boolean;
195
+ protected readonly logDirectory: string;
156
196
  private focusOrderCounter;
157
197
  private overlayStack;
158
- constructor(terminal: Terminal, showHardwareCursor?: boolean);
198
+ get hasOverlayEntries(): boolean;
199
+ private overlayFocusRestore;
200
+ constructor(terminal: Terminal, showHardwareCursor?: boolean, logDirectory?: string);
201
+ protected abstract doRender(): void;
202
+ protected resetRenderState(): void;
203
+ protected beforeTerminalStart(): void;
204
+ protected afterTerminalStart(): void;
205
+ protected onTerminalResize(): void;
206
+ protected onOverlayStackChanged(): void;
207
+ protected beforeTerminalStop(_options?: TuiStopOptions): void;
208
+ protected afterTerminalStop(_options?: TuiStopOptions): void;
159
209
  get fullRedraws(): number;
160
210
  getShowHardwareCursor(): boolean;
161
211
  setShowHardwareCursor(enabled: boolean): void;
@@ -166,7 +216,24 @@ export declare class TUI extends Container {
166
216
  * When false, empty rows remain (reduces redraws on slower terminals).
167
217
  */
168
218
  setClearOnShrink(enabled: boolean): void;
219
+ getFocusedComponent(): Component | null;
169
220
  setFocus(component: Component | null): void;
221
+ private resolveNonOverlayFocus;
222
+ private resolveNullFocus;
223
+ private resolveFocusTarget;
224
+ private applyFocus;
225
+ private setFocusInternal;
226
+ private clearOverlayFocusRestore;
227
+ private clearOverlayFocusRestoreFor;
228
+ private resolveBlockedOverlayFocusResume;
229
+ private getVisibleOverlayFocusRestore;
230
+ private isOverlayFocusAncestor;
231
+ private retargetOverlayPreFocus;
232
+ protected getMountedRoots(): readonly Component[];
233
+ private isComponentMounted;
234
+ private containsComponent;
235
+ private applyBlockedOverlayUnfocus;
236
+ private unfocusOverlay;
170
237
  /**
171
238
  * Show an overlay component with configurable positioning and sizing.
172
239
  * Returns a handle to control the overlay's visibility.
@@ -176,36 +243,44 @@ export declare class TUI extends Container {
176
243
  hideOverlay(): void;
177
244
  /** Check if there are any visible overlays */
178
245
  hasOverlay(): boolean;
246
+ protected hasCapturingOverlay(): boolean;
179
247
  /** Check if an overlay entry is currently visible */
180
248
  private isOverlayVisible;
181
- /** Find the topmost visible capturing overlay, if any */
249
+ /** Find the visual-frontmost visible capturing overlay, if any */
182
250
  private getTopmostVisibleOverlay;
251
+ private refreshOverlayVisibility;
252
+ private retargetFocusFromHiddenOverlay;
253
+ private focusNewlyVisibleOverlay;
254
+ private restoreVisibleOverlayFocus;
255
+ private reconcileOverlayFocus;
183
256
  invalidate(): void;
184
257
  start(): void;
185
- addInputListener(listener: InputListener): () => void;
186
- removeInputListener(listener: InputListener): void;
258
+ addInputListener(listener: TuiInputListener): () => void;
259
+ removeInputListener(listener: TuiInputListener): void;
187
260
  private queryCellSize;
188
- stop(): void;
261
+ stop(options?: TuiStopOptions): void;
262
+ renderNow(force?: boolean): void;
189
263
  requestRender(force?: boolean): void;
264
+ private requestImmediateRender;
265
+ private cancelRenderTimer;
190
266
  private scheduleRender;
191
- private handleInput;
267
+ private applyInputListeners;
268
+ private handleTerminalInput;
192
269
  private consumeCellSizeResponse;
193
- /**
194
- * Resolve overlay layout from options.
195
- * Returns { width, row, col, maxHeight } for rendering.
196
- */
270
+ private resolveOverlayBounds;
271
+ private resolveOverlayWidth;
272
+ private resolveOverlayMaxHeight;
273
+ private resolveOverlayRow;
274
+ private resolveOverlayColumn;
275
+ /** Resolve overlay layout from options. */
197
276
  private resolveOverlayLayout;
198
277
  private resolveAnchorRow;
199
278
  private resolveAnchorCol;
279
+ private prepareOverlayRenderPlan;
280
+ private compositeRenderedOverlay;
200
281
  /** Composite all overlays into content lines (sorted by focusOrder, higher = on top). */
201
- private compositeOverlays;
202
- private static readonly SEGMENT_RESET;
203
- private applyLineResets;
204
- private collectKittyImageIds;
205
- private deleteKittyImages;
206
- private expandLastChangedForKittyImages;
207
- private deleteChangedKittyImages;
208
- /** Splice overlay content into a base line at a specific column. Single-pass optimized. */
282
+ protected compositeOverlays(lines: string[], termWidth: number, termHeight: number): string[];
283
+ protected applyLineResets(lines: string[]): string[];
209
284
  private compositeLineAt;
210
285
  /**
211
286
  * Find and extract cursor position from rendered lines.
@@ -215,13 +290,6 @@ export declare class TUI extends Container {
215
290
  * @param height - Terminal height (visible viewport size)
216
291
  * @returns Cursor position { row, col } or null if no marker found
217
292
  */
218
- private extractCursorPosition;
219
- private doRender;
220
- /**
221
- * Position the hardware cursor for IME candidate window.
222
- * @param cursorPos The cursor position extracted from rendered output, or null
223
- * @param totalLines Total number of rendered lines
224
- */
225
- private positionHardwareCursor;
293
+ protected extractCursorPosition(lines: string[], height: number): RenderedCursorPosition | null;
226
294
  }
227
295
  //# sourceMappingURL=tui.d.ts.map
package/dist/tui.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"tui.d.ts","sourceRoot":"","sources":["../src/tui.ts"],"names":[],"mappings":"AAAA;;GAEG;AAOH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAA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* as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { performance } from \"node:perf_hooks\";\nimport { isKeyRelease, matchesKey } from \"./keys.ts\";\nimport type { Terminal } from \"./terminal.ts\";\nimport { deleteKittyImage, getCapabilities, isImageLine, setCellDimensions } from \"./terminal-image.ts\";\nimport { extractSegments, normalizeTerminalOutput, sliceByColumn, sliceWithWidth, visibleWidth } from \"./utils.ts\";\n\nconst KITTY_SEQUENCE_PREFIX = \"\\x1b_G\";\n\nfunction extractKittyImageIds(line: string): number[] {\n\tconst sequenceStart = line.indexOf(KITTY_SEQUENCE_PREFIX);\n\tif (sequenceStart === -1) return [];\n\n\tconst paramsStart = sequenceStart + KITTY_SEQUENCE_PREFIX.length;\n\tconst paramsEnd = line.indexOf(\";\", paramsStart);\n\tif (paramsEnd === -1) return [];\n\n\tconst params = line.slice(paramsStart, paramsEnd);\n\tfor (const param of params.split(\",\")) {\n\t\tconst [key, value] = param.split(\"=\", 2);\n\t\tif (key !== \"i\" || value === undefined) continue;\n\t\tconst id = Number(value);\n\t\tif (Number.isInteger(id) && id > 0 && id <= 0xffffffff) {\n\t\t\treturn [id];\n\t\t}\n\t}\n\treturn [];\n}\n\n/**\n * Component interface - all components must implement this\n */\nexport interface Component {\n\t/**\n\t * Render the component to lines for the given viewport width\n\t * @param width - Current viewport width\n\t * @returns Array of strings, each representing a line\n\t */\n\trender(width: number): string[];\n\n\t/**\n\t * Optional handler for keyboard input when component has focus\n\t */\n\thandleInput?(data: string): void;\n\n\t/**\n\t * If true, component receives key release events (Kitty protocol).\n\t * Default is false - release events are filtered out.\n\t */\n\twantsKeyRelease?: boolean;\n\n\t/**\n\t * Invalidate any cached rendering state.\n\t * Called when theme changes or when component needs to re-render from scratch.\n\t */\n\tinvalidate(): void;\n}\n\ntype InputListenerResult = { consume?: boolean; data?: string } | undefined;\ntype InputListener = (data: string) => InputListenerResult;\n\n/**\n * Interface for components that can receive focus and display a hardware cursor.\n * When focused, the component should emit CURSOR_MARKER at the cursor position\n * in its render output. TUI will find this marker and position the hardware\n * cursor there for proper IME candidate window positioning.\n */\nexport interface Focusable {\n\t/** Set by TUI when focus changes. Component should emit CURSOR_MARKER when true. */\n\tfocused: boolean;\n}\n\n/** Type guard to check if a component implements Focusable */\nexport function isFocusable(component: Component | null): component is Component & Focusable {\n\treturn component !== null && \"focused\" in component;\n}\n\n/**\n * Cursor position marker - APC (Application Program Command) sequence.\n * This is a zero-width escape sequence that terminals ignore.\n * Components emit this at the cursor position when focused.\n * TUI finds and strips this marker, then positions the hardware cursor there.\n */\nexport const CURSOR_MARKER = \"\\x1b_pi:c\\x07\";\n\nexport { visibleWidth };\n\n/**\n * Anchor position for overlays\n */\nexport type OverlayAnchor =\n\t| \"center\"\n\t| \"top-left\"\n\t| \"top-right\"\n\t| \"bottom-left\"\n\t| \"bottom-right\"\n\t| \"top-center\"\n\t| \"bottom-center\"\n\t| \"left-center\"\n\t| \"right-center\";\n\n/**\n * Margin configuration for overlays\n */\nexport interface OverlayMargin {\n\ttop?: number;\n\tright?: number;\n\tbottom?: number;\n\tleft?: number;\n}\n\n/** Value that can be absolute (number) or percentage (string like \"50%\") */\nexport type SizeValue = number | `${number}%`;\n\n/** Parse a SizeValue into absolute value given a reference size */\nfunction parseSizeValue(value: SizeValue | undefined, referenceSize: number): number | undefined {\n\tif (value === undefined) return undefined;\n\tif (typeof value === \"number\") return value;\n\t// Parse percentage string like \"50%\"\n\tconst match = value.match(/^(\\d+(?:\\.\\d+)?)%$/);\n\tif (match) {\n\t\treturn Math.floor((referenceSize * parseFloat(match[1])) / 100);\n\t}\n\treturn undefined;\n}\n\nfunction isTermuxSession(): boolean {\n\treturn Boolean(process.env.TERMUX_VERSION);\n}\n\n/**\n * Options for overlay positioning and sizing.\n * Values can be absolute numbers or percentage strings (e.g., \"50%\").\n */\nexport interface OverlayOptions {\n\t// === Sizing ===\n\t/** Width in columns, or percentage of terminal width (e.g., \"50%\") */\n\twidth?: SizeValue;\n\t/** Minimum width in columns */\n\tminWidth?: number;\n\t/** Maximum height in rows, or percentage of terminal height (e.g., \"50%\") */\n\tmaxHeight?: SizeValue;\n\n\t// === Positioning - anchor-based ===\n\t/** Anchor point for positioning (default: 'center') */\n\tanchor?: OverlayAnchor;\n\t/** Horizontal offset from anchor position (positive = right) */\n\toffsetX?: number;\n\t/** Vertical offset from anchor position (positive = down) */\n\toffsetY?: number;\n\n\t// === Positioning - percentage or absolute ===\n\t/** Row position: absolute number, or percentage (e.g., \"25%\" = 25% from top) */\n\trow?: SizeValue;\n\t/** Column position: absolute number, or percentage (e.g., \"50%\" = centered horizontally) */\n\tcol?: SizeValue;\n\n\t// === Margin from terminal edges ===\n\t/** Margin from terminal edges. Number applies to all sides. */\n\tmargin?: OverlayMargin | number;\n\n\t// === Visibility ===\n\t/**\n\t * Control overlay visibility based on terminal dimensions.\n\t * If provided, overlay is only rendered when this returns true.\n\t * Called each render cycle with current terminal dimensions.\n\t */\n\tvisible?: (termWidth: number, termHeight: number) => boolean;\n\t/** If true, don't capture keyboard focus when shown */\n\tnonCapturing?: boolean;\n}\n\n/**\n * Handle returned by showOverlay for controlling the overlay\n */\nexport interface OverlayHandle {\n\t/** Permanently remove the overlay (cannot be shown again) */\n\thide(): void;\n\t/** Temporarily hide or show the overlay */\n\tsetHidden(hidden: boolean): void;\n\t/** Check if overlay is temporarily hidden */\n\tisHidden(): boolean;\n\t/** Focus this overlay and bring it to the visual front */\n\tfocus(): void;\n\t/** Release focus to the previous target */\n\tunfocus(): void;\n\t/** Check if this overlay currently has focus */\n\tisFocused(): boolean;\n}\n\n/**\n * Container - a component that contains other components\n */\nexport class Container implements Component {\n\tchildren: Component[] = [];\n\n\taddChild(component: Component): void {\n\t\tthis.children.push(component);\n\t}\n\n\tremoveChild(component: Component): void {\n\t\tconst index = this.children.indexOf(component);\n\t\tif (index !== -1) {\n\t\t\tthis.children.splice(index, 1);\n\t\t}\n\t}\n\n\tclear(): void {\n\t\tthis.children = [];\n\t}\n\n\tinvalidate(): void {\n\t\tfor (const child of this.children) {\n\t\t\tchild.invalidate?.();\n\t\t}\n\t}\n\n\trender(width: number): string[] {\n\t\tconst lines: string[] = [];\n\t\tfor (const child of this.children) {\n\t\t\tconst childLines = child.render(width);\n\t\t\tfor (const line of childLines) {\n\t\t\t\tlines.push(line);\n\t\t\t}\n\t\t}\n\t\treturn lines;\n\t}\n}\n\n/**\n * TUI - Main class for managing terminal UI with differential rendering\n */\nexport class TUI extends Container {\n\tpublic terminal: Terminal;\n\tprivate previousLines: string[] = [];\n\tprivate previousKittyImageIds = new Set<number>();\n\tprivate previousWidth = 0;\n\tprivate previousHeight = 0;\n\tprivate focusedComponent: Component | null = null;\n\tprivate inputListeners = new Set<InputListener>();\n\n\t/** Global callback for debug key (Shift+Ctrl+D). Called before input is forwarded to focused component. */\n\tpublic onDebug?: () => void;\n\tprivate renderRequested = false;\n\tprivate renderTimer: NodeJS.Timeout | undefined;\n\tprivate lastRenderAt = 0;\n\tprivate static readonly MIN_RENDER_INTERVAL_MS = 16;\n\tprivate cursorRow = 0; // Logical cursor row (end of rendered content)\n\tprivate hardwareCursorRow = 0; // Actual terminal cursor row (may differ due to IME positioning)\n\tprivate showHardwareCursor = process.env.PI_HARDWARE_CURSOR === \"1\";\n\tprivate clearOnShrink = process.env.PI_CLEAR_ON_SHRINK === \"1\"; // Clear empty rows when content shrinks (default: off)\n\tprivate maxLinesRendered = 0; // Track terminal's working area (max lines ever rendered)\n\tprivate previousViewportTop = 0; // Track previous viewport top for resize-aware cursor moves\n\tprivate fullRedrawCount = 0;\n\tprivate stopped = false;\n\n\t// Overlay stack for modal components rendered on top of base content\n\tprivate focusOrderCounter = 0;\n\tprivate overlayStack: {\n\t\tcomponent: Component;\n\t\toptions?: OverlayOptions;\n\t\tpreFocus: Component | null;\n\t\thidden: boolean;\n\t\tfocusOrder: number;\n\t}[] = [];\n\n\tconstructor(terminal: Terminal, showHardwareCursor?: boolean) {\n\t\tsuper();\n\t\tthis.terminal = terminal;\n\t\tif (showHardwareCursor !== undefined) {\n\t\t\tthis.showHardwareCursor = showHardwareCursor;\n\t\t}\n\t}\n\n\tget fullRedraws(): number {\n\t\treturn this.fullRedrawCount;\n\t}\n\n\tgetShowHardwareCursor(): boolean {\n\t\treturn this.showHardwareCursor;\n\t}\n\n\tsetShowHardwareCursor(enabled: boolean): void {\n\t\tif (this.showHardwareCursor === enabled) return;\n\t\tthis.showHardwareCursor = enabled;\n\t\tif (!enabled) {\n\t\t\tthis.terminal.hideCursor();\n\t\t}\n\t\tthis.requestRender();\n\t}\n\n\tgetClearOnShrink(): boolean {\n\t\treturn this.clearOnShrink;\n\t}\n\n\t/**\n\t * Set whether to trigger full re-render when content shrinks.\n\t * When true (default), empty rows are cleared when content shrinks.\n\t * When false, empty rows remain (reduces redraws on slower terminals).\n\t */\n\tsetClearOnShrink(enabled: boolean): void {\n\t\tthis.clearOnShrink = enabled;\n\t}\n\n\tsetFocus(component: Component | null): void {\n\t\t// Clear focused flag on old component\n\t\tif (isFocusable(this.focusedComponent)) {\n\t\t\tthis.focusedComponent.focused = false;\n\t\t}\n\n\t\tthis.focusedComponent = component;\n\n\t\t// Set focused flag on new component\n\t\tif (isFocusable(component)) {\n\t\t\tcomponent.focused = true;\n\t\t}\n\t}\n\n\t/**\n\t * Show an overlay component with configurable positioning and sizing.\n\t * Returns a handle to control the overlay's visibility.\n\t */\n\tshowOverlay(component: Component, options?: OverlayOptions): OverlayHandle {\n\t\tconst entry = {\n\t\t\tcomponent,\n\t\t\toptions,\n\t\t\tpreFocus: this.focusedComponent,\n\t\t\thidden: false,\n\t\t\tfocusOrder: ++this.focusOrderCounter,\n\t\t};\n\t\tthis.overlayStack.push(entry);\n\t\t// Only focus if overlay is actually visible\n\t\tif (!options?.nonCapturing && this.isOverlayVisible(entry)) {\n\t\t\tthis.setFocus(component);\n\t\t}\n\t\tthis.terminal.hideCursor();\n\t\tthis.requestRender();\n\n\t\t// Return handle for controlling this overlay\n\t\treturn {\n\t\t\thide: () => {\n\t\t\t\tconst index = this.overlayStack.indexOf(entry);\n\t\t\t\tif (index !== -1) {\n\t\t\t\t\tthis.overlayStack.splice(index, 1);\n\t\t\t\t\t// Restore focus if this overlay had focus\n\t\t\t\t\tif (this.focusedComponent === component) {\n\t\t\t\t\t\tconst topVisible = this.getTopmostVisibleOverlay();\n\t\t\t\t\t\tthis.setFocus(topVisible?.component ?? entry.preFocus);\n\t\t\t\t\t}\n\t\t\t\t\tif (this.overlayStack.length === 0) this.terminal.hideCursor();\n\t\t\t\t\tthis.requestRender();\n\t\t\t\t}\n\t\t\t},\n\t\t\tsetHidden: (hidden: boolean) => {\n\t\t\t\tif (entry.hidden === hidden) return;\n\t\t\t\tentry.hidden = hidden;\n\t\t\t\t// Update focus when hiding/showing\n\t\t\t\tif (hidden) {\n\t\t\t\t\t// If this overlay had focus, move focus to next visible or preFocus\n\t\t\t\t\tif (this.focusedComponent === component) {\n\t\t\t\t\t\tconst topVisible = this.getTopmostVisibleOverlay();\n\t\t\t\t\t\tthis.setFocus(topVisible?.component ?? entry.preFocus);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Restore focus to this overlay when showing (if it's actually visible)\n\t\t\t\t\tif (!options?.nonCapturing && this.isOverlayVisible(entry)) {\n\t\t\t\t\t\tentry.focusOrder = ++this.focusOrderCounter;\n\t\t\t\t\t\tthis.setFocus(component);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.requestRender();\n\t\t\t},\n\t\t\tisHidden: () => entry.hidden,\n\t\t\tfocus: () => {\n\t\t\t\tif (!this.overlayStack.includes(entry) || !this.isOverlayVisible(entry)) return;\n\t\t\t\tif (this.focusedComponent !== component) {\n\t\t\t\t\tthis.setFocus(component);\n\t\t\t\t}\n\t\t\t\tentry.focusOrder = ++this.focusOrderCounter;\n\t\t\t\tthis.requestRender();\n\t\t\t},\n\t\t\tunfocus: () => {\n\t\t\t\tif (this.focusedComponent !== component) return;\n\t\t\t\tconst topVisible = this.getTopmostVisibleOverlay();\n\t\t\t\tthis.setFocus(topVisible && topVisible !== entry ? topVisible.component : entry.preFocus);\n\t\t\t\tthis.requestRender();\n\t\t\t},\n\t\t\tisFocused: () => this.focusedComponent === component,\n\t\t};\n\t}\n\n\t/** Hide the topmost overlay and restore previous focus. */\n\thideOverlay(): void {\n\t\tconst overlay = this.overlayStack.pop();\n\t\tif (!overlay) return;\n\t\tif (this.focusedComponent === overlay.component) {\n\t\t\t// Find topmost visible overlay, or fall back to preFocus\n\t\t\tconst topVisible = this.getTopmostVisibleOverlay();\n\t\t\tthis.setFocus(topVisible?.component ?? overlay.preFocus);\n\t\t}\n\t\tif (this.overlayStack.length === 0) this.terminal.hideCursor();\n\t\tthis.requestRender();\n\t}\n\n\t/** Check if there are any visible overlays */\n\thasOverlay(): boolean {\n\t\treturn this.overlayStack.some((o) => this.isOverlayVisible(o));\n\t}\n\n\t/** Check if an overlay entry is currently visible */\n\tprivate isOverlayVisible(entry: (typeof this.overlayStack)[number]): boolean {\n\t\tif (entry.hidden) return false;\n\t\tif (entry.options?.visible) {\n\t\t\treturn entry.options.visible(this.terminal.columns, this.terminal.rows);\n\t\t}\n\t\treturn true;\n\t}\n\n\t/** Find the topmost visible capturing overlay, if any */\n\tprivate getTopmostVisibleOverlay(): (typeof this.overlayStack)[number] | undefined {\n\t\tfor (let i = this.overlayStack.length - 1; i >= 0; i--) {\n\t\t\tif (this.overlayStack[i].options?.nonCapturing) continue;\n\t\t\tif (this.isOverlayVisible(this.overlayStack[i])) {\n\t\t\t\treturn this.overlayStack[i];\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\toverride invalidate(): void {\n\t\tsuper.invalidate();\n\t\tfor (const overlay of this.overlayStack) overlay.component.invalidate?.();\n\t}\n\n\tstart(): void {\n\t\tthis.stopped = false;\n\t\tthis.terminal.start(\n\t\t\t(data) => this.handleInput(data),\n\t\t\t() => this.requestRender(),\n\t\t);\n\t\tthis.terminal.hideCursor();\n\t\tthis.queryCellSize();\n\t\tthis.requestRender();\n\t}\n\n\taddInputListener(listener: InputListener): () => void {\n\t\tthis.inputListeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.inputListeners.delete(listener);\n\t\t};\n\t}\n\n\tremoveInputListener(listener: InputListener): void {\n\t\tthis.inputListeners.delete(listener);\n\t}\n\n\tprivate queryCellSize(): void {\n\t\t// Only query if terminal supports images (cell size is only used for image rendering)\n\t\tif (!getCapabilities().images) {\n\t\t\treturn;\n\t\t}\n\t\t// Query terminal for cell size in pixels: CSI 16 t\n\t\t// Response format: CSI 6 ; height ; width t\n\t\tthis.terminal.write(\"\\x1b[16t\");\n\t}\n\n\tstop(): void {\n\t\tthis.stopped = true;\n\t\tif (this.renderTimer) {\n\t\t\tclearTimeout(this.renderTimer);\n\t\t\tthis.renderTimer = undefined;\n\t\t}\n\t\t// Move cursor to the end of the content to prevent overwriting/artifacts on exit\n\t\tif (this.previousLines.length > 0) {\n\t\t\tconst targetRow = this.previousLines.length; // Line after the last content\n\t\t\tconst lineDiff = targetRow - this.hardwareCursorRow;\n\t\t\tif (lineDiff > 0) {\n\t\t\t\tthis.terminal.write(`\\x1b[${lineDiff}B`);\n\t\t\t} else if (lineDiff < 0) {\n\t\t\t\tthis.terminal.write(`\\x1b[${-lineDiff}A`);\n\t\t\t}\n\t\t\tthis.terminal.write(\"\\r\\n\");\n\t\t}\n\n\t\tthis.terminal.showCursor();\n\t\tthis.terminal.stop();\n\t}\n\n\trequestRender(force = false): void {\n\t\tif (force) {\n\t\t\tthis.previousLines = [];\n\t\t\tthis.previousWidth = -1; // -1 triggers widthChanged, forcing a full clear\n\t\t\tthis.previousHeight = -1; // -1 triggers heightChanged, forcing a full clear\n\t\t\tthis.cursorRow = 0;\n\t\t\tthis.hardwareCursorRow = 0;\n\t\t\tthis.maxLinesRendered = 0;\n\t\t\tthis.previousViewportTop = 0;\n\t\t\tif (this.renderTimer) {\n\t\t\t\tclearTimeout(this.renderTimer);\n\t\t\t\tthis.renderTimer = undefined;\n\t\t\t}\n\t\t\tthis.renderRequested = true;\n\t\t\tprocess.nextTick(() => {\n\t\t\t\tif (this.stopped || !this.renderRequested) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.renderRequested = false;\n\t\t\t\tthis.lastRenderAt = performance.now();\n\t\t\t\tthis.doRender();\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (this.renderRequested) return;\n\t\tthis.renderRequested = true;\n\t\tprocess.nextTick(() => this.scheduleRender());\n\t}\n\n\tprivate scheduleRender(): void {\n\t\tif (this.stopped || this.renderTimer || !this.renderRequested) {\n\t\t\treturn;\n\t\t}\n\t\tconst elapsed = performance.now() - this.lastRenderAt;\n\t\tconst delay = Math.max(0, TUI.MIN_RENDER_INTERVAL_MS - elapsed);\n\t\tthis.renderTimer = setTimeout(() => {\n\t\t\tthis.renderTimer = undefined;\n\t\t\tif (this.stopped || !this.renderRequested) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.renderRequested = false;\n\t\t\tthis.lastRenderAt = performance.now();\n\t\t\tthis.doRender();\n\t\t\tif (this.renderRequested) {\n\t\t\t\tthis.scheduleRender();\n\t\t\t}\n\t\t}, delay);\n\t}\n\n\tprivate handleInput(data: string): void {\n\t\tif (this.inputListeners.size > 0) {\n\t\t\tlet current = data;\n\t\t\tfor (const listener of this.inputListeners) {\n\t\t\t\tconst result = listener(current);\n\t\t\t\tif (result?.consume) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (result?.data !== undefined) {\n\t\t\t\t\tcurrent = result.data;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (current.length === 0) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tdata = current;\n\t\t}\n\n\t\t// Consume terminal cell size responses without blocking unrelated input.\n\t\tif (this.consumeCellSizeResponse(data)) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Global debug key handler (Shift+Ctrl+D)\n\t\tif (matchesKey(data, \"shift+ctrl+d\") && this.onDebug) {\n\t\t\tthis.onDebug();\n\t\t\treturn;\n\t\t}\n\n\t\t// If focused component is an overlay, verify it's still visible\n\t\t// (visibility can change due to terminal resize or visible() callback)\n\t\tconst focusedOverlay = this.overlayStack.find((o) => o.component === this.focusedComponent);\n\t\tif (focusedOverlay && !this.isOverlayVisible(focusedOverlay)) {\n\t\t\t// Focused overlay is no longer visible, redirect to topmost visible overlay\n\t\t\tconst topVisible = this.getTopmostVisibleOverlay();\n\t\t\tif (topVisible) {\n\t\t\t\tthis.setFocus(topVisible.component);\n\t\t\t} else {\n\t\t\t\t// No visible overlays, restore to preFocus\n\t\t\t\tthis.setFocus(focusedOverlay.preFocus);\n\t\t\t}\n\t\t}\n\n\t\t// Pass input to focused component (including Ctrl+C)\n\t\t// The focused component can decide how to handle Ctrl+C\n\t\tif (this.focusedComponent?.handleInput) {\n\t\t\t// Filter out key release events unless component opts in\n\t\t\tif (isKeyRelease(data) && !this.focusedComponent.wantsKeyRelease) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.focusedComponent.handleInput(data);\n\t\t\tthis.requestRender();\n\t\t}\n\t}\n\n\tprivate consumeCellSizeResponse(data: string): boolean {\n\t\t// Response format: ESC [ 6 ; height ; width t\n\t\tconst match = data.match(/^\\x1b\\[6;(\\d+);(\\d+)t$/);\n\t\tif (!match) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst heightPx = parseInt(match[1], 10);\n\t\tconst widthPx = parseInt(match[2], 10);\n\t\tif (heightPx <= 0 || widthPx <= 0) {\n\t\t\treturn true;\n\t\t}\n\n\t\tsetCellDimensions({ widthPx, heightPx });\n\t\t// Invalidate all components so images re-render with correct dimensions.\n\t\tthis.invalidate();\n\t\tthis.requestRender();\n\t\treturn true;\n\t}\n\n\t/**\n\t * Resolve overlay layout from options.\n\t * Returns { width, row, col, maxHeight } for rendering.\n\t */\n\tprivate resolveOverlayLayout(\n\t\toptions: OverlayOptions | undefined,\n\t\toverlayHeight: number,\n\t\ttermWidth: number,\n\t\ttermHeight: number,\n\t): { width: number; row: number; col: number; maxHeight: number | undefined } {\n\t\tconst opt = options ?? {};\n\n\t\t// Parse margin (clamp to non-negative)\n\t\tconst margin =\n\t\t\ttypeof opt.margin === \"number\"\n\t\t\t\t? { top: opt.margin, right: opt.margin, bottom: opt.margin, left: opt.margin }\n\t\t\t\t: (opt.margin ?? {});\n\t\tconst marginTop = Math.max(0, margin.top ?? 0);\n\t\tconst marginRight = Math.max(0, margin.right ?? 0);\n\t\tconst marginBottom = Math.max(0, margin.bottom ?? 0);\n\t\tconst marginLeft = Math.max(0, margin.left ?? 0);\n\n\t\t// Available space after margins\n\t\tconst availWidth = Math.max(1, termWidth - marginLeft - marginRight);\n\t\tconst availHeight = Math.max(1, termHeight - marginTop - marginBottom);\n\n\t\t// === Resolve width ===\n\t\tlet width = parseSizeValue(opt.width, termWidth) ?? Math.min(80, availWidth);\n\t\t// Apply minWidth\n\t\tif (opt.minWidth !== undefined) {\n\t\t\twidth = Math.max(width, opt.minWidth);\n\t\t}\n\t\t// Clamp to available space\n\t\twidth = Math.max(1, Math.min(width, availWidth));\n\n\t\t// === Resolve maxHeight ===\n\t\tlet maxHeight = parseSizeValue(opt.maxHeight, termHeight);\n\t\t// Clamp to available space\n\t\tif (maxHeight !== undefined) {\n\t\t\tmaxHeight = Math.max(1, Math.min(maxHeight, availHeight));\n\t\t}\n\n\t\t// Effective overlay height (may be clamped by maxHeight)\n\t\tconst effectiveHeight = maxHeight !== undefined ? Math.min(overlayHeight, maxHeight) : overlayHeight;\n\n\t\t// === Resolve position ===\n\t\tlet row: number;\n\t\tlet col: number;\n\n\t\tif (opt.row !== undefined) {\n\t\t\tif (typeof opt.row === \"string\") {\n\t\t\t\t// Percentage: 0% = top, 100% = bottom (overlay stays within bounds)\n\t\t\t\tconst match = opt.row.match(/^(\\d+(?:\\.\\d+)?)%$/);\n\t\t\t\tif (match) {\n\t\t\t\t\tconst maxRow = Math.max(0, availHeight - effectiveHeight);\n\t\t\t\t\tconst percent = parseFloat(match[1]) / 100;\n\t\t\t\t\trow = marginTop + Math.floor(maxRow * percent);\n\t\t\t\t} else {\n\t\t\t\t\t// Invalid format, fall back to center\n\t\t\t\t\trow = this.resolveAnchorRow(\"center\", effectiveHeight, availHeight, marginTop);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Absolute row position\n\t\t\t\trow = opt.row;\n\t\t\t}\n\t\t} else {\n\t\t\t// Anchor-based (default: center)\n\t\t\tconst anchor = opt.anchor ?? \"center\";\n\t\t\trow = this.resolveAnchorRow(anchor, effectiveHeight, availHeight, marginTop);\n\t\t}\n\n\t\tif (opt.col !== undefined) {\n\t\t\tif (typeof opt.col === \"string\") {\n\t\t\t\t// Percentage: 0% = left, 100% = right (overlay stays within bounds)\n\t\t\t\tconst match = opt.col.match(/^(\\d+(?:\\.\\d+)?)%$/);\n\t\t\t\tif (match) {\n\t\t\t\t\tconst maxCol = Math.max(0, availWidth - width);\n\t\t\t\t\tconst percent = parseFloat(match[1]) / 100;\n\t\t\t\t\tcol = marginLeft + Math.floor(maxCol * percent);\n\t\t\t\t} else {\n\t\t\t\t\t// Invalid format, fall back to center\n\t\t\t\t\tcol = this.resolveAnchorCol(\"center\", width, availWidth, marginLeft);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Absolute column position\n\t\t\t\tcol = opt.col;\n\t\t\t}\n\t\t} else {\n\t\t\t// Anchor-based (default: center)\n\t\t\tconst anchor = opt.anchor ?? \"center\";\n\t\t\tcol = this.resolveAnchorCol(anchor, width, availWidth, marginLeft);\n\t\t}\n\n\t\t// Apply offsets\n\t\tif (opt.offsetY !== undefined) row += opt.offsetY;\n\t\tif (opt.offsetX !== undefined) col += opt.offsetX;\n\n\t\t// Clamp to terminal bounds (respecting margins)\n\t\trow = Math.max(marginTop, Math.min(row, termHeight - marginBottom - effectiveHeight));\n\t\tcol = Math.max(marginLeft, Math.min(col, termWidth - marginRight - width));\n\n\t\treturn { width, row, col, maxHeight };\n\t}\n\n\tprivate resolveAnchorRow(anchor: OverlayAnchor, height: number, availHeight: number, marginTop: number): number {\n\t\tswitch (anchor) {\n\t\t\tcase \"top-left\":\n\t\t\tcase \"top-center\":\n\t\t\tcase \"top-right\":\n\t\t\t\treturn marginTop;\n\t\t\tcase \"bottom-left\":\n\t\t\tcase \"bottom-center\":\n\t\t\tcase \"bottom-right\":\n\t\t\t\treturn marginTop + availHeight - height;\n\t\t\tcase \"left-center\":\n\t\t\tcase \"center\":\n\t\t\tcase \"right-center\":\n\t\t\t\treturn marginTop + Math.floor((availHeight - height) / 2);\n\t\t}\n\t}\n\n\tprivate resolveAnchorCol(anchor: OverlayAnchor, width: number, availWidth: number, marginLeft: number): number {\n\t\tswitch (anchor) {\n\t\t\tcase \"top-left\":\n\t\t\tcase \"left-center\":\n\t\t\tcase \"bottom-left\":\n\t\t\t\treturn marginLeft;\n\t\t\tcase \"top-right\":\n\t\t\tcase \"right-center\":\n\t\t\tcase \"bottom-right\":\n\t\t\t\treturn marginLeft + availWidth - width;\n\t\t\tcase \"top-center\":\n\t\t\tcase \"center\":\n\t\t\tcase \"bottom-center\":\n\t\t\t\treturn marginLeft + Math.floor((availWidth - width) / 2);\n\t\t}\n\t}\n\n\t/** Composite all overlays into content lines (sorted by focusOrder, higher = on top). */\n\tprivate compositeOverlays(lines: string[], termWidth: number, termHeight: number): string[] {\n\t\tif (this.overlayStack.length === 0) return lines;\n\t\tconst result = [...lines];\n\n\t\t// Pre-render all visible overlays and calculate positions\n\t\tconst rendered: { overlayLines: string[]; row: number; col: number; w: number }[] = [];\n\t\tlet minLinesNeeded = result.length;\n\n\t\tconst visibleEntries = this.overlayStack.filter((e) => this.isOverlayVisible(e));\n\t\tvisibleEntries.sort((a, b) => a.focusOrder - b.focusOrder);\n\t\tfor (const entry of visibleEntries) {\n\t\t\tconst { component, options } = entry;\n\n\t\t\t// Get layout with height=0 first to determine width and maxHeight\n\t\t\t// (width and maxHeight don't depend on overlay height)\n\t\t\tconst { width, maxHeight } = this.resolveOverlayLayout(options, 0, termWidth, termHeight);\n\n\t\t\t// Render component at calculated width\n\t\t\tlet overlayLines = component.render(width);\n\n\t\t\t// Apply maxHeight if specified\n\t\t\tif (maxHeight !== undefined && overlayLines.length > maxHeight) {\n\t\t\t\toverlayLines = overlayLines.slice(0, maxHeight);\n\t\t\t}\n\n\t\t\t// Get final row/col with actual overlay height\n\t\t\tconst { row, col } = this.resolveOverlayLayout(options, overlayLines.length, termWidth, termHeight);\n\n\t\t\trendered.push({ overlayLines, row, col, w: width });\n\t\t\tminLinesNeeded = Math.max(minLinesNeeded, row + overlayLines.length);\n\t\t}\n\n\t\t// Pad to at least terminal height so overlays have screen-relative positions.\n\t\t// Excludes maxLinesRendered: the historical high-water mark caused self-reinforcing\n\t\t// inflation that pushed content into scrollback on terminal widen.\n\t\tconst workingHeight = Math.max(result.length, termHeight, minLinesNeeded);\n\n\t\t// Extend result with empty lines if content is too short for overlay placement or working area\n\t\twhile (result.length < workingHeight) {\n\t\t\tresult.push(\"\");\n\t\t}\n\n\t\tconst viewportStart = Math.max(0, workingHeight - termHeight);\n\n\t\t// Composite each overlay\n\t\tfor (const { overlayLines, row, col, w } of rendered) {\n\t\t\tfor (let i = 0; i < overlayLines.length; i++) {\n\t\t\t\tconst idx = viewportStart + row + i;\n\t\t\t\tif (idx >= 0 && idx < result.length) {\n\t\t\t\t\t// Defensive: truncate overlay line to declared width before compositing\n\t\t\t\t\t// (components should already respect width, but this ensures it)\n\t\t\t\t\tconst truncatedOverlayLine =\n\t\t\t\t\t\tvisibleWidth(overlayLines[i]) > w ? sliceByColumn(overlayLines[i], 0, w, true) : overlayLines[i];\n\t\t\t\t\tresult[idx] = this.compositeLineAt(result[idx], truncatedOverlayLine, col, w, termWidth);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tprivate static readonly SEGMENT_RESET = \"\\x1b[0m\\x1b]8;;\\x07\";\n\n\tprivate applyLineResets(lines: string[]): string[] {\n\t\tconst reset = TUI.SEGMENT_RESET;\n\t\tfor (let i = 0; i < lines.length; i++) {\n\t\t\tconst line = lines[i];\n\t\t\tif (!isImageLine(line)) {\n\t\t\t\tlines[i] = normalizeTerminalOutput(line) + reset;\n\t\t\t}\n\t\t}\n\t\treturn lines;\n\t}\n\n\tprivate collectKittyImageIds(lines: string[]): Set<number> {\n\t\tconst ids = new Set<number>();\n\t\tfor (const line of lines) {\n\t\t\tfor (const id of extractKittyImageIds(line)) {\n\t\t\t\tids.add(id);\n\t\t\t}\n\t\t}\n\t\treturn ids;\n\t}\n\n\tprivate deleteKittyImages(ids: Iterable<number>): string {\n\t\tlet buffer = \"\";\n\t\tfor (const id of ids) {\n\t\t\tbuffer += deleteKittyImage(id);\n\t\t}\n\t\treturn buffer;\n\t}\n\n\tprivate expandLastChangedForKittyImages(firstChanged: number, lastChanged: number): number {\n\t\tlet expandedLastChanged = lastChanged;\n\t\tfor (let i = firstChanged; i < this.previousLines.length; i++) {\n\t\t\tif (extractKittyImageIds(this.previousLines[i]).length > 0) {\n\t\t\t\texpandedLastChanged = Math.max(expandedLastChanged, i);\n\t\t\t}\n\t\t}\n\t\treturn expandedLastChanged;\n\t}\n\n\tprivate deleteChangedKittyImages(firstChanged: number, lastChanged: number): string {\n\t\tif (firstChanged < 0 || lastChanged < firstChanged) return \"\";\n\n\t\tconst ids = new Set<number>();\n\t\tconst maxLine = Math.min(lastChanged, this.previousLines.length - 1);\n\t\tfor (let i = firstChanged; i <= maxLine; i++) {\n\t\t\tfor (const id of extractKittyImageIds(this.previousLines[i] ?? \"\")) {\n\t\t\t\tids.add(id);\n\t\t\t}\n\t\t}\n\n\t\treturn this.deleteKittyImages(ids);\n\t}\n\n\t/** Splice overlay content into a base line at a specific column. Single-pass optimized. */\n\tprivate compositeLineAt(\n\t\tbaseLine: string,\n\t\toverlayLine: string,\n\t\tstartCol: number,\n\t\toverlayWidth: number,\n\t\ttotalWidth: number,\n\t): string {\n\t\tif (isImageLine(baseLine)) return baseLine;\n\n\t\t// Single pass through baseLine extracts both before and after segments\n\t\tconst afterStart = startCol + overlayWidth;\n\t\tconst base = extractSegments(baseLine, startCol, afterStart, totalWidth - afterStart, true);\n\n\t\t// Extract overlay with width tracking (strict=true to exclude wide chars at boundary)\n\t\tconst overlay = sliceWithWidth(overlayLine, 0, overlayWidth, true);\n\n\t\t// Pad segments to target widths\n\t\tconst beforePad = Math.max(0, startCol - base.beforeWidth);\n\t\tconst overlayPad = Math.max(0, overlayWidth - overlay.width);\n\t\tconst actualBeforeWidth = Math.max(startCol, base.beforeWidth);\n\t\tconst actualOverlayWidth = Math.max(overlayWidth, overlay.width);\n\t\tconst afterTarget = Math.max(0, totalWidth - actualBeforeWidth - actualOverlayWidth);\n\t\tconst afterPad = Math.max(0, afterTarget - base.afterWidth);\n\n\t\t// Compose result\n\t\tconst r = TUI.SEGMENT_RESET;\n\t\tconst result =\n\t\t\tbase.before +\n\t\t\t\" \".repeat(beforePad) +\n\t\t\tr +\n\t\t\toverlay.text +\n\t\t\t\" \".repeat(overlayPad) +\n\t\t\tr +\n\t\t\tbase.after +\n\t\t\t\" \".repeat(afterPad);\n\n\t\t// CRITICAL: Always verify and truncate to terminal width.\n\t\t// This is the final safeguard against width overflow which would crash the TUI.\n\t\t// Width tracking can drift from actual visible width due to:\n\t\t// - Complex ANSI/OSC sequences (hyperlinks, colors)\n\t\t// - Wide characters at segment boundaries\n\t\t// - Edge cases in segment extraction\n\t\tconst resultWidth = visibleWidth(result);\n\t\tif (resultWidth <= totalWidth) {\n\t\t\treturn result;\n\t\t}\n\t\t// Truncate with strict=true to ensure we don't exceed totalWidth\n\t\treturn sliceByColumn(result, 0, totalWidth, true);\n\t}\n\n\t/**\n\t * Find and extract cursor position from rendered lines.\n\t * Searches for CURSOR_MARKER, calculates its position, and strips it from the output.\n\t * Only scans the bottom terminal height lines (visible viewport).\n\t * @param lines - Rendered lines to search\n\t * @param height - Terminal height (visible viewport size)\n\t * @returns Cursor position { row, col } or null if no marker found\n\t */\n\tprivate extractCursorPosition(lines: string[], height: number): { row: number; col: number } | null {\n\t\t// Only scan the bottom `height` lines (visible viewport)\n\t\tconst viewportTop = Math.max(0, lines.length - height);\n\t\tfor (let row = lines.length - 1; row >= viewportTop; row--) {\n\t\t\tconst line = lines[row];\n\t\t\tconst markerIndex = line.indexOf(CURSOR_MARKER);\n\t\t\tif (markerIndex !== -1) {\n\t\t\t\t// Calculate visual column (width of text before marker)\n\t\t\t\tconst beforeMarker = line.slice(0, markerIndex);\n\t\t\t\tconst col = visibleWidth(beforeMarker);\n\n\t\t\t\t// Strip marker from the line\n\t\t\t\tlines[row] = line.slice(0, markerIndex) + line.slice(markerIndex + CURSOR_MARKER.length);\n\n\t\t\t\treturn { row, col };\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tprivate doRender(): void {\n\t\tif (this.stopped) return;\n\t\tconst width = this.terminal.columns;\n\t\tconst height = this.terminal.rows;\n\t\tconst widthChanged = this.previousWidth !== 0 && this.previousWidth !== width;\n\t\tconst heightChanged = this.previousHeight !== 0 && this.previousHeight !== height;\n\t\tconst previousBufferLength = this.previousHeight > 0 ? this.previousViewportTop + this.previousHeight : height;\n\t\tlet prevViewportTop = heightChanged ? Math.max(0, previousBufferLength - height) : this.previousViewportTop;\n\t\tlet viewportTop = prevViewportTop;\n\t\tlet hardwareCursorRow = this.hardwareCursorRow;\n\t\tconst computeLineDiff = (targetRow: number): number => {\n\t\t\tconst currentScreenRow = hardwareCursorRow - prevViewportTop;\n\t\t\tconst targetScreenRow = targetRow - viewportTop;\n\t\t\treturn targetScreenRow - currentScreenRow;\n\t\t};\n\n\t\t// Render all components to get new lines\n\t\tlet newLines = this.render(width);\n\n\t\t// Composite overlays into the rendered lines (before differential compare)\n\t\tif (this.overlayStack.length > 0) {\n\t\t\tnewLines = this.compositeOverlays(newLines, width, height);\n\t\t}\n\n\t\t// Extract cursor position before applying line resets (marker must be found first)\n\t\tconst cursorPos = this.extractCursorPosition(newLines, height);\n\n\t\tnewLines = this.applyLineResets(newLines);\n\n\t\t// Helper to clear scrollback and viewport and render all new lines\n\t\tconst fullRender = (clear: boolean): void => {\n\t\t\tthis.fullRedrawCount += 1;\n\t\t\tlet buffer = \"\\x1b[?2026h\"; // Begin synchronized output\n\t\t\tif (clear) {\n\t\t\t\tbuffer += this.deleteKittyImages(this.previousKittyImageIds);\n\t\t\t\tbuffer += \"\\x1b[2J\\x1b[H\\x1b[3J\"; // Clear screen, home, then clear scrollback\n\t\t\t}\n\t\t\tfor (let i = 0; i < newLines.length; i++) {\n\t\t\t\tif (i > 0) buffer += \"\\r\\n\";\n\t\t\t\tbuffer += newLines[i];\n\t\t\t}\n\t\t\tbuffer += \"\\x1b[?2026l\"; // End synchronized output\n\t\t\tthis.terminal.write(buffer);\n\t\t\tthis.cursorRow = Math.max(0, newLines.length - 1);\n\t\t\tthis.hardwareCursorRow = this.cursorRow;\n\t\t\t// Reset max lines when clearing, otherwise track growth\n\t\t\tif (clear) {\n\t\t\t\tthis.maxLinesRendered = newLines.length;\n\t\t\t} else {\n\t\t\t\tthis.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);\n\t\t\t}\n\t\t\tconst bufferLength = Math.max(height, newLines.length);\n\t\t\tthis.previousViewportTop = Math.max(0, bufferLength - height);\n\t\t\tthis.positionHardwareCursor(cursorPos, newLines.length);\n\t\t\tthis.previousLines = newLines;\n\t\t\tthis.previousKittyImageIds = this.collectKittyImageIds(newLines);\n\t\t\tthis.previousWidth = width;\n\t\t\tthis.previousHeight = height;\n\t\t};\n\n\t\tconst debugRedraw = process.env.PI_DEBUG_REDRAW === \"1\";\n\t\tconst logRedraw = (reason: string): void => {\n\t\t\tif (!debugRedraw) return;\n\t\t\tconst logPath = path.join(os.homedir(), \".pi\", \"agent\", \"pi-debug.log\");\n\t\t\tconst msg = `[${new Date().toISOString()}] fullRender: ${reason} (prev=${this.previousLines.length}, new=${newLines.length}, height=${height})\\n`;\n\t\t\tfs.appendFileSync(logPath, msg);\n\t\t};\n\n\t\t// First render - just output everything without clearing (assumes clean screen)\n\t\tif (this.previousLines.length === 0 && !widthChanged && !heightChanged) {\n\t\t\tlogRedraw(\"first render\");\n\t\t\tfullRender(false);\n\t\t\treturn;\n\t\t}\n\n\t\t// Width changes always need a full re-render because wrapping changes.\n\t\tif (widthChanged) {\n\t\t\tlogRedraw(`terminal width changed (${this.previousWidth} -> ${width})`);\n\t\t\tfullRender(true);\n\t\t\treturn;\n\t\t}\n\n\t\t// Height changes normally need a full re-render to keep the visible viewport aligned,\n\t\t// but Termux changes height when the software keyboard shows or hides.\n\t\t// In that environment, a full redraw causes the entire history to replay on every toggle.\n\t\tif (heightChanged && !isTermuxSession()) {\n\t\t\tlogRedraw(`terminal height changed (${this.previousHeight} -> ${height})`);\n\t\t\tfullRender(true);\n\t\t\treturn;\n\t\t}\n\n\t\t// Content shrunk below the working area and no overlays - re-render to clear empty rows\n\t\t// (overlays need the padding, so only do this when no overlays are active)\n\t\t// Configurable via setClearOnShrink() or PI_CLEAR_ON_SHRINK=0 env var\n\t\tif (this.clearOnShrink && newLines.length < this.maxLinesRendered && this.overlayStack.length === 0) {\n\t\t\tlogRedraw(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`);\n\t\t\tfullRender(true);\n\t\t\treturn;\n\t\t}\n\n\t\t// Find first and last changed lines\n\t\tlet firstChanged = -1;\n\t\tlet lastChanged = -1;\n\t\tconst maxLines = Math.max(newLines.length, this.previousLines.length);\n\t\tfor (let i = 0; i < maxLines; i++) {\n\t\t\tconst oldLine = i < this.previousLines.length ? this.previousLines[i] : \"\";\n\t\t\tconst newLine = i < newLines.length ? newLines[i] : \"\";\n\n\t\t\tif (oldLine !== newLine) {\n\t\t\t\tif (firstChanged === -1) {\n\t\t\t\t\tfirstChanged = i;\n\t\t\t\t}\n\t\t\t\tlastChanged = i;\n\t\t\t}\n\t\t}\n\t\tconst appendedLines = newLines.length > this.previousLines.length;\n\t\tif (appendedLines) {\n\t\t\tif (firstChanged === -1) {\n\t\t\t\tfirstChanged = this.previousLines.length;\n\t\t\t}\n\t\t\tlastChanged = newLines.length - 1;\n\t\t}\n\t\tif (firstChanged !== -1) {\n\t\t\tlastChanged = this.expandLastChangedForKittyImages(firstChanged, lastChanged);\n\t\t}\n\t\tconst appendStart = appendedLines && firstChanged === this.previousLines.length && firstChanged > 0;\n\n\t\t// No changes - but still need to update hardware cursor position if it moved\n\t\tif (firstChanged === -1) {\n\t\t\tthis.positionHardwareCursor(cursorPos, newLines.length);\n\t\t\tthis.previousViewportTop = prevViewportTop;\n\t\t\tthis.previousHeight = height;\n\t\t\treturn;\n\t\t}\n\n\t\t// All changes are in deleted lines (nothing to render, just clear)\n\t\tif (firstChanged >= newLines.length) {\n\t\t\tif (this.previousLines.length > newLines.length) {\n\t\t\t\tlet buffer = \"\\x1b[?2026h\";\n\t\t\t\tbuffer += this.deleteChangedKittyImages(firstChanged, lastChanged);\n\t\t\t\t// Move to end of new content (clamp to 0 for empty content)\n\t\t\t\tconst targetRow = Math.max(0, newLines.length - 1);\n\t\t\t\tif (targetRow < prevViewportTop) {\n\t\t\t\t\tlogRedraw(`deleted lines moved viewport up (${targetRow} < ${prevViewportTop})`);\n\t\t\t\t\tfullRender(true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst lineDiff = computeLineDiff(targetRow);\n\t\t\t\tif (lineDiff > 0) buffer += `\\x1b[${lineDiff}B`;\n\t\t\t\telse if (lineDiff < 0) buffer += `\\x1b[${-lineDiff}A`;\n\t\t\t\tbuffer += \"\\r\";\n\t\t\t\t// Clear extra lines without scrolling\n\t\t\t\tconst extraLines = this.previousLines.length - newLines.length;\n\t\t\t\tif (extraLines > height) {\n\t\t\t\t\tlogRedraw(`extraLines > height (${extraLines} > ${height})`);\n\t\t\t\t\tfullRender(true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (extraLines > 0) {\n\t\t\t\t\tbuffer += \"\\x1b[1B\";\n\t\t\t\t}\n\t\t\t\tfor (let i = 0; i < extraLines; i++) {\n\t\t\t\t\tbuffer += \"\\r\\x1b[2K\";\n\t\t\t\t\tif (i < extraLines - 1) buffer += \"\\x1b[1B\";\n\t\t\t\t}\n\t\t\t\tif (extraLines > 0) {\n\t\t\t\t\tbuffer += `\\x1b[${extraLines}A`;\n\t\t\t\t}\n\t\t\t\tbuffer += \"\\x1b[?2026l\";\n\t\t\t\tthis.terminal.write(buffer);\n\t\t\t\tthis.cursorRow = targetRow;\n\t\t\t\tthis.hardwareCursorRow = targetRow;\n\t\t\t}\n\t\t\tthis.positionHardwareCursor(cursorPos, newLines.length);\n\t\t\tthis.previousLines = newLines;\n\t\t\tthis.previousKittyImageIds = this.collectKittyImageIds(newLines);\n\t\t\tthis.previousWidth = width;\n\t\t\tthis.previousHeight = height;\n\t\t\tthis.previousViewportTop = prevViewportTop;\n\t\t\treturn;\n\t\t}\n\n\t\t// Differential rendering can only touch what was actually visible.\n\t\t// If the first changed line is above the previous viewport, we need a full redraw.\n\t\tif (firstChanged < prevViewportTop) {\n\t\t\tlogRedraw(`firstChanged < viewportTop (${firstChanged} < ${prevViewportTop})`);\n\t\t\tfullRender(true);\n\t\t\treturn;\n\t\t}\n\n\t\t// Render from first changed line to end\n\t\t// Build buffer with all updates wrapped in synchronized output\n\t\tlet buffer = \"\\x1b[?2026h\"; // Begin synchronized output\n\t\tbuffer += this.deleteChangedKittyImages(firstChanged, lastChanged);\n\t\tconst prevViewportBottom = prevViewportTop + height - 1;\n\t\tconst moveTargetRow = appendStart ? firstChanged - 1 : firstChanged;\n\t\tif (moveTargetRow > prevViewportBottom) {\n\t\t\tconst currentScreenRow = Math.max(0, Math.min(height - 1, hardwareCursorRow - prevViewportTop));\n\t\t\tconst moveToBottom = height - 1 - currentScreenRow;\n\t\t\tif (moveToBottom > 0) {\n\t\t\t\tbuffer += `\\x1b[${moveToBottom}B`;\n\t\t\t}\n\t\t\tconst scroll = moveTargetRow - prevViewportBottom;\n\t\t\tbuffer += \"\\r\\n\".repeat(scroll);\n\t\t\tprevViewportTop += scroll;\n\t\t\tviewportTop += scroll;\n\t\t\thardwareCursorRow = moveTargetRow;\n\t\t}\n\n\t\t// Move cursor to first changed line (use hardwareCursorRow for actual position)\n\t\tconst lineDiff = computeLineDiff(moveTargetRow);\n\t\tif (lineDiff > 0) {\n\t\t\tbuffer += `\\x1b[${lineDiff}B`; // Move down\n\t\t} else if (lineDiff < 0) {\n\t\t\tbuffer += `\\x1b[${-lineDiff}A`; // Move up\n\t\t}\n\n\t\tbuffer += appendStart ? \"\\r\\n\" : \"\\r\"; // Move to column 0\n\n\t\t// Only render changed lines (firstChanged to lastChanged), not all lines to end\n\t\t// This reduces flicker when only a single line changes (e.g., spinner animation)\n\t\tconst renderEnd = Math.min(lastChanged, newLines.length - 1);\n\t\tfor (let i = firstChanged; i <= renderEnd; i++) {\n\t\t\tif (i > firstChanged) buffer += \"\\r\\n\";\n\t\t\tbuffer += \"\\x1b[2K\"; // Clear current line\n\t\t\tconst line = newLines[i];\n\t\t\tconst isImage = isImageLine(line);\n\t\t\tif (!isImage && visibleWidth(line) > width) {\n\t\t\t\t// Log all lines to crash file for debugging\n\t\t\t\tconst crashLogPath = path.join(os.homedir(), \".pi\", \"agent\", \"pi-crash.log\");\n\t\t\t\tconst crashData = [\n\t\t\t\t\t`Crash at ${new Date().toISOString()}`,\n\t\t\t\t\t`Terminal width: ${width}`,\n\t\t\t\t\t`Line ${i} visible width: ${visibleWidth(line)}`,\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"=== All rendered lines ===\",\n\t\t\t\t\t...newLines.map((l, idx) => `[${idx}] (w=${visibleWidth(l)}) ${l}`),\n\t\t\t\t\t\"\",\n\t\t\t\t].join(\"\\n\");\n\t\t\t\tfs.mkdirSync(path.dirname(crashLogPath), { recursive: true });\n\t\t\t\tfs.writeFileSync(crashLogPath, crashData);\n\n\t\t\t\t// Clean up terminal state before throwing\n\t\t\t\tthis.stop();\n\n\t\t\t\tconst errorMsg = [\n\t\t\t\t\t`Rendered line ${i} exceeds terminal width (${visibleWidth(line)} > ${width}).`,\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"This is likely caused by a custom TUI component not truncating its output.\",\n\t\t\t\t\t\"Use visibleWidth() to measure and truncateToWidth() to truncate lines.\",\n\t\t\t\t\t\"\",\n\t\t\t\t\t`Debug log written to: ${crashLogPath}`,\n\t\t\t\t].join(\"\\n\");\n\t\t\t\tthrow new Error(errorMsg);\n\t\t\t}\n\t\t\tbuffer += line;\n\t\t}\n\n\t\t// Track where cursor ended up after rendering\n\t\tlet finalCursorRow = renderEnd;\n\n\t\t// If we had more lines before, clear them and move cursor back\n\t\tif (this.previousLines.length > newLines.length) {\n\t\t\t// Move to end of new content first if we stopped before it\n\t\t\tif (renderEnd < newLines.length - 1) {\n\t\t\t\tconst moveDown = newLines.length - 1 - renderEnd;\n\t\t\t\tbuffer += `\\x1b[${moveDown}B`;\n\t\t\t\tfinalCursorRow = newLines.length - 1;\n\t\t\t}\n\t\t\tconst extraLines = this.previousLines.length - newLines.length;\n\t\t\tfor (let i = newLines.length; i < this.previousLines.length; i++) {\n\t\t\t\tbuffer += \"\\r\\n\\x1b[2K\";\n\t\t\t}\n\t\t\t// Move cursor back to end of new content\n\t\t\tbuffer += `\\x1b[${extraLines}A`;\n\t\t}\n\n\t\tbuffer += \"\\x1b[?2026l\"; // End synchronized output\n\n\t\tif (process.env.PI_TUI_DEBUG === \"1\") {\n\t\t\tconst debugDir = \"/tmp/tui\";\n\t\t\tfs.mkdirSync(debugDir, { recursive: true });\n\t\t\tconst debugPath = path.join(debugDir, `render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`);\n\t\t\tconst debugData = [\n\t\t\t\t`firstChanged: ${firstChanged}`,\n\t\t\t\t`viewportTop: ${viewportTop}`,\n\t\t\t\t`cursorRow: ${this.cursorRow}`,\n\t\t\t\t`height: ${height}`,\n\t\t\t\t`lineDiff: ${lineDiff}`,\n\t\t\t\t`hardwareCursorRow: ${hardwareCursorRow}`,\n\t\t\t\t`renderEnd: ${renderEnd}`,\n\t\t\t\t`finalCursorRow: ${finalCursorRow}`,\n\t\t\t\t`cursorPos: ${JSON.stringify(cursorPos)}`,\n\t\t\t\t`newLines.length: ${newLines.length}`,\n\t\t\t\t`previousLines.length: ${this.previousLines.length}`,\n\t\t\t\t\"\",\n\t\t\t\t\"=== newLines ===\",\n\t\t\t\tJSON.stringify(newLines, null, 2),\n\t\t\t\t\"\",\n\t\t\t\t\"=== previousLines ===\",\n\t\t\t\tJSON.stringify(this.previousLines, null, 2),\n\t\t\t\t\"\",\n\t\t\t\t\"=== buffer ===\",\n\t\t\t\tJSON.stringify(buffer),\n\t\t\t].join(\"\\n\");\n\t\t\tfs.writeFileSync(debugPath, debugData);\n\t\t}\n\n\t\t// Write entire buffer at once\n\t\tthis.terminal.write(buffer);\n\n\t\t// Track cursor position for next render\n\t\t// cursorRow tracks end of content (for viewport calculation)\n\t\t// hardwareCursorRow tracks actual terminal cursor position (for movement)\n\t\tthis.cursorRow = Math.max(0, newLines.length - 1);\n\t\tthis.hardwareCursorRow = finalCursorRow;\n\t\t// Track terminal's working area (grows but doesn't shrink unless cleared)\n\t\tthis.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);\n\t\tthis.previousViewportTop = Math.max(prevViewportTop, finalCursorRow - height + 1);\n\n\t\t// Position hardware cursor for IME\n\t\tthis.positionHardwareCursor(cursorPos, newLines.length);\n\n\t\tthis.previousLines = newLines;\n\t\tthis.previousKittyImageIds = this.collectKittyImageIds(newLines);\n\t\tthis.previousWidth = width;\n\t\tthis.previousHeight = height;\n\t}\n\n\t/**\n\t * Position the hardware cursor for IME candidate window.\n\t * @param cursorPos The cursor position extracted from rendered output, or null\n\t * @param totalLines Total number of rendered lines\n\t */\n\tprivate positionHardwareCursor(cursorPos: { row: number; col: number } | null, totalLines: number): void {\n\t\tif (!cursorPos || totalLines <= 0) {\n\t\t\tthis.terminal.hideCursor();\n\t\t\treturn;\n\t\t}\n\n\t\t// Clamp cursor position to valid range\n\t\tconst targetRow = Math.max(0, Math.min(cursorPos.row, totalLines - 1));\n\t\tconst targetCol = Math.max(0, cursorPos.col);\n\n\t\t// Move cursor from current position to target\n\t\tconst rowDelta = targetRow - this.hardwareCursorRow;\n\t\tlet buffer = \"\";\n\t\tif (rowDelta > 0) {\n\t\t\tbuffer += `\\x1b[${rowDelta}B`; // Move down\n\t\t} else if (rowDelta < 0) {\n\t\t\tbuffer += `\\x1b[${-rowDelta}A`; // Move up\n\t\t}\n\t\t// Move to absolute column (1-indexed)\n\t\tbuffer += `\\x1b[${targetCol + 1}G`;\n\n\t\tif (buffer) {\n\t\t\tthis.terminal.write(buffer);\n\t\t}\n\n\t\tthis.hardwareCursorRow = targetRow;\n\t\tif (this.showHardwareCursor) {\n\t\t\tthis.terminal.showCursor();\n\t\t} else {\n\t\t\tthis.terminal.hideCursor();\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"tui.d.ts","sourceRoot":"","sources":["../src/tui.ts"],"names":[],"mappings":"AAAA;;GAEG;AAMH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAE9C,OAAO,EAA2E,YAAY,EAAE,MAAM,YAAY,CAAC;AAEnH;;GAEG;AACH,MAAM,WAAW,SAAS;IACzB;;;;OAIG;IACH,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAEhC;;OAEG;IACH,WAAW,CAAC,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAEjC;;;OAGG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;IAE1B;;;OAGG;IACH,UAAU,IAAI,IAAI,CAAC;CACnB;AAED,MAAM,MAAM,sBAAsB,GAAG;IAAE,OAAO,CAAC,EAAE,OAAO,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAAC;AACtF,MAAM,MAAM,gBAAgB,G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C,oBAAoB;IAkB5B,OAAO,CAAC,gBAAgB;IAiBxB,OAAO,CAAC,gBAAgB;IAiBxB,OAAO,CAAC,wBAAwB;IAkBhC,OAAO,CAAC,wBAAwB;IAwBhC,yFAAyF;IACzF,SAAS,CAAC,iBAAiB,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,EAAE,CAW5F;IAED,SAAS,CAAC,eAAe,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CASnD;IAED,OAAO,CAAC,eAAe;IAUvB;;;;;;;OAOG;IACH,SAAS,CAAC,qBAAqB,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,MAAM,GAAG,sBAAsB,GAAG,IAAI,CAkB9F;CACD","sourcesContent":["/**\n * Minimal TUI implementation with differential rendering\n */\n\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { performance } from \"node:perf_hooks\";\nimport { isKeyRelease, matchesKey } from \"./keys.ts\";\nimport type { Terminal } from \"./terminal.ts\";\nimport { getCapabilities, isImageLine, setCellDimensions } from \"./terminal-image.ts\";\nimport { extractSegments, normalizeTerminalOutput, sliceByColumn, sliceWithWidth, visibleWidth } from \"./utils.ts\";\n\n/**\n * Component interface - all components must implement this\n */\nexport interface Component {\n\t/**\n\t * Render the component to lines for the given viewport width\n\t * @param width - Current viewport width\n\t * @returns Array of strings, each representing a line\n\t */\n\trender(width: number): string[];\n\n\t/**\n\t * Optional handler for keyboard input when component has focus\n\t */\n\thandleInput?(data: string): void;\n\n\t/**\n\t * If true, component receives key release events (Kitty protocol).\n\t * Default is false - release events are filtered out.\n\t */\n\twantsKeyRelease?: boolean;\n\n\t/**\n\t * Invalidate any cached rendering state.\n\t * Called when theme changes or when component needs to re-render from scratch.\n\t */\n\tinvalidate(): void;\n}\n\nexport type TuiInputListenerResult = { consume?: boolean; data?: string } | undefined;\nexport type TuiInputListener = (data: string) => TuiInputListenerResult;\n\n/**\n * Interface for components that can receive focus and display a hardware cursor.\n * When focused, the component should emit CURSOR_MARKER at the cursor position\n * in its render output. TUI will find this marker and position the hardware\n * cursor there for proper IME candidate window positioning.\n */\nexport interface Focusable {\n\t/** Set by TUI when focus changes. Component should emit CURSOR_MARKER when true. */\n\tfocused: boolean;\n}\n\n/** Type guard to check if a component implements Focusable */\nexport function isFocusable(component: Component | null): component is Component & Focusable {\n\treturn component !== null && \"focused\" in component;\n}\n\n/**\n * Cursor position marker - APC (Application Program Command) sequence.\n * This is a zero-width escape sequence that terminals ignore.\n * Components emit this at the cursor position when focused.\n * TUI finds and strips this marker, then positions the hardware cursor there.\n */\nexport const CURSOR_MARKER = \"\\x1b_pi:c\\x07\";\n\nexport { visibleWidth };\n\n/**\n * Anchor position for overlays\n */\nexport type OverlayAnchor =\n\t| \"center\"\n\t| \"top-left\"\n\t| \"top-right\"\n\t| \"bottom-left\"\n\t| \"bottom-right\"\n\t| \"top-center\"\n\t| \"bottom-center\"\n\t| \"left-center\"\n\t| \"right-center\";\n\n/**\n * Margin configuration for overlays\n */\nexport interface OverlayMargin {\n\ttop?: number;\n\tright?: number;\n\tbottom?: number;\n\tleft?: number;\n}\n\n/** Value that can be absolute (number) or percentage (string like \"50%\") */\nexport type SizeValue = number | `${number}%`;\n\n/** Parse a SizeValue into absolute value given a reference size */\nfunction parseSizeValue(value: SizeValue | undefined, referenceSize: number): number | undefined {\n\tif (value === undefined) return undefined;\n\tif (typeof value === \"number\") return value;\n\t// Parse percentage string like \"50%\"\n\tconst match = value.match(/^(\\d+(?:\\.\\d+)?)%$/);\n\tif (match) {\n\t\treturn Math.floor((referenceSize * parseFloat(match[1])) / 100);\n\t}\n\treturn undefined;\n}\n\n/**\n * Options for overlay positioning and sizing.\n * Values can be absolute numbers or percentage strings (e.g., \"50%\").\n */\nexport interface OverlayOptions {\n\t// === Sizing ===\n\t/** Width in columns, or percentage of terminal width (e.g., \"50%\") */\n\twidth?: SizeValue;\n\t/** Minimum width in columns */\n\tminWidth?: number;\n\t/** Maximum height in rows, or percentage of terminal height (e.g., \"50%\") */\n\tmaxHeight?: SizeValue;\n\n\t// === Positioning - anchor-based ===\n\t/** Anchor point for positioning (default: 'center') */\n\tanchor?: OverlayAnchor;\n\t/** Horizontal offset from anchor position (positive = right) */\n\toffsetX?: number;\n\t/** Vertical offset from anchor position (positive = down) */\n\toffsetY?: number;\n\n\t// === Positioning - percentage or absolute ===\n\t/** Row position: absolute number, or percentage (e.g., \"25%\" = 25% from top) */\n\trow?: SizeValue;\n\t/** Column position: absolute number, or percentage (e.g., \"50%\" = centered horizontally) */\n\tcol?: SizeValue;\n\n\t// === Margin from terminal edges ===\n\t/** Margin from terminal edges. Number applies to all sides. */\n\tmargin?: OverlayMargin | number;\n\n\t// === Visibility ===\n\t/**\n\t * Control overlay visibility based on terminal dimensions.\n\t * If provided, overlay is only rendered when this returns true.\n\t * Called each render cycle with current terminal dimensions.\n\t */\n\tvisible?: (termWidth: number, termHeight: number) => boolean;\n\t/** If true, don't capture keyboard focus when shown */\n\tnonCapturing?: boolean;\n}\n\n/** Options for {@link OverlayHandle.unfocus}. */\nexport interface OverlayUnfocusOptions {\n\t/** Explicit target to focus after releasing this overlay. */\n\ttarget: Component | null;\n}\n\n/**\n * Handle returned by showOverlay for controlling the overlay\n */\nexport interface OverlayHandle {\n\t/** Permanently remove the overlay (cannot be shown again) */\n\thide(): void;\n\t/** Temporarily hide or show the overlay */\n\tsetHidden(hidden: boolean): void;\n\t/** Check if overlay is temporarily hidden */\n\tisHidden(): boolean;\n\t/** Focus this overlay and bring it to the visual front */\n\tfocus(): void;\n\t/** Release focus to the next visible capturing overlay or previous target, or to an explicit target when provided */\n\tunfocus(options?: OverlayUnfocusOptions): void;\n\t/** Check if this overlay currently has focus */\n\tisFocused(): boolean;\n}\n\ntype OverlayStackEntry = {\n\tcomponent: Component;\n\toptions?: OverlayOptions;\n\tpreFocus: Component | null;\n\thidden: boolean;\n\tfocusOrder: number;\n\tvisible: boolean;\n};\n\ntype OverlayBlockedFocusResume = { status: \"restore-overlay\" } | { status: \"focus-target\"; target: Component | null };\ntype EligibleOverlayFocusRestoreState = { status: \"eligible\"; overlay: OverlayStackEntry };\ntype BlockedOverlayFocusRestoreState = {\n\tstatus: \"blocked\";\n\toverlay: OverlayStackEntry;\n\tblockedBy: Component;\n\tresume: OverlayBlockedFocusResume;\n};\ntype ActiveOverlayFocusRestoreState = EligibleOverlayFocusRestoreState | BlockedOverlayFocusRestoreState;\ntype OverlayFocusRestoreState = { status: \"inactive\" } | ActiveOverlayFocusRestoreState;\ntype OverlayFocusRestorePolicy = \"clear\" | \"preserve\";\n\ninterface FocusTransitionRequest {\n\tcomponent: Component | null;\n\toverlayFocusRestore: OverlayFocusRestorePolicy;\n}\n\ninterface ResolvedOverlayLayout {\n\twidth: number;\n\trow: number;\n\tcol: number;\n\tmaxHeight: number | undefined;\n}\n\ninterface RenderedOverlay {\n\tlines: string[];\n\trow: number;\n\tcol: number;\n\twidth: number;\n}\n\ninterface OverlayRenderPlan {\n\toverlays: RenderedOverlay[];\n\tminimumLineCount: number;\n}\n\ninterface OverlayLayoutBounds {\n\tmarginTop: number;\n\tmarginRight: number;\n\tmarginBottom: number;\n\tmarginLeft: number;\n\tavailableWidth: number;\n\tavailableHeight: number;\n}\n\nexport interface RenderedCursorPosition {\n\trow: number;\n\tcol: number;\n}\n/**\n * Container - a component that contains other components\n */\nexport class Container implements Component {\n\tchildren: Component[] = [];\n\n\taddChild(component: Component): void {\n\t\tthis.children.push(component);\n\t}\n\n\tremoveChild(component: Component): void {\n\t\tconst index = this.children.indexOf(component);\n\t\tif (index !== -1) {\n\t\t\tthis.children.splice(index, 1);\n\t\t}\n\t}\n\n\tclear(): void {\n\t\tthis.children = [];\n\t}\n\n\tinvalidate(): void {\n\t\tfor (const child of this.children) {\n\t\t\tchild.invalidate?.();\n\t\t}\n\t}\n\n\trender(width: number): string[] {\n\t\tconst lines: string[] = [];\n\t\tfor (const child of this.children) {\n\t\t\tconst childLines = child.render(width);\n\t\t\tfor (const line of childLines) {\n\t\t\t\tlines.push(line);\n\t\t\t}\n\t\t}\n\t\treturn lines;\n\t}\n}\n\n/**\n * TUI - Main class for managing terminal UI with differential rendering\n */\nconst SEGMENT_RESET = \"\\x1b[0m\\x1b]8;;\\x07\";\n\n/** Composite overlay content into a terminal line at a fixed column. */\nexport function compositeTuiLine(\n\tbaseLine: string,\n\toverlayLine: string,\n\tstartCol: number,\n\toverlayWidth: number,\n\ttotalWidth: number,\n): string {\n\tif (isImageLine(baseLine)) return baseLine;\n\n\tconst afterStart = startCol + overlayWidth;\n\tconst base = extractSegments(baseLine, startCol, afterStart, totalWidth - afterStart, true);\n\tconst overlay = sliceWithWidth(overlayLine, 0, overlayWidth, true);\n\tconst beforePad = Math.max(0, startCol - base.beforeWidth);\n\tconst overlayPad = Math.max(0, overlayWidth - overlay.width);\n\tconst actualBeforeWidth = Math.max(startCol, base.beforeWidth);\n\tconst actualOverlayWidth = Math.max(overlayWidth, overlay.width);\n\tconst afterTarget = Math.max(0, totalWidth - actualBeforeWidth - actualOverlayWidth);\n\tconst afterPad = Math.max(0, afterTarget - base.afterWidth);\n\tconst result =\n\t\tbase.before +\n\t\t\" \".repeat(beforePad) +\n\t\tSEGMENT_RESET +\n\t\toverlay.text +\n\t\t\" \".repeat(overlayPad) +\n\t\tSEGMENT_RESET +\n\t\tbase.after +\n\t\t\" \".repeat(afterPad);\n\n\treturn visibleWidth(result) <= totalWidth ? result : sliceByColumn(result, 0, totalWidth, true);\n}\n\nexport type TuiMode = \"regular\" | \"fullscreen\";\n\nexport interface TuiStopOptions {\n\t/** Restore the previous main buffer without replaying renderer content. */\n\tpreserveScreen?: boolean;\n}\n\nexport interface TUI extends Component {\n\treadonly mode: TuiMode;\n\tchildren: Component[];\n\tterminal: Terminal;\n\tonDebug?: () => void;\n\treadonly fullRedraws: number;\n\treadonly hasOverlayEntries: boolean;\n\taddChild(component: Component): void;\n\tremoveChild(component: Component): void;\n\tclear(): void;\n\tgetShowHardwareCursor(): boolean;\n\tsetShowHardwareCursor(enabled: boolean): void;\n\tgetClearOnShrink(): boolean;\n\tsetClearOnShrink(enabled: boolean): void;\n\tgetFocusedComponent(): Component | null;\n\tsetFocus(component: Component | null): void;\n\tshowOverlay(component: Component, options?: OverlayOptions): OverlayHandle;\n\thideOverlay(): void;\n\thasOverlay(): boolean;\n\tstart(): void;\n\tstop(options?: TuiStopOptions): void;\n\trenderNow(force?: boolean): void;\n\trequestRender(force?: boolean): void;\n\taddInputListener(listener: TuiInputListener): () => void;\n\tremoveInputListener(listener: TuiInputListener): void;\n}\n\nexport const VIEWPORT_TUI = Symbol.for(\"@fleetagent/pi-tui/viewport\");\n\nexport interface ViewportTUI extends TUI {\n\treadonly [VIEWPORT_TUI]: true;\n\tsetLayoutRoot(component: Component | undefined): void;\n}\n\nexport function isViewportTUI(tui: TUI): tui is ViewportTUI {\n\treturn (tui as Partial<ViewportTUI>)[VIEWPORT_TUI] === true;\n}\n\nexport abstract class TuiBase extends Container implements TUI {\n\tabstract readonly mode: TuiMode;\n\tpublic terminal: Terminal;\n\tprivate focusedComponent: Component | null = null;\n\tprivate inputListeners = new Set<TuiInputListener>();\n\n\t/** Global callback for debug key (Shift+Ctrl+D). Called before input is forwarded to focused component. */\n\tpublic onDebug?: () => void;\n\tprivate renderRequested = false;\n\tprivate immediateRenderScheduled = false;\n\tprivate renderTimer: NodeJS.Timeout | undefined;\n\tprivate lastRenderAt = 0;\n\tprivate static readonly MIN_RENDER_INTERVAL_MS = 16;\n\tprivate showHardwareCursor = process.env.PI_HARDWARE_CURSOR === \"1\";\n\tprivate clearOnShrink = process.env.PI_CLEAR_ON_SHRINK === \"1\";\n\tprotected fullRedrawCount = 0;\n\tprotected stopped = false;\n\tprotected readonly logDirectory: string;\n\n\t// Overlay stack for modal components rendered on top of base content\n\tprivate focusOrderCounter = 0;\n\tprivate overlayStack: OverlayStackEntry[] = [];\n\n\tget hasOverlayEntries(): boolean {\n\t\treturn this.overlayStack.length > 0;\n\t}\n\tprivate overlayFocusRestore: OverlayFocusRestoreState = { status: \"inactive\" };\n\n\tconstructor(terminal: Terminal, showHardwareCursor?: boolean, logDirectory?: string) {\n\t\tsuper();\n\t\tthis.terminal = terminal;\n\t\tthis.logDirectory = logDirectory ?? process.env.PI_CODING_AGENT_DIR ?? path.join(os.homedir(), \".pi\", \"agent\");\n\t\tif (showHardwareCursor !== undefined) {\n\t\t\tthis.showHardwareCursor = showHardwareCursor;\n\t\t}\n\t}\n\n\tprotected abstract doRender(): void;\n\n\tprotected resetRenderState(): void {}\n\n\tprotected beforeTerminalStart(): void {}\n\n\tprotected afterTerminalStart(): void {}\n\n\tprotected onTerminalResize(): void {}\n\n\tprotected onOverlayStackChanged(): void {}\n\n\tprotected beforeTerminalStop(_options?: TuiStopOptions): void {}\n\n\tprotected afterTerminalStop(_options?: TuiStopOptions): void {}\n\n\tget fullRedraws(): number {\n\t\treturn this.fullRedrawCount;\n\t}\n\n\tgetShowHardwareCursor(): boolean {\n\t\treturn this.showHardwareCursor;\n\t}\n\n\tsetShowHardwareCursor(enabled: boolean): void {\n\t\tif (this.showHardwareCursor === enabled) return;\n\t\tthis.showHardwareCursor = enabled;\n\t\tif (!enabled) {\n\t\t\tthis.terminal.hideCursor();\n\t\t}\n\t\tthis.requestRender();\n\t}\n\n\tgetClearOnShrink(): boolean {\n\t\treturn this.clearOnShrink;\n\t}\n\n\t/**\n\t * Set whether to trigger full re-render when content shrinks.\n\t * When true (default), empty rows are cleared when content shrinks.\n\t * When false, empty rows remain (reduces redraws on slower terminals).\n\t */\n\tsetClearOnShrink(enabled: boolean): void {\n\t\tthis.clearOnShrink = enabled;\n\t}\n\n\tgetFocusedComponent(): Component | null {\n\t\treturn this.focusedComponent;\n\t}\n\n\tsetFocus(component: Component | null): void {\n\t\tthis.setFocusInternal({ component, overlayFocusRestore: \"clear\" });\n\t}\n\n\tprivate resolveNonOverlayFocus(\n\t\tnextFocus: Component,\n\t\tpreviousFocus: Component | null,\n\t\trestoreState: OverlayFocusRestoreState,\n\t): Component | null {\n\t\tif (restoreState.status === \"blocked\" && restoreState.blockedBy === previousFocus) {\n\t\t\tif (restoreState.resume.status === \"focus-target\" || !this.isComponentMounted(restoreState.blockedBy)) {\n\t\t\t\treturn this.resolveBlockedOverlayFocusResume(restoreState);\n\t\t\t}\n\t\t\tthis.overlayFocusRestore = {\n\t\t\t\tstatus: \"blocked\",\n\t\t\t\toverlay: restoreState.overlay,\n\t\t\t\tblockedBy: nextFocus,\n\t\t\t\tresume: restoreState.resume,\n\t\t\t};\n\t\t\treturn nextFocus;\n\t\t}\n\n\t\tconst previousFocusedOverlay = previousFocus\n\t\t\t? this.overlayStack.find((entry) => entry.component === previousFocus && this.isOverlayVisible(entry))\n\t\t\t: undefined;\n\t\tif (\n\t\t\tpreviousFocusedOverlay &&\n\t\t\trestoreState.status !== \"inactive\" &&\n\t\t\trestoreState.overlay === previousFocusedOverlay &&\n\t\t\t!this.isOverlayFocusAncestor(previousFocusedOverlay, nextFocus)\n\t\t) {\n\t\t\tthis.overlayFocusRestore = {\n\t\t\t\tstatus: \"blocked\",\n\t\t\t\toverlay: previousFocusedOverlay,\n\t\t\t\tblockedBy: nextFocus,\n\t\t\t\tresume: { status: \"restore-overlay\" },\n\t\t\t};\n\t\t}\n\t\treturn nextFocus;\n\t}\n\n\tprivate resolveNullFocus(\n\t\tpreviousFocus: Component | null,\n\t\trestoreState: OverlayFocusRestoreState,\n\t\toverlayFocusRestore: OverlayFocusRestorePolicy,\n\t): Component | null {\n\t\tif (restoreState.status === \"blocked\" && restoreState.blockedBy === previousFocus) {\n\t\t\treturn this.resolveBlockedOverlayFocusResume(restoreState);\n\t\t}\n\t\tif (overlayFocusRestore === \"clear\") this.clearOverlayFocusRestore();\n\t\treturn null;\n\t}\n\n\tprivate resolveFocusTarget(\n\t\tcomponent: Component | null,\n\t\toverlayFocusRestore: OverlayFocusRestorePolicy,\n\t): Component | null {\n\t\tconst previousFocus = this.focusedComponent;\n\t\tconst restoreState = this.getVisibleOverlayFocusRestore();\n\t\tif (component === null) return this.resolveNullFocus(previousFocus, restoreState, overlayFocusRestore);\n\t\tconst isOverlay = this.overlayStack.some((entry) => entry.component === component);\n\t\tif (isOverlay) return component;\n\t\treturn this.resolveNonOverlayFocus(component, previousFocus, restoreState);\n\t}\n\n\tprivate applyFocus(nextFocus: Component | null): void {\n\t\tif (isFocusable(this.focusedComponent)) this.focusedComponent.focused = false;\n\t\tthis.focusedComponent = nextFocus;\n\t\tif (isFocusable(nextFocus)) nextFocus.focused = true;\n\n\t\tconst focusedOverlay = nextFocus\n\t\t\t? this.overlayStack.find((entry) => entry.component === nextFocus && this.isOverlayVisible(entry))\n\t\t\t: undefined;\n\t\tif (focusedOverlay) this.overlayFocusRestore = { status: \"eligible\", overlay: focusedOverlay };\n\t}\n\n\tprivate setFocusInternal({ component, overlayFocusRestore }: FocusTransitionRequest): void {\n\t\tconst nextFocus = this.resolveFocusTarget(component, overlayFocusRestore);\n\t\tthis.applyFocus(nextFocus);\n\t}\n\n\tprivate clearOverlayFocusRestore(): void {\n\t\tthis.overlayFocusRestore = { status: \"inactive\" };\n\t}\n\n\tprivate clearOverlayFocusRestoreFor(overlay: OverlayStackEntry): void {\n\t\tif (this.overlayFocusRestore.status !== \"inactive\" && this.overlayFocusRestore.overlay === overlay) {\n\t\t\tthis.clearOverlayFocusRestore();\n\t\t}\n\t}\n\n\tprivate resolveBlockedOverlayFocusResume(restoreState: BlockedOverlayFocusRestoreState): Component | null {\n\t\tif (restoreState.resume.status === \"restore-overlay\") return restoreState.overlay.component;\n\t\tthis.clearOverlayFocusRestore();\n\t\treturn restoreState.resume.target;\n\t}\n\n\tprivate getVisibleOverlayFocusRestore(): OverlayFocusRestoreState {\n\t\tconst restoreState = this.overlayFocusRestore;\n\t\tif (restoreState.status === \"inactive\") return restoreState;\n\t\tif (!this.overlayStack.includes(restoreState.overlay) || !this.isOverlayVisible(restoreState.overlay)) {\n\t\t\treturn { status: \"inactive\" };\n\t\t}\n\t\treturn restoreState;\n\t}\n\n\tprivate isOverlayFocusAncestor(entry: OverlayStackEntry, component: Component): boolean {\n\t\tconst preFocusByComponent = new Map<Component, Component | null>();\n\t\tfor (const overlay of this.overlayStack) {\n\t\t\tif (!preFocusByComponent.has(overlay.component)) {\n\t\t\t\tpreFocusByComponent.set(overlay.component, overlay.preFocus);\n\t\t\t}\n\t\t}\n\n\t\tconst visited = new Set<Component>();\n\t\tlet current = entry.preFocus;\n\t\twhile (current && !visited.has(current)) {\n\t\t\tvisited.add(current);\n\t\t\tif (current === component) return true;\n\t\t\tcurrent = preFocusByComponent.get(current) ?? null;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate retargetOverlayPreFocus(removed: OverlayStackEntry): void {\n\t\tfor (const overlay of this.overlayStack) {\n\t\t\tif (overlay !== removed && overlay.preFocus === removed.component) {\n\t\t\t\toverlay.preFocus = removed.preFocus;\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected getMountedRoots(): readonly Component[] {\n\t\treturn this.children;\n\t}\n\n\tprivate isComponentMounted(component: Component): boolean {\n\t\treturn this.getMountedRoots().some((child) => this.containsComponent(child, component));\n\t}\n\n\tprivate containsComponent(root: Component, target: Component): boolean {\n\t\tif (root === target) return true;\n\t\tif (!(root instanceof Container)) return false;\n\t\treturn root.children.some((child) => this.containsComponent(child, target));\n\t}\n\n\tprivate applyBlockedOverlayUnfocus(\n\t\tentry: OverlayStackEntry,\n\t\trestoreState: OverlayFocusRestoreState,\n\t\toptions: OverlayUnfocusOptions | undefined,\n\t): boolean {\n\t\tif (\n\t\t\trestoreState.status !== \"blocked\" ||\n\t\t\trestoreState.overlay !== entry ||\n\t\t\tthis.focusedComponent !== restoreState.blockedBy\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\tif (options) {\n\t\t\tthis.overlayFocusRestore = {\n\t\t\t\tstatus: \"blocked\",\n\t\t\t\toverlay: entry,\n\t\t\t\tblockedBy: restoreState.blockedBy,\n\t\t\t\tresume: { status: \"focus-target\", target: options.target },\n\t\t\t};\n\t\t} else {\n\t\t\tthis.clearOverlayFocusRestore();\n\t\t}\n\t\tthis.requestRender();\n\t\treturn true;\n\t}\n\n\tprivate unfocusOverlay(entry: OverlayStackEntry, options: OverlayUnfocusOptions | undefined): void {\n\t\tconst isFocused = this.focusedComponent === entry.component;\n\t\tconst restoreState = this.overlayFocusRestore;\n\t\tconst hasPendingRestore = restoreState.status !== \"inactive\" && restoreState.overlay === entry;\n\t\tif (!isFocused && !hasPendingRestore) return;\n\t\tif (this.applyBlockedOverlayUnfocus(entry, restoreState, options)) return;\n\n\t\tthis.clearOverlayFocusRestoreFor(entry);\n\t\tif (isFocused || options) {\n\t\t\tconst topVisible = this.getTopmostVisibleOverlay();\n\t\t\tconst fallbackTarget = topVisible && topVisible !== entry ? topVisible.component : entry.preFocus;\n\t\t\tthis.setFocus(options ? options.target : fallbackTarget);\n\t\t}\n\t\tthis.requestRender();\n\t}\n\n\t/**\n\t * Show an overlay component with configurable positioning and sizing.\n\t * Returns a handle to control the overlay's visibility.\n\t */\n\tshowOverlay(component: Component, options?: OverlayOptions): OverlayHandle {\n\t\tconst entry: OverlayStackEntry = {\n\t\t\tcomponent,\n\t\t\t...(options === undefined ? {} : { options }),\n\t\t\tpreFocus: this.focusedComponent,\n\t\t\thidden: false,\n\t\t\tfocusOrder: ++this.focusOrderCounter,\n\t\t\tvisible: false,\n\t\t};\n\t\tthis.overlayStack.push(entry);\n\t\tentry.visible = this.isOverlayVisible(entry);\n\t\tthis.onOverlayStackChanged();\n\t\t// Only focus if overlay is actually visible\n\t\tif (!options?.nonCapturing && this.isOverlayVisible(entry)) {\n\t\t\tthis.setFocus(component);\n\t\t}\n\t\tthis.terminal.hideCursor();\n\t\tthis.requestRender();\n\n\t\t// Return handle for controlling this overlay\n\t\treturn {\n\t\t\thide: () => {\n\t\t\t\tconst index = this.overlayStack.indexOf(entry);\n\t\t\t\tif (index !== -1) {\n\t\t\t\t\tthis.clearOverlayFocusRestoreFor(entry);\n\t\t\t\t\tthis.retargetOverlayPreFocus(entry);\n\t\t\t\t\tthis.overlayStack.splice(index, 1);\n\t\t\t\t\tthis.onOverlayStackChanged();\n\t\t\t\t\t// Restore focus if this overlay had focus\n\t\t\t\t\tif (this.focusedComponent === component) {\n\t\t\t\t\t\tconst topVisible = this.getTopmostVisibleOverlay();\n\t\t\t\t\t\tthis.setFocus(topVisible?.component ?? entry.preFocus);\n\t\t\t\t\t}\n\t\t\t\t\tif (this.overlayStack.length === 0) this.terminal.hideCursor();\n\t\t\t\t\tthis.requestRender();\n\t\t\t\t}\n\t\t\t},\n\t\t\tsetHidden: (hidden: boolean) => {\n\t\t\t\tif (entry.hidden === hidden) return;\n\t\t\t\tentry.hidden = hidden;\n\t\t\t\tentry.visible = this.isOverlayVisible(entry);\n\t\t\t\t// Update focus when hiding/showing\n\t\t\t\tif (hidden) {\n\t\t\t\t\tthis.clearOverlayFocusRestoreFor(entry);\n\t\t\t\t\t// If this overlay had focus, move focus to next visible or preFocus\n\t\t\t\t\tif (this.focusedComponent === component) {\n\t\t\t\t\t\tconst topVisible = this.getTopmostVisibleOverlay();\n\t\t\t\t\t\tthis.setFocus(topVisible?.component ?? entry.preFocus);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Restore focus to this overlay when showing (if it's actually visible)\n\t\t\t\t\tif (!options?.nonCapturing && this.isOverlayVisible(entry)) {\n\t\t\t\t\t\tentry.focusOrder = ++this.focusOrderCounter;\n\t\t\t\t\t\tthis.setFocus(component);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.onOverlayStackChanged();\n\t\t\t\tthis.requestRender();\n\t\t\t},\n\t\t\tisHidden: () => entry.hidden,\n\t\t\tfocus: () => {\n\t\t\t\tif (!this.overlayStack.includes(entry) || !this.isOverlayVisible(entry)) return;\n\t\t\t\tentry.focusOrder = ++this.focusOrderCounter;\n\t\t\t\tthis.setFocus(component);\n\t\t\t\tthis.requestRender();\n\t\t\t},\n\t\t\tunfocus: (unfocusOptions) => this.unfocusOverlay(entry, unfocusOptions),\n\t\t\tisFocused: () => this.focusedComponent === component,\n\t\t};\n\t}\n\n\t/** Hide the topmost overlay and restore previous focus. */\n\thideOverlay(): void {\n\t\tconst overlay = this.overlayStack[this.overlayStack.length - 1];\n\t\tif (!overlay) return;\n\t\tthis.clearOverlayFocusRestoreFor(overlay);\n\t\tthis.retargetOverlayPreFocus(overlay);\n\t\tthis.overlayStack.pop();\n\t\tthis.onOverlayStackChanged();\n\t\tif (this.focusedComponent === overlay.component) {\n\t\t\t// Find topmost visible overlay, or fall back to preFocus\n\t\t\tconst topVisible = this.getTopmostVisibleOverlay();\n\t\t\tthis.setFocus(topVisible?.component ?? overlay.preFocus);\n\t\t}\n\t\tif (this.overlayStack.length === 0) this.terminal.hideCursor();\n\t\tthis.requestRender();\n\t}\n\n\t/** Check if there are any visible overlays */\n\thasOverlay(): boolean {\n\t\treturn this.overlayStack.some((o) => this.isOverlayVisible(o));\n\t}\n\n\tprotected hasCapturingOverlay(): boolean {\n\t\treturn this.overlayStack.some((o) => !o.options?.nonCapturing && this.isOverlayVisible(o));\n\t}\n\n\t/** Check if an overlay entry is currently visible */\n\tprivate isOverlayVisible(entry: OverlayStackEntry): boolean {\n\t\tif (entry.hidden) return false;\n\t\tif (entry.options?.visible) {\n\t\t\treturn entry.options.visible(this.terminal.columns, this.terminal.rows);\n\t\t}\n\t\treturn true;\n\t}\n\n\t/** Find the visual-frontmost visible capturing overlay, if any */\n\tprivate getTopmostVisibleOverlay(): OverlayStackEntry | undefined {\n\t\tlet topmost: OverlayStackEntry | undefined;\n\t\tfor (const overlay of this.overlayStack) {\n\t\t\tif (overlay.options?.nonCapturing || !this.isOverlayVisible(overlay)) continue;\n\t\t\tif (!topmost || overlay.focusOrder > topmost.focusOrder) {\n\t\t\t\ttopmost = overlay;\n\t\t\t}\n\t\t}\n\t\treturn topmost;\n\t}\n\n\tprivate refreshOverlayVisibility(): OverlayStackEntry | undefined {\n\t\tlet newlyVisible: OverlayStackEntry | undefined;\n\t\tfor (const overlay of this.overlayStack) {\n\t\t\tconst visible = this.isOverlayVisible(overlay);\n\t\t\tif (visible && !overlay.visible && !overlay.options?.nonCapturing) {\n\t\t\t\tif (!newlyVisible || overlay.focusOrder > newlyVisible.focusOrder) newlyVisible = overlay;\n\t\t\t}\n\t\t\toverlay.visible = visible;\n\t\t}\n\t\treturn newlyVisible;\n\t}\n\n\tprivate retargetFocusFromHiddenOverlay(): void {\n\t\tconst focusedOverlay = this.overlayStack.find((overlay) => overlay.component === this.focusedComponent);\n\t\tif (!focusedOverlay || this.isOverlayVisible(focusedOverlay)) return;\n\t\tconst topVisible = this.getTopmostVisibleOverlay();\n\t\tif (topVisible) {\n\t\t\tthis.setFocus(topVisible.component);\n\t\t\treturn;\n\t\t}\n\t\tthis.setFocusInternal({ component: focusedOverlay.preFocus, overlayFocusRestore: \"preserve\" });\n\t}\n\n\tprivate focusNewlyVisibleOverlay(newlyVisible: OverlayStackEntry | undefined): void {\n\t\tif (!newlyVisible) return;\n\t\tconst currentFocusedOverlay = this.overlayStack.find(\n\t\t\t(overlay) => overlay.component === this.focusedComponent && this.isOverlayVisible(overlay),\n\t\t);\n\t\tif (!currentFocusedOverlay || newlyVisible.focusOrder > currentFocusedOverlay.focusOrder) {\n\t\t\tthis.setFocus(newlyVisible.component);\n\t\t}\n\t}\n\n\tprivate restoreVisibleOverlayFocus(): void {\n\t\tif (this.overlayStack.some((overlay) => overlay.component === this.focusedComponent)) return;\n\t\tconst restoreState = this.getVisibleOverlayFocusRestore();\n\t\tif (restoreState.status === \"eligible\") {\n\t\t\tthis.setFocus(restoreState.overlay.component);\n\t\t\treturn;\n\t\t}\n\t\tif (restoreState.status !== \"blocked\" || restoreState.blockedBy === this.focusedComponent) return;\n\t\tif (restoreState.resume.status === \"restore-overlay\") {\n\t\t\tthis.setFocus(restoreState.overlay.component);\n\t\t\treturn;\n\t\t}\n\t\tthis.clearOverlayFocusRestore();\n\t\tthis.setFocus(restoreState.resume.target);\n\t}\n\n\tprivate reconcileOverlayFocus(): void {\n\t\tconst newlyVisible = this.refreshOverlayVisibility();\n\t\tthis.retargetFocusFromHiddenOverlay();\n\t\tthis.focusNewlyVisibleOverlay(newlyVisible);\n\t\tthis.restoreVisibleOverlayFocus();\n\t}\n\n\toverride invalidate(): void {\n\t\tfor (const root of this.getMountedRoots()) root.invalidate();\n\t\tfor (const overlay of this.overlayStack) overlay.component.invalidate?.();\n\t}\n\n\tstart(): void {\n\t\tthis.stopped = false;\n\t\ttry {\n\t\t\tthis.beforeTerminalStart();\n\t\t\tthis.terminal.start(\n\t\t\t\t(data) => this.handleTerminalInput(data),\n\t\t\t\t() => {\n\t\t\t\t\tthis.reconcileOverlayFocus();\n\t\t\t\t\tthis.onTerminalResize();\n\t\t\t\t\tthis.requestRender();\n\t\t\t\t},\n\t\t\t);\n\t\t\tthis.afterTerminalStart();\n\t\t\tthis.terminal.hideCursor();\n\t\t\tthis.queryCellSize();\n\t\t\tthis.requestRender();\n\t\t} catch (error) {\n\t\t\t// A terminal may throw after partially entering raw or alternate-screen mode.\n\t\t\t// Route startup failures through the same complete cleanup path as signals.\n\t\t\ttry {\n\t\t\t\tthis.stop();\n\t\t\t} catch {\n\t\t\t\t// Preserve the startup failure; cleanup is best-effort but exhaustive.\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\taddInputListener(listener: TuiInputListener): () => void {\n\t\tthis.inputListeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.inputListeners.delete(listener);\n\t\t};\n\t}\n\n\tremoveInputListener(listener: TuiInputListener): void {\n\t\tthis.inputListeners.delete(listener);\n\t}\n\n\tprivate queryCellSize(): void {\n\t\t// Only query if terminal supports images (cell size is only used for image rendering)\n\t\tif (!getCapabilities().images) {\n\t\t\treturn;\n\t\t}\n\t\t// Query terminal for cell size in pixels: CSI 16 t\n\t\t// Response format: CSI 6 ; height ; width t\n\t\tthis.terminal.write(\"\\x1b[16t\");\n\t}\n\n\tstop(options?: TuiStopOptions): void {\n\t\tthis.stopped = true;\n\t\tthis.renderRequested = false;\n\t\tthis.cancelRenderTimer();\n\t\tlet failure: unknown;\n\t\tconst cleanup = (action: () => void): void => {\n\t\t\ttry {\n\t\t\t\taction();\n\t\t\t} catch (error) {\n\t\t\t\tfailure ??= error;\n\t\t\t}\n\t\t};\n\t\tcleanup(() => this.beforeTerminalStop(options));\n\t\tcleanup(() => this.terminal.showCursor());\n\t\tcleanup(() => this.terminal.stop());\n\t\t// Alternate-screen exit and capability restoration must run even when\n\t\t// keyboard/raw-mode shutdown reports an error.\n\t\tcleanup(() => this.afterTerminalStop(options));\n\t\tif (failure !== undefined) throw failure;\n\t}\n\n\trenderNow(force = false): void {\n\t\tif (force) this.resetRenderState();\n\t\tthis.renderRequested = false;\n\t\tthis.cancelRenderTimer();\n\t\tthis.lastRenderAt = performance.now();\n\t\tthis.doRender();\n\t}\n\n\trequestRender(force = false): void {\n\t\tif (force) {\n\t\t\tthis.resetRenderState();\n\t\t\tthis.requestImmediateRender();\n\t\t\treturn;\n\t\t}\n\t\tif (this.renderRequested) return;\n\t\tthis.renderRequested = true;\n\t\tprocess.nextTick(() => this.scheduleRender());\n\t}\n\n\tprivate requestImmediateRender(): void {\n\t\tthis.cancelRenderTimer();\n\t\tthis.renderRequested = true;\n\t\tif (this.immediateRenderScheduled) return;\n\t\tthis.immediateRenderScheduled = true;\n\t\tprocess.nextTick(() => {\n\t\t\tthis.immediateRenderScheduled = false;\n\t\t\tif (this.stopped || !this.renderRequested) return;\n\t\t\tthis.cancelRenderTimer();\n\t\t\tthis.renderRequested = false;\n\t\t\tthis.lastRenderAt = performance.now();\n\t\t\tthis.doRender();\n\t\t});\n\t}\n\n\tprivate cancelRenderTimer(): void {\n\t\tif (!this.renderTimer) return;\n\t\tclearTimeout(this.renderTimer);\n\t\tthis.renderTimer = undefined;\n\t}\n\n\tprivate scheduleRender(): void {\n\t\tif (this.stopped || this.renderTimer || !this.renderRequested) return;\n\t\tconst elapsed = performance.now() - this.lastRenderAt;\n\t\tconst delay = Math.max(0, TuiBase.MIN_RENDER_INTERVAL_MS - elapsed);\n\t\tthis.renderTimer = setTimeout(() => {\n\t\t\tthis.renderTimer = undefined;\n\t\t\tif (this.stopped || !this.renderRequested) return;\n\t\t\tthis.renderRequested = false;\n\t\t\tthis.lastRenderAt = performance.now();\n\t\t\tthis.doRender();\n\t\t\tif (this.renderRequested) this.scheduleRender();\n\t\t}, delay);\n\t}\n\n\tprivate applyInputListeners(data: string): string | undefined {\n\t\tif (this.inputListeners.size === 0) return data;\n\t\tlet current = data;\n\t\tfor (const listener of this.inputListeners) {\n\t\t\tconst result = listener(current);\n\t\t\tif (result?.consume) return undefined;\n\t\t\tif (result?.data !== undefined) current = result.data;\n\t\t}\n\t\treturn current.length === 0 ? undefined : current;\n\t}\n\n\tprivate handleTerminalInput(data: string): void {\n\t\tthis.reconcileOverlayFocus();\n\t\tconst filteredData = this.applyInputListeners(data);\n\t\tif (filteredData === undefined) return;\n\t\tdata = filteredData;\n\n\t\t// Consume terminal cell size responses without blocking unrelated input.\n\t\tif (this.consumeCellSizeResponse(data)) return;\n\n\t\t// Global debug key handler (Shift+Ctrl+D)\n\t\tif (matchesKey(data, \"shift+ctrl+d\") && this.onDebug) {\n\t\t\tthis.onDebug();\n\t\t\treturn;\n\t\t}\n\n\t\t// Pass input to focused component (including Ctrl+C).\n\t\t// The focused component can decide how to handle Ctrl+C.\n\t\tif (!this.focusedComponent?.handleInput) return;\n\t\t// Filter out key release events unless component opts in.\n\t\tif (isKeyRelease(data) && !this.focusedComponent.wantsKeyRelease) return;\n\t\tthis.focusedComponent.handleInput(data);\n\t\tthis.requestImmediateRender();\n\t}\n\n\tprivate consumeCellSizeResponse(data: string): boolean {\n\t\t// Response format: ESC [ 6 ; height ; width t\n\t\tconst match = data.match(/^\\x1b\\[6;(\\d+);(\\d+)t$/);\n\t\tif (!match) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst heightPx = parseInt(match[1], 10);\n\t\tconst widthPx = parseInt(match[2], 10);\n\t\tif (heightPx <= 0 || widthPx <= 0) {\n\t\t\treturn true;\n\t\t}\n\n\t\tsetCellDimensions({ widthPx, heightPx });\n\t\t// Invalidate all components so images re-render with correct dimensions.\n\t\tthis.invalidate();\n\t\tthis.requestRender();\n\t\treturn true;\n\t}\n\n\tprivate resolveOverlayBounds(options: OverlayOptions, termWidth: number, termHeight: number): OverlayLayoutBounds {\n\t\tconst margin =\n\t\t\ttypeof options.margin === \"number\"\n\t\t\t\t? { top: options.margin, right: options.margin, bottom: options.margin, left: options.margin }\n\t\t\t\t: (options.margin ?? {});\n\t\tconst marginTop = Math.max(0, margin.top ?? 0);\n\t\tconst marginRight = Math.max(0, margin.right ?? 0);\n\t\tconst marginBottom = Math.max(0, margin.bottom ?? 0);\n\t\tconst marginLeft = Math.max(0, margin.left ?? 0);\n\t\treturn {\n\t\t\tmarginTop,\n\t\t\tmarginRight,\n\t\t\tmarginBottom,\n\t\t\tmarginLeft,\n\t\t\tavailableWidth: Math.max(1, termWidth - marginLeft - marginRight),\n\t\t\tavailableHeight: Math.max(1, termHeight - marginTop - marginBottom),\n\t\t};\n\t}\n\n\tprivate resolveOverlayWidth(options: OverlayOptions, termWidth: number, bounds: OverlayLayoutBounds): number {\n\t\tlet width = parseSizeValue(options.width, termWidth) ?? Math.min(80, bounds.availableWidth);\n\t\tif (options.minWidth !== undefined) width = Math.max(width, options.minWidth);\n\t\treturn Math.max(1, Math.min(width, bounds.availableWidth));\n\t}\n\n\tprivate resolveOverlayMaxHeight(\n\t\toptions: OverlayOptions,\n\t\ttermHeight: number,\n\t\tbounds: OverlayLayoutBounds,\n\t): number | undefined {\n\t\tconst maxHeight = parseSizeValue(options.maxHeight, termHeight);\n\t\treturn maxHeight === undefined ? undefined : Math.max(1, Math.min(maxHeight, bounds.availableHeight));\n\t}\n\n\tprivate resolveOverlayRow(options: OverlayOptions, overlayHeight: number, bounds: OverlayLayoutBounds): number {\n\t\tif (options.row === undefined) {\n\t\t\treturn this.resolveAnchorRow(\n\t\t\t\toptions.anchor ?? \"center\",\n\t\t\t\toverlayHeight,\n\t\t\t\tbounds.availableHeight,\n\t\t\t\tbounds.marginTop,\n\t\t\t);\n\t\t}\n\t\tif (typeof options.row === \"number\") return options.row;\n\t\tconst match = options.row.match(/^(\\d+(?:\\.\\d+)?)%$/);\n\t\tif (!match) return this.resolveAnchorRow(\"center\", overlayHeight, bounds.availableHeight, bounds.marginTop);\n\t\tconst maxRow = Math.max(0, bounds.availableHeight - overlayHeight);\n\t\treturn bounds.marginTop + Math.floor(maxRow * (parseFloat(match[1]) / 100));\n\t}\n\n\tprivate resolveOverlayColumn(options: OverlayOptions, width: number, bounds: OverlayLayoutBounds): number {\n\t\tif (options.col === undefined) {\n\t\t\treturn this.resolveAnchorCol(options.anchor ?? \"center\", width, bounds.availableWidth, bounds.marginLeft);\n\t\t}\n\t\tif (typeof options.col === \"number\") return options.col;\n\t\tconst match = options.col.match(/^(\\d+(?:\\.\\d+)?)%$/);\n\t\tif (!match) return this.resolveAnchorCol(\"center\", width, bounds.availableWidth, bounds.marginLeft);\n\t\tconst maxCol = Math.max(0, bounds.availableWidth - width);\n\t\treturn bounds.marginLeft + Math.floor(maxCol * (parseFloat(match[1]) / 100));\n\t}\n\n\t/** Resolve overlay layout from options. */\n\tprivate resolveOverlayLayout(\n\t\toptions: OverlayOptions | undefined,\n\t\toverlayHeight: number,\n\t\ttermWidth: number,\n\t\ttermHeight: number,\n\t): ResolvedOverlayLayout {\n\t\tconst resolvedOptions = options ?? {};\n\t\tconst bounds = this.resolveOverlayBounds(resolvedOptions, termWidth, termHeight);\n\t\tconst width = this.resolveOverlayWidth(resolvedOptions, termWidth, bounds);\n\t\tconst maxHeight = this.resolveOverlayMaxHeight(resolvedOptions, termHeight, bounds);\n\t\tconst effectiveHeight = maxHeight === undefined ? overlayHeight : Math.min(overlayHeight, maxHeight);\n\t\tlet row = this.resolveOverlayRow(resolvedOptions, effectiveHeight, bounds) + (resolvedOptions.offsetY ?? 0);\n\t\tlet col = this.resolveOverlayColumn(resolvedOptions, width, bounds) + (resolvedOptions.offsetX ?? 0);\n\t\trow = Math.max(bounds.marginTop, Math.min(row, termHeight - bounds.marginBottom - effectiveHeight));\n\t\tcol = Math.max(bounds.marginLeft, Math.min(col, termWidth - bounds.marginRight - width));\n\t\treturn { width, row, col, maxHeight };\n\t}\n\n\tprivate resolveAnchorRow(anchor: OverlayAnchor, height: number, availHeight: number, marginTop: number): number {\n\t\tswitch (anchor) {\n\t\t\tcase \"top-left\":\n\t\t\tcase \"top-center\":\n\t\t\tcase \"top-right\":\n\t\t\t\treturn marginTop;\n\t\t\tcase \"bottom-left\":\n\t\t\tcase \"bottom-center\":\n\t\t\tcase \"bottom-right\":\n\t\t\t\treturn marginTop + availHeight - height;\n\t\t\tcase \"left-center\":\n\t\t\tcase \"center\":\n\t\t\tcase \"right-center\":\n\t\t\t\treturn marginTop + Math.floor((availHeight - height) / 2);\n\t\t}\n\t}\n\n\tprivate resolveAnchorCol(anchor: OverlayAnchor, width: number, availWidth: number, marginLeft: number): number {\n\t\tswitch (anchor) {\n\t\t\tcase \"top-left\":\n\t\t\tcase \"left-center\":\n\t\t\tcase \"bottom-left\":\n\t\t\t\treturn marginLeft;\n\t\t\tcase \"top-right\":\n\t\t\tcase \"right-center\":\n\t\t\tcase \"bottom-right\":\n\t\t\t\treturn marginLeft + availWidth - width;\n\t\t\tcase \"top-center\":\n\t\t\tcase \"center\":\n\t\t\tcase \"bottom-center\":\n\t\t\t\treturn marginLeft + Math.floor((availWidth - width) / 2);\n\t\t}\n\t}\n\n\tprivate prepareOverlayRenderPlan(baseLineCount: number, termWidth: number, termHeight: number): OverlayRenderPlan {\n\t\tconst visibleEntries = this.overlayStack.filter((entry) => this.isOverlayVisible(entry));\n\t\tvisibleEntries.sort((left, right) => left.focusOrder - right.focusOrder);\n\t\tconst overlays: RenderedOverlay[] = [];\n\t\tlet minimumLineCount = baseLineCount;\n\t\tfor (const entry of visibleEntries) {\n\t\t\tconst { width, maxHeight } = this.resolveOverlayLayout(entry.options, 0, termWidth, termHeight);\n\t\t\tlet overlayLines = entry.component.render(width);\n\t\t\tif (maxHeight !== undefined && overlayLines.length > maxHeight) {\n\t\t\t\toverlayLines = overlayLines.slice(0, maxHeight);\n\t\t\t}\n\t\t\tconst { row, col } = this.resolveOverlayLayout(entry.options, overlayLines.length, termWidth, termHeight);\n\t\t\toverlays.push({ lines: overlayLines, row, col, width });\n\t\t\tminimumLineCount = Math.max(minimumLineCount, row + overlayLines.length);\n\t\t}\n\t\treturn { overlays, minimumLineCount };\n\t}\n\n\tprivate compositeRenderedOverlay(\n\t\tresult: string[],\n\t\toverlay: RenderedOverlay,\n\t\tviewportStart: number,\n\t\ttermWidth: number,\n\t): void {\n\t\tfor (let lineIndex = 0; lineIndex < overlay.lines.length; lineIndex++) {\n\t\t\tconst targetIndex = viewportStart + overlay.row + lineIndex;\n\t\t\tif (targetIndex < 0 || targetIndex >= result.length) continue;\n\t\t\tconst overlayLine = overlay.lines[lineIndex]!;\n\t\t\tconst truncatedLine =\n\t\t\t\tvisibleWidth(overlayLine) > overlay.width\n\t\t\t\t\t? sliceByColumn(overlayLine, 0, overlay.width, true)\n\t\t\t\t\t: overlayLine;\n\t\t\tresult[targetIndex] = this.compositeLineAt(\n\t\t\t\tresult[targetIndex]!,\n\t\t\t\ttruncatedLine,\n\t\t\t\toverlay.col,\n\t\t\t\toverlay.width,\n\t\t\t\ttermWidth,\n\t\t\t);\n\t\t}\n\t}\n\n\t/** Composite all overlays into content lines (sorted by focusOrder, higher = on top). */\n\tprotected compositeOverlays(lines: string[], termWidth: number, termHeight: number): string[] {\n\t\tif (this.overlayStack.length === 0) return lines;\n\t\tconst result = [...lines];\n\t\tconst plan = this.prepareOverlayRenderPlan(result.length, termWidth, termHeight);\n\t\tconst workingHeight = Math.max(result.length, termHeight, plan.minimumLineCount);\n\t\twhile (result.length < workingHeight) result.push(\"\");\n\t\tconst viewportStart = Math.max(0, workingHeight - termHeight);\n\t\tfor (const overlay of plan.overlays) {\n\t\t\tthis.compositeRenderedOverlay(result, overlay, viewportStart, termWidth);\n\t\t}\n\t\treturn result;\n\t}\n\n\tprotected applyLineResets(lines: string[]): string[] {\n\t\tconst reset = SEGMENT_RESET;\n\t\tfor (let i = 0; i < lines.length; i++) {\n\t\t\tconst line = lines[i];\n\t\t\tif (!isImageLine(line)) {\n\t\t\t\tlines[i] = normalizeTerminalOutput(line) + reset;\n\t\t\t}\n\t\t}\n\t\treturn lines;\n\t}\n\n\tprivate compositeLineAt(\n\t\tbaseLine: string,\n\t\toverlayLine: string,\n\t\tstartCol: number,\n\t\toverlayWidth: number,\n\t\ttotalWidth: number,\n\t): string {\n\t\treturn compositeTuiLine(baseLine, overlayLine, startCol, overlayWidth, totalWidth);\n\t}\n\n\t/**\n\t * Find and extract cursor position from rendered lines.\n\t * Searches for CURSOR_MARKER, calculates its position, and strips it from the output.\n\t * Only scans the bottom terminal height lines (visible viewport).\n\t * @param lines - Rendered lines to search\n\t * @param height - Terminal height (visible viewport size)\n\t * @returns Cursor position { row, col } or null if no marker found\n\t */\n\tprotected extractCursorPosition(lines: string[], height: number): RenderedCursorPosition | null {\n\t\t// Only scan the bottom `height` lines (visible viewport)\n\t\tconst viewportTop = Math.max(0, lines.length - height);\n\t\tfor (let row = lines.length - 1; row >= viewportTop; row--) {\n\t\t\tconst line = lines[row];\n\t\t\tconst markerIndex = line.indexOf(CURSOR_MARKER);\n\t\t\tif (markerIndex !== -1) {\n\t\t\t\t// Calculate visual column (width of text before marker)\n\t\t\t\tconst beforeMarker = line.slice(0, markerIndex);\n\t\t\t\tconst col = visibleWidth(beforeMarker);\n\n\t\t\t\t// Strip marker from the line\n\t\t\t\tlines[row] = line.slice(0, markerIndex) + line.slice(markerIndex + CURSOR_MARKER.length);\n\n\t\t\t\treturn { row, col };\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n}\n"]}