@code-yeongyu/senpi-tui 2026.7.25-2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/README.md +790 -0
  2. package/dist/autocomplete.d.ts +57 -0
  3. package/dist/autocomplete.d.ts.map +1 -0
  4. package/dist/autocomplete.js +646 -0
  5. package/dist/autocomplete.js.map +1 -0
  6. package/dist/components/box.d.ts +25 -0
  7. package/dist/components/box.d.ts.map +1 -0
  8. package/dist/components/box.js +117 -0
  9. package/dist/components/box.js.map +1 -0
  10. package/dist/components/cancellable-loader.d.ts +22 -0
  11. package/dist/components/cancellable-loader.d.ts.map +1 -0
  12. package/dist/components/cancellable-loader.js +36 -0
  13. package/dist/components/cancellable-loader.js.map +1 -0
  14. package/dist/components/editor.d.ts +257 -0
  15. package/dist/components/editor.d.ts.map +1 -0
  16. package/dist/components/editor.js +2014 -0
  17. package/dist/components/editor.js.map +1 -0
  18. package/dist/components/image.d.ts +28 -0
  19. package/dist/components/image.d.ts.map +1 -0
  20. package/dist/components/image.js +82 -0
  21. package/dist/components/image.js.map +1 -0
  22. package/dist/components/input.d.ts +37 -0
  23. package/dist/components/input.d.ts.map +1 -0
  24. package/dist/components/input.js +378 -0
  25. package/dist/components/input.js.map +1 -0
  26. package/dist/components/loader.d.ts +46 -0
  27. package/dist/components/loader.d.ts.map +1 -0
  28. package/dist/components/loader.js +110 -0
  29. package/dist/components/loader.js.map +1 -0
  30. package/dist/components/markdown.d.ts +105 -0
  31. package/dist/components/markdown.d.ts.map +1 -0
  32. package/dist/components/markdown.js +789 -0
  33. package/dist/components/markdown.js.map +1 -0
  34. package/dist/components/select-list.d.ts +50 -0
  35. package/dist/components/select-list.d.ts.map +1 -0
  36. package/dist/components/select-list.js +154 -0
  37. package/dist/components/select-list.js.map +1 -0
  38. package/dist/components/settings-list.d.ts +50 -0
  39. package/dist/components/settings-list.d.ts.map +1 -0
  40. package/dist/components/settings-list.js +177 -0
  41. package/dist/components/settings-list.js.map +1 -0
  42. package/dist/components/spacer.d.ts +12 -0
  43. package/dist/components/spacer.d.ts.map +1 -0
  44. package/dist/components/spacer.js +22 -0
  45. package/dist/components/spacer.js.map +1 -0
  46. package/dist/components/text.d.ts +19 -0
  47. package/dist/components/text.d.ts.map +1 -0
  48. package/dist/components/text.js +81 -0
  49. package/dist/components/text.js.map +1 -0
  50. package/dist/components/truncated-text.d.ts +13 -0
  51. package/dist/components/truncated-text.d.ts.map +1 -0
  52. package/dist/components/truncated-text.js +48 -0
  53. package/dist/components/truncated-text.js.map +1 -0
  54. package/dist/editor-component.d.ts +39 -0
  55. package/dist/editor-component.d.ts.map +1 -0
  56. package/dist/editor-component.js +2 -0
  57. package/dist/editor-component.js.map +1 -0
  58. package/dist/fuzzy.d.ts +16 -0
  59. package/dist/fuzzy.d.ts.map +1 -0
  60. package/dist/fuzzy.js +180 -0
  61. package/dist/fuzzy.js.map +1 -0
  62. package/dist/index.d.ts +25 -0
  63. package/dist/index.d.ts.map +1 -0
  64. package/dist/index.js +35 -0
  65. package/dist/index.js.map +1 -0
  66. package/dist/keybindings.d.ts +193 -0
  67. package/dist/keybindings.d.ts.map +1 -0
  68. package/dist/keybindings.js +172 -0
  69. package/dist/keybindings.js.map +1 -0
  70. package/dist/keys.d.ts +184 -0
  71. package/dist/keys.d.ts.map +1 -0
  72. package/dist/keys.js +1174 -0
  73. package/dist/keys.js.map +1 -0
  74. package/dist/kill-ring.d.ts +28 -0
  75. package/dist/kill-ring.d.ts.map +1 -0
  76. package/dist/kill-ring.js +46 -0
  77. package/dist/kill-ring.js.map +1 -0
  78. package/dist/mux.d.ts +4 -0
  79. package/dist/mux.d.ts.map +1 -0
  80. package/dist/mux.js +10 -0
  81. package/dist/mux.js.map +1 -0
  82. package/dist/native-modifiers.d.ts +3 -0
  83. package/dist/native-modifiers.d.ts.map +1 -0
  84. package/dist/native-modifiers.js +53 -0
  85. package/dist/native-modifiers.js.map +1 -0
  86. package/dist/slash-command-autocomplete.d.ts +3 -0
  87. package/dist/slash-command-autocomplete.d.ts.map +1 -0
  88. package/dist/slash-command-autocomplete.js +38 -0
  89. package/dist/slash-command-autocomplete.js.map +1 -0
  90. package/dist/stdin-buffer.d.ts +51 -0
  91. package/dist/stdin-buffer.d.ts.map +1 -0
  92. package/dist/stdin-buffer.js +366 -0
  93. package/dist/stdin-buffer.js.map +1 -0
  94. package/dist/terminal-colors.d.ts +10 -0
  95. package/dist/terminal-colors.d.ts.map +1 -0
  96. package/dist/terminal-colors.js +59 -0
  97. package/dist/terminal-colors.js.map +1 -0
  98. package/dist/terminal-image.d.ts +88 -0
  99. package/dist/terminal-image.d.ts.map +1 -0
  100. package/dist/terminal-image.js +358 -0
  101. package/dist/terminal-image.js.map +1 -0
  102. package/dist/terminal-text.d.ts +4 -0
  103. package/dist/terminal-text.d.ts.map +1 -0
  104. package/dist/terminal-text.js +18 -0
  105. package/dist/terminal-text.js.map +1 -0
  106. package/dist/terminal.d.ts +128 -0
  107. package/dist/terminal.d.ts.map +1 -0
  108. package/dist/terminal.js +493 -0
  109. package/dist/terminal.js.map +1 -0
  110. package/dist/tui.d.ts +325 -0
  111. package/dist/tui.d.ts.map +1 -0
  112. package/dist/tui.js +1955 -0
  113. package/dist/tui.js.map +1 -0
  114. package/dist/undo-stack.d.ts +17 -0
  115. package/dist/undo-stack.d.ts.map +1 -0
  116. package/dist/undo-stack.js +27 -0
  117. package/dist/undo-stack.js.map +1 -0
  118. package/dist/utils.d.ts +91 -0
  119. package/dist/utils.d.ts.map +1 -0
  120. package/dist/utils.js +1173 -0
  121. package/dist/utils.js.map +1 -0
  122. package/dist/word-navigation.d.ts +25 -0
  123. package/dist/word-navigation.d.ts.map +1 -0
  124. package/dist/word-navigation.js +96 -0
  125. package/dist/word-navigation.js.map +1 -0
  126. package/native/darwin/prebuilds/darwin-arm64/darwin-modifiers.node +0 -0
  127. package/native/darwin/prebuilds/darwin-x64/darwin-modifiers.node +0 -0
  128. package/native/win32/prebuilds/win32-arm64/win32-console-mode.node +0 -0
  129. package/native/win32/prebuilds/win32-x64/win32-console-mode.node +0 -0
  130. package/package.json +48 -0
package/dist/tui.js ADDED
@@ -0,0 +1,1955 @@
1
+ /**
2
+ * Minimal TUI implementation with differential rendering
3
+ */
4
+ import * as fs from "node:fs";
5
+ import * as os from "node:os";
6
+ import * as path from "node:path";
7
+ import { performance } from "node:perf_hooks";
8
+ import { isKeyRelease, matchesKey } from "./keys.js";
9
+ import { isMultiplexerSession, useLegacyMuxRender, viewportRenderEnabled } from "./mux.js";
10
+ import { isOsc11BackgroundColorResponse, parseOsc11BackgroundColor, parseTerminalColorSchemeReport, } from "./terminal-colors.js";
11
+ import { deleteKittyImage, getCapabilities, isImageLine, setCellDimensions } from "./terminal-image.js";
12
+ import { extractSegments, normalizeTerminalOutput, sliceByColumn, sliceWithWidth, visibleWidth } from "./utils.js";
13
+ const KITTY_SEQUENCE_PREFIX = "\x1b_G";
14
+ function parseKittyImageHeader(line) {
15
+ const sequenceStart = line.indexOf(KITTY_SEQUENCE_PREFIX);
16
+ if (sequenceStart === -1)
17
+ return undefined;
18
+ const paramsStart = sequenceStart + KITTY_SEQUENCE_PREFIX.length;
19
+ const paramsEnd = line.indexOf(";", paramsStart);
20
+ if (paramsEnd === -1)
21
+ return undefined;
22
+ const ids = [];
23
+ let rows = 1;
24
+ const params = line.slice(paramsStart, paramsEnd);
25
+ for (const param of params.split(",")) {
26
+ const [key, value] = param.split("=", 2);
27
+ if (value === undefined)
28
+ continue;
29
+ const numberValue = Number(value);
30
+ if (!Number.isInteger(numberValue) || numberValue <= 0 || numberValue > 0xffffffff)
31
+ continue;
32
+ if (key === "i") {
33
+ ids.push(numberValue);
34
+ }
35
+ else if (key === "r") {
36
+ rows = numberValue;
37
+ }
38
+ }
39
+ return { ids, rows };
40
+ }
41
+ function extractKittyImageIds(line) {
42
+ return parseKittyImageHeader(line)?.ids ?? [];
43
+ }
44
+ function extractKittyImageRows(line) {
45
+ return parseKittyImageHeader(line)?.rows ?? 1;
46
+ }
47
+ /** Type guard to check if a component implements Focusable */
48
+ export function isFocusable(component) {
49
+ return component !== null && "focused" in component;
50
+ }
51
+ /**
52
+ * Cursor position marker - APC (Application Program Command) sequence.
53
+ * This is a zero-width escape sequence that terminals ignore.
54
+ * Components emit this at the cursor position when focused.
55
+ * TUI finds and strips this marker, then positions the hardware cursor there.
56
+ */
57
+ export const CURSOR_MARKER = "\x1b_pi:c\x07";
58
+ export { visibleWidth };
59
+ const renderErrorLoggedClasses = new Set();
60
+ let renderErrorLogWrites = 0;
61
+ const DIAGNOSTIC_LOG_MODE = 0o600;
62
+ const VIEWPORT_RENDER_OVERSCAN = 16;
63
+ // Keep scroll-region wins cheap when a few visible rows mutate during append streaming.
64
+ const MAX_SCROLL_DIFF_ROWS = 4;
65
+ const viewportRenderStats = {
66
+ lastNormalizedLines: 0,
67
+ lastKittyImageScannedLines: 0,
68
+ totalNormalizedLines: 0,
69
+ totalKittyImageScannedLines: 0,
70
+ boundedFrames: 0,
71
+ escapedFrames: 0,
72
+ fullFrames: 0,
73
+ };
74
+ export function __renderErrorLogStats() {
75
+ if (process.env.PI_TUI_TEST_SEAMS !== "1") {
76
+ return undefined;
77
+ }
78
+ return { writes: renderErrorLogWrites };
79
+ }
80
+ export function __viewportRenderStats() {
81
+ if (process.env.PI_TUI_TEST_SEAMS !== "1") {
82
+ return undefined;
83
+ }
84
+ return { ...viewportRenderStats };
85
+ }
86
+ function recordViewportRenderStats(normalizedLines, mode) {
87
+ viewportRenderStats.lastNormalizedLines = normalizedLines;
88
+ viewportRenderStats.totalNormalizedLines += normalizedLines;
89
+ if (mode === "bounded") {
90
+ viewportRenderStats.boundedFrames += 1;
91
+ }
92
+ else if (mode === "escaped") {
93
+ viewportRenderStats.escapedFrames += 1;
94
+ }
95
+ else {
96
+ viewportRenderStats.fullFrames += 1;
97
+ }
98
+ }
99
+ function recordKittyImageScanStats(scannedLines) {
100
+ viewportRenderStats.lastKittyImageScannedLines = scannedLines;
101
+ viewportRenderStats.totalKittyImageScannedLines += scannedLines;
102
+ }
103
+ function componentRenderErrorName(component) {
104
+ return component.constructor.name || "AnonymousComponent";
105
+ }
106
+ function logRenderErrorOnce(component, error) {
107
+ const componentName = componentRenderErrorName(component);
108
+ if (renderErrorLoggedClasses.has(componentName)) {
109
+ return;
110
+ }
111
+ renderErrorLoggedClasses.add(componentName);
112
+ renderErrorLogWrites += 1;
113
+ const errorText = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
114
+ const logPath = path.join(os.homedir(), ".senpi", "agent", "senpi-debug.log");
115
+ const msg = `[${new Date().toISOString()}] render error: ${componentName}: ${errorText}\n`;
116
+ appendRenderErrorLogBestEffort(logPath, msg);
117
+ }
118
+ function appendRenderErrorLogBestEffort(logPath, msg) {
119
+ try {
120
+ fs.mkdirSync(path.dirname(logPath), { recursive: true });
121
+ fs.appendFileSync(logPath, msg, { encoding: "utf8", mode: DIAGNOSTIC_LOG_MODE });
122
+ chmodDiagnosticLogBestEffort(logPath);
123
+ }
124
+ catch (error) {
125
+ if (error instanceof Error) {
126
+ return;
127
+ }
128
+ throw error;
129
+ }
130
+ }
131
+ function writeRenderDiagnosticBestEffort(logPath, data) {
132
+ try {
133
+ fs.mkdirSync(path.dirname(logPath), { recursive: true });
134
+ fs.writeFileSync(logPath, data, { encoding: "utf8", mode: DIAGNOSTIC_LOG_MODE });
135
+ chmodDiagnosticLogBestEffort(logPath);
136
+ return true;
137
+ }
138
+ catch (error) {
139
+ if (error instanceof Error) {
140
+ return false;
141
+ }
142
+ throw error;
143
+ }
144
+ }
145
+ function chmodDiagnosticLogBestEffort(logPath) {
146
+ try {
147
+ fs.chmodSync(logPath, DIAGNOSTIC_LOG_MODE);
148
+ }
149
+ catch (error) {
150
+ if (error instanceof Error) {
151
+ return;
152
+ }
153
+ throw error;
154
+ }
155
+ }
156
+ /** Parse a SizeValue into absolute value given a reference size */
157
+ function parseSizeValue(value, referenceSize) {
158
+ if (value === undefined)
159
+ return undefined;
160
+ if (typeof value === "number")
161
+ return value;
162
+ // Parse percentage string like "50%"
163
+ const match = value.match(/^(\d+(?:\.\d+)?)%$/);
164
+ if (match) {
165
+ return Math.floor((referenceSize * parseFloat(match[1])) / 100);
166
+ }
167
+ return undefined;
168
+ }
169
+ function isTermuxSession() {
170
+ return Boolean(process.env.TERMUX_VERSION);
171
+ }
172
+ /**
173
+ * Container - a component that contains other components
174
+ */
175
+ export class Container {
176
+ constructor() {
177
+ this.children = [];
178
+ this.disposed = false;
179
+ }
180
+ addChild(component) {
181
+ this.children.push(component);
182
+ }
183
+ removeChild(component) {
184
+ const index = this.children.indexOf(component);
185
+ if (index !== -1) {
186
+ this.children.splice(index, 1);
187
+ component.dispose?.();
188
+ }
189
+ }
190
+ detachChild(component) {
191
+ const index = this.children.indexOf(component);
192
+ if (index !== -1) {
193
+ this.children.splice(index, 1);
194
+ }
195
+ }
196
+ clear() {
197
+ for (const child of this.children) {
198
+ child.dispose?.();
199
+ }
200
+ this.children = [];
201
+ }
202
+ detachAll() {
203
+ this.children = [];
204
+ }
205
+ dispose() {
206
+ if (this.disposed)
207
+ return;
208
+ this.disposed = true;
209
+ for (const child of this.children) {
210
+ child.dispose?.();
211
+ }
212
+ }
213
+ invalidate() {
214
+ for (const child of this.children) {
215
+ child.invalidate?.();
216
+ }
217
+ }
218
+ render(width) {
219
+ const lines = [];
220
+ for (const child of this.children) {
221
+ let childLines;
222
+ try {
223
+ childLines = child.render(width);
224
+ }
225
+ catch (error) {
226
+ logRenderErrorOnce(child, error);
227
+ const componentName = componentRenderErrorName(child);
228
+ // Focus ownership stays unchanged; render containment must not steal or clear focus implicitly.
229
+ childLines = [`[render error: ${componentName}]`];
230
+ }
231
+ for (const line of childLines) {
232
+ lines.push(line);
233
+ }
234
+ }
235
+ return lines;
236
+ }
237
+ }
238
+ /**
239
+ * TUI - Main class for managing terminal UI with differential rendering
240
+ */
241
+ export class TUI extends Container {
242
+ /** Minimum interval between scheduled renders. Default preserves the historic ~60fps cap. */
243
+ #minRenderIntervalMs;
244
+ #lastCursorVisibility;
245
+ #muxDetector;
246
+ constructor(terminal, options) {
247
+ super();
248
+ this.previousLines = [];
249
+ this.previousRawLines = [];
250
+ this.previousKittyImageIds = new Set();
251
+ this.previousWidth = 0;
252
+ this.previousHeight = 0;
253
+ this.focusedComponent = null;
254
+ this.inputListeners = new Set();
255
+ this.renderRequested = false;
256
+ this.lastRenderAt = 0;
257
+ /** Minimum interval between scheduled renders. Default preserves the historic ~60fps cap. */
258
+ this.#minRenderIntervalMs = 16;
259
+ this.inputRenderPending = false;
260
+ this.cursorRow = 0; // Logical cursor row (end of rendered content)
261
+ this.hardwareCursorRow = 0; // Actual terminal cursor row (may differ due to IME positioning)
262
+ this.showHardwareCursor = process.env.PI_HARDWARE_CURSOR === "1";
263
+ this.clearOnShrink = process.env.PI_CLEAR_ON_SHRINK === "1"; // Clear empty rows when content shrinks (default: off)
264
+ this.maxLinesRendered = 0; // Track terminal's working area (max lines ever rendered)
265
+ this.previousViewportTop = 0; // Track previous viewport top for resize-aware cursor moves
266
+ this.fullRedrawCount = 0;
267
+ this.muxViewportRepaintCount = 0;
268
+ this.overWideCrashDumpWritten = false;
269
+ this.stopped = false;
270
+ this.pendingOsc11BackgroundReplies = 0;
271
+ this.pendingOsc11BackgroundQueries = [];
272
+ this.terminalColorSchemeListeners = new Set();
273
+ this.terminalColorSchemeNotificationsEnabled = false;
274
+ // Overlay stack for modal components rendered on top of base content
275
+ this.focusOrderCounter = 0;
276
+ this.overlayStack = [];
277
+ this.overlayFocusRestore = { status: "inactive" };
278
+ this.terminal = terminal;
279
+ // Preserve existing positional boolean callers while allowing explicit render-policy overrides.
280
+ const normalizedOptions = typeof options === "boolean" ? { showHardwareCursor: options } : (options ?? {});
281
+ this.#muxDetector = normalizedOptions.muxDetector ?? isMultiplexerSession;
282
+ if (normalizedOptions.showHardwareCursor !== undefined) {
283
+ this.showHardwareCursor = normalizedOptions.showHardwareCursor;
284
+ }
285
+ }
286
+ get fullRedraws() {
287
+ return this.fullRedrawCount;
288
+ }
289
+ get muxViewportRepaints() {
290
+ return this.muxViewportRepaintCount;
291
+ }
292
+ getShowHardwareCursor() {
293
+ return this.showHardwareCursor;
294
+ }
295
+ setShowHardwareCursor(enabled) {
296
+ if (this.showHardwareCursor === enabled)
297
+ return;
298
+ this.showHardwareCursor = enabled;
299
+ if (!enabled) {
300
+ this.#setCursorVisibility(false);
301
+ }
302
+ this.requestRender();
303
+ }
304
+ getClearOnShrink() {
305
+ return this.clearOnShrink;
306
+ }
307
+ /**
308
+ * Set whether to trigger full re-render when content shrinks.
309
+ * When true (default), empty rows are cleared when content shrinks.
310
+ * When false, empty rows remain (reduces redraws on slower terminals).
311
+ */
312
+ setClearOnShrink(enabled) {
313
+ this.clearOnShrink = enabled;
314
+ }
315
+ setFocus(component) {
316
+ this.setFocusInternal({ component, overlayFocusRestore: "clear" });
317
+ }
318
+ setFocusInternal({ component, overlayFocusRestore, }) {
319
+ const previousFocus = this.focusedComponent;
320
+ let nextFocus = component;
321
+ const previousFocusedOverlay = previousFocus
322
+ ? this.overlayStack.find((entry) => entry.component === previousFocus && this.isOverlayVisible(entry))
323
+ : undefined;
324
+ const nextFocusIsOverlay = nextFocus ? this.overlayStack.some((entry) => entry.component === nextFocus) : false;
325
+ const restoreState = this.getVisibleOverlayFocusRestore();
326
+ if (nextFocus && !nextFocusIsOverlay) {
327
+ if (restoreState.status === "blocked" && restoreState.blockedBy === previousFocus) {
328
+ if (restoreState.resume.status === "focus-target" || !this.isComponentMounted(restoreState.blockedBy)) {
329
+ nextFocus = this.resolveBlockedOverlayFocusResume(restoreState);
330
+ }
331
+ else {
332
+ this.overlayFocusRestore = {
333
+ status: "blocked",
334
+ overlay: restoreState.overlay,
335
+ blockedBy: nextFocus,
336
+ resume: restoreState.resume,
337
+ };
338
+ }
339
+ }
340
+ else if (previousFocusedOverlay &&
341
+ restoreState.status !== "inactive" &&
342
+ restoreState.overlay === previousFocusedOverlay &&
343
+ !this.isOverlayFocusAncestor(previousFocusedOverlay, nextFocus)) {
344
+ this.overlayFocusRestore = {
345
+ status: "blocked",
346
+ overlay: previousFocusedOverlay,
347
+ blockedBy: nextFocus,
348
+ resume: { status: "restore-overlay" },
349
+ };
350
+ }
351
+ }
352
+ else if (nextFocus === null) {
353
+ if (restoreState.status === "blocked" && restoreState.blockedBy === previousFocus) {
354
+ nextFocus = this.resolveBlockedOverlayFocusResume(restoreState);
355
+ }
356
+ else if (overlayFocusRestore === "clear") {
357
+ this.clearOverlayFocusRestore();
358
+ }
359
+ }
360
+ if (isFocusable(this.focusedComponent)) {
361
+ this.focusedComponent.focused = false;
362
+ }
363
+ this.focusedComponent = nextFocus;
364
+ if (isFocusable(nextFocus)) {
365
+ nextFocus.focused = true;
366
+ }
367
+ const focusedOverlay = nextFocus
368
+ ? this.overlayStack.find((entry) => entry.component === nextFocus && this.isOverlayVisible(entry))
369
+ : undefined;
370
+ if (focusedOverlay) {
371
+ this.overlayFocusRestore = { status: "eligible", overlay: focusedOverlay };
372
+ }
373
+ }
374
+ clearOverlayFocusRestore() {
375
+ this.overlayFocusRestore = { status: "inactive" };
376
+ }
377
+ clearOverlayFocusRestoreFor(overlay) {
378
+ if (this.overlayFocusRestore.status !== "inactive" && this.overlayFocusRestore.overlay === overlay) {
379
+ this.clearOverlayFocusRestore();
380
+ }
381
+ }
382
+ resolveBlockedOverlayFocusResume(restoreState) {
383
+ if (restoreState.resume.status === "restore-overlay")
384
+ return restoreState.overlay.component;
385
+ this.clearOverlayFocusRestore();
386
+ return restoreState.resume.target;
387
+ }
388
+ getVisibleOverlayFocusRestore() {
389
+ const restoreState = this.overlayFocusRestore;
390
+ if (restoreState.status === "inactive")
391
+ return restoreState;
392
+ if (!this.overlayStack.includes(restoreState.overlay) || !this.isOverlayVisible(restoreState.overlay)) {
393
+ return { status: "inactive" };
394
+ }
395
+ return restoreState;
396
+ }
397
+ isOverlayFocusAncestor(entry, component) {
398
+ const visited = new Set();
399
+ let current = entry.preFocus;
400
+ while (current && !visited.has(current)) {
401
+ visited.add(current);
402
+ if (current === component)
403
+ return true;
404
+ current = this.overlayStack.find((overlay) => overlay.component === current)?.preFocus ?? null;
405
+ }
406
+ return false;
407
+ }
408
+ retargetOverlayPreFocus(removed) {
409
+ for (const overlay of this.overlayStack) {
410
+ if (overlay !== removed && overlay.preFocus === removed.component) {
411
+ overlay.preFocus = removed.preFocus;
412
+ }
413
+ }
414
+ }
415
+ isComponentMounted(component) {
416
+ return this.children.some((child) => this.containsComponent(child, component));
417
+ }
418
+ containsComponent(root, target) {
419
+ if (root === target)
420
+ return true;
421
+ if (!(root instanceof Container))
422
+ return false;
423
+ return root.children.some((child) => this.containsComponent(child, target));
424
+ }
425
+ /**
426
+ * Show an overlay component with configurable positioning and sizing.
427
+ * Returns a handle to control the overlay's visibility.
428
+ */
429
+ showOverlay(component, options) {
430
+ const entry = {
431
+ component,
432
+ ...(options === undefined ? {} : { options }),
433
+ preFocus: this.focusedComponent,
434
+ hidden: false,
435
+ focusOrder: ++this.focusOrderCounter,
436
+ };
437
+ this.overlayStack.push(entry);
438
+ // Only focus if overlay is actually visible
439
+ if (!options?.nonCapturing && this.isOverlayVisible(entry)) {
440
+ this.setFocus(component);
441
+ }
442
+ this.#setCursorVisibility(false);
443
+ this.requestRender();
444
+ // Return handle for controlling this overlay
445
+ return {
446
+ hide: () => {
447
+ const index = this.overlayStack.indexOf(entry);
448
+ if (index !== -1) {
449
+ this.clearOverlayFocusRestoreFor(entry);
450
+ this.retargetOverlayPreFocus(entry);
451
+ this.overlayStack.splice(index, 1);
452
+ // Restore focus if this overlay had focus
453
+ if (this.focusedComponent === component) {
454
+ const topVisible = this.getTopmostVisibleOverlay();
455
+ this.setFocus(topVisible?.component ?? entry.preFocus);
456
+ }
457
+ if (this.overlayStack.length === 0)
458
+ this.#setCursorVisibility(false);
459
+ this.requestRender();
460
+ }
461
+ },
462
+ setHidden: (hidden) => {
463
+ if (entry.hidden === hidden)
464
+ return;
465
+ entry.hidden = hidden;
466
+ // Update focus when hiding/showing
467
+ if (hidden) {
468
+ this.clearOverlayFocusRestoreFor(entry);
469
+ // If this overlay had focus, move focus to next visible or preFocus
470
+ if (this.focusedComponent === component) {
471
+ const topVisible = this.getTopmostVisibleOverlay();
472
+ this.setFocus(topVisible?.component ?? entry.preFocus);
473
+ }
474
+ }
475
+ else {
476
+ // Restore focus to this overlay when showing (if it's actually visible)
477
+ if (!options?.nonCapturing && this.isOverlayVisible(entry)) {
478
+ entry.focusOrder = ++this.focusOrderCounter;
479
+ this.setFocus(component);
480
+ }
481
+ }
482
+ this.requestRender();
483
+ },
484
+ isHidden: () => entry.hidden,
485
+ focus: () => {
486
+ if (!this.overlayStack.includes(entry) || !this.isOverlayVisible(entry))
487
+ return;
488
+ entry.focusOrder = ++this.focusOrderCounter;
489
+ this.setFocus(component);
490
+ this.requestRender();
491
+ },
492
+ unfocus: (unfocusOptions) => {
493
+ const isFocused = this.focusedComponent === component;
494
+ const restoreState = this.overlayFocusRestore;
495
+ const hasPendingRestore = restoreState.status !== "inactive" && restoreState.overlay === entry;
496
+ if (!isFocused && !hasPendingRestore)
497
+ return;
498
+ if (restoreState.status === "blocked" &&
499
+ restoreState.overlay === entry &&
500
+ this.focusedComponent === restoreState.blockedBy) {
501
+ if (unfocusOptions) {
502
+ this.overlayFocusRestore = {
503
+ status: "blocked",
504
+ overlay: entry,
505
+ blockedBy: restoreState.blockedBy,
506
+ resume: { status: "focus-target", target: unfocusOptions.target },
507
+ };
508
+ }
509
+ else {
510
+ this.clearOverlayFocusRestore();
511
+ }
512
+ this.requestRender();
513
+ return;
514
+ }
515
+ this.clearOverlayFocusRestoreFor(entry);
516
+ if (isFocused || unfocusOptions) {
517
+ const topVisible = this.getTopmostVisibleOverlay();
518
+ const fallbackTarget = topVisible && topVisible !== entry ? topVisible.component : entry.preFocus;
519
+ this.setFocus(unfocusOptions ? unfocusOptions.target : fallbackTarget);
520
+ }
521
+ this.requestRender();
522
+ },
523
+ isFocused: () => this.focusedComponent === component,
524
+ };
525
+ }
526
+ /** Hide the topmost overlay and restore previous focus. */
527
+ hideOverlay() {
528
+ const overlay = this.overlayStack[this.overlayStack.length - 1];
529
+ if (!overlay)
530
+ return;
531
+ this.clearOverlayFocusRestoreFor(overlay);
532
+ this.retargetOverlayPreFocus(overlay);
533
+ this.overlayStack.pop();
534
+ if (this.focusedComponent === overlay.component) {
535
+ // Find topmost visible overlay, or fall back to preFocus
536
+ const topVisible = this.getTopmostVisibleOverlay();
537
+ this.setFocus(topVisible?.component ?? overlay.preFocus);
538
+ }
539
+ if (this.overlayStack.length === 0)
540
+ this.#setCursorVisibility(false);
541
+ this.requestRender();
542
+ }
543
+ /** Check if there are any visible overlays */
544
+ hasOverlay() {
545
+ return this.overlayStack.some((o) => this.isOverlayVisible(o));
546
+ }
547
+ /** Check if an overlay entry is currently visible */
548
+ isOverlayVisible(entry) {
549
+ if (entry.hidden)
550
+ return false;
551
+ if (entry.options?.visible) {
552
+ return entry.options.visible(this.terminal.columns, this.terminal.rows);
553
+ }
554
+ return true;
555
+ }
556
+ /** Find the visual-frontmost visible capturing overlay, if any */
557
+ getTopmostVisibleOverlay() {
558
+ let topmost;
559
+ for (const overlay of this.overlayStack) {
560
+ if (overlay.options?.nonCapturing || !this.isOverlayVisible(overlay))
561
+ continue;
562
+ if (!topmost || overlay.focusOrder > topmost.focusOrder) {
563
+ topmost = overlay;
564
+ }
565
+ }
566
+ return topmost;
567
+ }
568
+ invalidate() {
569
+ super.invalidate();
570
+ for (const overlay of this.overlayStack)
571
+ overlay.component.invalidate?.();
572
+ }
573
+ start() {
574
+ this.stopped = false;
575
+ this.renderRequested = false;
576
+ this.inputRenderPending = false;
577
+ this.#lastCursorVisibility = undefined;
578
+ this.terminal.start((data) => this.handleInput(data), () => this.requestRender());
579
+ this.#setCursorVisibility(false);
580
+ if (this.terminalColorSchemeNotificationsEnabled) {
581
+ this.terminal.write("\x1b[?2031h");
582
+ }
583
+ this.queryCellSize();
584
+ this.requestRender();
585
+ }
586
+ addInputListener(listener) {
587
+ this.inputListeners.add(listener);
588
+ return () => {
589
+ this.inputListeners.delete(listener);
590
+ };
591
+ }
592
+ removeInputListener(listener) {
593
+ this.inputListeners.delete(listener);
594
+ }
595
+ onTerminalColorSchemeChange(listener) {
596
+ this.terminalColorSchemeListeners.add(listener);
597
+ return () => {
598
+ this.terminalColorSchemeListeners.delete(listener);
599
+ };
600
+ }
601
+ setTerminalColorSchemeNotifications(enabled) {
602
+ if (this.terminalColorSchemeNotificationsEnabled === enabled) {
603
+ return;
604
+ }
605
+ this.terminalColorSchemeNotificationsEnabled = enabled;
606
+ if (!this.stopped) {
607
+ this.terminal.write(enabled ? "\x1b[?2031h" : "\x1b[?2031l");
608
+ }
609
+ }
610
+ queryCellSize() {
611
+ // Only query if terminal supports images (cell size is only used for image rendering)
612
+ if (!getCapabilities().images) {
613
+ return;
614
+ }
615
+ // Query terminal for cell size in pixels: CSI 16 t
616
+ // Response format: CSI 6 ; height ; width t
617
+ this.terminal.write("\x1b[16t");
618
+ }
619
+ stop() {
620
+ this.stopped = true;
621
+ this.renderRequested = false;
622
+ this.inputRenderPending = false;
623
+ if (this.renderTimer) {
624
+ clearTimeout(this.renderTimer);
625
+ this.renderTimer = undefined;
626
+ }
627
+ if (this.terminalColorSchemeNotificationsEnabled) {
628
+ this.terminal.write("\x1b[?2031l");
629
+ }
630
+ // Move cursor to the end of the content to prevent overwriting/artifacts on exit
631
+ if (this.previousLines.length > 0) {
632
+ // Overwrite the inverted cursor with a normal space to clear the artifact
633
+ this.terminal.write(" ");
634
+ const targetRow = this.previousLines.length; // Line after the last content
635
+ const lineDiff = targetRow - this.hardwareCursorRow;
636
+ if (lineDiff > 0) {
637
+ this.terminal.write(`\x1b[${lineDiff}B`);
638
+ }
639
+ else if (lineDiff < 0) {
640
+ this.terminal.write(`\x1b[${-lineDiff}A`);
641
+ }
642
+ this.terminal.write("\r\n");
643
+ }
644
+ this.#lastCursorVisibility = undefined;
645
+ this.#setCursorVisibility(true);
646
+ this.terminal.stop();
647
+ this.#lastCursorVisibility = undefined;
648
+ this.previousLines = [];
649
+ this.previousRawLines = [];
650
+ this.previousKittyImageIds.clear();
651
+ this.previousWidth = 0;
652
+ this.previousHeight = 0;
653
+ this.cursorRow = 0;
654
+ this.hardwareCursorRow = 0;
655
+ this.maxLinesRendered = 0;
656
+ this.previousViewportTop = 0;
657
+ }
658
+ #setCursorVisibility(visible) {
659
+ if (this.#lastCursorVisibility === visible)
660
+ return;
661
+ if (visible) {
662
+ this.terminal.showCursor();
663
+ }
664
+ else {
665
+ this.terminal.hideCursor();
666
+ }
667
+ this.#lastCursorVisibility = visible;
668
+ }
669
+ requestRender(force = false, source = "unknown") {
670
+ if (force) {
671
+ this.inputRenderPending = false;
672
+ this.previousLines = [];
673
+ this.previousRawLines = [];
674
+ this.previousWidth = -1; // -1 triggers widthChanged, forcing a full clear
675
+ this.previousHeight = -1; // -1 triggers heightChanged, forcing a full clear
676
+ this.cursorRow = 0;
677
+ this.hardwareCursorRow = 0;
678
+ this.maxLinesRendered = 0;
679
+ this.previousViewportTop = 0;
680
+ if (this.renderTimer) {
681
+ clearTimeout(this.renderTimer);
682
+ this.renderTimer = undefined;
683
+ }
684
+ this.renderRequested = true;
685
+ process.nextTick(() => {
686
+ if (this.stopped || !this.renderRequested) {
687
+ return;
688
+ }
689
+ this.renderRequested = false;
690
+ this.lastRenderAt = performance.now();
691
+ this.doRender();
692
+ });
693
+ return;
694
+ }
695
+ if (source === "input" || source === "editor.input") {
696
+ if (!this.inputRenderPending) {
697
+ this.inputRenderPending = true;
698
+ this.renderRequested = true;
699
+ process.nextTick(() => this.commitExpeditedRender());
700
+ }
701
+ return;
702
+ }
703
+ if (this.renderRequested)
704
+ return;
705
+ this.renderRequested = true;
706
+ process.nextTick(() => this.scheduleRender());
707
+ }
708
+ /**
709
+ * Cap the render scheduler at `fps` frames per second. Values are clamped
710
+ * to 30-120fps (120fps yields an 8ms minimum interval). Never calling this
711
+ * preserves the historic 16ms (~60fps) throttle.
712
+ */
713
+ setMaxRenderFps(fps) {
714
+ const clamped = Math.min(120, Math.max(30, Math.round(fps)));
715
+ this.#minRenderIntervalMs = Math.floor(1000 / clamped);
716
+ }
717
+ scheduleRender() {
718
+ if (this.stopped || this.renderTimer || !this.renderRequested) {
719
+ return;
720
+ }
721
+ const elapsed = performance.now() - this.lastRenderAt;
722
+ const delay = Math.max(0, this.#minRenderIntervalMs - elapsed);
723
+ this.renderTimer = setTimeout(() => {
724
+ this.renderTimer = undefined;
725
+ if (this.stopped || !this.renderRequested) {
726
+ return;
727
+ }
728
+ this.renderRequested = false;
729
+ this.lastRenderAt = performance.now();
730
+ this.doRender();
731
+ if (this.renderRequested) {
732
+ this.scheduleRender();
733
+ }
734
+ }, delay);
735
+ }
736
+ commitExpeditedRender() {
737
+ if (!this.inputRenderPending)
738
+ return;
739
+ this.inputRenderPending = false;
740
+ if (this.stopped || !this.renderRequested) {
741
+ return;
742
+ }
743
+ if (this.renderTimer) {
744
+ clearTimeout(this.renderTimer);
745
+ this.renderTimer = undefined;
746
+ }
747
+ this.renderRequested = false;
748
+ this.lastRenderAt = performance.now();
749
+ this.doRender();
750
+ }
751
+ handleInput(data) {
752
+ if (this.consumeOsc11BackgroundResponse(data)) {
753
+ return;
754
+ }
755
+ if (this.consumeTerminalColorSchemeReport(data)) {
756
+ return;
757
+ }
758
+ if (this.inputListeners.size > 0) {
759
+ let current = data;
760
+ for (const listener of this.inputListeners) {
761
+ const result = listener(current);
762
+ if (result?.consume) {
763
+ return;
764
+ }
765
+ if (result?.data !== undefined) {
766
+ current = result.data;
767
+ }
768
+ }
769
+ if (current.length === 0) {
770
+ return;
771
+ }
772
+ data = current;
773
+ }
774
+ // Consume terminal cell size responses without blocking unrelated input.
775
+ if (this.consumeCellSizeResponse(data)) {
776
+ return;
777
+ }
778
+ // Global debug key handler (Shift+Ctrl+D)
779
+ if (matchesKey(data, "shift+ctrl+d") && this.onDebug) {
780
+ this.onDebug();
781
+ return;
782
+ }
783
+ // If focused component is an overlay, verify it's still visible
784
+ // (visibility can change due to terminal resize or visible() callback)
785
+ const focusedOverlay = this.overlayStack.find((o) => o.component === this.focusedComponent);
786
+ if (focusedOverlay && !this.isOverlayVisible(focusedOverlay)) {
787
+ // Focused overlay is no longer visible, redirect to topmost visible overlay
788
+ const topVisible = this.getTopmostVisibleOverlay();
789
+ if (topVisible) {
790
+ this.setFocus(topVisible.component);
791
+ }
792
+ else {
793
+ this.setFocusInternal({ component: focusedOverlay.preFocus, overlayFocusRestore: "preserve" });
794
+ }
795
+ }
796
+ const focusIsOverlay = this.overlayStack.some((o) => o.component === this.focusedComponent);
797
+ if (!focusIsOverlay) {
798
+ const restoreState = this.getVisibleOverlayFocusRestore();
799
+ if (restoreState.status === "eligible") {
800
+ this.setFocus(restoreState.overlay.component);
801
+ }
802
+ else if (restoreState.status === "blocked" && restoreState.blockedBy !== this.focusedComponent) {
803
+ if (restoreState.resume.status === "restore-overlay") {
804
+ this.setFocus(restoreState.overlay.component);
805
+ }
806
+ else {
807
+ this.clearOverlayFocusRestore();
808
+ this.setFocus(restoreState.resume.target);
809
+ }
810
+ }
811
+ }
812
+ // Pass input to focused component (including Ctrl+C)
813
+ // The focused component can decide how to handle Ctrl+C
814
+ if (this.focusedComponent?.handleInput) {
815
+ // Filter out key release events unless component opts in
816
+ if (isKeyRelease(data) && !this.focusedComponent.wantsKeyRelease) {
817
+ return;
818
+ }
819
+ this.focusedComponent.handleInput(data);
820
+ this.requestRender(false, "input");
821
+ }
822
+ }
823
+ consumeOsc11BackgroundResponse(data) {
824
+ if (this.pendingOsc11BackgroundReplies <= 0) {
825
+ return false;
826
+ }
827
+ if (!isOsc11BackgroundColorResponse(data)) {
828
+ return false;
829
+ }
830
+ const rgb = parseOsc11BackgroundColor(data);
831
+ this.pendingOsc11BackgroundReplies -= 1;
832
+ const query = this.pendingOsc11BackgroundQueries.shift();
833
+ if (query && !query.settled) {
834
+ query.settled = true;
835
+ if (query.timer) {
836
+ clearTimeout(query.timer);
837
+ query.timer = undefined;
838
+ }
839
+ query.resolve?.(rgb);
840
+ query.resolve = undefined;
841
+ }
842
+ return true;
843
+ }
844
+ consumeTerminalColorSchemeReport(data) {
845
+ const scheme = parseTerminalColorSchemeReport(data);
846
+ if (!scheme) {
847
+ return false;
848
+ }
849
+ for (const listener of this.terminalColorSchemeListeners) {
850
+ listener(scheme);
851
+ }
852
+ return true;
853
+ }
854
+ consumeCellSizeResponse(data) {
855
+ // Response format: ESC [ 6 ; height ; width t
856
+ const match = data.match(/^\x1b\[6;(\d+);(\d+)t$/);
857
+ if (!match) {
858
+ return false;
859
+ }
860
+ const heightPx = parseInt(match[1], 10);
861
+ const widthPx = parseInt(match[2], 10);
862
+ if (heightPx <= 0 || widthPx <= 0) {
863
+ return true;
864
+ }
865
+ setCellDimensions({ widthPx, heightPx });
866
+ // Invalidate all components so images re-render with correct dimensions.
867
+ this.invalidate();
868
+ this.requestRender();
869
+ return true;
870
+ }
871
+ /**
872
+ * Resolve overlay layout from options.
873
+ * Returns { width, row, col, maxHeight } for rendering.
874
+ */
875
+ resolveOverlayLayout(options, overlayHeight, termWidth, termHeight) {
876
+ const opt = options ?? {};
877
+ // Parse margin (clamp to non-negative)
878
+ const margin = typeof opt.margin === "number"
879
+ ? { top: opt.margin, right: opt.margin, bottom: opt.margin, left: opt.margin }
880
+ : (opt.margin ?? {});
881
+ const marginTop = Math.max(0, margin.top ?? 0);
882
+ const marginRight = Math.max(0, margin.right ?? 0);
883
+ const marginBottom = Math.max(0, margin.bottom ?? 0);
884
+ const marginLeft = Math.max(0, margin.left ?? 0);
885
+ // Available space after margins
886
+ const availWidth = Math.max(1, termWidth - marginLeft - marginRight);
887
+ const availHeight = Math.max(1, termHeight - marginTop - marginBottom);
888
+ // === Resolve width ===
889
+ let width = parseSizeValue(opt.width, termWidth) ?? Math.min(80, availWidth);
890
+ // Apply minWidth
891
+ if (opt.minWidth !== undefined) {
892
+ width = Math.max(width, opt.minWidth);
893
+ }
894
+ // Clamp to available space
895
+ width = Math.max(1, Math.min(width, availWidth));
896
+ // === Resolve maxHeight ===
897
+ let maxHeight = parseSizeValue(opt.maxHeight, termHeight);
898
+ // Clamp to available space
899
+ if (maxHeight !== undefined) {
900
+ maxHeight = Math.max(1, Math.min(maxHeight, availHeight));
901
+ }
902
+ // Effective overlay height (may be clamped by maxHeight)
903
+ const effectiveHeight = maxHeight !== undefined ? Math.min(overlayHeight, maxHeight) : overlayHeight;
904
+ // === Resolve position ===
905
+ let row;
906
+ let col;
907
+ if (opt.row !== undefined) {
908
+ if (typeof opt.row === "string") {
909
+ // Percentage: 0% = top, 100% = bottom (overlay stays within bounds)
910
+ const match = opt.row.match(/^(\d+(?:\.\d+)?)%$/);
911
+ if (match) {
912
+ const maxRow = Math.max(0, availHeight - effectiveHeight);
913
+ const percent = parseFloat(match[1]) / 100;
914
+ row = marginTop + Math.floor(maxRow * percent);
915
+ }
916
+ else {
917
+ // Invalid format, fall back to center
918
+ row = this.resolveAnchorRow("center", effectiveHeight, availHeight, marginTop);
919
+ }
920
+ }
921
+ else {
922
+ // Absolute row position
923
+ row = opt.row;
924
+ }
925
+ }
926
+ else {
927
+ // Anchor-based (default: center)
928
+ const anchor = opt.anchor ?? "center";
929
+ row = this.resolveAnchorRow(anchor, effectiveHeight, availHeight, marginTop);
930
+ }
931
+ if (opt.col !== undefined) {
932
+ if (typeof opt.col === "string") {
933
+ // Percentage: 0% = left, 100% = right (overlay stays within bounds)
934
+ const match = opt.col.match(/^(\d+(?:\.\d+)?)%$/);
935
+ if (match) {
936
+ const maxCol = Math.max(0, availWidth - width);
937
+ const percent = parseFloat(match[1]) / 100;
938
+ col = marginLeft + Math.floor(maxCol * percent);
939
+ }
940
+ else {
941
+ // Invalid format, fall back to center
942
+ col = this.resolveAnchorCol("center", width, availWidth, marginLeft);
943
+ }
944
+ }
945
+ else {
946
+ // Absolute column position
947
+ col = opt.col;
948
+ }
949
+ }
950
+ else {
951
+ // Anchor-based (default: center)
952
+ const anchor = opt.anchor ?? "center";
953
+ col = this.resolveAnchorCol(anchor, width, availWidth, marginLeft);
954
+ }
955
+ // Apply offsets
956
+ if (opt.offsetY !== undefined)
957
+ row += opt.offsetY;
958
+ if (opt.offsetX !== undefined)
959
+ col += opt.offsetX;
960
+ // Clamp to terminal bounds (respecting margins)
961
+ row = Math.max(marginTop, Math.min(row, termHeight - marginBottom - effectiveHeight));
962
+ col = Math.max(marginLeft, Math.min(col, termWidth - marginRight - width));
963
+ return { width, row, col, maxHeight };
964
+ }
965
+ resolveAnchorRow(anchor, height, availHeight, marginTop) {
966
+ switch (anchor) {
967
+ case "top-left":
968
+ case "top-center":
969
+ case "top-right":
970
+ return marginTop;
971
+ case "bottom-left":
972
+ case "bottom-center":
973
+ case "bottom-right":
974
+ return marginTop + availHeight - height;
975
+ case "left-center":
976
+ case "center":
977
+ case "right-center":
978
+ return marginTop + Math.floor((availHeight - height) / 2);
979
+ }
980
+ }
981
+ resolveAnchorCol(anchor, width, availWidth, marginLeft) {
982
+ switch (anchor) {
983
+ case "top-left":
984
+ case "left-center":
985
+ case "bottom-left":
986
+ return marginLeft;
987
+ case "top-right":
988
+ case "right-center":
989
+ case "bottom-right":
990
+ return marginLeft + availWidth - width;
991
+ case "top-center":
992
+ case "center":
993
+ case "bottom-center":
994
+ return marginLeft + Math.floor((availWidth - width) / 2);
995
+ }
996
+ }
997
+ /** Composite all overlays into content lines (sorted by focusOrder, higher = on top). */
998
+ compositeOverlays(lines, termWidth, termHeight) {
999
+ if (this.overlayStack.length === 0)
1000
+ return lines;
1001
+ const result = [...lines];
1002
+ // Pre-render all visible overlays and calculate positions
1003
+ const rendered = [];
1004
+ let minLinesNeeded = result.length;
1005
+ const visibleEntries = this.overlayStack.filter((e) => this.isOverlayVisible(e));
1006
+ visibleEntries.sort((a, b) => a.focusOrder - b.focusOrder);
1007
+ for (const entry of visibleEntries) {
1008
+ const { component, options } = entry;
1009
+ // Get layout with height=0 first to determine width and maxHeight
1010
+ // (width and maxHeight don't depend on overlay height)
1011
+ const { width, maxHeight } = this.resolveOverlayLayout(options, 0, termWidth, termHeight);
1012
+ // Render component at calculated width
1013
+ let overlayLines = component.render(width);
1014
+ // Apply maxHeight if specified
1015
+ if (maxHeight !== undefined && overlayLines.length > maxHeight) {
1016
+ overlayLines = overlayLines.slice(0, maxHeight);
1017
+ }
1018
+ // Get final row/col with actual overlay height
1019
+ const { row, col } = this.resolveOverlayLayout(options, overlayLines.length, termWidth, termHeight);
1020
+ rendered.push({ overlayLines, row, col, w: width });
1021
+ minLinesNeeded = Math.max(minLinesNeeded, row + overlayLines.length);
1022
+ }
1023
+ // Pad to at least terminal height so overlays have screen-relative positions.
1024
+ // Excludes maxLinesRendered: the historical high-water mark caused self-reinforcing
1025
+ // inflation that pushed content into scrollback on terminal widen.
1026
+ const workingHeight = Math.max(result.length, termHeight, minLinesNeeded);
1027
+ // Extend result with empty lines if content is too short for overlay placement or working area
1028
+ while (result.length < workingHeight) {
1029
+ result.push("");
1030
+ }
1031
+ const viewportStart = Math.max(0, workingHeight - termHeight);
1032
+ // Composite each overlay
1033
+ for (const { overlayLines, row, col, w } of rendered) {
1034
+ for (let i = 0; i < overlayLines.length; i++) {
1035
+ const idx = viewportStart + row + i;
1036
+ if (idx >= 0 && idx < result.length) {
1037
+ // Defensive: truncate overlay line to declared width before compositing
1038
+ // (components should already respect width, but this ensures it)
1039
+ const truncatedOverlayLine = visibleWidth(overlayLines[i]) > w ? sliceByColumn(overlayLines[i], 0, w, true) : overlayLines[i];
1040
+ result[idx] = this.compositeLineAt(result[idx], truncatedOverlayLine, col, w, termWidth);
1041
+ }
1042
+ }
1043
+ }
1044
+ return result;
1045
+ }
1046
+ static { this.SEGMENT_RESET = "\x1b[0m\x1b]8;;\x07"; }
1047
+ /**
1048
+ * Every frame write is bracketed by synchronized output (DECSET 2026) and
1049
+ * disables autowrap (DECAWM, DECRST 7) while rows are painted. Differential
1050
+ * rendering tracks the cursor with relative moves only, so a row the
1051
+ * terminal draws wider than visibleWidth() measured (East-Asian-ambiguous
1052
+ * glyphs, emoji newer than the terminal's Unicode tables, decomposed jamo)
1053
+ * would wrap, silently shift the cursor one row down, and leave stale ghost
1054
+ * rows behind on every following diff. With autowrap off such rows clip at
1055
+ * the last column instead. Autowrap is restored at frame end so the shell
1056
+ * never observes the disabled state.
1057
+ */
1058
+ static { this.FRAME_BEGIN = "\x1b[?2026h\x1b[?7l"; }
1059
+ static { this.FRAME_END = "\x1b[?7h\x1b[?2026l"; }
1060
+ setPreviousLines(lines, rawLines) {
1061
+ this.previousLines = lines;
1062
+ this.previousRawLines = rawLines;
1063
+ }
1064
+ normalizeLine(line) {
1065
+ if (isImageLine(line)) {
1066
+ return { line, normalized: false };
1067
+ }
1068
+ return { line: normalizeTerminalOutput(line) + TUI.SEGMENT_RESET, normalized: true };
1069
+ }
1070
+ applyLineResets(lines, mode = "full") {
1071
+ const normalizedLines = [];
1072
+ let normalizedCount = 0;
1073
+ for (let i = 0; i < lines.length; i++) {
1074
+ const line = lines[i];
1075
+ if (isImageLine(line)) {
1076
+ normalizedLines.push(line);
1077
+ }
1078
+ else {
1079
+ normalizedLines.push(normalizeTerminalOutput(line) + TUI.SEGMENT_RESET);
1080
+ normalizedCount += 1;
1081
+ }
1082
+ }
1083
+ recordViewportRenderStats(normalizedCount, mode);
1084
+ return {
1085
+ lines: normalizedLines,
1086
+ firstRawChanged: 0,
1087
+ compareEndExclusive: normalizedLines.length,
1088
+ bounded: false,
1089
+ };
1090
+ }
1091
+ applyViewportLineResets(rawLines, viewportTop, height, stableDimensions) {
1092
+ if (!viewportRenderEnabled() ||
1093
+ !stableDimensions ||
1094
+ this.previousLines.length === 0 ||
1095
+ this.previousLines.length !== rawLines.length ||
1096
+ this.previousRawLines.length !== rawLines.length) {
1097
+ return this.applyLineResets(rawLines);
1098
+ }
1099
+ const windowStart = Math.max(0, viewportTop - VIEWPORT_RENDER_OVERSCAN);
1100
+ const windowEnd = Math.min(rawLines.length, viewportTop + height + VIEWPORT_RENDER_OVERSCAN);
1101
+ let firstRawChanged = -1;
1102
+ for (let i = 0; i < rawLines.length; i++) {
1103
+ if (rawLines[i] === this.previousRawLines[i]) {
1104
+ continue;
1105
+ }
1106
+ if (firstRawChanged === -1) {
1107
+ firstRawChanged = i;
1108
+ }
1109
+ if (i < windowStart || i >= windowEnd) {
1110
+ return this.applyLineResets(rawLines, "escaped");
1111
+ }
1112
+ }
1113
+ const lines = this.previousLines.slice();
1114
+ let normalizedCount = 0;
1115
+ if (firstRawChanged !== -1) {
1116
+ for (let i = windowStart; i < windowEnd; i++) {
1117
+ if (rawLines[i] === this.previousRawLines[i]) {
1118
+ continue;
1119
+ }
1120
+ const normalized = this.normalizeLine(rawLines[i] ?? "");
1121
+ lines[i] = normalized.line;
1122
+ if (normalized.normalized) {
1123
+ normalizedCount += 1;
1124
+ }
1125
+ }
1126
+ }
1127
+ recordViewportRenderStats(normalizedCount, "bounded");
1128
+ return {
1129
+ lines,
1130
+ firstRawChanged,
1131
+ compareEndExclusive: windowEnd,
1132
+ bounded: true,
1133
+ };
1134
+ }
1135
+ collectKittyImageIds(lines) {
1136
+ recordKittyImageScanStats(lines.length);
1137
+ const ids = new Set();
1138
+ for (const line of lines) {
1139
+ for (const id of extractKittyImageIds(line)) {
1140
+ ids.add(id);
1141
+ }
1142
+ }
1143
+ return ids;
1144
+ }
1145
+ deleteKittyImages(ids) {
1146
+ let buffer = "";
1147
+ for (const id of ids) {
1148
+ buffer += deleteKittyImage(id);
1149
+ }
1150
+ return buffer;
1151
+ }
1152
+ getKittyImageReservedRows(lines, index, maxIndex = lines.length - 1) {
1153
+ const rows = extractKittyImageRows(lines[index] ?? "");
1154
+ if (rows <= 1)
1155
+ return 1;
1156
+ const maxRows = Math.min(rows, maxIndex - index + 1, lines.length - index);
1157
+ let reservedRows = 1;
1158
+ while (reservedRows < maxRows) {
1159
+ const line = lines[index + reservedRows] ?? "";
1160
+ if (isImageLine(line) || visibleWidth(line) > 0)
1161
+ break;
1162
+ reservedRows++;
1163
+ }
1164
+ return reservedRows;
1165
+ }
1166
+ expandChangedRangeForKittyImages(firstChanged, lastChanged, newLines) {
1167
+ let expandedFirstChanged = firstChanged;
1168
+ let expandedLastChanged = lastChanged;
1169
+ const expandForLines = (lines) => {
1170
+ for (let i = 0; i < lines.length; i++) {
1171
+ if (extractKittyImageIds(lines[i]).length === 0)
1172
+ continue;
1173
+ const blockEnd = i + this.getKittyImageReservedRows(lines, i) - 1;
1174
+ if (i >= firstChanged || (i <= lastChanged && blockEnd >= firstChanged)) {
1175
+ expandedFirstChanged = Math.min(expandedFirstChanged, i);
1176
+ expandedLastChanged = Math.max(expandedLastChanged, blockEnd);
1177
+ }
1178
+ }
1179
+ };
1180
+ expandForLines(this.previousLines);
1181
+ expandForLines(newLines);
1182
+ return { firstChanged: expandedFirstChanged, lastChanged: expandedLastChanged };
1183
+ }
1184
+ changedRangeNeedsKittyImageExpansion(lines, firstChanged, lastChanged) {
1185
+ if (this.previousKittyImageIds.size > 0) {
1186
+ return true;
1187
+ }
1188
+ const start = Math.max(0, firstChanged);
1189
+ const end = Math.min(lines.length - 1, lastChanged);
1190
+ let scannedLines = 0;
1191
+ for (let i = start; i <= end; i++) {
1192
+ scannedLines += 1;
1193
+ const line = lines[i] ?? "";
1194
+ if (isImageLine(line) || extractKittyImageIds(line).length > 0) {
1195
+ recordKittyImageScanStats(scannedLines);
1196
+ return true;
1197
+ }
1198
+ }
1199
+ recordKittyImageScanStats(scannedLines);
1200
+ return false;
1201
+ }
1202
+ deleteChangedKittyImages(firstChanged, lastChanged) {
1203
+ if (firstChanged < 0 || lastChanged < firstChanged)
1204
+ return "";
1205
+ const ids = new Set();
1206
+ const maxLine = Math.min(lastChanged, this.previousLines.length - 1);
1207
+ for (let i = firstChanged; i <= maxLine; i++) {
1208
+ for (const id of extractKittyImageIds(this.previousLines[i] ?? "")) {
1209
+ ids.add(id);
1210
+ }
1211
+ }
1212
+ return this.deleteKittyImages(ids);
1213
+ }
1214
+ getViewportRows(lines, viewportTop, height) {
1215
+ return Array.from({ length: height }, (_, row) => lines[viewportTop + row] ?? "");
1216
+ }
1217
+ shouldPreserveMuxScrollback() {
1218
+ return this.#muxDetector() && !useLegacyMuxRender();
1219
+ }
1220
+ createViewportInsertScrollPlan(newLines, prevViewportTop, height, lineCountDelta) {
1221
+ if (lineCountDelta <= 0 || lineCountDelta >= height || this.overlayStack.length > 0) {
1222
+ return undefined;
1223
+ }
1224
+ const maxViewportTop = Math.max(0, newLines.length - height);
1225
+ const viewportTop = Math.min(maxViewportTop, prevViewportTop + lineCountDelta);
1226
+ if (viewportTop <= prevViewportTop) {
1227
+ return undefined;
1228
+ }
1229
+ const previousVisible = this.getViewportRows(this.previousLines, prevViewportTop, height);
1230
+ const nextVisible = this.getViewportRows(newLines, viewportTop, height);
1231
+ if (previousVisible.some(isImageLine) || nextVisible.some(isImageLine)) {
1232
+ return undefined;
1233
+ }
1234
+ let stableSuffixRows = 0;
1235
+ while (stableSuffixRows < height &&
1236
+ previousVisible[height - stableSuffixRows - 1] === nextVisible[height - stableSuffixRows - 1]) {
1237
+ stableSuffixRows += 1;
1238
+ }
1239
+ const regionHeight = height - stableSuffixRows;
1240
+ if (regionHeight <= 0 || regionHeight < lineCountDelta) {
1241
+ return undefined;
1242
+ }
1243
+ const mutatedRows = [];
1244
+ for (let row = 0; row < regionHeight - lineCountDelta; row++) {
1245
+ if (previousVisible[row + lineCountDelta] !== nextVisible[row]) {
1246
+ mutatedRows.push({ screenRow: row, content: nextVisible[row] });
1247
+ if (mutatedRows.length > MAX_SCROLL_DIFF_ROWS) {
1248
+ return undefined;
1249
+ }
1250
+ }
1251
+ }
1252
+ return {
1253
+ viewportTop,
1254
+ regionBottom: regionHeight - 1,
1255
+ insertedRows: nextVisible.slice(regionHeight - lineCountDelta, regionHeight),
1256
+ mutatedRows,
1257
+ };
1258
+ }
1259
+ renderViewportInsertScroll(plan, newLines, rawLines, cursorPos, width, height) {
1260
+ let buffer = TUI.FRAME_BEGIN;
1261
+ const regionTop = 0;
1262
+ const regionBottom = plan.regionBottom;
1263
+ buffer += `\x1b[${regionTop + 1};${regionBottom + 1}r`;
1264
+ buffer += `\x1b[${regionBottom + 1};1H`;
1265
+ buffer += "\n".repeat(plan.insertedRows.length);
1266
+ buffer += "\x1b[r";
1267
+ const firstInsertedScreenRow = regionBottom - plan.insertedRows.length + 1;
1268
+ let finalPaintedScreenRow = firstInsertedScreenRow + plan.insertedRows.length - 1;
1269
+ for (let index = 0; index < plan.insertedRows.length; index++) {
1270
+ const screenRow = firstInsertedScreenRow + index;
1271
+ buffer += `\x1b[${screenRow + 1};1H\x1b[2K${TUI.SEGMENT_RESET}`;
1272
+ buffer += plan.insertedRows[index] ?? "";
1273
+ }
1274
+ for (const row of plan.mutatedRows) {
1275
+ buffer += `\x1b[${row.screenRow + 1};1H\x1b[2K${TUI.SEGMENT_RESET}`;
1276
+ buffer += row.content;
1277
+ finalPaintedScreenRow = row.screenRow;
1278
+ }
1279
+ buffer += TUI.FRAME_END;
1280
+ this.terminal.write(buffer);
1281
+ this.cursorRow = Math.max(0, newLines.length - 1);
1282
+ this.hardwareCursorRow = plan.viewportTop + finalPaintedScreenRow;
1283
+ this.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);
1284
+ this.previousViewportTop = plan.viewportTop;
1285
+ this.positionHardwareCursor(cursorPos, newLines.length);
1286
+ this.setPreviousLines(newLines, rawLines);
1287
+ this.previousKittyImageIds = this.collectKittyImageIds(newLines);
1288
+ this.previousWidth = width;
1289
+ this.previousHeight = height;
1290
+ }
1291
+ renderScrollbackReplay(newLines, rawLines, cursorPos, width, height, prevViewportTop, hardwareCursorRow) {
1292
+ let buffer = TUI.FRAME_BEGIN;
1293
+ buffer += this.deleteKittyImages(this.previousKittyImageIds);
1294
+ if (!this.shouldPreserveMuxScrollback()) {
1295
+ buffer += "\x1b[3J";
1296
+ }
1297
+ const currentScreenRow = Math.max(0, Math.min(height - 1, hardwareCursorRow - prevViewportTop));
1298
+ if (currentScreenRow > 0) {
1299
+ buffer += `\x1b[${currentScreenRow}A`;
1300
+ }
1301
+ const bufferLength = Math.max(height, newLines.length);
1302
+ for (let row = 0; row < bufferLength; row++) {
1303
+ if (row > 0)
1304
+ buffer += "\r\n";
1305
+ buffer += `\r\x1b[2K${TUI.SEGMENT_RESET}`;
1306
+ buffer += newLines[row] ?? "";
1307
+ }
1308
+ buffer += TUI.FRAME_END;
1309
+ this.terminal.write(buffer);
1310
+ this.cursorRow = Math.max(0, newLines.length - 1);
1311
+ this.hardwareCursorRow = bufferLength - 1;
1312
+ this.maxLinesRendered = newLines.length;
1313
+ this.previousViewportTop = Math.max(0, bufferLength - height);
1314
+ this.positionHardwareCursor(cursorPos, newLines.length);
1315
+ this.setPreviousLines(newLines, rawLines);
1316
+ this.previousKittyImageIds = this.collectKittyImageIds(newLines);
1317
+ this.previousWidth = width;
1318
+ this.previousHeight = height;
1319
+ }
1320
+ renderMuxViewportRepaint(newLines, rawLines, cursorPos, width, height, viewportTop = Math.max(0, newLines.length - height)) {
1321
+ const previousVisible = this.getViewportRows(this.previousLines, this.previousViewportTop, height);
1322
+ const nextVisible = this.getViewportRows(newLines, viewportTop, height);
1323
+ if (previousVisible.some(isImageLine) || nextVisible.some(isImageLine)) {
1324
+ return false;
1325
+ }
1326
+ let buffer = TUI.FRAME_BEGIN;
1327
+ const currentScreenRow = Math.max(0, Math.min(height - 1, this.hardwareCursorRow - this.previousViewportTop));
1328
+ if (currentScreenRow > 0) {
1329
+ buffer += `\x1b[${currentScreenRow}A`;
1330
+ }
1331
+ for (let row = 0; row < height; row++) {
1332
+ if (row > 0)
1333
+ buffer += "\r\n";
1334
+ buffer += `\r\x1b[2K${TUI.SEGMENT_RESET}`;
1335
+ buffer += newLines[viewportTop + row] ?? "";
1336
+ }
1337
+ buffer += TUI.FRAME_END;
1338
+ this.terminal.write(buffer);
1339
+ this.muxViewportRepaintCount += 1;
1340
+ this.cursorRow = Math.max(0, newLines.length - 1);
1341
+ this.hardwareCursorRow = viewportTop + Math.max(0, height - 1);
1342
+ this.maxLinesRendered = newLines.length;
1343
+ this.previousViewportTop = viewportTop;
1344
+ this.positionHardwareCursor(cursorPos, newLines.length);
1345
+ this.setPreviousLines(newLines, rawLines);
1346
+ this.previousKittyImageIds = this.collectKittyImageIds(newLines);
1347
+ this.previousWidth = width;
1348
+ this.previousHeight = height;
1349
+ return true;
1350
+ }
1351
+ /** Splice overlay content into a base line at a specific column. Single-pass optimized. */
1352
+ compositeLineAt(baseLine, overlayLine, startCol, overlayWidth, totalWidth) {
1353
+ if (isImageLine(baseLine))
1354
+ return baseLine;
1355
+ // Single pass through baseLine extracts both before and after segments
1356
+ const afterStart = startCol + overlayWidth;
1357
+ const base = extractSegments(baseLine, startCol, afterStart, totalWidth - afterStart, true);
1358
+ // Extract overlay with width tracking (strict=true to exclude wide chars at boundary)
1359
+ const overlay = sliceWithWidth(overlayLine, 0, overlayWidth, true);
1360
+ // Pad segments to target widths
1361
+ const beforePad = Math.max(0, startCol - base.beforeWidth);
1362
+ const overlayPad = Math.max(0, overlayWidth - overlay.width);
1363
+ const actualBeforeWidth = Math.max(startCol, base.beforeWidth);
1364
+ const actualOverlayWidth = Math.max(overlayWidth, overlay.width);
1365
+ const afterTarget = Math.max(0, totalWidth - actualBeforeWidth - actualOverlayWidth);
1366
+ const afterPad = Math.max(0, afterTarget - base.afterWidth);
1367
+ // Compose result
1368
+ const r = TUI.SEGMENT_RESET;
1369
+ const result = base.before +
1370
+ " ".repeat(beforePad) +
1371
+ r +
1372
+ overlay.text +
1373
+ " ".repeat(overlayPad) +
1374
+ r +
1375
+ base.after +
1376
+ " ".repeat(afterPad);
1377
+ // CRITICAL: Always verify and truncate to terminal width.
1378
+ // This is the final safeguard against width overflow which would crash the TUI.
1379
+ // Width tracking can drift from actual visible width due to:
1380
+ // - Complex ANSI/OSC sequences (hyperlinks, colors)
1381
+ // - Wide characters at segment boundaries
1382
+ // - Edge cases in segment extraction
1383
+ const resultWidth = visibleWidth(result);
1384
+ if (resultWidth <= totalWidth) {
1385
+ return result;
1386
+ }
1387
+ // Truncate with strict=true to ensure we don't exceed totalWidth
1388
+ return sliceByColumn(result, 0, totalWidth, true);
1389
+ }
1390
+ /**
1391
+ * Find and extract cursor position from rendered lines.
1392
+ * Searches for CURSOR_MARKER, calculates its position, and strips it from the output.
1393
+ * Only scans the bottom terminal height lines (visible viewport).
1394
+ * @param lines - Rendered lines to search
1395
+ * @param height - Terminal height (visible viewport size)
1396
+ * @returns Cursor position { row, col } or null if no marker found
1397
+ */
1398
+ extractCursorPosition(lines, height) {
1399
+ // Only scan the bottom `height` lines (visible viewport)
1400
+ const viewportTop = Math.max(0, lines.length - height);
1401
+ for (let row = lines.length - 1; row >= viewportTop; row--) {
1402
+ const line = lines[row];
1403
+ const markerIndex = line.indexOf(CURSOR_MARKER);
1404
+ if (markerIndex !== -1) {
1405
+ // Calculate visual column (width of text before marker)
1406
+ const beforeMarker = line.slice(0, markerIndex);
1407
+ const col = visibleWidth(beforeMarker);
1408
+ // Strip marker from the line
1409
+ lines[row] = line.slice(0, markerIndex) + line.slice(markerIndex + CURSOR_MARKER.length);
1410
+ return { row, col };
1411
+ }
1412
+ }
1413
+ return null;
1414
+ }
1415
+ doRender() {
1416
+ if (this.stopped)
1417
+ return;
1418
+ const width = this.terminal.columns;
1419
+ const height = this.terminal.rows;
1420
+ const widthChanged = this.previousWidth !== 0 && this.previousWidth !== width;
1421
+ const heightChanged = this.previousHeight !== 0 && this.previousHeight !== height;
1422
+ const previousBufferLength = this.previousHeight > 0 ? this.previousViewportTop + this.previousHeight : height;
1423
+ let prevViewportTop = heightChanged ? Math.max(0, previousBufferLength - height) : this.previousViewportTop;
1424
+ let viewportTop = prevViewportTop;
1425
+ let hardwareCursorRow = this.hardwareCursorRow;
1426
+ const computeLineDiff = (targetRow) => {
1427
+ const currentScreenRow = hardwareCursorRow - prevViewportTop;
1428
+ const targetScreenRow = targetRow - viewportTop;
1429
+ return targetScreenRow - currentScreenRow;
1430
+ };
1431
+ // Render all components to get new lines
1432
+ let newLines = this.render(width);
1433
+ // Composite overlays into the rendered lines (before differential compare)
1434
+ if (this.overlayStack.length > 0) {
1435
+ newLines = this.compositeOverlays(newLines, width, height);
1436
+ }
1437
+ // Extract cursor position before applying line resets (marker must be found first)
1438
+ const cursorPos = this.extractCursorPosition(newLines, height);
1439
+ const rawLines = newLines;
1440
+ const normalizedLines = this.applyViewportLineResets(rawLines, prevViewportTop, height, !widthChanged && !heightChanged);
1441
+ newLines = normalizedLines.lines;
1442
+ const preserveMuxScrollback = this.shouldPreserveMuxScrollback();
1443
+ // Helper to clear scrollback and viewport and render all new lines
1444
+ const fullRender = (clear, clearScrollback = clear) => {
1445
+ this.fullRedrawCount += 1;
1446
+ let buffer = TUI.FRAME_BEGIN;
1447
+ if (clear) {
1448
+ buffer += this.deleteKittyImages(this.previousKittyImageIds);
1449
+ buffer += "\x1b[2J\x1b[H";
1450
+ if (clearScrollback && !preserveMuxScrollback) {
1451
+ buffer += "\x1b[3J";
1452
+ }
1453
+ }
1454
+ else {
1455
+ buffer += `\r\x1b[2K${TUI.SEGMENT_RESET}`;
1456
+ }
1457
+ for (let i = 0; i < newLines.length; i++) {
1458
+ if (i > 0)
1459
+ buffer += "\r\n";
1460
+ const line = newLines[i];
1461
+ const isImage = isImageLine(line);
1462
+ const imageReservedRows = isImage ? this.getKittyImageReservedRows(newLines, i) : 1;
1463
+ if (imageReservedRows > 1 && imageReservedRows <= height) {
1464
+ for (let row = 1; row < imageReservedRows; row++) {
1465
+ buffer += "\r\n";
1466
+ }
1467
+ buffer += `\x1b[${imageReservedRows - 1}A`;
1468
+ buffer += line;
1469
+ buffer += `\x1b[${imageReservedRows - 1}B`;
1470
+ i += imageReservedRows - 1;
1471
+ continue;
1472
+ }
1473
+ buffer += line;
1474
+ }
1475
+ buffer += TUI.FRAME_END;
1476
+ this.terminal.write(buffer);
1477
+ this.cursorRow = Math.max(0, newLines.length - 1);
1478
+ this.hardwareCursorRow = this.cursorRow;
1479
+ // Reset max lines when clearing, otherwise track growth
1480
+ if (clear) {
1481
+ this.maxLinesRendered = newLines.length;
1482
+ }
1483
+ else {
1484
+ this.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);
1485
+ }
1486
+ const bufferLength = Math.max(height, newLines.length);
1487
+ this.previousViewportTop = Math.max(0, bufferLength - height);
1488
+ this.positionHardwareCursor(cursorPos, newLines.length);
1489
+ this.setPreviousLines(newLines, rawLines);
1490
+ this.previousKittyImageIds = this.collectKittyImageIds(newLines);
1491
+ this.previousWidth = width;
1492
+ this.previousHeight = height;
1493
+ };
1494
+ const debugRedraw = process.env.PI_DEBUG_REDRAW === "1";
1495
+ const logRedraw = (reason) => {
1496
+ if (!debugRedraw)
1497
+ return;
1498
+ const logPath = path.join(os.homedir(), ".senpi", "agent", "senpi-debug.log");
1499
+ const msg = `[${new Date().toISOString()}] fullRender: ${reason} (prev=${this.previousLines.length}, new=${newLines.length}, height=${height})\n`;
1500
+ fs.appendFileSync(logPath, msg, { encoding: "utf8", mode: DIAGNOSTIC_LOG_MODE });
1501
+ chmodDiagnosticLogBestEffort(logPath);
1502
+ };
1503
+ // First render - just output everything without clearing (assumes clean screen)
1504
+ if (this.previousLines.length === 0 && !widthChanged && !heightChanged) {
1505
+ logRedraw("first render");
1506
+ fullRender(false);
1507
+ return;
1508
+ }
1509
+ // Width changes always need a full re-render because wrapping changes.
1510
+ if (widthChanged) {
1511
+ logRedraw(`terminal width changed (${this.previousWidth} -> ${width})`);
1512
+ // In multiplexers, re-emit the viewport without 3J so pane history survives; an older copy may remain above.
1513
+ fullRender(true, !preserveMuxScrollback);
1514
+ return;
1515
+ }
1516
+ // Height changes normally need a full re-render to keep the visible viewport aligned,
1517
+ // but Termux changes height when the software keyboard shows or hides.
1518
+ // In that environment, a full redraw causes the entire history to replay on every toggle.
1519
+ if (heightChanged && !isTermuxSession()) {
1520
+ logRedraw(`terminal height changed (${this.previousHeight} -> ${height})`);
1521
+ if (preserveMuxScrollback) {
1522
+ if (!this.renderMuxViewportRepaint(newLines, rawLines, cursorPos, width, height)) {
1523
+ fullRender(true, false);
1524
+ }
1525
+ }
1526
+ else {
1527
+ fullRender(true);
1528
+ }
1529
+ return;
1530
+ }
1531
+ // Content shrunk below the working area and no overlays - re-render to clear empty rows
1532
+ // (overlays need the padding, so only do this when no overlays are active)
1533
+ // Configurable via setClearOnShrink() or PI_CLEAR_ON_SHRINK=0 env var
1534
+ if (this.clearOnShrink && newLines.length < this.maxLinesRendered && this.overlayStack.length === 0) {
1535
+ logRedraw(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`);
1536
+ fullRender(true, !preserveMuxScrollback);
1537
+ return;
1538
+ }
1539
+ // Find first and last changed lines
1540
+ let firstChanged = -1;
1541
+ let lastChanged = -1;
1542
+ const maxLines = Math.max(newLines.length, this.previousLines.length);
1543
+ const diffScanStart = normalizedLines.bounded && normalizedLines.firstRawChanged !== -1 ? normalizedLines.firstRawChanged : 0;
1544
+ const diffScanEndExclusive = normalizedLines.bounded ? normalizedLines.compareEndExclusive : maxLines;
1545
+ for (let i = diffScanStart; i < diffScanEndExclusive; i++) {
1546
+ const oldLine = i < this.previousLines.length ? this.previousLines[i] : "";
1547
+ const newLine = i < newLines.length ? newLines[i] : "";
1548
+ if (oldLine !== newLine) {
1549
+ if (firstChanged === -1) {
1550
+ firstChanged = i;
1551
+ }
1552
+ lastChanged = i;
1553
+ }
1554
+ }
1555
+ const appendedLines = newLines.length > this.previousLines.length;
1556
+ const lineCountDelta = newLines.length - this.previousLines.length;
1557
+ if (appendedLines) {
1558
+ if (firstChanged === -1) {
1559
+ firstChanged = this.previousLines.length;
1560
+ }
1561
+ lastChanged = newLines.length - 1;
1562
+ }
1563
+ const needsKittyImageExpansion = firstChanged !== -1 && this.changedRangeNeedsKittyImageExpansion(newLines, firstChanged, lastChanged);
1564
+ if (needsKittyImageExpansion) {
1565
+ const expandedRange = this.expandChangedRangeForKittyImages(firstChanged, lastChanged, newLines);
1566
+ firstChanged = expandedRange.firstChanged;
1567
+ lastChanged = expandedRange.lastChanged;
1568
+ }
1569
+ const appendStart = appendedLines && firstChanged === this.previousLines.length && firstChanged > 0;
1570
+ const insertScrollPlan = this.createViewportInsertScrollPlan(newLines, prevViewportTop, height, lineCountDelta);
1571
+ // No changes - but still need to update hardware cursor position if it moved
1572
+ if (firstChanged === -1) {
1573
+ this.positionHardwareCursor(cursorPos, newLines.length);
1574
+ this.previousViewportTop = prevViewportTop;
1575
+ this.previousHeight = height;
1576
+ return;
1577
+ }
1578
+ if (insertScrollPlan) {
1579
+ this.renderViewportInsertScroll(insertScrollPlan, newLines, rawLines, cursorPos, width, height);
1580
+ return;
1581
+ }
1582
+ // All changes are in deleted lines (nothing to render, just clear)
1583
+ if (firstChanged >= newLines.length) {
1584
+ if (this.previousLines.length > newLines.length) {
1585
+ let buffer = TUI.FRAME_BEGIN;
1586
+ buffer += this.deleteChangedKittyImages(firstChanged, lastChanged);
1587
+ // Move to end of new content (clamp to 0 for empty content)
1588
+ const targetRow = Math.max(0, newLines.length - 1);
1589
+ if (targetRow < prevViewportTop) {
1590
+ logRedraw(`deleted lines moved viewport up (${targetRow} < ${prevViewportTop})`);
1591
+ fullRender(true, !preserveMuxScrollback);
1592
+ return;
1593
+ }
1594
+ const lineDiff = computeLineDiff(targetRow);
1595
+ if (lineDiff > 0)
1596
+ buffer += `\x1b[${lineDiff}B`;
1597
+ else if (lineDiff < 0)
1598
+ buffer += `\x1b[${-lineDiff}A`;
1599
+ buffer += "\r";
1600
+ // Clear extra lines without scrolling
1601
+ const extraLines = this.previousLines.length - newLines.length;
1602
+ if (extraLines > height) {
1603
+ logRedraw(`extraLines > height (${extraLines} > ${height})`);
1604
+ fullRender(true, !preserveMuxScrollback);
1605
+ return;
1606
+ }
1607
+ const clearStartOffset = newLines.length === 0 ? 0 : 1;
1608
+ if (extraLines > 0 && clearStartOffset > 0) {
1609
+ buffer += `\x1b[${clearStartOffset}B`;
1610
+ }
1611
+ for (let i = 0; i < extraLines; i++) {
1612
+ buffer += `\r\x1b[2K${TUI.SEGMENT_RESET}`;
1613
+ if (i < extraLines - 1)
1614
+ buffer += "\x1b[1B";
1615
+ }
1616
+ const moveBack = Math.max(0, extraLines - 1 + clearStartOffset);
1617
+ if (moveBack > 0) {
1618
+ buffer += `\x1b[${moveBack}A`;
1619
+ }
1620
+ buffer += TUI.FRAME_END;
1621
+ this.terminal.write(buffer);
1622
+ this.cursorRow = targetRow;
1623
+ this.hardwareCursorRow = targetRow;
1624
+ }
1625
+ this.positionHardwareCursor(cursorPos, newLines.length);
1626
+ this.setPreviousLines(newLines, rawLines);
1627
+ this.previousKittyImageIds = this.collectKittyImageIds(newLines);
1628
+ this.previousWidth = width;
1629
+ this.previousHeight = height;
1630
+ this.previousViewportTop = prevViewportTop;
1631
+ return;
1632
+ }
1633
+ // Differential rendering can only touch what was actually visible.
1634
+ if (firstChanged < prevViewportTop) {
1635
+ if (newLines.length < this.previousLines.length) {
1636
+ viewportTop = Math.max(0, newLines.length - height);
1637
+ }
1638
+ if (newLines.length > this.previousLines.length) {
1639
+ const maxViewportTop = Math.max(0, newLines.length - height);
1640
+ viewportTop = Math.min(maxViewportTop, prevViewportTop + lineCountDelta);
1641
+ }
1642
+ let firstVisibleChanged = -1;
1643
+ let lastVisibleChanged = -1;
1644
+ for (let row = 0; row < height; row++) {
1645
+ const previousLine = this.previousLines[prevViewportTop + row] ?? "";
1646
+ const nextLine = newLines[viewportTop + row] ?? "";
1647
+ if (previousLine !== nextLine) {
1648
+ if (firstVisibleChanged === -1) {
1649
+ firstVisibleChanged = row;
1650
+ }
1651
+ lastVisibleChanged = row;
1652
+ }
1653
+ }
1654
+ if (firstVisibleChanged === -1) {
1655
+ if (lineCountDelta !== 0) {
1656
+ if (preserveMuxScrollback) {
1657
+ // Above-viewport scrollback may stay stale in mux panes; only the visible viewport is repainted.
1658
+ if (!this.renderMuxViewportRepaint(newLines, rawLines, cursorPos, width, height, viewportTop)) {
1659
+ fullRender(true, false);
1660
+ }
1661
+ }
1662
+ else {
1663
+ this.renderScrollbackReplay(newLines, rawLines, cursorPos, width, height, prevViewportTop, hardwareCursorRow);
1664
+ }
1665
+ return;
1666
+ }
1667
+ this.cursorRow = Math.max(0, newLines.length - 1);
1668
+ this.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);
1669
+ this.setPreviousLines(newLines, rawLines);
1670
+ this.previousWidth = width;
1671
+ this.previousHeight = height;
1672
+ this.previousViewportTop = viewportTop;
1673
+ return;
1674
+ }
1675
+ if (viewportTop !== prevViewportTop) {
1676
+ const previousViewportBottom = Math.min(this.previousLines.length - 1, prevViewportTop + height - 1);
1677
+ let buffer = TUI.FRAME_BEGIN;
1678
+ buffer += this.deleteChangedKittyImages(prevViewportTop, previousViewportBottom);
1679
+ const currentScreenRow = Math.max(0, Math.min(height - 1, hardwareCursorRow - prevViewportTop));
1680
+ if (currentScreenRow > 0) {
1681
+ buffer += `\x1b[${currentScreenRow}A`;
1682
+ }
1683
+ for (let row = 0; row < height; row++) {
1684
+ if (row > 0)
1685
+ buffer += "\r\n";
1686
+ buffer += `\r\x1b[2K${TUI.SEGMENT_RESET}`;
1687
+ buffer += newLines[viewportTop + row] ?? "";
1688
+ }
1689
+ buffer += TUI.FRAME_END;
1690
+ this.terminal.write(buffer);
1691
+ this.cursorRow = Math.max(0, newLines.length - 1);
1692
+ this.hardwareCursorRow = viewportTop + Math.max(0, height - 1);
1693
+ this.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);
1694
+ this.previousViewportTop = viewportTop;
1695
+ this.positionHardwareCursor(cursorPos, newLines.length);
1696
+ this.setPreviousLines(newLines, rawLines);
1697
+ this.previousKittyImageIds = this.collectKittyImageIds(newLines);
1698
+ this.previousWidth = width;
1699
+ this.previousHeight = height;
1700
+ return;
1701
+ }
1702
+ firstChanged = viewportTop + firstVisibleChanged;
1703
+ lastChanged = Math.min(newLines.length - 1, viewportTop + lastVisibleChanged);
1704
+ }
1705
+ // Render from first changed line to end
1706
+ // Build buffer with all updates wrapped in synchronized output
1707
+ let buffer = TUI.FRAME_BEGIN;
1708
+ buffer += this.deleteChangedKittyImages(firstChanged, lastChanged);
1709
+ const prevViewportBottom = prevViewportTop + height - 1;
1710
+ const moveTargetRow = appendStart ? firstChanged - 1 : firstChanged;
1711
+ if (moveTargetRow > prevViewportBottom) {
1712
+ const currentScreenRow = Math.max(0, Math.min(height - 1, hardwareCursorRow - prevViewportTop));
1713
+ const moveToBottom = height - 1 - currentScreenRow;
1714
+ if (moveToBottom > 0) {
1715
+ buffer += `\x1b[${moveToBottom}B`;
1716
+ }
1717
+ const scroll = moveTargetRow - prevViewportBottom;
1718
+ buffer += "\r\n".repeat(scroll);
1719
+ prevViewportTop += scroll;
1720
+ viewportTop += scroll;
1721
+ hardwareCursorRow = moveTargetRow;
1722
+ }
1723
+ // Move cursor to first changed line (use hardwareCursorRow for actual position)
1724
+ const lineDiff = computeLineDiff(moveTargetRow);
1725
+ if (lineDiff > 0) {
1726
+ buffer += `\x1b[${lineDiff}B`; // Move down
1727
+ }
1728
+ else if (lineDiff < 0) {
1729
+ buffer += `\x1b[${-lineDiff}A`; // Move up
1730
+ }
1731
+ buffer += appendStart ? "\r\n" : "\r"; // Move to column 0
1732
+ // Only render changed lines (firstChanged to lastChanged), not all lines to end
1733
+ // This reduces flicker when only a single line changes (e.g., spinner animation)
1734
+ const renderEnd = Math.min(lastChanged, newLines.length - 1);
1735
+ for (let i = firstChanged; i <= renderEnd; i++) {
1736
+ if (i > firstChanged)
1737
+ buffer += "\r\n";
1738
+ const line = newLines[i];
1739
+ const isImage = isImageLine(line);
1740
+ const imageReservedRows = isImage ? this.getKittyImageReservedRows(newLines, i, renderEnd) : 1;
1741
+ if (imageReservedRows > 1) {
1742
+ const imageStartScreenRow = i - viewportTop;
1743
+ if (imageStartScreenRow < 0 || imageStartScreenRow + imageReservedRows > height) {
1744
+ logRedraw(`kitty image pre-clear would scroll (${imageStartScreenRow} + ${imageReservedRows} > ${height})`);
1745
+ fullRender(true, !preserveMuxScrollback);
1746
+ return;
1747
+ }
1748
+ buffer += `\x1b[2K${TUI.SEGMENT_RESET}`;
1749
+ for (let row = 1; row < imageReservedRows; row++) {
1750
+ buffer += `\r\n\x1b[2K${TUI.SEGMENT_RESET}`;
1751
+ }
1752
+ buffer += `\x1b[${imageReservedRows - 1}A`;
1753
+ buffer += line;
1754
+ buffer += `\x1b[${imageReservedRows - 1}B`;
1755
+ i += imageReservedRows - 1;
1756
+ continue;
1757
+ }
1758
+ buffer += `\x1b[2K${TUI.SEGMENT_RESET}`; // Clear current line
1759
+ const lineWidth = visibleWidth(line);
1760
+ if (!isImage && lineWidth > width) {
1761
+ // Log all lines to crash file for debugging
1762
+ const crashLogPath = path.join(os.homedir(), ".senpi", "agent", "senpi-crash.log");
1763
+ const crashData = [
1764
+ `Crash at ${new Date().toISOString()}`,
1765
+ `Terminal width: ${width}`,
1766
+ `Line ${i} visible width: ${lineWidth}`,
1767
+ "",
1768
+ "=== All rendered lines ===",
1769
+ ...newLines.map((l, idx) => `[${idx}] (w=${visibleWidth(l)}) ${l}`),
1770
+ "",
1771
+ ].join("\n");
1772
+ if (process.env.PI_TUI_STRICT_RENDER === "1") {
1773
+ const crashDumpWritten = writeRenderDiagnosticBestEffort(crashLogPath, crashData);
1774
+ // Clean up terminal state before throwing
1775
+ this.stop();
1776
+ const errorMsg = [
1777
+ `Rendered line ${i} exceeds terminal width (${lineWidth} > ${width}).`,
1778
+ "",
1779
+ "This is likely caused by a custom TUI component not truncating its output.",
1780
+ "Use visibleWidth() to measure and truncateToWidth() to truncate lines.",
1781
+ "",
1782
+ crashDumpWritten
1783
+ ? `Debug log written to: ${crashLogPath}`
1784
+ : `Debug log could not be written to: ${crashLogPath}`,
1785
+ ].join("\n");
1786
+ throw new Error(errorMsg);
1787
+ }
1788
+ if (!this.overWideCrashDumpWritten) {
1789
+ writeRenderDiagnosticBestEffort(crashLogPath, crashData);
1790
+ this.overWideCrashDumpWritten = true;
1791
+ }
1792
+ const truncatedLine = sliceByColumn(line, 0, width, true) + TUI.SEGMENT_RESET;
1793
+ newLines[i] = truncatedLine;
1794
+ buffer += truncatedLine;
1795
+ continue;
1796
+ }
1797
+ buffer += line;
1798
+ }
1799
+ // Track where cursor ended up after rendering
1800
+ let finalCursorRow = renderEnd;
1801
+ // If we had more lines before, clear them and move cursor back
1802
+ if (this.previousLines.length > newLines.length) {
1803
+ // Move to end of new content first if we stopped before it
1804
+ if (renderEnd < newLines.length - 1) {
1805
+ const moveDown = newLines.length - 1 - renderEnd;
1806
+ buffer += `\x1b[${moveDown}B`;
1807
+ finalCursorRow = newLines.length - 1;
1808
+ }
1809
+ const extraLines = this.previousLines.length - newLines.length;
1810
+ for (let i = newLines.length; i < this.previousLines.length; i++) {
1811
+ buffer += `\r\n\x1b[2K${TUI.SEGMENT_RESET}`;
1812
+ }
1813
+ // Move cursor back to end of new content
1814
+ buffer += `\x1b[${extraLines}A`;
1815
+ }
1816
+ buffer += TUI.FRAME_END;
1817
+ if (process.env.PI_TUI_DEBUG === "1") {
1818
+ const debugDir = "/tmp/tui";
1819
+ fs.mkdirSync(debugDir, { recursive: true });
1820
+ const debugPath = path.join(debugDir, `render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`);
1821
+ const debugData = [
1822
+ `firstChanged: ${firstChanged}`,
1823
+ `viewportTop: ${viewportTop}`,
1824
+ `cursorRow: ${this.cursorRow}`,
1825
+ `height: ${height}`,
1826
+ `lineDiff: ${lineDiff}`,
1827
+ `hardwareCursorRow: ${hardwareCursorRow}`,
1828
+ `renderEnd: ${renderEnd}`,
1829
+ `finalCursorRow: ${finalCursorRow}`,
1830
+ `cursorPos: ${JSON.stringify(cursorPos)}`,
1831
+ `newLines.length: ${newLines.length}`,
1832
+ `previousLines.length: ${this.previousLines.length}`,
1833
+ "",
1834
+ "=== newLines ===",
1835
+ JSON.stringify(newLines, null, 2),
1836
+ "",
1837
+ "=== previousLines ===",
1838
+ JSON.stringify(this.previousLines, null, 2),
1839
+ "",
1840
+ "=== buffer ===",
1841
+ JSON.stringify(buffer),
1842
+ ].join("\n");
1843
+ fs.writeFileSync(debugPath, debugData, { encoding: "utf8", mode: DIAGNOSTIC_LOG_MODE });
1844
+ chmodDiagnosticLogBestEffort(debugPath);
1845
+ }
1846
+ // Write entire buffer at once
1847
+ this.terminal.write(buffer);
1848
+ // Track cursor position for next render
1849
+ // cursorRow tracks end of content (for viewport calculation)
1850
+ // hardwareCursorRow tracks actual terminal cursor position (for movement)
1851
+ this.cursorRow = Math.max(0, newLines.length - 1);
1852
+ this.hardwareCursorRow = finalCursorRow;
1853
+ // Track terminal's working area (grows but doesn't shrink unless cleared)
1854
+ this.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);
1855
+ this.previousViewportTop = Math.max(prevViewportTop, finalCursorRow - height + 1);
1856
+ // Position hardware cursor for IME
1857
+ this.positionHardwareCursor(cursorPos, newLines.length);
1858
+ this.setPreviousLines(newLines, rawLines);
1859
+ if (needsKittyImageExpansion) {
1860
+ this.previousKittyImageIds = this.collectKittyImageIds(newLines);
1861
+ }
1862
+ this.previousWidth = width;
1863
+ this.previousHeight = height;
1864
+ }
1865
+ /**
1866
+ * Position the hardware cursor for IME candidate window.
1867
+ * @param cursorPos The cursor position extracted from rendered output, or null
1868
+ * @param totalLines Total number of rendered lines
1869
+ */
1870
+ positionHardwareCursor(cursorPos, totalLines) {
1871
+ let buffer = "";
1872
+ if (!cursorPos || totalLines <= 0) {
1873
+ if (this.#lastCursorVisibility !== false) {
1874
+ buffer += "\x1b[?25l";
1875
+ this.#lastCursorVisibility = false;
1876
+ }
1877
+ }
1878
+ else {
1879
+ // Clamp cursor position to valid range
1880
+ const targetRow = Math.max(0, Math.min(cursorPos.row, totalLines - 1));
1881
+ const targetCol = Math.max(0, cursorPos.col);
1882
+ // Move cursor from current position to target
1883
+ const rowDelta = targetRow - this.hardwareCursorRow;
1884
+ if (rowDelta > 0) {
1885
+ buffer += `\x1b[${rowDelta}B`; // Move down
1886
+ }
1887
+ else if (rowDelta < 0) {
1888
+ buffer += `\x1b[${-rowDelta}A`; // Move up
1889
+ }
1890
+ // Move to absolute column (1-indexed)
1891
+ buffer += `\x1b[${targetCol + 1}G`;
1892
+ this.hardwareCursorRow = targetRow;
1893
+ if (this.#lastCursorVisibility !== this.showHardwareCursor) {
1894
+ buffer += this.showHardwareCursor ? "\x1b[?25h" : "\x1b[?25l";
1895
+ this.#lastCursorVisibility = this.showHardwareCursor;
1896
+ }
1897
+ }
1898
+ if (buffer) {
1899
+ this.terminal.write(buffer);
1900
+ }
1901
+ }
1902
+ /**
1903
+ * Query the terminal's default background color with OSC 11 (`ESC ] 11 ; ? BEL`).
1904
+ * @param timeoutMs Query timeout in milliseconds.
1905
+ * @returns Promise containing the parsed RGB color, or undefined if it times out or fails to parse.
1906
+ */
1907
+ queryTerminalBackgroundColor({ timeoutMs }) {
1908
+ return new Promise((resolve) => {
1909
+ const query = {
1910
+ settled: false,
1911
+ resolve,
1912
+ timer: undefined,
1913
+ };
1914
+ query.timer = setTimeout(() => {
1915
+ if (query.settled) {
1916
+ return;
1917
+ }
1918
+ query.settled = true;
1919
+ query.timer = undefined;
1920
+ query.resolve?.(undefined);
1921
+ query.resolve = undefined;
1922
+ }, timeoutMs);
1923
+ this.pendingOsc11BackgroundQueries.push(query);
1924
+ this.pendingOsc11BackgroundReplies += 1;
1925
+ this.terminal.write("\x1b]11;?\x07");
1926
+ });
1927
+ }
1928
+ /**
1929
+ * Query the terminal's color-scheme preference with DSR (`CSI ? 996 n`).
1930
+ * Terminals that support the color palette notification protocol reply with
1931
+ * `CSI ? 997 ; 1 n` for dark or `CSI ? 997 ; 2 n` for light.
1932
+ */
1933
+ queryTerminalColorScheme({ timeoutMs }) {
1934
+ return new Promise((resolve) => {
1935
+ let settled = false;
1936
+ let timer;
1937
+ let unsubscribe = () => { };
1938
+ const settle = (scheme) => {
1939
+ if (settled)
1940
+ return;
1941
+ settled = true;
1942
+ if (timer) {
1943
+ clearTimeout(timer);
1944
+ timer = undefined;
1945
+ }
1946
+ unsubscribe();
1947
+ resolve(scheme);
1948
+ };
1949
+ unsubscribe = this.onTerminalColorSchemeChange(settle);
1950
+ timer = setTimeout(() => settle(undefined), timeoutMs);
1951
+ this.terminal.write("\x1b[?996n");
1952
+ });
1953
+ }
1954
+ }
1955
+ //# sourceMappingURL=tui.js.map